將序列填充到相同的長度。
用法
tf.keras.preprocessing.sequence.pad_sequences(
sequences, maxlen=None, dtype='int32', padding='pre',
truncating='pre', value=0.0
)
參數
-
sequences
序列列表(每個序列都是整數列表)。 -
maxlen
可選 Int,所有序列的最大長度。如果未提供,序列將被填充到最長的單個序列的長度。 -
dtype
(可選,默認為 int32)。輸出序列的類型。要使用可變長度字符串填充序列,可以使用object
。 -
padding
字符串,'pre' 或 'post'(可選,默認為 'pre'):在每個序列之前或之後填充。 -
truncating
字符串,'pre' 或 'post'(可選,默認為 'pre'):從序列的開頭或結尾刪除大於maxlen
的值。 -
value
浮點數或字符串,填充值。 (可選,默認為 0。)
返回
-
形狀為
(len(sequences), maxlen)
的 Numpy 數組
拋出
-
ValueError
如果truncating
或padding
的值無效,或者sequences
條目的形狀無效。
此函數將序列(整數列表)的列表(長度為 num_samples
)轉換為形狀為 (num_samples, num_timesteps)
的二維 Numpy 數組。 num_timesteps
是 maxlen
參數(如果提供),或者是列表中最長序列的長度。
比num_timesteps
短的序列用value
填充,直到它們長到num_timesteps
。
長於 num_timesteps
的序列將被截斷,以使其符合所需的長度。
發生填充或截斷的位置分別由參數 padding
和 truncating
確定。從序列的開頭預填充或刪除值是默認設置。
sequence = [[1], [2, 3], [4, 5, 6]]
tf.keras.preprocessing.sequence.pad_sequences(sequence)
array([[0, 0, 1],
[0, 2, 3],
[4, 5, 6]], dtype=int32)
tf.keras.preprocessing.sequence.pad_sequences(sequence, value=-1)
array([[-1, -1, 1],
[-1, 2, 3],
[ 4, 5, 6]], dtype=int32)
tf.keras.preprocessing.sequence.pad_sequences(sequence, padding='post')
array([[1, 0, 0],
[2, 3, 0],
[4, 5, 6]], dtype=int32)
tf.keras.preprocessing.sequence.pad_sequences(sequence, maxlen=2)
array([[0, 1],
[2, 3],
[5, 6]], dtype=int32)
相關用法
- Python tf.keras.preprocessing.sequence.TimeseriesGenerator用法及代碼示例
- Python tf.keras.preprocessing.sequence.make_sampling_table用法及代碼示例
- Python tf.keras.preprocessing.image.ImageDataGenerator用法及代碼示例
- Python tf.keras.preprocessing.image.smart_resize用法及代碼示例
- Python tf.keras.preprocessing.image.DirectoryIterator.__len__用法及代碼示例
- Python tf.keras.preprocessing.text.text_to_word_sequence用法及代碼示例
- Python tf.keras.applications.inception_resnet_v2.preprocess_input用法及代碼示例
- Python tf.keras.metrics.Mean.merge_state用法及代碼示例
- Python tf.keras.layers.InputLayer用法及代碼示例
- Python tf.keras.callbacks.ReduceLROnPlateau用法及代碼示例
- Python tf.keras.layers.serialize用法及代碼示例
- Python tf.keras.metrics.Hinge用法及代碼示例
- Python tf.keras.experimental.WideDeepModel.compute_loss用法及代碼示例
- Python tf.keras.metrics.SparseCategoricalAccuracy.merge_state用法及代碼示例
- Python tf.keras.metrics.RootMeanSquaredError用法及代碼示例
- Python tf.keras.applications.resnet50.preprocess_input用法及代碼示例
- Python tf.keras.metrics.SparseCategoricalCrossentropy.merge_state用法及代碼示例
- Python tf.keras.metrics.sparse_categorical_accuracy用法及代碼示例
- Python tf.keras.layers.Dropout用法及代碼示例
- Python tf.keras.activations.softplus用法及代碼示例
注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.keras.preprocessing.sequence.pad_sequences。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。