AttributeError' GridSearchCV'对象没有属性' cv_results _'
我正在通过Scikit-Learn教程的load_boston()
数据进行工作。我正在遇到此属性错误:
AttributeError 'GridSearchCV' object has no attribute 'cv_results_'
有人知道是否有错误?我正在使用1.1.1版本的Scikit-Learn。
import sklearn
from sklearn.datasets import load_boston
from sklearn.neighbors import KNeighborsRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LinearRegression
import matplotlib.pylab as plt
import pandas as pd
from sklearn.model_selection import cross_val_score
print(sklearn.__version__)
X, y = load_boston(return_X_y=True)
mod = KNeighborsRegressor().fit(X, y)
pipe = Pipeline([
("scale", StandardScaler()),
("model", KNeighborsRegressor(n_neighbors=3))
])
print(pipe.get_params())
mod1 = GridSearchCV(estimator=pipe, param_grid={'model__n_neighbors': [1,2,3,4,5,6,7,8,9,10]},cv = 3)
pipe.fit(X, y)
pred = pipe.predict(X)
df = pd.DataFrame(mod1.cv_results_)
plt.scatter(pred, y) #pred instead of X
plt.title("Boston Housing Market")
plt.show()
I'm working through the load_boston()
data for a scikit-learn tutorial. I'm running into this attribute error:
AttributeError 'GridSearchCV' object has no attribute 'cv_results_'
Does anyone know if there is a bug? I am using 1.1.1 version of scikit-learn.
import sklearn
from sklearn.datasets import load_boston
from sklearn.neighbors import KNeighborsRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LinearRegression
import matplotlib.pylab as plt
import pandas as pd
from sklearn.model_selection import cross_val_score
print(sklearn.__version__)
X, y = load_boston(return_X_y=True)
mod = KNeighborsRegressor().fit(X, y)
pipe = Pipeline([
("scale", StandardScaler()),
("model", KNeighborsRegressor(n_neighbors=3))
])
print(pipe.get_params())
mod1 = GridSearchCV(estimator=pipe, param_grid={'model__n_neighbors': [1,2,3,4,5,6,7,8,9,10]},cv = 3)
pipe.fit(X, y)
pred = pipe.predict(X)
df = pd.DataFrame(mod1.cv_results_)
plt.scatter(pred, y) #pred instead of X
plt.title("Boston Housing Market")
plt.show()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要点是
cv_results _
是 fittinggridSearchcv
实例的属性,而您仅安装了管道(其基本估算器)。因此,您应该适合mod1
使其正常工作。但是请注意,该方法
.fit()
gridSearchCV
不会返回拟合的基本估计器(当然,尽管拟合了)。因此,您将无法调用pipe.predict(x)
,如果您只替换pipe> pipe.fit(x,y)
viamod1.fit( x,y)
。Point is that
cv_results_
is an attribute of the fittedGridSearchCV
instance, while you've only fitted the pipeline (its base estimator). Therefore, you should fitmod1
to make it work.Be aware, though, that method
.fit()
ofGridSearchCV
does not return the fitted base estimator (despite fitting it, of course). Therefore, you won't be able to callpipe.predict(X)
if you just substitutepipe.fit(X, y)
viamod1.fit(X, y)
.