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

模型评估与验证:确保模型在未知数据上的表现----示例:使用K折交叉验证评估分类模型、房价预测问题使用K折交叉验证来评估一个线性回归模型的性能

模型评估与验证是机器学习流程中的关键步骤,它帮助我们了解模型在未见过的数据上的泛化能力。交叉验证(Cross-Validation, CV)是一种常用的技术,通过将数据集划分为多个子集并进行多次训练和测试来估计模型的性能。此外,选择合适的评价指标对于不同类型的任务至关重要。

交叉验证

交叉验证的主要目的是减少由于数据划分带来的偏差,并提供更可靠的性能估计。常见的交叉验证方法包括K折交叉验证(K-Fold Cross-Validation)和留一法交叉验证(Leave-One-Out Cross-Validation)。

示例:使用K折交叉验证评估分类模型

假设二分类问题,将使用K折交叉验证来评估一个随机森林分类器的性能。

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix# 加载数据
data = pd.read_csv('binary_classification_data.csv')
X = data.drop('target', axis=1)
y = data['target']# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 定义分类器
classifier = RandomForestClassifier(random_state=42)# 使用K折交叉验证评估模型
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(classifier, X_train, y_train, cv=kfold, scoring='accuracy')print("Cross-Validation Accuracy Scores:", cv_scores)
print("Mean CV Accuracy:", np.mean(cv_scores))# 训练最终模型
classifier.fit(X_train, y_train)# 在测试集上评估
y_pred = classifier.predict(X_test)# 计算各种评价指标
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)print(f"Test Set Accuracy: {accuracy:.4f}")
print(f"Test Set Precision: {precision:.4f}")
print(f"Test Set Recall: {recall:.4f}")
print(f"Test Set F1 Score: {f1:.4f}")
print("Confusion Matrix:\n", conf_matrix)

 

  • 数据加载

    • 使用pandas读取CSV文件,并分离特征和标签。
  • 数据划分

    • 使用train_test_split将数据划分为训练集和测试集。
  • 定义分类器

    • 创建一个随机森林分类器实例。
  • K折交叉验证

    • 使用KFold创建一个5折交叉验证对象。
    • 使用cross_val_score对训练集进行交叉验证,并计算准确率。
  • 训练最终模型

    • 使用整个训练集训练最终的分类器。
  • 测试集评估

    • 在测试集上进行预测。
    • 计算并打印多种评价指标,包括准确率、精确度、召回率、F1分数和混淆矩阵。
回归任务的评估

对于回归任务,常用的评价指标包括均方误差(MSE)、平均绝对误差(MAE)和决定系数(R²)等。

示例:使用K折交叉验证评估回归模型

假设房价预测问题使用K折交叉验证来评估一个线性回归模型的性能。

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, KFold
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score# 加载数据
data = pd.read_csv('house_prices.csv')
X = data.drop('price', axis=1)
y = data['price']# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# 定义回归器
regressor = LinearRegression()# 使用K折交叉验证评估模型
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
cv_scores = cross_val_score(regressor, X_train, y_train, cv=kfold, scoring='neg_mean_squared_error')print("Cross-Validation MSE Scores (negative values):", cv_scores)
print("Mean CV MSE (positive value):", -np.mean(cv_scores))# 训练最终模型
regressor.fit(X_train, y_train)# 在测试集上评估
y_pred = regressor.predict(X_test)# 计算各种评价指标
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)print(f"Test Set MSE: {mse:.4f}")
print(f"Test Set MAE: {mae:.4f}")
print(f"Test Set R^2: {r2:.4f}")

 

  • 数据加载

    • 使用pandas读取CSV文件,并分离特征和标签。
  • 数据划分

    • 使用train_test_split将数据划分为训练集和测试集。
  • 定义回归器

    • 创建一个线性回归模型实例。
  • K折交叉验证

    • 使用KFold创建一个5折交叉验证对象。
    • 使用cross_val_score对训练集进行交叉验证,并计算负均方误差(因为cross_val_score默认返回的是负值以方便排序)。
  • 训练最终模型

    • 使用整个训练集训练最终的回归模型。
  • 测试集评估

    • 在测试集上进行预测。
    • 计算并打印多种评价指标,包括均方误差(MSE)、平均绝对误差(MAE)和决定系数(R²)。
http://www.lryc.cn/news/452507.html

相关文章:

  • awd基础学习
  • C#基于SkiaSharp实现印章管理(10)
  • 通过栈实现字符串中查找是否有指定字符串的存在
  • MongoDB伪分布式部署(mac M2)
  • Golang | Leetcode Golang题解之第454题四数相加II
  • [ComfyUI]Flux:超美3D微观山水禅意,经典中文元素AI重现,佛陀楼阁山水画卷
  • Linux 系统 nvm 管理node无法使用
  • 信号处理快速傅里叶变换(FFT)的学习
  • vue3项目el-table表格行内编辑加输入框校验
  • 【Node.js】内置模块FileSystem的保姆级入门讲解
  • 问:LINUXWINDOWS线程CPU时间如何排序?
  • postgresql-重复执行相同语句,试试 prepare!
  • wpf加载带材料的3D模型(下载的3D预览一样有纹理)
  • 【k8s之深入理解调度】调度框架扩展点理解
  • 音视频基础理论
  • 《江苏科技大学学报(自然科学版)》
  • C++初学者指南-5.标准库(第二部分)–随机数生成
  • Unity2017在安卓下获取GPS位置时闪退的解决办法
  • OpenGL ES 索引缓冲区(4)
  • 01:(寄存器开发)点亮一个LED灯
  • .Net 6.0 Windows平台如何判断当前电脑是否联网
  • 微软准备了 Windows 11 24H2 ISO “OOBE/BypassNRO“命令依然可用
  • MacOS 终端执行安装 Brew
  • 【设计模式-解释模式】
  • 51单片机应用开发(进阶)---数码管+按键+蜂鸣器(电磁炉显示模拟)
  • Emergency Stop (ES)
  • [C++][第三方库][gtest]详细讲解
  • 【Java数据结构】 链表
  • 前端——Ajax和jQuery
  • C++-vector模拟实现