使用Keras LSTM拟合和预测数据时,如何使用不同大小的训练数据和测试数据以及不同的batch_size?

时间:2019-01-06 23:09:22

标签: python tensorflow keras neural-network lstm

我的源代码如下所示。仅当batch_sizes具有相同的大小(在这种情况下为300且具有相同的形状(在此情况下为(300, 50, 74))下才有效。有谁知道如何在使用Keras LSTM拟合和预测数据时使用不同大小的训练数据和测试数据以及不同的batch_size?

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

2 个答案:

答案 0 :(得分:0)

根据文档判断LSTM单元格的输入形状:

  

具有形状(batch_size,时间步长,input_dim)的3D张量。

这意味着您将需要每个批次的大小不变的时间步长,因此不可能有不同的批次大小来进行培训和测试。

但是,您可以更改输入序列的长度,例如通过使用pad_sequences(有关更多详细信息,请参见https://keras.io/preprocessing/sequence/#pad_sequence

示例:

from keras.preprocessing.sequence import pad_sequences
# define sequences
sequences = [
    [1, 2, 3, 4],
       [1, 2, 3],
             [1]
    ]
# pad sequence
padded = pad_sequences(sequences, maxlen=5)
print(padded)
[[0 1 2 3 4]
[0 0 1 2 3]
[0 0 0 0 1]]

评论后编辑:

您需要调整测试数据的尺寸。例如,请参见有关顺序模型(https://keras.io/getting-started/sequential-model-guide/)的文档。这里的x_train和y_train定义如下:

data_dim = 16
timesteps = 8
num_classes = 10
batch_size = 32

# Generate dummy training data
x_train = np.random.random((batch_size * 10, timesteps, data_dim))
y_train = np.random.random((batch_size * 10, num_classes))

请注意形状是

x_train.shape
>> (320, 8, 16)
y_train.shape
>> (320, 10)

您的形状应显示为:

input_one_hot_encoded.shape
>> (300, timesteps, data_dim)
output_one_hot_encoded.shape
>>(300, num_classes)

分别

答案 1 :(得分:0)

在训练和测试运行时不能使用不同批次大小的原因是模型具有状态LSTM,即状态参数的值设置为True

现在,有两种方法可以解决此问题:

  1. 在训练时使用有状态LSTM。在训练过程的最后,将模型的权重本地保存到文件中,并定义一个与现有模型相同的新模型架构,只是区别在于lstms不是有状态的:

    model.save_weights("your_weights.h5")
    

    例如lstm层

    model.add(LSTM(len(dict), return_sequences=True, stateful=False, batch_input_shape=shape))
    
  2. 只需使您的lstm层变为无状态,即如上所述将有状态参数的值设置为False。

有关更多详细说明,请参考此链接https://machinelearningmastery.com/use-different-batch-sizes-training-predicting-python-keras/

相关问题