gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:43:20 24 4
gpt4 key购买 nike

我想使用带有 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, input_dim, 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, output_dim, Look_ahead),因此 (100, 3, 24) 但网络是生成(batch_size,input_dim,look_ahead)的输出形状。本例中的问题是 output_dim != input_dim。如果您的时间维度发生变化,您可能需要填充或删除所述时间步长的网络节点。

关于python-3.x - keras LSTM 模型中的尺寸不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40088381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com