Lesson 8.1 决策树的核心思想与建模流程

  • 与此前的聚类算法类似,树模型也同样不是一个模型,而是一类模型的概称。
  • 树模型不仅运算效率高、模型判别能力强、而且原理简单过程清晰、可解释性强,是机器学习领域内为数不多的白箱模型。
  • 并且就树模型本身的功能来说,除了能够同时进行分类和回归预测外,还能够产出包括特征重要性、连续变量分箱指标等重要附加结论,而在集成学习中,最为常用的基础分类器也正是树模型。
  • 正是这些优势,使得树模型成为目前机器学习领域最为重要的模型之一。

一、借助逻辑回归构建决策树

1. 决策树实例

# 科学计算模块
import numpy as np
import pandas as pd
​
# 绘图模块
import matplotlib as mpl
import matplotlib.pyplot as plt
​
# 自定义模块
from ML_basic_function import *
​
# Scikit-Learn相关模块
# 评估器类
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
​
# 实用函数
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
​
# 数据准备
from sklearn.datasets import load_iris
# 数据准备
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=24)

# 模型训练
​# 实例化模型
clf = LogisticRegression(max_iter=int(1e6), solver='saga')
# 构建参数空间
param_grid_simple = {'penalty': ['l1', 'l2'], 'C': [1, 0.5, 0.1, 0.05, 0.01]}
# 构建网格搜索评估器
search = GridSearchCV(estimator=clf, param_grid=param_grid_simple)​
# 模型训练
search.fit(X_train, y_train)
#GridSearchCV(estimator=LogisticRegression(max_iter=1000000, solver='saga'),
#             param_grid={'C': [1, 0.5, 0.1, 0.05, 0.01], 'penalty': ['l1', 'l2']})

search.best_params_
#{'C': 1, 'penalty': 'l1'}

search.best_estimator_.coef_
#array([[ 0.        ,  0.        , -3.47337669,  0.        ],
#       [ 0.        ,  0.        ,  0.        ,  0.        ],
#       [-0.55511761, -0.34237661,  3.03227709,  4.12148646]])

search.best_estimator_.intercept_
#array([ 11.85884734,   2.65291107, -14.51175841])
iris = load_iris(as_frame=True)
iris.data
#	sepal length (cm)	sepal width (cm)	petal length (cm)	petal width (cm)
#0	5.1	3.5	1.4	0.2
#1	4.9	3.0	1.4	0.2
#2	4.7	3.2	1.3	0.2
#3	4.6	3.1	1.5	0.2
#4	5.0	3.6	1.4	0.2
#...	...	...	...	...
#145	6.7	3.0	5.2	2.3
#146	6.3	2.5	5.0	1.9
#147	6.5	3.0	5.2	2.0
#148	6.2	3.4	5.4	2.3
#149	5.9	3.0	5.1	1.8
#150 rows × 4 columns

t = np.array(iris.target)
t[50:]
#array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
#       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
#       1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
#       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
#       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

# 将2、3类划归为一类
t[50:] = 1
t
#array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
#       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
#       0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
#       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
#       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
#       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
#       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

# 此处提取第3、4个特征放置二维空间进行观察,用第三个特征和其他特征组合也是类似
d = np.array(iris.data.iloc[:, 2: 4])

plt.scatter(d[:, 0], d[:, 1], c=t)
plt.plot(np.array([2.5]*25), np.arange(0, 2.5, 0.1), 'r--')

Lesson 8.1 决策树的核心思想与建模流程

Lesson 8.1 决策树的核心思想与建模流程

# 提取待分类的子数据集
X = np.array(iris.data)[t == 1]
y = np.array(iris.target)[t == 1]
C_l = np.linspace(1, 0.1, 100)

coef_l = []
​
for C in C_l:
    clf = LogisticRegression(penalty='l1', C=C, max_iter=int(1e6), solver='saga').fit(X, y)
    coef_l.append(clf.coef_.flatten())

ax = plt.gca()
ax.plot(C_l, coef_l)
ax.set_xlim(ax.get_xlim()[::-1])
plt.xlabel('C')
plt.ylabel('weights')
Text(0, 0.5, 'weights')

Lesson 8.1 决策树的核心思想与建模流程

coef_l
clf = LogisticRegression(penalty='l1', C=0.2, max_iter=int(1e6), solver='saga').fit(X, y)

clf.coef_, clf.intercept_
#(array([[0.        , 0.        , 2.84518611, 0.        ]]),
# array([-13.88186328]))

clf.score(X, y)
#0.93
b = 13.88186328 / 2.84518611
b
#4.87907038179657
plt.plot(X[:, 2][y==1], X[:, 3][y==1], 'ro')
plt.plot(X[:, 2][y==2], X[:, 3][y==2], 'bo')
plt.plot(np.array([b]*20), np.arange(0.5, 2.5, 0.1), 'r--')

Lesson 8.1 决策树的核心思想与建模流程

y_pred = clf.predict(X)

plt.scatter(X[:, 2], X[:, 3], c=y_pred)
plt.plot(np.array([b]*20), np.arange(0.5, 2.5, 0.1), 'r--')

Lesson 8.1 决策树的核心思想与建模流程

Lesson 8.1 决策树的核心思想与建模流程

1-(y != y_pred).sum() / 150
#0.9533333333333334

2. 决策树知识补充

2.1 决策树简单构建

2.2 决策树的分类过程

2.3 决策树模型本质

2.4 决策树的树生长过程

2.5 树模型的基本结构

二、决策树的分类与流派

1. ID3(Iterative Dichotomiser 3) 、C4.5、C5.0 决策树

2. CART 决策树

Lesson 8.1 决策树的核心思想与建模流程

3. CHAID 树

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年3月29日
下一篇 2023年3月29日

相关推荐