python - LSTM 输出 Dense 需要 2d 输入

标签 python machine-learning neural-network keras recurrent-neural-network

我有形状为 (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/

相关文章:

python - 使用 Keras 递归神经网络进行预测 - 准确度始终为 1.0

machine-learning - 使用反向传播训练实值神经网络

python - 如果列表包含相同的元素,则在嵌套列表中组合列表?

python - 如何将html直接传递给模板

python - Python 中的运行平均值

machine-learning - 小批量 SGD 梯度计算 - 平均值或总和

r - 为什么使用 glmnet 模型时 R 中的 `predict` 返回高维预测?

R 中多类分类的 ROC 曲线

image-processing - 图像相似性 - 深度学习与手工制作的特征

python - ERR_TOO_MANY_REDIRECTS django 2.1 的问题