首页 > 解决方案 > ML 算法和 RNN 的集合

问题描述

我正在尝试加入 ML 算法和 LSTM (RNN) 的集合。但是,我无法将它们全部连接在一起,因为 LSTM 具有 3 维 [n_samples, timesteps, n_features] 而 ML 算法具有 2 维数组,并且当我尝试训练估计器时,它给了我以下错误:

expected ndim=2, found ndim=3

这是我到目前为止的代码。

#Initially, the LSTM model was created and reshaped into 3-dimensional arrays

#split into train and test sets
n_train_days = 176920
train = dataset[:n_train_days, :]
test = dataset[n_train_days:, :]

train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]

# reshape input to be 3D [samples, timesteps, features]
train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))
test_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

model = Sequential()
model.add(LSTM(10, activation='relu', input_shape=(train_X.shape[1], train_X.shape[2])))
#model.add(LSTM(10, input_shape=(1, look_back)))

model.add(Dense(1, activation='linear'))
opt = Adam(learning_rate=0.01)
model.compile(loss='mse', optimizer=opt)

es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=50)
#history =model.fit(train_X, train_y, epochs=30, batch_size=72, validation_data=(test_X, test_y), verbose=2, callbacks=[es])
model.fit(train_X, train_y, epochs=30, batch_size=72, validation_data=(test_X, test_y), verbose=2, callbacks=[es])

#Then, I applied the ensemble:

#I tried to reshape into 2-dimensional arrays:

#reshape into 2d dimensional
train_X, train_y = train[:, :-1], train[:, -1]
test_X, test_y = test[:, :-1], test[:, -1]
print(train_X.shape, train_y.shape, test_X.shape, test_y.shape)

estimators = {'rf': DecisionTreesRegressor(),
'knn': KNeighborsRegressor(),
'svr': SVR(kernel='rbf'),
'rnn': model}

for name, estimator in estimators.items():
estimator = estimator.fit(train_X, train_y)

编辑:我尝试使用这种技术

train_X = train_X.reshape((nsamples,nx*ny))
train_X.shape

但我收到一个错误,它在第一个错误和第二个错误之间交换。 Input 0 of layer sequential is incompatible with the layer: expected ndim=3, found ndim=2. Full shape received: (None, 10)

标签: pythonmachine-learningkeraslstm

解决方案


推荐阅读