Python: 'GridSearchCV'对象没有属性'coef_'

3

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

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_和其他函数,看能否以另一种方式找到系数。但没有成功。你知道我该如何解决吗?

2个回答

4
您需要选择一个具体的估算器来访问coef_属性。尝试使用以下方法:
model.best_estimator_.coef_
GridSearchCV对象本身没有系数,因为它不是评估器,它是一个循环遍历参数并训练各种评估器的对象。

谢谢您的回复。我尝试了一下,但是我仍然遇到了相似的错误:“GridSearchCV”对象没有“best_estimator_”属性。 - eli
如果您按照我所写的操作进行,就不可能会收到相同的错误信息。 - Nicolas Gervais
好的,我在Jupyter笔记本中尝试在一个新单元格中运行它,以为它会起作用。但是将它放在fit之后,现在它可以工作了。谢谢! - eli
你是否在测试代码时 1) 不小心设置了 refit=False 或者 2) 没有运行 .fit 方法? - M Z

1
我认为您正在寻找由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_属性是在网格搜索期间找到的具有最高精度的估算器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接