Python ValueError:检查输入时出错:预期lstm_11_输入具有形状(1,1),但获得具有形状(13841)的数组
我尝试了各种方法来重塑LTSM神经网络的数据,但我仍然得到以下错误:Python ValueError:检查输入时出错:预期lstm_11_输入具有形状(1,1),但获得具有形状(13841)的数组,python,tensorflow,lstm,recurrent-neural-network,Python,Tensorflow,Lstm,Recurrent Neural Network,我尝试了各种方法来重塑LTSM神经网络的数据,但我仍然得到以下错误: ValueError: Error when checking input: expected lstm_29_input to have shape (1, 1) but got array with shape (1, 3841) 我的原始x_列车数据的形状如下: array([[-1.86994147, -2.28655553, -2.13504696, ..., 2.38827443, 1.295
ValueError: Error when checking input: expected lstm_29_input to have shape (1, 1) but got array with shape (1, 3841)
我的原始x_列车数据的形状如下:
array([[-1.86994147, -2.28655553, -2.13504696, ..., 2.38827443,
1.29554594, 46. ],
[-1.99436975, -2.41145158, -1.93463695, ..., 2.57659554,
1.27274537, 68. ],
[-2.19207883, -2.24740434, -1.73407733, ..., 2.66955543,
1.80862379, 50. ]
x_列车形状:(11253841)
x\u有效形状:(3753841)
y\u列车形状:(1125,)
因此,为了正确编译模型,我对我的x_序列和x_有效数据(用于预测)进行了重塑。我已经看了很多有类似错误的例子,他们对其进行了重塑,如下图所示,他们通常会让他们的模型工作,但在我的例子中,我不确定到底发生了什么
# reshape input to be [samples, time steps, features]
trainX = np.reshape(x_train, (x_train.shape[0], 1, x_train.shape[1]))
validX = np.reshape(x_valid, (x_valid.shape[0], 1, x_valid.shape[1]))
模型构造
呼叫与训练模式
使用以下行更改
trainX
的形状时
trainX=np.重塑(x_-train,(x_-train.shape[0],1,x_-train.shape[1]))
它变成
112513841
现在,当你写下下面一行
model.add(LSTM(单位=50,返回序列=True,输入形状=(1,trainX.shape[1]))
模型期望input\u shape
为(批量大小,1,1)
你应该写信的
model.add(LSTM(单位=50,返回序列=True,输入形状=(1,trainX.shape[2]))
现在,模型预计input\u shape
为(批量大小,13841)
,与新的tranX
相对应
另一方面,由于序列长度/回溯/滞后时间为
1
,输入特征为3841
,使用LSTM实际上没有意义,因为LSTM旨在提取时间特征,而这里没有时间/历史数据。在将输入重塑为(批次大小,3148,1)
之前,Conv1D
层可能更具相关性。这只是一个建议。感谢您的澄清。我对一个后续问题很好奇。我仍然是深入学习领域的新手,在尝试将特定神经网络用于特定回归案例时,我仍然试图理解。我在问题中加入的功能是否有效?我用我想用的CNN模型更新了这个问题。
def cnn_model():
""""
Creates the model of the CNN.
:param nr_measures: the number of output nodes needed
:return: the model of the CNN
"""
# Initializing the ANN
model = Sequential()
# Adding the input layer and the first hidden layer
model.add(Conv1D(64, 2, activation="relu", input_shape=(x_train.shape[1], 1)))
model.add(Flatten())
model.add(BatchNormalization())
# Adding the second hidden layer
model.add(Dense(128, activation="relu"))
model.add(BatchNormalization())
# Adding the output layer
model.add(Dense(1, activation = "softplus"))
model.compile(loss="mse", optimizer="adam", metrics = ['mse'])
return model
#Call Model
cnn_model= cnn_model(trainX)
#Train Model
history = cnn_model.fit(trainX, y_train, batch_size = 50, epochs = 150, verbose = 0 ,validation_data = (validX, y_valid))