我想将两个不同维数的张量传递给一个< code>tf.nn.dynamic_rnn。我有困难,因为尺寸不匹配。我愿意听取最好的建议。这些张量是来自< code>tf.data.Dataset的批次
我有两个形状张量:
张量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])))