机器学习之决策树随机森林

决策树

什么是决策树

决策树,就以二叉树为例,关键是选取哪一个特征进行分类,以及选好特征之后,怎么进行分类。
首先要取决于信息熵,算出父节点的信息熵,以及该节点的子节点的平均信息熵。
H(y) - H(y | x) = gain(y | x) 的差值就是信息增益。
哪个特征的信息增益大,就选那个特征。

在这里插入图片描述

决策树的特点

在这里插入图片描述

信息熵

看相关文档,在此不做解释。

在这里插入图片描述

H(y) - H(y | x) = gain(y | x) 的差值就是信息增益

ID3(决策树) : 使用信息增益率作为特征选取的标准。得到的决策树

信息增益率: gain(y | x) / H(x)

CART(决策树)

使用gini系数作为特征值的选取度量,得到的决策树。
在这里插入图片描述

随机森林

  1. 在n个样本中,随机选择若干个样本(随机选择的过程中也可能重复选择一个样本),组成n个样本,然后使用n个样本采用信息增益率等的方式选择特征,然后生成一个决策树。
  2. 以相同的方式生成多个决策树,然后组成一个随机森林。
  3. 随机森林采用少数服从多数原则,决定预测的结果。

注意:在随机森林生成的过程中,有两个随机,第一:样本选择的随机,第二是特征选取的随机。
但是在特征选取,取最优的情况,生成随机森林不一定是最好的,可以采取在特征选取的过程中,让其犯错误,
比如选取百分制70的特征进行信息增率的比较,参数是DecisionTreeClassifier(max_features = 0.8) 表示选取80%的特征值

OOB数据

在这里插入图片描述
在这里插入图片描述

相关问题

在这里插入图片描述

代码实现

https://blog.csdn.net/zsdust/article/details/79726118

#!/usr/bin/python
# -*- coding:utf-8 -*-

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

if __name__ == "__main__":
    mpl.rcParams['font.sans-serif'] = ['SimHei']  #用来正常显示中文标签
    mpl.rcParams['axes.unicode_minus'] = False  #用来正常显示负号

    iris_feature = '花萼长度', '花萼宽度', '花瓣长度', '花瓣宽度'
    path = 'iris.data'  # 数据文件路径
    data = pd.read_csv(path, header=None)
    x_prime = data[list(range(4))]
    # print(x_prime)
    # 将读取的数据类型按照索引从0开始,进行数值的替换,相同的数据使用相同的索引
    y = pd.Categorical(data[4]).codes
    # print(y)
    # 将数据分成训练集,测试集,test_size=0.3占百分之30。random_state要赋任意一个值,保证随机数相同。
    x_prime_train, x_prime_test, y_train, y_test = train_test_split(x_prime, y, test_size=0.3, random_state=0)

    feature_pairs = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
    # figsize=(8, 6):指的图像的宽和高  facecolor:背景颜色
    plt.figure(figsize=(8, 6), facecolor='#FFFFFF')
    # enumerate 获取数组的下标
    for i, pair in enumerate(feature_pairs):
        # 准备数据
        x_train = x_prime_train[pair]
        x_test = x_prime_test[pair]

        # 决策树学习  n_estimators:森林中树木的数量。 criterion:使用信息增量作为特征选取的度量 max_depth:树的最大深度  oob_score:使用袋外数据
        model = RandomForestClassifier(n_estimators=100, criterion='entropy', max_depth=5, oob_score=True)
        model.fit(x_train, y_train)

        # 画图
        N, M = 500, 500  # 横纵各采样多少个值
        x1_min, x2_min = x_train.min()
        x1_max, x2_max = x_train.max()
        t1 = np.linspace(x1_min, x1_max, N)
        t2 = np.linspace(x2_min, x2_max, M)
        x1, x2 = np.meshgrid(t1, t2)  # 生成网格采样点,二维数组
        # 沿着新轴连接数组的序列。(x1.flat, x2.flat)有两个,就是2维,axis表示维数放的位置
        x_show = np.stack((x1.flat, x2.flat), axis=1)  # 测试点

        # 训练集上的预测结果
        y_train_pred = model.predict(x_train)
        # 计算准确率,衡量模型好坏的度量单位
        acc_train = accuracy_score(y_train, y_train_pred)
        # 测试集上的预测结果
        y_test_pred = model.predict(x_test)
        acc_test = accuracy_score(y_test, y_test_pred)

        print('特征:', iris_feature[pair[0]], ' + ', iris_feature[pair[1]])
        print('OOB Score:', model.oob_score_)
        print('\t训练集准确率: %.4f%%' % (100*acc_train))
        print('\t测试集准确率: %.4f%%\n' % (100*acc_test))

        # 颜色映射(colormap)功能
        cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
        cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
        y_hat = model.predict(x_show)
        y_hat = y_hat.reshape(x1.shape)
        print(y_hat)
        plt.subplot(2, 3, i+1)
        plt.contour(x1, x2, y_hat, colors='k', levels=[0, 1], antialiased=True, linestyles='--', linewidths=1)

        # 绘制分类图
        plt.pcolormesh(x1, x2, y_hat, cmap=cm_light)  # 预测值
        # 绘制散点图
        plt.scatter(x_train[pair[0]], x_train[pair[1]], c=y_train, s=20, edgecolors='k', cmap=cm_dark, label='训练集')
        plt.scatter(x_test[pair[0]], x_test[pair[1]], c=y_test, s=100, marker='*', edgecolors='k', cmap=cm_dark, label='测试集')

        plt.xlabel(iris_feature[pair[0]], fontsize=12) # x轴标题
        plt.ylabel(iris_feature[pair[1]], fontsize=12) # y轴标题
        # plt.legend(loc='upper right', fancybox=True, framealpha=0.3)
        plt.xlim(x1_min, x1_max) # x轴数值范围
        plt.ylim(x2_min, x2_max) # y轴数值范围
        # 显示网格 b:1、true   axis='x'只显示x轴网格线  color:网格颜色
        plt.grid(b=True, ls=':', color='#606060')
    # 总图像的标题
    plt.suptitle('随机森林对鸢尾花数据两特征组合的分类结果', fontsize=15)
    # 自动调整子图参数,使之填充整个图像区域
    plt.tight_layout(1, rect=(0, 0, 1, 0.95))    # (left, bottom, right, top)
    # 显示图像
    plt.show()

绘图plt

https://blog.csdn.net/zsdust/article/details/79726118

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值