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

我想将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]

最佳答案 这是我设法找到的解决方案,可能并不理想,但解决问题,除非有人有更好的解决方案.此外,如果我的推理不正确,我是TensorFlow的新手并且可以进行编辑.

由于张量存储在tf.data.Dataset中,并且任何提议的Dataset.map函数(用于执行逐元素操作)在符号张量上运行(在这种情况下没有确切的形状).出于这个原因,我无法使用tf.pad创建一个Dataset.map函数,但我对这些解决方案持开放态度.

此解决方案使用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])))
点赞