我在构建第一个使用LSTM的神经网络时,遇到了输入大小的错误。
我猜测错误出在输入参数的尺寸和维度上,但我无法理解这个错误。
print df.shapedata_dim = 13timesteps = 13num_classes = 1batch_size = 32model = Sequential()model.add(LSTM(32, return_sequences = True, stateful = True, batch_input_shape = (batch_size, timesteps, data_dim)))model.add(LSTM(32, return_sequences = True, stateful = True))model.add(LSTM(32, stateful = True))model.add(Dense(1, activation = 'relu'))#Compile.model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])model.summary()#Fit.history = model.fit(data[train], label[train], epochs = iteraciones, verbose = 0)#Eval.scores = model.evaluate(data[test], label[test], verbose = 0)#Save.cvshistory.append(history)cvscores.append(scores[1] * 100)
形状:
(303, 14)summary:_________________________________________________________________Layer (type) Output Shape Param # =================================================================lstm_19 (LSTM) (32, 13, 32) 5888 _________________________________________________________________lstm_20 (LSTM) (32, 13, 32) 8320 _________________________________________________________________lstm_21 (LSTM) (32, 32) 8320 _________________________________________________________________dense_171 (Dense) (32, 1) 33 =================================================================Total params: 22,561Trainable params: 22,561Non-trainable params: 0_________________________________________________________________
错误输出告诉我以下信息:
---> 45 history = model.fit(data[train], label[train], epochs = iteraciones, verbose = 0)ValueError: Error when checking input: expected lstm_19_input to have 3 dimensions, but got array with shape (226, 13)
回答:
LSTM需要形状为(batch_size, timestep, feature_size)
的输入。你传递的只是二维特征。由于timesteps=13
,你需要为你的输入增加一个维度。
如果数据是numpy数组,那么data = data[..., np.newaxis]
应该可以解决这个问题。
现在数据的形状将变为(batch_size, timesteps, feature)
,即(226, 13, 1)
。