我有形状为 (size,2) 的特征和形状为 (size,1) 的标签,即对于特征中的 [x,y] ,标签将为 z。我想在 keras 中构建一个可以完成此类工作的 LSTM,因为该功能以某种方式与之前的输入(即 1 个或多个)相关联(我相信它是一个超参数)。
示例数据集值为:-
features labels
[1,2] [5]
[3,4] [84]
这是我到目前为止所做的:-
print(labels.shape) #prints (1414,2)
print(features.shape) #prints(1414,1)
look_back=2
# reshape input to be [samples, time steps, features]
features = np.reshape(features, (features.shape[0], 1, features.shape[1]))
labels = np.reshape(labels, (labels.shape[0], 1, 1))
X_train, X_test, y_train, y_test = train_test_split(features,labels,test_size=0.2)
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back))) #executing correctly
model.add(Dense(1)) #error here is "ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (1131, 1, 1)"
model.summary()
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=2)
那么有人可以帮我构建一个最小的 LSTM 示例来运行我的代码吗?谢谢。我不知道密集层如何具有二维,我的意思是它是一个整数,告诉密集层中要使用多少个单位。
最佳答案
您不得 reshape 标签。
试试这个:
features = np.reshape(features, (features.shape[0], 1, features.shape[1]))
model = Sequential()
model.add(LSTM(4, input_shape=(1, features.shape[1])))
model.add(Dense(1))
model.summary()
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=2)
关于python - LSTM 输出 Dense 需要 2d 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51827349/