gpt4 book ai didi

python - 为什么我会收到 Keras LSTM RNN input_shape 错误?

转载 作者:太空狗 更新时间:2023-10-29 17:33:24 25 4
gpt4 key购买 nike

我不断从以下代码中收到 input_shape 错误。

from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM

def _load_data(data):
"""
data should be pd.DataFrame()
"""
n_prev = 10
docX, docY = [], []
for i in range(len(data)-n_prev):
docX.append(data.iloc[i:i+n_prev].as_matrix())
docY.append(data.iloc[i+n_prev].as_matrix())
if not docX:
pass
else:
alsX = np.array(docX)
alsY = np.array(docY)
return alsX, alsY

X, y = _load_data(dframe)
poi = int(len(X) * .8)
X_train = X[:poi]
X_test = X[poi:]
y_train = y[:poi]
y_test = y[poi:]

input_dim = 3

以上所有运行顺利。这就是问题所在。

in_out_neurons = 2
hidden_neurons = 300
model = Sequential()
#model.add(Masking(mask_value=0, input_shape=(input_dim,)))
model.add(LSTM(in_out_neurons, hidden_neurons, return_sequences=False, input_shape=(len(full_data),)))
model.add(Dense(hidden_neurons, in_out_neurons))
model.add(Activation("linear"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
model.fit(X_train, y_train, nb_epoch=10, validation_split=0.05)

它返回这个错误。

Exception: Invalid input shape - Layer expects input ndim=3, was provided with input shape (None, 10320)

当我检查 the website 时它说要指定一个元组“(例如(100,)用于 100 维输入)。”

也就是说,我的数据集由一列组成,长度为 10320。我认为这意味着我应该将 (10320,) 作为 input_shape,但我得到了错误无论如何。有人有解决方案吗?

最佳答案

我的理解是你的输入和输出都是一维向量。诀窍是根据 Keras 要求 reshape 它们:

from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
import numpy as np

X= np.random.rand(1000)
y = 2*X

poi = int(len(X) * .8)
X_train = X[:poi]
y_train = y[:poi]

X_test = X[poi:]
y_test = y[poi:]

# you have to change your input shape (nb_samples, timesteps, input_dim)
X_train = X_train.reshape(len(X_train), 1, 1)
# and also the output shape (note that the output *shape* is 2 dimensional)
y_train = y_train.reshape(len(y_train), 1)


#in_out_neurons = 2
in_out_neurons = 1

hidden_neurons = 300
model = Sequential()
#model.add(Masking(mask_value=0, input_shape=(input_dim,)))
model.add(LSTM(hidden_neurons, return_sequences=False, batch_input_shape=X_train.shape))
# only specify the output dimension
model.add(Dense(in_out_neurons))
model.add(Activation("linear"))
model.compile(loss="mean_squared_error", optimizer="rmsprop")
model.fit(X_train, y_train, nb_epoch=10, validation_split=0.05)

# calculate test set MSE
preds = model.predict(X_test).reshape(len(y_test))
MSE = np.mean((preds-y_test)**2)

这里是关键点:

  • 添加第一层时,您需要指定隐藏节点的数量和输入形状。后续层不需要输入形状,因为它们可以从前一层的隐藏节点推断出形状
  • 同样,对于您的输出层,您指定输出节点的数量

希望这对您有所帮助。

关于python - 为什么我会收到 Keras LSTM RNN input_shape 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36069260/

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