你真的和你有不同的输出数量(10!=1)

2024-04-24 12:37:31 发布

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

我正在使用Scikit learn wrapper KerasClassifier为我的LSTM模型使用随机搜索CV进行超参数调整。以下是我所做工作的总结: 1xtrain的形状是[355,5,10],ytrain的形状是[355,10],有355个训练样本和10个特征和标签。 2首先,我使用build_lsm_model函数创建模型 三。定义KerasClassifier 4指定要用于拟合以确定划线的参数 5使用RandomizedSearchCV指定要搜索的参数 5拟合模型

我用“负均方误差”作为评分标准。当我运行代码时,我得到了一个错误“y\u true和y\u pred有不同数量的输出(10!=1)

我发现,如果我不指定任何评分标准,那么它工作得很好。但是,我想用负均方误差,因为这是一个回归问题。在

# keras model
def build_lstm_model(n_blocks=6, n_cells=40, lr=0.001, lookback=lookback, n=n):
    model = Sequential()

    for i in range(n_blocks-1):
        model.add(LSTM(n_cells, input_shape=(lookback, n), return_sequences=True, activation='tanh', kernel_initializer='uniform'))

    model.add(LSTM(n_cells, input_shape=(lookback, n), activation='tanh', kernel_initializer='uniform'))
    model.add(Dense(n))

    adam = optimizers.Adam(lr=lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
    model.compile(loss='mean_squared_error', optimizer=adam, metrics=['accuracy'])

    return model

# pass in fixed parameters n_input and n_class
model_lstm = KerasClassifier(
    build_fn = build_lstm_model,
    lookback = lookback, n = n)

# specify other extra parameters pass to the .fit
# number of epochs is set to a large number
keras_fit_params = {   
    'epochs': 10,
    'batch_size': 16,
    'validation_data': (xvalid, yvalid),
    'verbose': 0
}

# random search parameters 
# specify the options and store them inside the dictionary
# batch size and training method can also be hyperparameters, but it is fixed
n_blocks_params = [3, 4, 5, 6, 7, 8]
n_cells_params = [20, 30, 40, 50, 60]
lr_params = [0.001, 0.0001]

keras_param_options = {
    'n_blocks': n_blocks_params,
    'n_cells': n_cells_params,  
    'lr': lr_params
}

# `verbose` 2 will print the class info for every cross-validation, kind of too much
rs_lstm = GridSearchCV( 
    model_lstm, 
    param_distributions = keras_param_options,
    #fit_params = keras_fit_params,
    scoring = 'neg_mean_squared_error',
    n_iter = 3, 
    cv = 5,
    n_jobs = -1
    #verbose = 0
)

rs_lstm.fit(xtrain, ytrain)

有没有办法可以用均方误差作为随机搜索的指标?在


Tags: the模型build参数modelparamsfitkeras
1条回答
网友
1楼 · 发布于 2024-04-24 12:37:31

我用的是KerasClassifier。我不知道SKlearn中还有另一个包装器KerasRegressor。当我使用KerasRegressor时,我可以使用回归相关的度量来找到一个好的模型。谢谢您。在

相关问题 更多 >