### 使用管道进行岭回归的网格搜索

我正在尝试优化岭回归的超参数,同时还添加多项式特征。因此,管道看起来不错,但在尝试使用GridSearchCV时遇到错误。以下是代码:

# 导入库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import mean_squared_error
from collections import Counter
from IPython.core.display import display, HTML
sns.set_style('darkgrid')

# 数据预处理
from sklearn.datasets import load_boston
boston_dataset = load_boston()
dataset = pd.DataFrame(boston_dataset.data, columns = boston_dataset.feature_names)
dataset['MEDV'] = boston_dataset.target

# X和y变量
X = dataset.iloc[:, 0:13].values
y = dataset.iloc[:, 13].values.reshape(-1,1)

# 将数据集拆分为训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 25)

# 构建模型 ------------------------------------------------------------------------
# 对训练集进行拟合
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
steps = [
    ('scalar', StandardScaler()),
    ('poly', PolynomialFeatures(degree=2)),
    ('model', Ridge())
]
ridge_pipe = Pipeline(steps)
ridge_pipe.fit(X_train, y_train)

# 预测测试集结果
y_pred = ridge_pipe.predict(X_test)

# 应用k折交叉验证
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = ridge_pipe, X = X_train, y = y_train, cv = 10)
accuracies.mean()
#accuracies.std()

# 应用网格搜索查找最佳模型和最佳参数
from sklearn.model_selection import GridSearchCV
parameters = [ {'alpha': np.arange(0, 0.2, 0.01) } ]
grid_search = GridSearchCV(estimator = ridge_pipe,
                           param_grid = parameters,
                           scoring = 'accuracy',
                           cv = 10,
                           n_jobs = -1)
grid_search = grid_search.fit(X_train, y_train)  # <-- 在这里遇到错误

错误:

ValueError: Invalid parameter ridge for estimator

该如何做,或者是否有更好的方法使用管道进行岭回归?我是网格搜索的新手,如果能提供一些关于网格搜索的资源,我会很感激。错误如下:


回答:

你的代码中有两个问题。首先,由于你使用了pipeline,你需要在params列表中指定参数属于管道的哪一部分。请参阅官方文档了解更多信息:

管道的目的是将多个步骤组合在一起,以便可以一起进行交叉验证,同时设置不同的参数。为此,它允许使用它们的名称和参数名称(中间用‘__’分隔)来设置各个步骤的参数,如下例所示

在这种情况下,由于alpha将用于ridge-regression,并且你在Pipeline定义中使用了字符串model,你需要将键alpha重命名为model__alpha

steps = [
    ('scalar', StandardScaler()),
    ('poly', PolynomialFeatures(degree=2)),
    ('model', Ridge())  # <------ 你在这里使用的任何字符串稍后都会被使用
]
# 由于你将其命名为'model',你需要将其更改为'model__alpha'
parameters = [ {'model__alpha': np.arange(0, 0.2, 0.01) } ]

接下来,你需要明白这个数据集是用于回归的。你不应该在这里使用accuracy,而应该使用基于回归的评分函数,如mean_squared_error。这里有一些其他用于回归的指标供你使用。类似这样的代码:

from sklearn.metrics import mean_squared_error, make_scorer
scoring_func = make_scorer(mean_squared_error)
grid_search = GridSearchCV(estimator = ridge_pipe,
                           param_grid = parameters,
                           scoring = scoring_func,  #<--- 使用上面定义的评分函数
                           cv = 10,
                           n_jobs = -1)

这是一个指向Google Colab笔记本的链接,其中包含可运行的代码。

Related Posts

在使用k近邻算法时,有没有办法获取被使用的“邻居”?

我想找到一种方法来确定在我的knn算法中实际使用了哪些…

Theano在Google Colab上无法启用GPU支持

我在尝试使用Theano库训练一个模型。由于我的电脑内…

准确性评分似乎有误

这里是代码: from sklearn.metrics…

Keras Functional API: “错误检查输入时:期望input_1具有4个维度,但得到形状为(X, Y)的数组”

我在尝试使用Keras的fit_generator来训…

如何使用sklearn.datasets.make_classification在指定范围内生成合成数据?

我想为分类问题创建合成数据。我使用了sklearn.d…

如何处理预测时不在训练集中的标签

已关闭。 此问题与编程或软件开发无关。目前不接受回答。…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注