【深耕 Python】Data Science with Python 数据科学(19)书402页练习题:模型准确率对比研究、KMeans算法的一点探讨

写在前面

关于数据科学环境的建立,可以参考我的博客:

【深耕 Python】Data Science with Python 数据科学(1)环境搭建

往期数据科学博文一览:

【深耕 Python】Data Science with Python 数据科学(2)jupyter-lab和numpy数组

【深耕 Python】Data Science with Python 数据科学(3)Numpy 常量、函数和线性空间

【深耕 Python】Data Science with Python 数据科学(4)(书337页)练习题及解答

【深耕 Python】Data Science with Python 数据科学(5)Matplotlib可视化(1)

【深耕 Python】Data Science with Python 数据科学(6)Matplotlib可视化(2)

【深耕 Python】Data Science with Python 数据科学(7)书352页练习题

【深耕 Python】Data Science with Python 数据科学(8)pandas数据结构:Series和DataFrame

【深耕 Python】Data Science with Python 数据科学(9)书361页练习题

【深耕 Python】Data Science with Python 数据科学(10)pandas 数据处理(一)

【深耕 Python】Data Science with Python 数据科学(11)pandas 数据处理(二)

【深耕 Python】Data Science with Python 数据科学(12)pandas 数据处理(三)

【深耕 Python】Data Science with Python 数据科学(13)pandas 数据处理(四):书377页练习题

【深耕 Python】Data Science with Python 数据科学(14)pandas 数据处理(五):泰坦尼克号亡魂 Perished Souls on “RMS Titanic”

【深耕 Python】Data Science with Python 数据科学(15)pandas 数据处理(六):书385页练习题

【深耕 Python】Data Science with Python 数据科学(16)Scikit-learn机器学习(一)

【深耕 Python】Data Science with Python 数据科学(17)Scikit-learn机器学习(二)

【深耕 Python】Data Science with Python 数据科学(18)Scikit-learn机器学习(三)

代码说明: 由于实机运行的原因,可能省略了某些导入(import)语句。

11.7.4 Exercises

1. The RandomForestClassifier( ) function takes a keyword argument called n_estimators that represents the “number of trees in the forest”. According to the documentation, what is the default value for n_estimators? Use random_state=1.

Answer in Python:

# ex 1
from sklearn.ensemble import RandomForestClassifier
random_forest = RandomForestClassifier(random_state=1)
print(random_forest.n_estimators)  # default value of number of trees
random_forest_2 = RandomForestClassifier(random_state=1, n_estimators=10)
print(random_forest_2.n_estimators)  # set the value of number of trees

程序输出:

100  # 默认树棵数
10   # 设置值

2. By varying n_estimators in the call to RandomForestClassifier( ), determine the approximate value where the Random Forest classifier is less accurate than Decision Tree. Use random_state=1.

Answer in Python:
首先取n_estimators=50:

import numpy as np
import pandas as pd
import matplotlib.pyplot as pltURL = "https://learnenough.s3.amazonaws.com/titanic.csv"
titanic = pd.read_csv(URL)from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifierdropped_columns = ["PassengerId", "Name", "Cabin", "Embarked", "SibSp", "Parch", "Ticket", "Fare"]
for column in dropped_columns:titanic = titanic.drop(column, axis=1)for column in ["Age", "Sex", "Pclass"]:titanic = titanic[titanic[column].notna()]sexes = {"male": 0, "female": 1}
titanic["Sex"] = titanic["Sex"].map(sexes)X = titanic.drop("Survived", axis=1)
Y = titanic["Survived"]from sklearn.model_selection import train_test_split(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, random_state=1)decision_tree = DecisionTreeClassifier(random_state=1)
decision_tree.fit(X_train, Y_train)
accuracy_decision_tree = decision_tree.score(X_test, Y_test)random_forest = RandomForestClassifier(random_state=1, n_estimators=50)
random_forest.fit(X_train, Y_train)
accuracy_random_forest = random_forest.score(X_test, Y_test)results = pd.DataFrame({"Model": ["Decision Tree", "Random Forest"],"Score": [accuracy_decision_tree, accuracy_random_forest]
})result_df = results.sort_values(by="Score", ascending=False)
result_df = result_df.set_index("Score")
print(result_df)

模型准确率排序输出:

# 准确率    模型
Score      Model                  
0.854749  Decision Tree
0.854749  Random Forest

此时,使用50棵树的随机森林模型和决策树模型的识别准确率恰好相等(保留至小数点后第6位)。经过多次尝试,当取n_estimators=18时两种模型的识别准确率相等:

random_forest = RandomForestClassifier(random_state=1, n_estimators=18)
random_forest.fit(X_train, Y_train)
accuracy_random_forest = random_forest.score(X_test, Y_test)
# 准确率   模型
Score     Model           
0.854749  Decision Tree
0.854749  Random Forest

n_estimators=17时,随机森林模型的识别准确率首次变为低于决策树模型。

random_forest = RandomForestClassifier(random_state=1, n_estimators=17)
random_forest.fit(X_train, Y_train)
accuracy_random_forest = random_forest.score(X_test, Y_test)
# 准确率   模型
Score     Model             
0.854749  Decision Tree
0.843575  Random Forest

综上,要寻找的阈值大约为17.

3. By rerunning the steps in Section 11.7.2 using a few different values of random_state, verify that the ordering is not always the same as shown in Listing 11.25. Hint: Try values like 0, 2, 3, and 4.

Answer:
在划分数据集过程中和部分模型中,修改random_state参数的值。
random_state=0:

from sklearn.model_selection import train_test_split(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, random_state=0)

(模型参数省略)
模型识别准确率输出:

# 准确率   模型
Score     Model                   
0.821229  Logistic Regression  # 逻辑斯蒂回归
0.793296        Decision Tree  # 决策树
0.782123          Naive Bayes  # 朴素贝叶斯
0.776536        Random Forest  # 随机森林
0.681564           Perceptron  # 感知机

random_state=2:

from sklearn.model_selection import train_test_split(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, random_state=2)

(模型参数省略)
模型识别准确率输出:

# 准确率         模型                        
Score           Model                        
0.837989        Decision Tree  # 决策树
0.826816  Logistic Regression  # 逻辑斯蒂回归
0.821229        Random Forest  # 随机森林
0.787709           Perceptron  # 感知机
0.782123          Naive Bayes  # 朴素贝叶斯

random_state=3:

from sklearn.model_selection import train_test_split(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, random_state=3)

(模型参数省略)
模型识别准确率输出:

# 准确率        模型                        
Score           Model           
0.810056        Decision Tree  # 决策树
0.810056        Random Forest  # 随机森林
0.782123  Logistic Regression  # 逻辑斯蒂回归
0.765363          Naive Bayes  # 朴素贝叶斯
0.402235           Perceptron  # 感知机

和random_state=1时的准确率排序相同,但整体上存在大幅度下降趋势。

random_state=4:

from sklearn.model_selection import train_test_split(X_train, X_test, Y_train, Y_test) = train_test_split(X, Y, random_state=4)

(模型参数省略)
模型识别准确率输出:

# 准确率        模型                        
Score           Model           
0.837989        Random Forest  # 随机森林
0.798883  Logistic Regression  # 逻辑斯蒂回归
0.782123        Decision Tree  # 决策树
0.765363          Naive Bayes  # 朴素贝叶斯
0.603352           Perceptron  # 感知机

日后可以深究一下random_state参数对不同模型识别准确率的影响,本文在此不作赘述。不过显而易见的是,简单感知机的识别准确率性能确实基本上是垫底的。

4. Repeat the clustering steps in Section 11.7.3 using two clusters and eight clusters. Does the algorithm still work well in both cases?

Answer in Python:
首先取KMeans算法中的n_clusters=2,输出聚类结果(聚类中心点坐标):

from sklearn.datasets import make_blobs
import matplotlib.pyplot as pltX, _ = make_blobs(n_samples=300, centers=4, random_state=42)from sklearn.cluster import KMeanskmeans = KMeans(n_clusters=2)
kmeans.fit(X)
centers = kmeans.cluster_centers_
print(centers)

程序输出:

[[-6.83235205 -6.83045748]   # 中心点1[-2.26099839  6.07059051]]  # 中心点2

聚类结果可视化:

fig, ax = plt.subplots()
ax.scatter(X[:, 0], X[:, 1])
ax.scatter(centers[:, 0], centers[:, 1], s=200, alpha=0.9, color="orange")
plt.title("Cluster Result Illustration")
plt.xlabel("X")
plt.ylabel("Y")
plt.grid()
plt.show()

输出的图像:

在这里插入图片描述

可见,上方3个簇被模型划分为1个类。

再取KMeans算法中的n_clusters=8,输出聚类结果(聚类中心点坐标):

kmeans = KMeans(n_clusters=8)  # 修改的代码行

聚类结果图示:

在这里插入图片描述

结果比较好理解,8 = 4 * 2,模型对每一个数据簇赋了2个聚类中心。

但是当n_clusters=16时,出人意料的是,模型并没有简单地按照4 * 4的方式进行“分配”,而是3 + 5 + 4 + 4

kmeans = KMeans(n_clusters=16)

在这里插入图片描述

直观上,认为导致这种现象的原因可能是样本点的数量。

再分别观察n_clusters=24n_clusters=32时的情形:

平均分配,6 + 6 + 6 + 6

在这里插入图片描述

8 + 8 + 7 + 9,“平均率”被打破。

在这里插入图片描述

看来模型对于聚类中心的“分配”是随机的,但位置基本落在各个数据簇的边缘内,这个结果是可以令人满意的。

参考文献 Reference

《Learn Enough Python to be Dangerous——Software Development, Flask Web Apps, and Beginning Data Science with Python》, Michael Hartl, Boston, Pearson, 2023.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/1410663.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

Redis 实战1

SDS Redis 只会使用 C 字符串作为字面量, 在大多数情况下, Redis 使用 SDS (Simple Dynamic String,简单动态字符串)作为字符串表示。 比起 C 字符串, SDS 具有以下优点: 常数复杂度获取字符串…

【高质量精品】2024五一数学建模C题成品论文22页matlab和13页python完整建模代码、可视图表+分解结果等(后续会更新)

您的点赞收藏是我继续更新的最大动力! 一定要点击如下卡片,那是获取资料的入口! 【高质量精品】2024五一数学建模C题成品论文22页matlab和13页python完整建模代码、可视图表分解结果等「首先来看看目前已有的资料,还会不断更新哦…

『MySQL 实战 45 讲』19 - 为什么我只查一行的语句,也执行这么慢?

为什么我只查一行的语句,也执行这么慢? 需求:创建一个表,有两个字段 id 和 c,并且在里面插入了 10 万行记录 CREATE TABLE t (id int(11) NOT NULL,c int(11) DEFAULT NULL,PRIMARY KEY (id) ) ENGINEInnoDB;delimit…

硬件知识积累 DP 接口简单介绍以及 DP信号飞线到显示屏的问题

1. DP 接口的介绍 定义与起源: DP接口是由PC及芯片制造商联盟开发,并由视频电子标准协会(VESA)标准化的数字式视频接口标准。它的设计初衷是为了取代传统的VGA、DVI和FPD-Link(LVDS)接口,以满足…

Qt QImageReader类介绍

1.简介 QImageReader 是用于读取图像文件的类。它提供了读取不同图像格式的功能,包括但不限于 PNG、JPEG、BMP 等。QImageReader 可以用于文件,也可以用于任何 QIODevice,如 QByteArray ,这使得它非常灵活。 QImageReader 是一个…

323_C++_QT_QProcess执行cmd解压、压缩、删除tar.gz等等其他压缩包文件到指定目录,不需要外部库,QT自带API的就行

// decompressPath : 解压到此目录 // fileName : 解压的tar.gz文件名executeCommand(decompressPath , QString::fromStdString(fileName));// 开始解压 void executeCommand

uni-app scroll-view隐藏滚动条的小细节 兼容主流浏览器

开端 想写个横向滚动的列表适配浏览器,主要就是隐藏一下滚动条在手机上美观一点。 但是使用uni-app官方文档建议的::-webkit-scrollbar在目标标签时发现没生效。 .scroll-view_H::-webkit-scrollbar{display: none; }解决 F12看了一下,原来编译到浏览…

漏洞扫描神器:Nessus 保姆级教程(附破解步骤)

一、介绍 Nessus是一款广泛使用的网络漏洞扫描工具,用于发现和评估计算机系统和网络中的安全漏洞。它是一款功能强大的商业工具,由Tenable Network Security开发和维护。 以下是Nessus的一些主要特点和功能: 1. 漏洞扫描:Nessu…

转义字符解释

也许在一些代码中你看到 \n, \0 很纳闷是啥。其实在字符中有一组特殊的字符是转义字符,转义字符顾名思义:转变原来的意思的字符。 比如:我们有字符n,在字符串中打印的时候自然能打印出这个字符,如下: #in…

通过 API 接口,实现增值税发票智能识别

增值税发票智能识别是一项应用于财务管理和数据分析的技术,通过使用API接口,我们可以轻松地将增值税发票的各项信息进行结构化识别。本文将详细介绍如何通过API接口实现增值税发票的智能识别,并给出相应的代码说明。 首先,我们需…

自动安装环境shell脚本使用和运维基础使用讲解

title: 自动安装环境shell脚本使用和运维基础使用讲解 tags: [shell,linux,运维] categories: [开发记录,系统运维] date: 2024-3-27 14:10:15 description: 准备和说明 确认有网。 依赖程序集,官网只提供32位压缩包,手动编译安装后,在64位机…

Java 新手上路常见的5个经典问题,你遇到过吗?

当我们开始学习一门新的编程语言或者开发平台时,经常会遇到一些常见的问题。这些问题不仅是学习过程中的一部分,也是成长和提高的机会。 1. 空指针异常(NullPointerException) 空指针异常是 Java 开发中最常见的问题之一。它的产…

docker学习笔记3:VmWare CentOS7安装与静态ip配置

文章目录 一、安装CentOS71、下载centos镜像2、安装二、设置静态ip三、xshell连接centos本专栏的docker环境是在centos7里安装,因此首先需要会安装centos虚拟机。 本篇博客介绍如何在vm虚拟机里安装centos7。 一、安装CentOS7 1、下载centos镜像 推荐清华源,下载如下版本 …

OpenCV4.9去运动模糊滤镜(68)

返回:OpenCV系列文章目录(持续更新中......) 上一篇:OpenCV4.9失焦去模糊滤镜(67) 下一篇 :OpenCV系列文章目录(持续更新中......) 目标 在本教程中,您将学习: 运动模糊图像的 PSF 是多少如何恢复运动模…

2024-5-3学习笔记 继承关系拓展

一.继承与友元 友元类不能继承,也就是说基类友元不能访问子类私有和保护成员。简单的理解就是,爸爸的朋友不是儿子的朋友。 二.继承与静态成员 基类定义了static静态成员,则整个继承体系里面只有一个这样的成员。无论派生出多少个子类&…

Mac 更新 Homebrew软件包时提示 zsh: command not found: brew 错误

问题 通过Mac电脑更新Homebrew软件包时出现如下错误: xxxxxxxpiaodeMacBook-Pro ~ % brew update zsh: command not found: brew解决方案 在命令行输入如下指令: /bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/H…

string(上)

目录 一、string类的简单介绍 二、string类中成员函数介绍 1.构造函数 1)string() 2)string(const string& str) 3)string(const string& str,size_t pos&…

cmake的使用方法: 多个源文件的编译

一. 简介 前面一篇文章学习了针对只有一个 .c源文件,如何编写 CMakeLists.txt内容,从而使用 cmake工具如何编译工程。文章如下: cmake的使用方法: 单个源文件的编译-CSDN博客 本文学习针对 多个 .c源文件, CMakeLists.txt文件如…

ICode国际青少年编程竞赛- Python-1级训练场-基础训练1

ICode国际青少年编程竞赛- Python-1级训练场-基础训练1 1、 Dev.step(4)2、 Dev.step(-4) Dev.step(8)3、 Dev.turnLeft() Dev.step(4)4、 Dev.step(3) Dev.turnLeft() Dev.step(-1) Dev.step(4)5、 Dev.step(-1) Dev.step(3) Dev.step(-2) Dev.turnLeft() Dev.step(…

ICode国际青少年编程竞赛- Python-1级训练场-路线规划

ICode国际青少年编程竞赛- Python-1级训练场-路线规划 1、 Dev.step(3) Dev.turnLeft() Dev.step(4)2、 Dev.step(3) Dev.turnLeft() Dev.step(3) Dev.step(-6)3、 Dev.step(-2) Dev.step(4) Dev.turnLeft() Dev.step(3)4、 Dev.step(2) Spaceship.step(2) Dev.step(3)5、…