我是机器学习的新手并坚持这一点 .
当我试图在线性模型中实现多项式回归时,比如使用多个多项式范围(1,10)并得到不同的MSE . 我实际上使用 GridsearchCV
方法来找到多项式的最佳参数 .
from sklearn.model_selection import GridSearchCV
poly_grid = GridSearchCV(PolynomialRegression(), param_grid, cv=10, scoring='neg_mean_squared_error')
我不知道如何获得上述 PolynomialRegression()
估算器 . 我搜索的一个解决方案是:
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
def PolynomialRegression(degree=2, **kwargs):
return make_pipeline(PolynomialFeatures(degree), LinearRegression(**kwargs))
param_grid = {'polynomialfeatures__degree': np.arange(10), 'linearregression__fit_intercept': [True, False], 'linearregression__normalize': [True, False]}
poly_grid = GridSearchCV(PolynomialRegression(), param_grid, cv=10, scoring='neg_mean_squared_error')
但它甚至没有产生任何结果 .
1 回答
poly_grid = GridSearchCV...
只会声明并实例化网格搜索对象 . 您需要使用fit()方法提供一些数据来进行任何训练或超参数搜索 .
像这样的东西:
其中X和y是您的训练数据和标签 .
请参阅the documentation:
然后使用
cv_results_
和/或best_params_
来分析结果 .请看下面给出的例子:
http://scikit-learn.org/stable/auto_examples/exercises/plot_cv_diabetes.html
http://scikit-learn.org/stable/auto_examples/model_selection/plot_randomized_search.html
http://scikit-learn.org/stable/auto_examples/model_selection/plot_nested_cross_validation_iris.html
回应评论:
@BillyChow你是否打电话给
poly_grid.fit()
?如果不是,那么显然它不会产生任何结果 .如果是,那么根据你的数据,这需要花费很多时间,因为你已经指定1到10的度数,参数为10倍cv . 因此,随着学位的增加,拟合和交叉验证的时间会迅速增加 .
仍然如果你想看到工作,你可以添加
verbose
param到gridSearchCV,如下所示:然后拨打
poly_grid.fit(X, y)