xxdd123321

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

K折交叉验证

  • 目的:

    • 选出最为合适的模型超参数的取值,然后将超参数的值作用到模型的创建中

  • 思想:

    • 将样本的训练数据交叉的拆分出不同的训练集和验证集,使用交叉拆分出不同的训练集和验证集分别实验模型的精准度,然后就求出的精准度的均值就是此次交叉验证的结果,将交叉验证作用到不同的超参数中,选取出精准度最高的超参数作为模型创建的超参数即可

  • 实现思路:

    • 将数据集平均分隔成K个等分

    • 使用一份数据作为测试数据,其余作为训练数据

    • 计算测试准确率

    • 使用不同的测试集,重复2,3步骤

    • 对准确率做平均,作为对未知数据预测准确率的估计

  • API:from sklearn.model_selection import cross_val_score

  • cross_val_score(exstimator, X, y, cv):

    • estimator:模型对象

    • X, y:训练集数据

    • cv:折数

from sklearn.model_selection import cross_val_score
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
import sklearn.datasets as datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt


# 提取样本数据
iris = datasets.load_iris()
feature = iris['data']
target = iris['target']

# 拆分
x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.2, random_state=2020)

# 对训练集进行交叉验证
knn = KNeighborsClassifier(n_neighbors=5)
cross = cross_val_score(knn, x_train, y_train, cv=5).mean()
print(cross)
scores = []
ks = []
for i in range(3, 20):
   knn = KNeighborsClassifier(n_neighbors=i)
   score = cross_val_score(knn, x_train, y_train, cv=6).mean()
   scores.append(score)
   ks.append(i)

plt.plot(ks, scores)
plt.show()

0.9916666666666668

Process finished with exit code 0
posted on   xxdd123321  阅读(68)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
 
点击右上角即可分享
微信分享提示