我的源代码如下所示。仅当 batch_sizes 具有相同的大小(在本例中为 300)和相同的形状(在本例中为 (300, 50, 74))时才有效。有谁知道如何在使用 Keras LSTM 拟合和预测数据时使用不同大小的训练数据和测试数据以及不同的 batch_sizes?
shape = input_one_hot_encoded.shape
print('input_one_hot_encoded: ' + str(shape))
shape = output_one_hot_encoded.shape
print('output_one_hot_encoded: ' + str(shape))
shape = test_input_one_hot_encoded.shape
print('test_input_one_hot_encoded: ' + str(shape))
model = Sequential()
model.add(LSTM(len(dict), return_sequences=True, stateful=True,
batch_input_shape=shape))
model.add(LSTM(len(dict), return_sequences=True, stateful=True))
model.add(LSTM(len(dict), return_sequences=True, stateful=True))
model.add(Dense(len(dict), activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
print(model.summary())
model.fit(input_one_hot_encoded, output_one_hot_encoded, epochs=20, batch_size=300)
data = model.predict(test_input_one_hot_encoded, batch_size=300)
它返回:
input_one_hot_encoded: (300, 50, 74)
output_one_hot_encoded: (300, 50, 74)
test_input_one_hot_encoded: (300, 50, 74)
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
lstm_1 (LSTM) (300, 50, 74) 44104
_________________________________________________________________
lstm_2 (LSTM) (300, 50, 74) 44104
_________________________________________________________________
lstm_3 (LSTM) (300, 50, 74) 44104
_________________________________________________________________
dense_1 (Dense) (300, 50, 74) 5550
=================================================================
Total params: 137,862
Trainable params: 137,862
Non-trainable params: 0
请您参考如下方法:
在训练和测试运行时不能使用不同批量大小的原因是您的模型具有有状态 LSTM,即有状态参数的值设置为 True
现在,有两种方法可以解决这个问题:
在训练时使用有状态 LSTM。在训练过程结束时,将模型的权重本地保存到一个文件中,并定义一个与现有模型相同的新模型架构,唯一的区别是 lstms 不是有状态的:
model.save_weights("your_weights.h5")例如lstm层
model.add(LSTM(len(dict), return_sequences=True, stateful=False, batch_input_shape=shape))只需让您的 lstm 层成为无状态的,即将有状态参数的值设置为 False,如上所述。
更多详细说明请引用此链接https://machinelearningmastery.com/use-different-batch-sizes-training-predicting-python-keras/
