GridSearchCV scikitlearn:TypeError LogisticRegression…未实现“获取参数”方法

2024-04-25 21:31:50 发布

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

我想基于以下代码,使用sklearn的GridSearchCV(参见https://towardsdatascience.com/hyperparameter-tuning-c5619e7e6624)优化logistic回归估计器的超参数:

X_train, X_test, y_train, y_test,indices_train,indices_test = train_test_split(features_all2, df_all['labels'], df_all.index, test_size=0.25, random_state=1)

penalty = ['l1', 'l2']
C = [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000]
class_weight = ['balanced']
solver = ['liblinear', 'saga']

param_grid = dict(penalty=penalty,
                  C=C,
                  class_weight=class_weight,
                  solver=solver)

grid = GridSearchCV(estimator=LogisticRegression,
                    param_grid=param_grid,
                    scoring='roc_auc',
                    verbose=1,
                    n_jobs=-1)
grid_result = grid.fit(X_train, y_train)

print('Best Score: ', grid_result.best_score_)
print('Best Params: ', grid_result.best_params_)

它在grid_result = grid.fit(X_train, y_train)出现错误之前工作正常类型错误:无法克隆对象“”(类型):它似乎不是scikit学习估计器,因为它没有实现“get_params”方法。

虽然在做hasattr(LogisticRegression, 'get_params')的时候我得到了真的

我被困在这里了。任何人都可能知道如何处理这件事?非常感谢


Tags: testdfparamtrainparamsresultallclass
1条回答
网友
1楼 · 发布于 2024-04-25 21:31:50

您需要传递estimator= LogisticRegression(),而不是estimator= LogisticRegression

示例:

from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
grid={"C":np.logspace(-3,3,7), "penalty":["l1","l2"]}# l1 lasso l2 ridge
logreg=LogisticRegression()
logreg_cv=GridSearchCV(logreg,grid,cv=10)

相关问题 更多 >