【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、机器学习、深度学习、人工智能系列基础知识与应用案例。致力于只做原创,以最简单的方式理解和学习,关注我一起交流成长。

相关推荐
脑袋大大的15 分钟前
判断当前是否为钉钉环境
开发语言·前端·javascript·钉钉·企业应用开发
运器12317 分钟前
【一起来学AI大模型】PyTorch DataLoader 实战指南
大数据·人工智能·pytorch·python·深度学习·ai·ai编程
音元系统20 分钟前
Copilot 在 VS Code 中的免费替代方案
python·github·copilot
超龄超能程序猿32 分钟前
(5)机器学习小白入门 YOLOv:数据需求与图像不足应对策略
人工智能·python·机器学习·numpy·pandas·scipy
Wy. Lsy42 分钟前
Kotlin基础学习记录
开发语言·学习·kotlin
Tanecious.1 小时前
C++--红黑树
开发语言·c++
Top`1 小时前
Java 泛型 (Generics)
java·开发语言·windows
cwn_2 小时前
回归(多项式回归)
人工智能·机器学习·数据挖掘·回归
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
如何使用Java WebSocket API实现客户端和服务器端的通信?
java·开发语言·websocket
Shartin2 小时前
Can201-Introduction to Networking: Application Layer应用层
服务器·开发语言·php