我应该如何使用 Keras 和 Tensorflow 2.4.1 编写 LSTM 层?

how should I code LSTM layer with Keras and Tensorflow 2.4.1?

我正在学习深度学习Python François Chollet 的书第 10.2.5 章 我使用 tensorflow 2.4.1.

这是 LSTM 天气预报的代码:

inputs = keras.Input(shape=(sequence_length, raw_data.shape[-1]))
x = layers.LSTM(16)(inputs)
outputs = layers.Dense(1)(x)
model = keras.Model(inputs, outputs)

callbacks = [
    keras.callbacks.ModelCheckpoint("jena_lstm.keras",
                                    save_best_only=True)
]
model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"])
history = model.fit(train_dataset,
                    epochs=10,
                    validation_data=val_dataset,
                    callbacks=callbacks)

model = keras.models.load_model("jena_lstm.keras")
print(f"Test MAE: {model.evaluate(test_dataset)[1]:.2f}")

当我尝试将输入传递给 LSTM 层时,我遇到以下错误:

--> 852 raise NotImplementedError( 853 "Cannot convert a symbolic Tensor ({}) to a numpy array." 854 " This error may indicate that you're trying to pass a Tensor to"

NotImplementedError: Cannot convert a symbolic Tensor (lstm_6/strided_slice:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported

我对 Dense 层或 conv2D 层没有问题我无法将输入传递给 LSTM 层。 知道为什么吗?

输入是来自 keras 的 jena_climate_2009_2016.csv.zip 数据集。像这样构建:

train_dataset = tf.keras.preprocessing.timeseries_dataset_from_array(
    raw_data[:-delay],
    targets=temperature[delay:],
    sampling_rate=sampling_rate,
    sequence_length=sequence_length,
    shuffle=True,
    batch_size=batch_size,
    start_index=0,
    end_index=num_train_samples)

我通过将 numpy 从 1.21 降级到 1.19 来解决问题