gpt4 book ai didi

python - Keras 序列 : Specify input shape with three parameters

转载 作者:行者123 更新时间:2023-12-01 08:55:53 26 4
gpt4 key购买 nike

我有一个具有以下设置的数据框:

import numpy as np

X = np.random.rand(100, 20, 3)

这里有 100 个时间片、20 个观察值和每个观察值 3 个属性。

我试图弄清楚如何将上面的数据传递给以下 Keras 序列:

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

# config
stateful = False
look_back = 3
lstm_cells = 1024
dropout_rate = 0.5
n_features = int(X.shape[1]*3)
input_shape = (look_back, n_features, 3)
output_shape = n_features

def loss(y_true, y_pred):
return keras.losses.mean_squared_error(y_true, y_pred)

model = Sequential()
model.add(LSTM(lstm_cells, stateful=stateful, return_sequences=True, input_shape=input_shape))
model.add(Dense(output_shape, activation='relu'))
model.compile(loss=loss, optimizer='sgd')

运行此抛出:

ValueError: Input 0 is incompatible with layer lstm_23: expected ndim=3, found ndim=4

有谁知道如何 reshape X 以将其传递到模型中?任何建议都会有帮助!

最佳答案

这似乎让事情开始发展:

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

# config
stateful = False
look_back = 3
lstm_cells = 1024
dropout_rate = 0.5
n_features = int(X.shape[1]) * 3
input_shape = (look_back, n_features)
output_shape = n_features

def loss(y_true, y_pred):
return keras.losses.mean_squared_error(y_true, y_pred)

model = Sequential()
model.add(LSTM(lstm_cells, stateful=stateful, return_sequences=True, input_shape=input_shape))
model.add(LSTM(lstm_cells, stateful=stateful, return_sequences=True))
model.add(LSTM(lstm_cells, stateful=stateful))
model.add(Dense(output_shape, activation='relu'))
model.compile(loss=loss, optimizer='sgd')

然后可以按如下方式对训练数据进行分区:

# build training data
train_x = []
train_y = []
n_time = int(X.shape[0])
n_obs = int(X.shape[1])
n_attrs = int(X.shape[2])

# note we flatten the last dimension
for i in range(look_back, n_time-1, 1):
train_x.append( X[i-look_back:i].reshape(look_back, n_obs * n_attrs ) )
train_y.append( X[i+1].ravel() )

train_x = np.array(train_x)
train_y = np.array(train_y)

然后就可以训练玩具模型了:

model.fit(train_x, train_y, epochs=10, batch_size=10)

关于python - Keras 序列 : Specify input shape with three parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52770595/

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