【发布时间】:2020-08-20 02:32:17
【问题描述】:
我正在使用 Python、Keras 和 Tensorflow 构建基于 LSTM 的深度 Q 学习网络,但遇到了以下问题。在我用给定的 batch_input_shape 创建网络并尝试使网络适应该形状的数据后,我收到以下错误:
警告:tensorflow:模型是用形状 (64, 1, 10) 构造的 输入张量("lstm_34_input:0", shape=(64, 1, 10), dtype=float32), 但是 它是在形状不兼容的输入上调用的 (32, 1, 10)。
我创建了以下玩具示例来简单地演示导致问题的代码。
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.python.keras.layers import Flatten
from tensorflow.keras.layers import Dense, Dropout, LSTM
from tensorflow.keras.optimizers import Adam
# Hyperparameters
action_space = range(0, 10)
input_length = 10
batch_size = 64
timesteps = 1
learning_rate = 0.0001
# Create random input variables
state = np.random.randint(0, 100, size=(batch_size, timesteps, input_length))
target = np.random.randint(0, 100, size=(batch_size, len(action_space)))
# Build the model
model = Sequential()
model.add(LSTM(10, batch_input_shape=(batch_size, timesteps, input_length), return_sequences=True, activation="tanh",
recurrent_dropout=0, stateful=False))
model.add(LSTM(10, activation="tanh", return_sequences=True, recurrent_dropout=0, stateful=False))
model.add(Flatten())
model.add(Dense(len(action_space), activation="relu"))
model.compile(loss="mean_squared_error", optimizer=Adam(lr=learning_rate))
# Fit the model
model.fit(state, target, epochs=1, verbose=1)
这会产生上面看到的错误。
我的理解是输入层应该期望接收到一批形状 (64, 1, 10),然后我们将这个形状传递给它。但是,输入层似乎接收到 (32, 1, 10) 的形状。我们可以验证 state.shape 是否为 (64, 1, 10) 符合预期,因此在某个阶段会对该输入进行重新整形,或者错误可能与隐藏层或输出层的输入有关?
任何帮助将不胜感激。
更新 我正在使用 Tensorflow GPU 2.3.0 版 和 Keras 版本 2.3.1
【问题讨论】:
-
我无法使用
'tf 2.1'重现此行为 -
感谢 Nicolas,我已经更新了问题以包括我使用 tf 2.3.0 和 Keras 2.3.1 的事实。我会尝试升级/降级我的版本,看看这是否能说明问题。
-
将 batch_size=batch_size 添加到 model.fit 以便于修复,但实际上您不应该对网络中的批量大小进行硬编码。对于输入形状,您可以只使用 input_shape=(time_steps, input_length) (或者如果您想使用 batch_input_shape (None, time_steps, input_length) 甚至 (None, None, input_length))
-
谢谢,西蒙。我以前一直在使用后者,但是我正在研究使用我认为需要 batch_size 的状态性。我会尽快尝试以前的解决方案,看看它是否能解决问题 - 感谢您查看
标签: python tensorflow keras deep-learning