python代码实现决策树分类

0. 前言

上一篇博客对决策树算法的思想作了描述,也详细写了如何构造一棵决策树。现在希望用python代码来实现它。此处先调用机器学习中的算法库来实现。

2. python代码实现决策树(决策树分类器–DecisionTreeClassifier)

Example1

先用一些简单的数据来进行预测。

在这里插入图片描述

这里的数据是通过天气是否晴朗和交通是否拥堵来决定是否前往旅行;

天气交通状况是否前往

新的待预测的样本(阴天,)这里需要预测的这个新的样本只有一个属性,另一个属性值为空。

from sklearn import tree
# 1. 数据
X = [[1, 0], [1, 1]]  # 1表示晴天,0表示拥堵
y = [0, 1]  # 标签
# 2. 调用决策树模型
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)  # 拟合
# 预测
predict_y = clf.predict([[0, -1]])  # -1表示这个属性为空
print("新样本预测结果:", predict_y)

输出结果:

新样本预测结果: [0]

根据结果可以看到,根据该样本的特征,预测其标签为0,即不会前往(取消)。与实际的结果也是相符的!

from sklearn import tree
# 1. 数据
X = [[1, 0], [1, 1]]  # 1表示晴天,0表示拥堵
y = [0, 1]  # 标签
# 2. 调用决策树模型
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)  # 拟合
# 预测每个类的概率
# predict_y = clf.predict([[0, -1]])
predict_y = clf.predict_proba([[0, -1]])  # -1表示这个属性为空
print("新样本预测结果:", predict_y)

这段代码与上面的区别是predict_y = clf.predict_proba([[0, -1]]),这里的predict_proba表示预测每个类的概率,输出结果如下:

新样本预测结果: [[1. 0.]]
Example2

前边是自己创建的简单数据进行预测,这里使用已有鸢尾花数据集进行验证。

from sklearn.datasets import load_iris
from sklearn import model_selection
from sklearn.tree import DecisionTreeClassifier

# 加载鸢尾花数据集
dataSet = load_iris()
X = dataSet.data
y = dataSet.target
# print(X)
# print(y)
# 划分数据集
X_trainer, X_test, Y_trainer, Y_test = model_selection.train_test_split(X, y, test_size=0.2)
clf = DecisionTreeClassifier()
clf = clf.fit(X_trainer, Y_trainer)  # 拟合
predict_y = clf.predict(X_test)
print("对测试集样本的预测结果:\n", predict_y)
predict_y1 = clf.predict_proba(X_test)
print("预测样本为某个标签的概率:\n", predict_y1)


运行结果:

对测试集样本的预测结果:
 [2 1 1 2 2 2 2 2 0 2 2 1 0 1 1 0 0 1 1 0 1 2 0 2 1 1 1 0 1 0]
预测样本为某个标签的概率:
 [[0. 0. 1.]
 [0. 1. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [0. 0. 1.]
 [0. 0. 1.]
 [0. 0. 1.]
 [0. 0. 1.]
 [1. 0. 0.]
 [0. 0. 1.]
 [0. 0. 1.]
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 1. 0.]
 [0. 1. 0.]
 [1. 0. 0.]
 [1. 0. 0.]
 [0. 1. 0.]
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 0. 0.]
 [0. 0. 1.]
 [0. 1. 0.]
 [0. 1. 0.]
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 1. 0.]
 [1. 0. 0.]]

3. python代码实现决策树(决策树回归–DecisionTreeRegressor)

  1. 准备数据集

# 1. 准备数据
X = np.linspace(1, 5, num=300).reshape(300, 1)
# print(X)
y = np.sin(X)
# print(y)

numpy.linspace()用法:主要用于创建等差数列,这里对它的参数进行如下说明:
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

  • start:表示开始数据点
  • stop:表示数据结束点
  • num:表示生成样本数据的数量,默认num的值为50
  • endpoint:值为True表示包含数据结束点stop,为False不包含
  • retstep:若为True,输出会给出公差,即数据间隔量
  • dtype:输出数组的类型

这里通过一小段代码进行演示:

import numpy as np
X = np.linspace(1, 3, num=5, endpoint=True, retstep=True)
print(X)

结果输出:

# (array([1. , 1.5, 2. , 2.5, 3. ]), 0.5)

根据结果可以看到,是从1-3生成等差数列,公差为0.5,且endpoint=True,所以包含了3;

import numpy as np
X = np.linspace(1, 3, num=5,  endpoint=False, retstep=True)
print(X)

结果输出:

# (array([1. , 1.4, 1.8, 2.2, 2.6]), 0.4)

根据结果可以看到,是从1-3生成等差数列,公差为0.4,且endpoint=False,所以结束点不包含3;

reshape()函数:主要用于改变数组的形状,但需要注意该函数的参数乘积要等于数组中的数据总数。
此处仍然用一小段代码演示:

import numpy as np
X = np.linspace(1, 10, num=6)
print("before:", X)
Y = np.linspace(1, 10, num=6).reshape(6, 1)
print("later:\n", Y)

输出结果:

before: [ 1.   2.8  4.6  6.4  8.2 10. ]
later:
 [[ 1. ]
 [ 2.8]
 [ 4.6]
 [ 6.4]
 [ 8.2]
 [10. ]]

由结果可以看到,我们将1X6的矩阵重新构造成了6X1的矩阵。

  1. 调用算法
# 2. 调用决策树模型
# max_depth指明树的深度
model = DecisionTreeRegressor(max_depth=5)
# 训练
model.fit(X, y)
# 3. 数据准确率,即得分
print("准确率:", model.score(X, y))

  1. 可视化
# 预测值
h5 = model.predict(X)
# 可视化
plt.scatter(X, y)
plt.plot(X, h5, c='r')
plt.show()
  1. 完整代码
"""决策树算法"""
import numpy as np
from sklearn.tree import DecisionTreeRegressor
from matplotlib import pyplot as plt

# 1. 准备数据
X = np.linspace(1, 5, num=300).reshape(300, 1)
# print(X)
y = np.sin(X)
# print(y)

# 2. 调用决策树模型
# max_depth指明树的深度
model = DecisionTreeRegressor(max_depth=5)
# 训练
model.fit(X, y)
# 3. 数据准确率,即得分
print("准确率:", model.score(X, y))
# 预测值
h5 = model.predict(X)
# 可视化
plt.scatter(X, y)
plt.plot(X, h5, c='r')
plt.show()

结果:

准确率: 0.9993712866996124

在这里插入图片描述

  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的决策树分类器的Python代码实现: ```python import numpy as np class DecisionTree: def __init__(self, max_depth=None): self.max_depth = max_depth def fit(self, X, y): self.tree = self.build_tree(X, y) def predict(self, X): y_pred = [] for x in X: node = self.tree while node["feature"] is not None: if x[node["feature"]] <= node["threshold"]: node = node["left"] else: node = node["right"] y_pred.append(node["class"]) return y_pred def build_tree(self, X, y, depth=0): num_samples, num_features = X.shape num_classes = len(np.unique(y)) if depth == self.max_depth or num_classes == 1 or num_samples < 2: return {"feature": None, "threshold": None, "left": None, "right": None, "class": np.bincount(y).argmax()} best_feature, best_threshold = self.find_best_split(X, y) left_indices = X[:, best_feature] <= best_threshold right_indices = X[:, best_feature] > best_threshold left = self.build_tree(X[left_indices], y[left_indices], depth+1) right = self.build_tree(X[right_indices], y[right_indices], depth+1) return {"feature": best_feature, "threshold": best_threshold, "left": left, "right": right, "class": None} def find_best_split(self, X, y): num_samples, num_features = X.shape best_gini = 1 best_feature = None best_threshold = None for feature in range(num_features): thresholds = np.unique(X[:, feature]) for threshold in thresholds: left_indices = X[:, feature] <= threshold right_indices = X[:, feature] > threshold if left_indices.sum() == 0 or right_indices.sum() == 0: continue left_classes = y[left_indices] right_classes = y[right_indices] gini = left_classes.size/num_samples * self.gini(left_classes) + right_classes.size/num_samples * self.gini(right_classes) if gini < best_gini: best_gini = gini best_feature = feature best_threshold = threshold return best_feature, best_threshold def gini(self, y): _, counts = np.unique(y, return_counts=True) proportions = counts / y.size return 1 - np.sum(proportions ** 2) ``` 这个决策树分类器使用的是基于基尼指数的二元切分,即将每个特征的所有值作为划分阈值进行尝试,并计算每个划分的基尼指数,选取基尼指数最小的划分作为最优划分。`fit`函数用于拟合模型,建立决策树。`predict`函数用于预测新数据点的类别。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值