网格搜索交叉验证用于多项式回归

3
我是机器学习的新手,遇到了困难。
当我尝试在线性模型中实现多项式回归时,使用了多个次数为1到10的多项式,并得到不同的均方误差。我实际上使用了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')

但它甚至没有生成任何结果。
2个回答

1

poly_grid = GridSearchCV...

这只是声明和实例化网格搜索对象,你需要使用fit()方法提供一些数据来进行任何训练或超参数搜索。

就像这样:

poly_grid.fit(X, y)

其中 X 和 y 是您的训练数据和标签。

请参阅文档

fit(X, y=None, groups=None, **fit_params)[source]

Run fit with all sets of parameters.
然后使用 cv_results_ 和/或 best_params_ 来分析结果。
请查看以下示例:

回应评论:

@BillyChow 你是否调用了 poly_grid.fit()?如果没有,那么显然不会产生任何结果。

如果是的话,那么根据你的数据,由于在参数中指定了1到10的阶数和10倍交叉验证,所以需要很长时间。因此,随着阶数的增加,拟合和交叉验证的时间会非常快地增加。

如果你仍然想看到工作情况,可以将 verbose 参数添加到 gridSearchCV 中,像这样:

poly_grid = GridSearchCV(PolynomialRegression(), param_grid, 
                         cv=10, 
                         scoring='neg_mean_squared_error', 
                         verbose=3) 

然后调用 poly_grid.fit(X, y)



1
是的,我之前已经完成了这些步骤。但我的问题是如何在gridsearchCV中构建多项式分类器,或者如何通过交叉验证集找到最佳的多项式次数。 - Billy Chow
@BillyChow 请澄清一下你的意思,是指“没有生成任何结果”吗? - Vivek Kumar
参数网格为:{'polynomialfeatures__degree': [2,3,4,5], 'linearregression__fit_intercept': [True, False], 'linearregression__normalize': [True, False]}然后,进行多项式回归的网格搜索交叉验证,使用参数网格和10折交叉验证,评分标准为负均方误差。 - Billy Chow
@BillyChow 你为什么点赞并批准了这个回答?它与你的问题无关。 - AturSams

1

将pandas导入为numpy:

import numpy as np
import pandas as pd

创建一个样本数据集:
df = pd.DataFrame(data={'X': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
                        'Y': [1, 4, 9, 16, 25, 36, 49, 64, 81, 100], 
                        'Label': [1, 3, 10, 17, 23, 45, 50, 55, 90, 114]})
X_train = df[['X', 'Y']]
y_train = df['Label']

在多项式回归中,您会更改数据集特征的次数,也就是说,您实际上并没有更改超参数。因此,我认为使用for循环模拟GridSearchCV比使用GridSearchCV更好。在下面的代码中,列表degrees是将被测试的次数。
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import cross_val_score 
degrees = [2, 3, 4, 5, 6] # Change degree "hyperparameter" here
normalizes = [True, False] # Change normalize hyperparameter here
best_score = 0
best_degree = 0
for degree in degrees:
    for normalize in normalizes:
        poly_features = PolynomialFeatures(degree = degree)
        X_train_poly = poly_features.fit_transform(X_train)
        polynomial_regressor = LinearRegression(normalize=normalize)
        polynomial_regressor.fit(X_train_poly, y_train)
        scores = cross_val_score(polynomial_regressor, X_train_poly, y_train, cv=5) # Change k-fold cv value here
        if max(scores) > best_score:
            best_score = max(scores)
            best_degree = degree
            best_normalize = normalize

打印最佳分数:
print(best_score)

0.9031682820376132

打印出最佳超参数:
print(best_normalize)
print(best_degree)

False
2

使用最佳超参数创建最佳的多项式回归:
poly_features = PolynomialFeatures(degree = best_degree)
X_train_poly = poly_features.fit_transform(X_train)
best_polynomial_regressor = LinearRegression(normalize=best_normalize)
polynomial_regressor.fit(X_train_poly, y_train)

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