Keras有状态LSTM错误

sha*_*pta 3 lstm keras

我想在keras中创建有状态的LSTM.我给它一个这样的命令:

model.add(LSTM(300,input_dim=4,activation='tanh',stateful=True,batch_input_shape=(19,13,4),return_sequences=True))
Run Code Online (Sandbox Code Playgroud)

批量大小= 19.但是在运行时会出错

 Exception: In a stateful network, you should only pass inputs with a number of samples that can be divided by the batch size. Found: 8816 samples. Batch size: 32.
Run Code Online (Sandbox Code Playgroud)

我没有在我的脚本中的任何地方指定批量大小32,而19可以被8816整除

nem*_*emo 11

model.fit()进行批处理(与model.train_on_batch例如相反).因此它有一个batch_size默认为32 的参数.

将其更改为您的输入批量大小,它应该按预期工作.

例:

batch_size = 19

model = Sequential()
model.add(LSTM(300,input_dim=4,activation='tanh',stateful=True,batch_input_shape=(19,13,4),return_sequences=True))

model.fit(x, y, batch_size=batch_size)
Run Code Online (Sandbox Code Playgroud)


小智 5

有两种情况可能会发生 batch_size 错误。

  1. 模型.fit(train_x,train_y,batch_size= n_batch,shuffle=True,verbose=2)

  2. trainPredict = model.predict(train_x, batch_size=n_batch ) 或 testPredict = model.predict(test_x, batch_size=n_batch )

在这两种情况下,你都必须提到不。批次。

注意:我们需要同时预测训练和测试,因此最佳实践是以这样一种方式划分测试和训练,即在stateful=True 的情况下,您的批量大小是两者的倍数