导航
×
   ❮   
HTML CSS JavaScript PHP Python C C++ Go Sass W3C Colors TypeScript ECMS

Python 教程

Python 简介 Python 历史 Python 下载安装配置 Python 入门 Python 语法 Python 语句 Python 输出 Python 注释 Python 变量 Python 数据类型 Python 数值类型 Python 类型转换 Python 字符串 Python 布尔值 Python 运算符 Python 列表 Python 元组 Python 集合 Python 字典 Python If...Else Python While 循环 Python For 循环 Python 函数 Python Range Python 数组 Python 类和对象 Python 继承 Python 迭代 Python 模块 Python 日期时间 Python 数学运算 Python JSON Python 正则表达式 Python PIP Python Try...Except Python 用户输入 Python 字符串格式化

Python 文件处理

Python 文件处理 Python 打开文件 Python 创建/写入文件 Python 删除文件

Python NumPy

NumPy 简介 NumPy 入门 NumPy 创建数组 NumPy 数组索引 NumPy 数组裁切 NumPy 数据类型 NumPy 副本 vs 视图 NumPy 数组形状 NumPy 数组重塑 NumPy 数组迭代 NumPy 数组连接 NumPy 数组拆分 NumPy 数组搜索 NumPy 数组排序 NumPy 数组过滤 NumPy 随机数 NumPy ufunc 通用函数

Python SciPy

SciPy 简介 SciPy 入门 SciPy 常量 SciPy 优化器 SciPy 稀疏数据 SciPy 图表 SciPy 空间数据 SciPy Matlab 数组 SciPy 插值 SciPy 统计显着性检验

Python 机器学习

Machine 机器学习入门 Machine 平均中位数模式 Machine 标准差 Machine 百分位数 Machine 数据分布 Machine 正态数据分布 Machine 散点图 Machine 线性回归 Machine 多项式回归 Machine 多元回归 Machine 缩放 Machine 训练/测试 Machine 决策树

Python MySQL

MySQL 入门 MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join

Python MongoDB

MongoDB 入门 MongoDB 创建数据库 MongoDB 创建集合 MongoDB 插入 MongoDB 查找 MongoDB 查询 MongoDB 排序 MongoDB 删除 MongoDB 删除集合 MongoDB 更新 MongoDB 限制

Python 参考手册

Python 参考手册 Python 内置函数 Python 字符串方法 Python 列表/数组方法 Python 字典方法 Python 元组方法 Python 集合方法 Python 文件方法 Python 关键字 Python 内置异常 Python 词汇表
Python 词汇表 Indentation Multi Line Comments Creating Variables Variable Names Output Variables String Concatenation Global Variables Built-In Data Types Getting Data Type Setting Data Type Numbers Int Float Complex Random Number Specify a Variable Type String Literals Assigning a String to a Variable Multiline Strings Strings are Arrays Slicing a String Negative Indexing on a String String Length Check In String Format String Escape Characters Evaluate Booleans Return Boolean Value Comparison Operators Identity Operators Access List Items Change List Item Loop Through List Items Check if List Item Exists List Length Add List Items Remove List Items Copy a List Join Two Lists Access Tuple Items Change Tuple Item Loop List Items Check if Tuple Item Exists Tuple Length Tuple With One Item Remove Tuple Items Join Two Tuples 访问集合项 添加集合项目 Loop Set Items 检查集合项是否存在 集合长度 删除集合项 连接两个集合 Access Dictionary Items Change Dictionary Item Loop Dictionary Items Check if Dictionary Item Exists Dictionary Length Add Dictionary Item Remove Dictionary Items Copy Dictionary Nested Dictionaries If Statement If 缩进 Elif Else 简写 If Else If AND If OR 嵌套 If If中的pass关键字 While While Break While Continue While Else Loop Through a String For Break For Continue Looping Through a rangee For Else Nested Loops For pass Call a Function *args Keyword Arguments *kwargs Default Parameter Value Passing a List as an Argument Function Return Value The pass Statement i Functions Function Recursion Why Use Lambda Functions Array What is an Array Array Length Looping Array Elements Add Array Element Remove Array Element Array Methods Class Create Class The Class __init__() Function Object Methods self Modify Object Properties Delete Object Properties Delete Object Class pass Statement Create Parent Class Create Child Class Create the __init__() Function Add Class Properties Add Class Methods Iterator vs Iterable Loop Through an Iterator Create an Iterator StopIteration Global Scope Global Keyword Create a Module Variables in Modules Renaming a Module Built-in Modules Using the dir() Function Import From Module Date Output Create a Date Object The strftime Method Date Format Codes Parse JSON Convert into JSON Format JSON Sort JSON RegEx Functions Metacharacters in RegEx RegEx Special Sequences RegEx Sets RegEx Match Object Install PIP PIP Packages PIP Remove Package Error Handling Try Else Try Finally raise Comments Assign Values to Multiple Variables Type Conversion Boolean Values Operators Arithmetic Operators Assignment Operators Logical Operators 成员运算符 Bitwise Operators Lists Tuple 集合 Dictionary 简写 If For Function Function Arguments Lambda Function super Function Iterators Datetime Module JSON RegEx Module Handle Many Exceptions Access Arrays

Python 模块参考

Python 内置模块 Python random 随机模块 Python requests 请求模块 Python statistics 统计模块 Python math 数学模块 Python cMath 模块

Python 如何使用

Python 删除列表重复项 Python 反转字符串 Python 添加两个数字

Python 实例

Python 实例 Python 测验

机器学习 - 决策树



决策树(Decision Tree)

在本章中,我们将向您展示如何制作"决策树"。决策树是一种流程图,可以帮助您根据以前的经验进行决策。

在这个例子中,一个人将尝试决定他/她是否应该参加喜剧节目。

幸运的是,我们的例中人物每次在镇上举办喜剧节目时都进行注册,并注册一些关于喜剧演员的信息,并且还登记了他/她是否去过。

Age Experience Rank Nationality Go
36 10 9 UK NO
42 12 4 USA NO
23 4 6 N NO
52 4 4 USA NO
43 21 8 USA YES
44 14 5 UK NO
66 3 7 N YES
35 14 9 UK YES
52 13 7 N YES
35 5 9 N YES
24 3 5 USA NO
18 3 7 UK YES
45 9 9 UK YES

现在,基于此数据集,Python 可以创建决策树,这个决策树可用于决定是否值得参加任何新的演出。


工作原理

首先,导入所需的模块,并使用 pandas 读取数据集:

实例

读取并打印数据集:

import pandas
from sklearn import tree
import pydotplus
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import matplotlib.image as pltimg

df = pandas.read_csv("shows.csv")

print(df)

运行实例 »

如需制作决策树,所有数据都必须是数字。

我们必须将非数字列 "Nationality" 和 "Go" 转换为数值。

Pandas 有一个 map() 方法,该方法接受字典,其中包含有关如何转换值的信息。

{'UK': 0, 'USA': 1, 'N': 2}

表示将值 'UK' 转换为 0,将 'USA' 转换为 1,将 'N' 转换为 2。

实例

将字符串值更改为数值:

d = {'UK': 0, 'USA': 1, 'N': 2}
df['Nationality'] = df['Nationality'].map(d)
d = {'YES': 1, 'NO': 0}
df['Go'] = df['Go'].map(d)

print(df)

运行实例 »

然后,我们必须将特征列与目标列分开。

特征列是我们尝试从中预测的列,目标列是具有我们尝试预测的值的列。

实例

X is the feature columns, y is the target column:

features = ['Age', 'Experience', 'Rank', 'Nationality']

X = df[features]
y = df['Go']

print(X)
print(y)

运行实例 »

现在,我们可以创建实际的决策树,使其适合我们的细节,然后在计算机上保存一个 .png 文件:

实例

创建一个决策树,将其另存为图像,然后显示该图像:

dtree = DecisionTreeClassifier()
dtree = dtree.fit(X, y)
data = tree.export_graphviz(dtree, out_file=None, feature_names=features)
graph = pydotplus.graph_from_dot_data(data)
graph.write_png('mydecisiontree.png')

img=pltimg.imread('mydecisiontree.png')
imgplot = plt.imshow(img)
plt.show()

运行实例 »


结果解释

决策树使用您先前的决策来计算您是否愿意去看喜剧演员的几率。

让我们阅读决策树的不同方面:

Rank

Rank <= 6.5 表示排名在 6.5 以下的喜剧演员将遵循 True 箭头(向左),其余的则遵循 False 箭头(向右)。

gini = 0.497 表示分割的质量,并且始终是 0.0 到 0.5 之间的数字,其中 0.0 表示所有样本均得到相同的结果,而 0.5 表示分割完全在中间进行。

samples = 13 表示在决策的这一点上还剩下 13 位喜剧演员,因为这是第一步,所以他们全部都是喜剧演员。

value = [6, 7] 表示在这 13 位喜剧演员中,有 6 位将获得 "NO",而 7 位将获得 "GO"。

Gini

分割样本的方法有很多,我们在本教程中使用 GINI 方法。

基尼方法使用以下公式:

Gini = 1 - (x/n)2 - (y/n)2

其中,x 是肯定答案的数量 ("GO"),n 是样本数量,y 是否定答案的数量 ("NO"),使用以下公式进行计算:

1 - (7 / 13)2 - (6 / 13)2 = 0.497

下一步包含两个框,其中一个框用于喜剧演员,其 'Rank' 为 6.5 或更低,其余为一个框。

True - 5 名喜剧演员在这里结束:

gini = 0.0 表示所有样本均得到相同的结果。

samples = 5 表示该分支中还剩下 5 位喜剧演员(5 位的等级为 6.5 或更低的喜剧演员)。

value = [5, 0] 表示 5 得到 "NO" 而 0 得到 "GO"。

False - 8 位戏剧演员继续:

Nationality(国籍)

Nationality <= 0.5 表示国籍值小于 0.5 的喜剧演员将遵循左箭头(这表示来自英国的所有人),其余的将遵循右箭头。

gini = 0.219 意味着大约 22% 的样本将朝一个方向移动。

samples = 8 表示该分支中还剩下 8 个喜剧演员(8 个喜剧演员的等级高于 6.5)。

value = [1, 7] 表示在这 8 位喜剧演员中,1 位将获得 "NO",而 7 位将获得 "GO"。

 
 

True - 4 名戏剧演员继续:

Age

Age <= 35.5 表示年龄在 35.5 岁或以下的喜剧演员将遵循左箭头,其余的将遵循右箭头。

gini = 0.375 意味着大约 37.5% 的样本将朝一个方向移动。

samples = 4 表示该分支中还剩下 4 位喜剧演员(来自英国的 4 位喜剧演员)。

value = [1, 3] 表示在这 4 位喜剧演员中,1 位将获得 "NO",而 3 位将获得 "GO"。

False - 4 名喜剧演员到这里结束:

gini = 0.0 表示所有样本都得到相同的结果。

samples = 4 表示该分支中还剩下 4 位喜剧演员(来自英国的 4 位喜剧演员)。

value = [0, 4] 表示在这 4 位喜剧演员中,0 将获得 "NO",而 4 将获得 "GO"。

 
 

True - 2 名喜剧演员在这里结束:

gini = 0.0 表示所有样本都得到相同的结果。

samples = 2 表示该分支中还剩下 2 名喜剧演员(2 名 35.5 岁或更年轻的喜剧演员)。

value = [0, 2] 表示在这 2 位喜剧演员中,0 将获得 "NO",而 2 将获得 "GO"。

False - 2 名戏剧演员继续:

Experience(经验)

Experience <= 9.5 表示具有 9.5 年或以上经验的喜剧演员将遵循左侧的箭头,其余的将遵循右侧的箭头。

gini = 0.5 表示 50% 的样本将朝一个方向移动。

samples = 2 表示此分支中还剩下 2 个喜剧演员(2 个年龄超过 35.5 的喜剧演员)。

value = [1, 1] 表示这两个喜剧演员中,1 将获得 "NO",而 1 将获得 "GO"。

 
 

True - 1 名喜剧演员在这里结束:

gini = 0.0 表示所有样本都得到相同的结果。

samples = 1 表示此分支中还剩下 1 名喜剧演员(1 名具有 9.5 年或以下经验的喜剧演员)。

value = [0, 1] 表示 0 表示 "NO",1 表示 "GO"。

False - 1 名喜剧演员到这里为止:

gini = 0.0 表示所有样本都得到相同的结果。

samples = 1 表示此分支中还剩下 1 位喜剧演员(其中 1 位具有超过 9.5 年经验的喜剧演员)。

value = [1, 0] 表示 1 表示 "NO",0 表示 "GO"。


预测值

我们可以使用决策树来预测新值。

例如:我是否应该去看一个由 40 岁的美国喜剧演员主演的节目,该喜剧演员有 10 年的经验,喜剧排名为 7?

实例

使用 predict() 方法来预测新值:

print(dtree.predict([[40, 10, 7, 1]]))

运行实例 »

实例

如果喜剧等级为 6,答案是什么?

print(dtree.predict([[40, 10, 6, 1]]))

运行实例 »


不同的结果

如果运行足够多次,即使您输入的数据相同,决策树也会为您提供不同的结果。

这是因为决策树无法给我们 100% 的肯定答案。它基于结果的可能性,答案会有所不同。


Copyright ©2026 蒙ICP备2026009383号 All Rights Reserved 提供的内容仅用于学习和测试,不保证内容的正确性。