Python:“GridSearchCV”对象没有属性“coef\ux”

2024-09-22 16:31:29 发布

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

我试图返回我的逻辑回归模型的系数。以下是我创建模型的方式:

logreg = LogisticRegression(solver = 'liblinear')

model = GridSearchCV(logreg, cv = 3, param_grid = {
    'penalty': ('l1', 'l2'),
    'C': [0.5, 0.6, 0.7, 0.8, 0.9],
    'max_iter': [100]
})

model.fit(X_train, y_train)
model.coef_ # here is where I get the error
# Validation (test)
y_pred = model.predict(X_test)

但我得到了以下错误:

AttributeError: 'GridSearchCV' object has no attribute 'coef_'

我甚至尝试了.best_score_和其他函数,看看是否可以用另一种方法找到系数。但是没有运气。你知道我怎样才能解决这个问题吗


Tags: 模型testmodelparam方式train逻辑cv
2条回答

我认为您正在寻找GridSearchCV提供的最佳模型:

...
model.fit(X_train, y_train)
best_model = model.best_estimator_
best_model.coef_ # This should be what you're looking for

y_pred = best_model.predict(X_test)

您的模型只是一个GridSearchCV对象,而coef_是一个logreg对象的属性。best_estimator_属性是在网格搜索期间发现的具有最高精度的估计器

您必须选择一个特定的估计器来访问coef_属性。尝试:

model.best_estimator_.coef_

{}对象本身没有系数,因为它不是一个估计器,它是一个循环参数并训练各种估计器的对象

相关问题 更多 >