当前位置: 首页 > article >正文

机器学习——KNN超参数

sklearn.model_selection.GridSearchCV 是 scikit-learn 中用于超参数调优的核心工具,通过结合交叉验证和网格搜索实现模型参数的自动化优化。以下是详细介绍:


一、功能概述

GridSearchCV 在指定参数网格上穷举所有可能的超参数组合,通过交叉验证评估每组参数的性能,最终选择最优参数组合。其核心价值在于:

  1. 自动化调参:替代手动参数调试,提升效率3。
  2. 交叉验证支持:通过 K 折交叉验证减少过拟合风险,评估结果更可靠。


二、核心参数说明

参数类型作用
estimator估计器对象需调参的模型(如 SVC()RandomForestClassifier()
param_grid字典或列表参数名称(字符串)为键,候选参数值列表为值(如 {'C': [1,10], 'kernel': ['linear','rbf']}
scoring字符串/可调用对象评估指标(如 'accuracy''roc_auc'),默认使用模型的 score() 方法1013
cvint/交叉验证生成器交叉验证折数(默认 5 折),或自定义数据划分策略28
n_jobsint并行任务数(-1 表示使用所有 CPU 核)

三、主要属性

调用 fit() 方法后可通过以下属性获取结果:

  • best_score_:交叉验证中的最高得分。
  • best_params_:最优参数组合(如 {'C': 10, 'kernel': 'rbf'})。
  • cv_results_:详细结果字典,包含每组参数的平均得分、标准差等。

四、工作流程

  1. 数据划分:原始数据分为训练集和测试集,训练集进一步通过 K 折交叉验证划分为子集。
  2. 参数组合生成:根据 param_grid 生成所有可能的超参数组合(如 2×2 网格生成 4 组参数。
  3. 交叉验证评估:每组参数在 K 折数据上训练并验证,计算平均得分。
  4. 最优模型选择:选择平均得分最高的参数组合,最终在完整训练集上训练模型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))


http://www.kler.cn/a/596509.html

相关文章:

  • 从PGC到AIGC:海螺AI多模态内容生成系统的技术革命
  • Docker 部署医学影像 DICOM 服务器 Orthanc
  • [node] 3 path与http
  • 美国国家数据浮标中心(NDBC)
  • 软考程序员-操作系统基本知识核心考点和知识重点总结
  • SQL授予用户查询某个模式或者具体某个表
  • VideoHelper 油猴脚本,重塑你的视频观看体验
  • [01-01-02].第02节:开发工具 - Pycharm使用
  • 【HarmonyOS Next之旅】DevEco Studio使用指南(六)
  • Springboot集成Debezium监听postgresql变更
  • Assembly语言的软件工程
  • AI密码学
  • Windows Server 2025 使用 IIS 搭建 ASP.NET 3.5 网站
  • 【免费】2000-2019年各省地方财政房产税数据
  • Redis分布式锁如何实现——简单理解版
  • 题单:排队接水1
  • form 表单内容序列化成一个字符串
  • MyBatis之参数传递
  • 代码随想录算法训练营第十四天(2)|151.翻转字符串里的单词
  • 一个完整的小项目案例,涉及到项目的规划,模块的设计功能的衔接等。