使用tf.pad在tensorflow中填充序列

时间:2017-04-09 03:17:17

标签: python-3.x tensorflow

我正在尝试在python中加载imdb数据集。我想填充序列,以便每个序列长度相同。我目前正在使用numpy。使用tf.pad在tensorflow中执行此操作的好方法是什么。我看到了给定的here,但我不知道如何用2 d矩阵应用它。 这是我目前的代码

import tensorflow as tf
from keras.datasets import imdb
max_features = 5000
print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)

def padSequence(dataset,max_length):
    dataset_p = []
    for x in dataset:
        if(len(x) <=max_length):
            dataset_p.append(np.pad(x,pad_width=(0,max_length-len(x)),mode='constant',constant_values=0))
        else:
            dataset_p.append(x[0:max_length])
    return np.array(x_train_p)

max_length = max(len(x) for x in x_train)
x_train_p = padSequence(x_train,max_length)
x_test_p = padSequence(x_test,max_length)
print("input x shape: " ,x_train_p.shape)

有人可以帮忙吗? 我正在使用tensorflow 1.0 在回应评论时: 填充尺寸由
给出 # 'paddings' is [[1, 1,], [2, 2]]

我有一个2 d矩阵,每行的长度不同。我希望能够填充以使它们具有相同的长度。在我的padSequence(dataset,max_length)函数中,我得到len(x)函数的每一行的长度。我应该和tf一样吗?或者有没有办法像Keras功能

那样做
x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen)

1 个答案:

答案 0 :(得分:0)

如果要使用tf.pad,根据我的说法,您必须为每一行进行迭代。

代码将如下所示:

max_length = 250
number_of_samples = 5

padded_data = np.ndarray(shape=[number_of_samples, max_length],dtype=np.int32)   
sess = tf.InteractiveSession()

for i in range(number_of_samples):
    reviewToBePadded = dataSet[i] #dataSet numpy array
    paddings = [[0,0], [0, maxLength-len(reviewToBePadded)]]
    data_tf = tf.convert_to_tensor(reviewToBePadded,tf.int32)
    data_tf = tf.reshape(data_tf,[1,len(reviewToBePadded)])
    data_tf =  tf.pad(data_tf, paddings, 'CONSTANT')
    padded_data[i] = data_tf.eval()
print(padded_data)
sess.close()

Python的新手,可能不是最好的代码。但是我只想解释一下这个概念。