【Python机器学习系列】一文讲透机器学习中的K折交叉验证(源码)

一、简介

前面我详细介绍了关于机器学习的归一化和反归一化 以及表格数据在机器学习中的输入格式问题:

一文彻底搞懂机器学习中的归一化与反归一化问题

【Python机器学习系列】一文彻底搞懂机器学习中表格数据的输入形式(理论+源码)

本文将介绍机器系学习中的K折交叉验证的使用方法。

交叉验证(Cross-validation)是一种在机器学习中常用的模型评估技术,用于估计模型在未知数据上的性能。它通过将数据集划分为训练集和验证集,并多次重复这个过程来评估模型的性能。

k折交叉验证是将数据分为k份,选取其中的k-1份为训练数据,剩余的一份为测试数据。k份数据循环做测试集进行测试。此原理适用于数据量小的数据。

使用交叉验证,可以实现:

  • 寻找单个模型最好的效果时候的数据集划分以及参数

  • 比较多个模型,选择最佳模型

二、实现

准备数据

python 复制代码
import pandas as pd

# 准备数据
data = pd.read_csv(r'G:\数据杂坛\\UCI Heart Disease Dataset.csv')
df = pd.DataFrame(data)

# 目标变量和特征变量
target = 'target'
features = df.columns.drop(target)
X = df[features].values
y = df[target].values

方法1

python 复制代码
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import KFold

kf = KFold(n_splits = 5, shuffle=True, random_state=0)
score=0
for train_index, test_index in kf.split(y):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clt = DecisionTreeClassifier(max_depth=5, random_state=0).fit(X_train, y_train)
    curr_score = clt.score(X_test, y_test)
    print("准确率为:", curr_score)
    score = score + curr_score

avg_score = score / 5
print("平均准确率为:", avg_score)

n_splits = 5,表示进行5折交叉验证,分别计算每一次的准确率,最后求得平均准确率。使用KFold.split()实现,效果如下:

方法2

python 复制代码
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score

kf = KFold(n_splits=5, shuffle=True, random_state=0)
model1 = DecisionTreeClassifier(max_depth=5, random_state=0)
scores_model1 = cross_val_score(model1, X, y, cv=kf)
print("准确率为:", scores_model1)
print("平均准确率为:", scores_model1.mean())

直接使用sklearn中的cross_val_score()函数实现,效果和第一种方法一样,结果如下:

三、应用场景

方法1 选择模型效果最好的数据集划分

python 复制代码
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import KFold

kf = KFold(n_splits = 5, shuffle=True, random_state=0)
score=0
best_score = -float('inf')  # 初始化为正无穷大
best_train_index = None
best_test_index = None
for train_index, test_index in kf.split(y):
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clt = DecisionTreeClassifier(max_depth=5, random_state=0).fit(X_train, y_train)
    curr_score = clt.score(X_test, y_test)
    print("准确率为:", curr_score)
    score = score + curr_score

    # 如果当前数据集划分的性能更好,则更新最佳数据集划分
    if curr_score > best_score:
        best_score = curr_score
        best_train_index = train_index
        best_test_index = test_index

avg_score = score / 5
print("平均准确率为:", avg_score)
print("Best train indices:", best_train_index)
print("Best test indices:", best_test_index)
X_train, X_test = X[best_train_index], X[best_test_index]
y_train, y_test = y[best_train_index], y[best_test_index]

KFold的split方法会生成交叉验证的训练集和测试集索引,然后你可以使用这些索引将数据集划分为相应的训练集和测试集。通过在每个数据集划分上训练模型并评估性能,你可以选择具有最佳性能的数据集划分。最后,你可以打印最佳数据集划分的索引,以便进一步分析和使用。

方法2 用于比较不同模型的评分,选择最优模型

python 复制代码
from sklearn.linear_model import LogisticRegression

kf = KFold(n_splits=5, shuffle=True, random_state=0)
model1 = DecisionTreeClassifier(max_depth=5, random_state=0)
model2 = LogisticRegression()
scores_model1 = cross_val_score(model1, X, y, cv=kf)
scores_model2 = cross_val_score(model2, X, y, cv=kf)
print("model1准确率为:", scores_model1)
print("model1平均准确率为:", scores_model1.mean())
print("model2准确率为:", scores_model2)
print("model2平均准确率为:", scores_model2.mean())

通过比较不同模型的评分,你可以选择最佳模型,评分较高的模型通常具有更好的性能。

好了,本篇内容就到这里, 需要数据集和源码的小伙伴可以关注我领取

++作者简介:++

读研期间发表6篇SCI数据挖掘相关论文,现在某研究院从事数据算法相关科研工作,结合自身科研实践经历不定期分享关于Python、机器学习、深度学习、人工智能系列基础知识与应用案例。致力于只做原创,以最简单的方式理解和学习,关注我一起交流成长。

相关推荐
MATLAB代码顾问1 小时前
5大智能算法优化标准测试函数对比(Python实现)
开发语言·python
ting94520001 小时前
Tornado 全栈技术深度指南:从原理到实战
人工智能·python·架构·tornado
果汁华2 小时前
Browserbase Skills:让 Claude Agent 真正“看见“网页世界
人工智能·python
ZhengEnCi2 小时前
04-缩放点积注意力代码实现 💻
人工智能·python
2zcode2 小时前
基于LSTM神经网络的金属材料机器学习本构模型研究(硕士级别)
神经网络·机器学习·lstm·金属材料
DeepReinforce2 小时前
三、AI量化投资:使用akshare获取A股主板20260430所有的涨停股票
python·量化·akshare·龙头战法
段一凡-华北理工大学3 小时前
【高炉炼铁领域炉温监测、预警、调控智能体设计与应用】~系列文章08:多模态数据融合:让数据更聪明
人工智能·python·高炉炼铁·ai赋能·工业智能体·高炉炉温
万粉变现经纪人3 小时前
如何解决 pip install llama-cpp-python 报错 未安装 CMake/Ninja 或 CPU 不支持 AVX 问题
开发语言·python·开源·aigc·pip·ai写作·llama
清风明月一壶酒3 小时前
OpenClaw自动处理Word文档全流程
开发语言·c#·word
其实防守也摸鱼3 小时前
CTF密码学综合教学指南--第五章
开发语言·网络·笔记·python·安全·网络安全·密码学