根据文档,LSTM 层应处理具有(None、CONST、CONST)形状的输入。对于可变时间步长,它应该能够处理具有(无、无、常量)形状的输入。
假设我的数据如下:
X = [
[
[1, 2, 3],
[4, 5, 6]
],
[
[7, 8, 9]
]
]
Y = [0, 1]
还有我的模型:
model = tf.keras.models.Sequential([
tf.keras.layers.LSTM(32, activation='tanh',input_shape=(None, 3)),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.fit(X, Y)
我的问题是:我应该如何格式化这些输入才能使此代码正常工作?
我不能像以前那样在这里使用 pandas 数据框。如果我运行上面的代码,我会收到此错误:
Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), but instead got the following list of 2 arrays:
如果我用以下内容更改最后一行:
model.fit(np.array(X), np.array(Y))
现在的错误是:
Error when checking input: expected lstm_8_input to have 3 dimensions, but got array with shape (2, 1)
最佳答案
你已经很接近了,但是在 Keras/Tensorflow 中你需要填充你的序列,然后使用 Masking让 LSTM 跳过那些填充的。 为什么?因为张量中的条目需要具有相同的形状(batch_size、max_length、features)
。因此,如果长度可变,序列将被填充。
您可以使用keras.preprocessing.sequence.pad_sequences填充序列以获得类似以下内容:
X = [
[
[1, 2, 3],
[4, 5, 6]
],
[
[7, 8, 9],
[0, 0, 0],
]
]
X.shape == (2, 2, 3)
Y = [0, 1]
Y.shape == (2, 1)
然后使用 mask 层:
model = tf.keras.models.Sequential([
tf.keras.layers.Masking(), # this tells LSTM to skip certain timesteps
tf.keras.layers.LSTM(32, activation='tanh',input_shape=(None, 3)),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(X, Y)
您还需要 binary_crossentropy
,因为您有一个带有 sigmoid
输出的二元分类问题。
关于python - 使用 Tensorflow 格式化具有可变时间步长的 LSTM 层的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54727823/