简体   繁体   English

卡在输入/输出形状中,在Keras,LSTM中

[英]Stuck with input/output shapes in keras, lstm

I'm trying train a time series of energy demand using lstm. 我正在尝试使用lstm训练能源需求的时间序列。 I had used timestamp and got the results but for this experiment I'm trying to split date time in days, month, year, hours. 我使用了时间戳并获得了结果,但是对于本实验,我试图将日期时间划分为天,月,年,小时。 So after splitting data my csv file looks like this 所以分割数据后,我的csv文件看起来像这样

timestamp     | day | month | year | hour | demand
01-07-15 1:00 |  1  |   7   | 2015 |   1  | 431607

I'm using keras for LSTM(I'm very new to it). 我正在将keras用于LSTM(这是我的新手)。 I have following code written so far. 到目前为止,我已经编写了以下代码。

from pandas import read_csv
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error

dataframe = read_csv('patched_data_sorted.csv', engine='python')
dataset = dataframe.values
trainX = dataset[:, 1:5]
sampleSize = len(trainX)
trainX = trainX.reshape(1, len(trainX), 4)
trainY = dataset[:, 5]
trainY = trainY.reshape(1, len(trainY))
print(trainY)

# print(trainX)

model = Sequential()
model.add(LSTM(4, input_shape=(sampleSize, 4)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)
trainPredict = model.predict(trainX)
print(trainPredict)

But I'm getting this error 但是我收到这个错误

ValueError: Error when checking target: expected dense_1 to have shape (None, 1) but got array with shape (1, 20544)

I'm not sure why is this happening but I think I'm not reshaping correctly. 我不确定为什么会这样,但是我认为我的造型没有正确。

In your data you have a label for every timestep of the sequence. 在数据中,序列的每个时间步都有标签。 Your current network is set up to have only one label for the whole sequence. 您当前的网络设置为整个序列只有一个标签。

To get an output for every timestep you need to add return_sequences=True to your LSTM and wrap the Dense layer in a TimeDistributed layer so that it gets applied in every timestep. 要获得每个时间步的输出,您需要在LSTM中添加return_sequences=True并将Dense层包装在TimeDistributed层中,以便将其应用于每个时间步。

model = Sequential()
model.add(LSTM(4, input_shape=(sampleSize, 4), return_sequences=True))
model.add(TimeDistributed(Dense(1)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM