首页 > 解决方案 > 带有 Keras LSTM 的 RandomizedSearchCV(回归)

问题描述

我正在尝试使用 RandomizedSearchCV 调整 LSTM 的超参数。我的代码:

train_X, train_y = train[:, :-1], train[:, -1]
train_X = train_X.reshape((train_X.shape[0], timesteps, features))


def create_model(neurons =50, hidden_layers=1):
    model = Sequential()
    model.add(LSTM(neurons, 
                   return_sequences = True, 
                   input_shape=(train_X.shape[1], train_X.shape[2])))
    model.add(Dropout(0.2))
    for i in range(hidden_layers):
        model.add(LSTM(neurons))
        model.add(Dropout(0.2))

    model.add(Dense(1))
    model.compile(loss='mean_squared_error', optimizer='adam', metrics=['acc'])
    return model

my_regressor = KerasRegressor(build_fn=create_model, verbose=0)

# Create hyperparameter space
epochs = [100, 150]
batches = [5, 10]
hidden_layers = [1, 2]
neurons = [50, 100]

hyperparameters = dict(neurons=neurons,
                       epochs=epochs, 
                       batch_size=batches, 
                       hidden_layers = hidden_layers)

grid = RandomizedSearchCV(estimator=my_regressor, 
                          param_distributions=hyperparameters)


# Fit grid search


grid_result = grid.fit(train_X, train_y)

这会引发错误:

ValueError:输入 0 与层 lstm_93 不兼容:预期 ndim=3,发现 ndim=2

知道我在这里做错了什么吗?

标签: pythonkeras

解决方案


推荐阅读