InvalidArgumentError:从形状为 [56,9] 的张量中指定了形状为 [60,9] 的列表

Djb*_*blo 5 python lstm keras tensorflow recurrent-neural-network

在运行我的模型一个时期后,它崩溃并显示以下错误消息:

InvalidArgumentError:从形状为 [56,9] 的张量中指定了形状为 [60,9] 的列表 [[{{node TensorArrayUnstack/TensorListFromTensor}}]] [[sequential_7/lstm_17/PartitionedCall]] [Op:__inference_train_function_29986]

这发生在我将 LSTM 层更改为stateful=True并且必须传递batch_input_shape参数而不是input_shape

下面是我的代码,我确定它与我的数据形状有关:

test_split = 0.2
history_points = 60
n = int(histories.shape[0] * test_split)

histories_train = histories[:n]
y_train = next_values_normalized[:n]

histories_test = histories[n:]
y_test = next_values_normalized[n:]

next_values_test = next_values[n:]

print(histories_train.shape)
print(y_train.shape)

-->(1421, 60, 9)
-->(1421, 1)

# model architecture

´´´model = Sequential()
model.add(LSTM(units=128, stateful=True,return_sequences=True, batch_input_shape=(60,history_points, 9)))
model.add(LSTM(units=64,stateful=True,return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=32))
model.add(Dropout(0.2))
model.add(Dense(20))
ADAM=keras.optimizers.Adam(0.0005, beta_1=0.9, beta_2=0.999, amsgrad=False)
model.compile(loss='mean_squared_error', optimizer=ADAM)

model.fit(x=histories_train, y=y_train, batch_size=batchsize, epochs=50, shuffle=False, validation_split=0.2,verbose=1)
´´´
Run Code Online (Sandbox Code Playgroud)

Phi*_*l_G 7

对于有状态的 LSTM,应该以某种方式选择批大小,以便样本数可以被批大小整除。另见此处:

Keras:如果数据大小不能被batch_size整除怎么办?

在您的情况下,考虑到您从训练数据中提取 20% 作为验证集,您还有 1136 个样本。所以你应该选择一个可以被 1136 整除的批量大小。

此外,您可以例如删除一些样本或重新使用样本,以便能够选择各种批量大小。