【机器学习】西瓜书习题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
相关推荐
开MINI的工科男27 分钟前
深蓝学院-- 量产自动驾驶中的规划控制算法 小鹏
人工智能·机器学习·自动驾驶
waterHBO34 分钟前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AI大模型知识分享2 小时前
Prompt最佳实践|如何用参考文本让ChatGPT答案更精准?
人工智能·深度学习·机器学习·chatgpt·prompt·gpt-3
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
FreakStudio6 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy
redcocal7 小时前
地平线秋招
python·嵌入式硬件·算法·fpga开发·求职招聘
artificiali7 小时前
Anaconda配置pytorch的基本操作
人工智能·pytorch·python
RaidenQ7 小时前
2024.9.13 Python与图像处理新国大EE5731课程大作业,索贝尔算子计算边缘,高斯核模糊边缘,Haar小波计算边缘
图像处理·python·算法·课程设计