如何将两个只有一个公共尺寸(批大小)的3D张量传递给dynamic_lstm?

时间:2018-08-06 16:06:24

标签: python python-3.x tensorflow lstm tensorflow-datasets

我想将2个具有不同尺寸的张量传递给tf.nn.dynamic_rnn。我遇到了困难,因为尺寸不匹配。我乐于为实现此目的的最佳方法提出建议。这些张量是tf.data.Dataset

的批处理

我有2个形状的张量:

张量1:(?,?,1024)

张量2:(?,?,128)

第一个维度是批处理大小,第二个维度是时间步数,第三个维度是每个时间步要输入的要素数。

当前,我遇到一个问题,即每个维度的时间步数不匹配。不仅如此,而且它们在样本之间的大小也不一致(对于某些样本,张量1具有71个时间步长,有时可能具有74或77个时间步长。)

对于每个样本,在较短的张量中动态填充时间步长的最佳解决方案是最好的解决方案吗?如果是这样,我该怎么办?

下面是显示我想做什么的代码段:

#Get the next batch from my tf.data.Dataset
video_id, label, rgb, audio = my_iter.get_next()

print (rgb.shape)    #(?, ?, 1024)
print (audio.shape)    #(?, ?, 128)

lstm_layer = tf.contrib.rnn.BasicLSTMCell(lstm_size)

#This instruction throws an InvalidArgumentError, I have shown the output below this code
concatenated_features = tf.concat([rgb, audio], 2)
print (concatenated_features.shape)    #(?, ?, 1152)

outputs,_= tf.nn.dynamic_rnn(lstm_layer, concatenated_features, dtype="float32")

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(num_epochs):
        sess.run(my_iter.initializer)
        for j in range(num_steps):
            my_outputs = sess.run(outputs)

在会话中调用tf.concat时出错:

InvalidArgumentError (see above for traceback): ConcatOp : Dimensions of inputs should match: shape[0] = [52,77,1024] vs. shape[1] = [52,101,128]

1 个答案:

答案 0 :(得分:1)

这是我设法找到的解决方案,虽然可能没有理想的解决方案,但是除非有人有更好的解决方案,否则它可以解决问题。另外,我是TensorFlow的新手,如果我的推理不正确,我可以进行编辑。

将张量存储在tf.data.Dataset中并且任何建议的Dataset.map函数(用于执行按元素的运算)都对符号张量进行操作(在这种情况下,外壳没有确切的形状)。由于这个原因,我无法使用Dataset.map创建一个tf.pad函数,但是可以接受这样做的解决方案。

此解决方案使用Dataset.map函数和tf.py_func将python函数包装为TensorFlow操作。此函数查找2个张量(现在是函数内部的np.arrays)之间的差,然后使用np.pad在数据后的0处填充时间步长维度。

def pad_timesteps(video, labs, rgb, audio):
""" Function to pad the timesteps of visual or audio features so that they are equal    
"""
    rgb_timesteps = rgb.shape[1] #Get the number of timesteps for rgb
    audio_timesteps = audio.shape[1] #Get the number of timesteps for audio

    if rgb_timesteps < audio_timesteps:
        difference = audio_timesteps - rgb_timesteps
        #How much you want to pad dimension 1, 2 and 3
        #Each padding tuple is the amount to pad before and after the data in that dimension
        np_padding = ((0, 0), (0,difference), (0,0))
        #This tuple contains the values that are to be used to pad the data
        padding_values = ((0,0), (0,0), (0,0))
        rgb = np.pad(rgb, np_padding, mode='constant', constant_values=padding_values)

    elif rgb_timesteps > audio_timesteps:
        difference = rgb_timesteps - audio_timesteps
        np_padding = ((0,0), (0,difference), (0,0))
        padding_values = ((0,0), (0,0), (0,0))
        audio = np.pad(audio, np_padding, mode='constant', constant_values=padding_values)

    return video, labs, rgb, audio

dataset = dataset.map(lambda video, label, rgb, audio: tuple(tf.py_func(pad_timesteps, [video, label, rgb, audio], [tf.string, tf.int64, tf.float32, tf.float32])))
相关问题