机器学习——KNN超参数
sklearn.model_selection.GridSearchCV 是 scikit-learn 中用于超参数调优的核心工具,通过结合交叉验证和网格搜索实现模型参数的自动化优化。以下是详细介绍:
一、功能概述
GridSearchCV 在指定参数网格上穷举所有可能的超参数组合,通过交叉验证评估每组参数的性能,最终选择最优参数组合。其核心价值在于:
- 自动化调参:替代手动参数调试,提升效率3。
- 交叉验证支持:通过 K 折交叉验证减少过拟合风险,评估结果更可靠。
二、核心参数说明
参数 | 类型 | 作用 |
---|---|---|
estimator | 估计器对象 | 需调参的模型(如 SVC() 、RandomForestClassifier() ) |
param_grid | 字典或列表 | 参数名称(字符串)为键,候选参数值列表为值(如 {'C': [1,10], 'kernel': ['linear','rbf']} ) |
scoring | 字符串/可调用对象 | 评估指标(如 'accuracy' 、'roc_auc' ),默认使用模型的 score() 方法1013 |
cv | int/交叉验证生成器 | 交叉验证折数(默认 5 折),或自定义数据划分策略28 |
n_jobs | int | 并行任务数(-1 表示使用所有 CPU 核) |
三、主要属性
调用 fit()
方法后可通过以下属性获取结果:
best_score_
:交叉验证中的最高得分。best_params_
:最优参数组合(如{'C': 10, 'kernel': 'rbf'}
)。cv_results_
:详细结果字典,包含每组参数的平均得分、标准差等。
四、工作流程
- 数据划分:原始数据分为训练集和测试集,训练集进一步通过 K 折交叉验证划分为子集。
- 参数组合生成:根据
param_grid
生成所有可能的超参数组合(如 2×2 网格生成 4 组参数。 - 交叉验证评估:每组参数在 K 折数据上训练并验证,计算平均得分。
- 最优模型选择:选择平均得分最高的参数组合,最终在完整训练集上训练模型8。
五、代码演示
1、手动调参(循环调参)
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
#加载数据集
iris = load_iris()
x = iris.data
y = iris.target
#划分数据集
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7, random_state=233, stratify=y)
#分类
from sklearn.neighbors import KNeighborsClassifier
#设置默认参数
neigh = KNeighborsClassifier(
n_neighbors=3,
weights='distance',#'uniform',
p = 2
)
#适配参数
neigh.fit(x_train, y_train)
#评估模型
neigh.score(x_test, y_test) #结果:0.9777777777777777
#自动设参(主要遍历每个参数,找出最佳结果的参数)
best_score = -1
best_n = -1
best_weight = ''
best_p = -1
for n in range(1, 20):
for weight in ['uniform', 'distance']:
for p in range(1, 7):
neigh = KNeighborsClassifier(
n_neighbors=n,
weights=weight,
p = p
)
neigh.fit(x_train, y_train)
score = neigh.score(x_test, y_test)
if score > best_score:
best_score = score
best_n = n
best_weight = weight
best_p = p
print("n_neighbors:", best_n)
print("weights:", best_weight)
print("p:", best_p)
print("score:", best_score)
#结果:n_neighbors: 5
#weights: uniform
#p: 2
#score: 1.0
2、KNN-sklearn.model_selection.GridSearchCV调参
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
#加载数据集
iris=load_iris()
x=iris.data
y=iris.target
#划分数据集(7:3)
x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7, random_state=233, stratify=y)
#设置参数范围
params = {
'n_neighbors': [n for n in range(1, 20)],
'weights': ['uniform', 'distance'],
'p': [p for p in range(1, 7)]
}
#定义调参对象
grid = GridSearchCV(
estimator=KNeighborsClassifier(),
param_grid=params,
n_jobs=-1
)
#适配参数
grid.fit(x_train, y_train)
#打印最佳参数
print(grid.best_params_)
#输出预测值
print(grid.best_estimator_.predict(x_test))
#模型评估
print(grid.best_estimator_.score(x_test, y_test))