首页 > 解决方案 > 如何在 Keras 中将 (None, 10) 维张量重塑为 (None, None, 10)?

问题描述

我正在尝试将可变大小的序列输入 LSTM。因此,我使用了一个生成器和 1 的批量大小。
我有一个(sequence_length,)嵌入的 -input-tensor,并输出一个(batch_size, sequence_length, embeding_dimension)-tensor。
同时,我拥有的其他输入数据的大小为(sequence_length, features)ie (None, 10),我想将其重塑为(batch_size, sequence_length, features)ie (None, None, 10)

我尝试使用带有 target_shape 的 Keras Reshape-Layer,(-1, 10)它应该相当于展开(None, 10)to (None, None, 10),但我收到的是一个(None, 1, 10)张量,这使得无法连接这个和嵌入的数据以便将它提供给 LSTM。
我的代码:

cluster = Input(shape=(None,))
embeded = Embedding(115, 25, input_length = None)(cluster)

features = Input(shape=(10,)) #variable
reshape = Reshape(target_shape=(-1, 10))(features)

merged = Concatenate(axis=-1)([embeded, reshape])

[...]

model.fit_generator(generator(), steps_per_epoch=1, epochs=5)

输出:

[...]
ValueError: A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, None, 25), (None, 1, 10)]

如何在 Keras 中将(None, 10)a 重塑为张量?(None, None, 10)

标签: pythonmachine-learningkerasneural-networkrecurrent-neural-network

解决方案


这样做 Keras 不会比在 NumPy 中进行重塑有任何好处。你可以:

# perform reshaping prior to passing to Keras
features = Input(shape=(None, 10))

并在传递到 Keras 之前执行重塑,您的输入中有实际batch_size可用sequence_length的。


推荐阅读