【问题标题】:LSTM output Dense expects 2d inputLSTM 输出 Dense 需要 2d 输入
【发布时间】:2019-01-20 11:31:28
【问题描述】:

我有 (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 示例来运行我的代码吗?谢谢你。我不知道密集层怎么会有二维我的意思是它是一个整数,告诉在密集层中使用多少个单位。

【问题讨论】:

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


    【解决方案1】:

    您不得重塑标签。

    试试这个:

    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)
    

    【讨论】:

    • 如果我的标签的形状为 (1414,100)。那我也不应该重塑吗?那么密集层将如何工作?
    猜你喜欢
    • 1970-01-01
    • 2019-03-11
    • 2018-07-06
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    相关资源
    最近更新 更多