【机器学习】西瓜书习题3.4Python编程比较 10 折交叉验证法和留一法所估计出的对率回归的错误率

3.4 选择两个 UCI 数据集,比较 10 折交叉验证法和留一法所估计出的对率回归的错误率.

参考代码

结合自己的理解,添加注释。

数据集链接,下载后的数据在后缀名是data的文件中,使用记事本打开,本次解题需要去掉第一行属性名称,再保存为txt格式文件。

代码

  1. 导入相关库
python 复制代码
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn.model_selection import LeaveOneOut
from sklearn.model_selection import cross_val_score
  1. 读取数据,处理数据
python 复制代码
data_path = r'Transfusion.txt'
# 读取数据,将数据强制转换为int型
data = np.loadtxt(data_path, delimiter=',').astype(int)
# 前4列(属性值)赋值给X,第5列赋值给y(label值)
X = data[:, :4]
y = data[:, 4]

m, n = X.shape
# normalization,标准化,将数据减去均值,再除以方差,将数据平均数变成0,标准差变成1
X = (X - X.mean(0)) / X.std(0)
# np.arange返回一个有终点和起点的固定步长的排列(可理解为一个等差数组)
index = np.arange(m)
# shuffle打乱index排列
np.random.shuffle(index)
# 将数据按照打乱后的index重新排列
X = X[index]
y = y[index]
  1. 计算十折交叉验证的平均准确度
python 复制代码
# 使用sklarn 中自带的api先
# k-10 cross validation
lr = linear_model.LogisticRegression(C=2)  # C越大表示正则化程度越低
score = cross_val_score(lr, X, y, cv=10)
print(score.mean())

结果

复制代码
0.7674234234234236
  1. 使用留一法验证的平均准确度
python 复制代码
# 留一法leave-one-out
loo = LeaveOneOut()

accuracy = 0
for train, test in loo.split(X, y):
    lr_ = linear_model.LogisticRegression(C=2)
    X_train = X[train]
    X_test = X[test]
    y_train = y[train]
    y_test = y[test]
    lr_.fit(X_train, y_train)

    accuracy += lr_.score(X_test, y_test)

print(accuracy / m)

结果

复制代码
0.7687165775401069
相关推荐
冷雨夜中漫步5 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴6 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再6 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
喵手7 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934737 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy8 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
九河云8 小时前
5秒开服,你的应用部署还卡在“加载中”吗?
大数据·人工智能·安全·机器学习·华为云
肖永威9 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ9 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
枷锁—sha9 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全