加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-3.x – keras LSTM模型中的尺寸不匹配

发布时间:2020-12-20 13:14:33 所属栏目:Python 来源:网络整理
导读:我想使用带有keras的LSTM神经网络来预测时间序列组,我在使模型匹配我想要的东西时遇到麻烦.我的数据的维度是: 输入张量:(数据长度,训练系列数,回顾时间步长) 输出张量:(数据长度,要预测的序列数,向前看的时间步长) Note: I want to keep the dimensions exa
我想使用带有keras的LSTM神经网络来预测时间序列组,我在使模型匹配我想要的东西时遇到麻烦.我的数据的维度是:

输入张量:(数据长度,训练系列数,回顾时间步长)

输出张量:(数据长度,要预测的序列数,向前看的时间步长)

Note: I want to keep the dimensions exactly like that,no
transposition.

重现问题的虚拟数据代码是:

import numpy as np
from keras.models import Sequential
from keras.layers import Dense,TimeDistributed,LSTM

epoch_number = 100
batch_size = 20
input_dim = 4
output_dim = 3
look_back = 24
look_ahead = 24
n = 100

trainX = np.random.rand(n,input_dim,look_back)
trainY = np.random.rand(n,output_dim,look_ahead)
print('test X:',trainX.shape)
print('test Y:',trainY.shape)

model = Sequential()

# Add the first LSTM layer (The intermediate layers need to pass the sequences to the next layer)
model.add(LSTM(10,batch_input_shape=(None,look_back),return_sequences=True))

# add the first LSTM layer (the dimensions are only needed in the first layer)
model.add(LSTM(10,return_sequences=True))

# the TimeDistributed object allows a 3D output
model.add(TimeDistributed(Dense(look_ahead)))

model.compile(loss='mean_squared_error',optimizer='adam',metrics=['accuracy'])
model.fit(trainX,trainY,nb_epoch=epoch_number,batch_size=batch_size,verbose=1)

这个流程:

Exception: Error when checking model target: expected
timedistributed_1 to have shape (None,4,24) but got array with shape
(100,3,24)

问题似乎是在定义TimeDistributed层时.

如何定义TimeDistributed层以便编译和训练?

解决方法

在您的情况下,错误消息有点误导.您的网络输出节点称为timedistributed_1,因为它是顺序模型中的最后一个节点.错误消息试图告诉您的是,此节点的输出与您的模型适合的目标不匹配,即您的标签trainY.

您的trainY的形状为(n,look_ahead),因此(100,24)但网络正在生成(batch_size,look_ahead)的输出形状.这种情况下的问题是output_dim!= input_dim.如果时间维度发生变化,则可能需要填充或删除所述时间步长的网络节点.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读