tf.keras.preprocessing.sequence.pad_sequences用法(详解)

*本函数的作用是将序列填充到相同的长度

我们先看一看该函数的格式:

tf.keras.preprocessing.sequence.pad_sequence(
                                             sequences, maxlen=None,dtype='int32', padding='pre'
                                             truncating='pre',value=0.0 )

·sequences:序列列表(每个序列都是整数列表)。

·maxlen :可以对此参数进行设定,代表所有序列的最大长度。如果没有提供默认为补齐到最长序列。

·dtype : 参数设置可供选择。可以让序列中的数以不同的进制显示

·padding:参数选择为“pre”和“post”,pre为在序列前进行拉伸或者截断,post是在序列最后进行拉伸或者截断

·truncating:参数可以选择为‘pre’或者‘post’在序列的开头或结尾从大于 maxlen 的序列中删除值。

·value :浮点或字符串,填充值。(可选,默认为0)

该函数可以将长度为num_samples的整数列表转换为一个二维的形式为(num_samples, num_timesteps)的numpy数组。num_timesteps是被提供的或者列表中最长的的序列。
序列长度长于num_timesteps的被截断以适应与预期设定的长度。
序列长度小于num_timesteps的将被填充值拉伸为num_timesteps长度。
那个位置拉伸或者截断分别由拉伸和截断来决定。默认在序列的开始进行拉伸或者移除数值。具体看函数操作如下:

import tensorflow as tf
sequence = [[1], [2, 3], [4, 5, 6]]

将上述数组长度进行统一,代码如下:

tf.keras.preprocessing.sequence.pad_sequences(sequence)
array([[0, 0, 1],
       [0, 2, 3],
       [4, 5, 6]])

序列长度统一填入值-1

tf.keras.preprocessing.sequence.pad_sequences(sequence, value=-1)
array([[-1, -1,  1],
       [-1,  2,  3],
       [ 4,  5,  6]])

序列长度统一改变后置拉伸方式

tf.keras.preprocessing.sequence.pad_sequences(sequence, padding='post')
array([[1, 0, 0],
       [2, 3, 0],
       [4, 5, 6]])

对序列中进行阶段,长度为2

tf.keras.preprocessing.sequence.pad_sequences(sequence, maxlen=2)
array([[0, 1],
       [2, 3],
       [5, 6]])
sequence = [[1], [2, 3], [4, 5, 6]]
tf.keras.preprocessing.sequence.pad_sequences(sequence, maxlen=2,atruncating='pre')
array([[0, 1],
       [2, 3],
       [5, 6]])
sequence = [[1], [2, 3], [4, 5, 6]]
tf.keras.preprocessing.sequence.pad_sequences(sequence, maxlen=2,truncating='post')
array([[0, 1],
       [2, 3],
       [4, 5]])

你可能感兴趣的:(TensorFlow,tensorflow,keras)