python - 使用 Tensorflow 格式化具有可变时间步长的 LSTM 层的输入

标签 python tensorflow keras neural-network recurrent-neural-network

根据文档,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/

相关文章:

python - DRF - 嵌套路由器 - 在 POST/PUT/PATCH 上创建/更新嵌套对象

python - 查找所有包含字符串的列名并转换列的内容

python - 如何将 protobuf 图形转换为二进制线格式?

python - 如何在 map 方法中预处理和标记 TensorFlow CsvDataset?

python - 没有名为 'keras.legacy' 的模块

python - 从 Keras model.predict_generator 计算准确性

python - 描述一下你为 Python/Django 开发定制的 Vim 编辑器?

Python shift() 来自同一列,如 Excel 中的日期

python-3.x - 最小化 AdamOptimizer 时,运算输入和计算输入梯度之间的形状不兼容

python - Tensorflow:微调 Inception 模型