随机搜索CV与Keras LSTM(回归)

2024-04-23 20:37:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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: Input 0 is incompatible with layer lstm_93: expected ndim=3, found ndim=2

知道我做错了什么吗?你知道吗


Tags: addmodelreturnmylayerscreatetrainhidden