Random Forests iris data to achieve

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
import matplotlib as mpl
def iris_type(s):
    it = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
    return it[s]
# 'sepal length', 'sepal width', 'petal length', 'petal width'
iris_feature = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度'
if __name__ == "__main__":
    mpl.rcParams['font.sans-serif'] = [u'SimHei']  # 黑体 FangSong/KaiTi
    mpl.rcParams['axes.unicode_minus'] = False
# 显示树
path = 'E:\pyCharmprojects\homework\iris.csv'  # 数据文件路径
iris_data = pd.read_csv(path, header=None)
x_data, y = iris_data[list(range(4))], iris_data[4]
y = pd.Categorical(y).codes #把文本数据进行编码,比如a b c编码为 0 1 2
feature_combination = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
plt.figure(figsize=(8, 6), facecolor='#FFFFFF')  # 设置图的比例
for i, combination in enumerate(feature_combination):
    # 准备数据
    x = x_data[combination]
    # 随机森林 n_estimators表示子模型的数量 criterion表示特征选择标准 max_depth 最大深度
    clf = RandomForestClassifier(n_estimators=200, criterion='entropy', max_depth=3)
    rf_clf = clf.fit(x, y.ravel())  # y.ravel()
    # 画图
    N, M = 500, 500  # 横纵各采样多少个值
    x1_min, x1_max = x[combination[0]].min(), x[combination[0]].max()  # 第0列的范围
    x2_min, x2_max = x[combination[1]].min(), x[combination[1]].max()  # 第1列的范围
    # print(x2_min, x2_max)
    t1 = np.linspace(x1_min, x1_max, N)
    t2 = np.linspace(x2_min, x2_max, M)
    x1, x2 = np.meshgrid(t1, t2)  # 生成网格采样点
    x_test = np.dstack((x1.flat, x2.flat))[0]
    y_pre = rf_clf.predict(x)
    y = y.reshape(-1)
    bingo = np.count_nonzero(y_pre == y)  # 统计预测正确的个数
    print('特征:  ', iris_feature[combination[0]], ' + ', iris_feature[combination[1]])
    print('\t准确率: %.2f%%' % ( float(bingo) / float(len(y))))
    # 显示
    cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
    cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
    y_pre = rf_clf.predict(x_test)  # 预测值
    y_pre = y_pre.reshape(x1.shape)  # 使之与输入的形状相同
    plt.subplot(2, 3, i + 1)
    plt.pcolormesh(x1, x2, y_pre, cmap=cm_light)  # 预测值
    plt.scatter(x[combination[0]], x[combination[1]], c=y, edgecolors='k', cmap=cm_dark)  # 样本
    plt.xlabel(iris_feature[combination[0]], fontsize=14)
    plt.ylabel(iris_feature[combination[1]], fontsize=14)
    plt.xlim(x1_min, x1_max)
    plt.ylim(x2_min, x2_max)
    plt.grid()
plt.tight_layout(2.5)
plt.subplots_adjust(top=0.92)
plt.suptitle(u'随机森林对鸢尾花数据特征组合的分类结果', fontsize=14, verticalalignment='bottom')
plt.show()

 

Guess you like

Origin blog.csdn.net/weixin_44179909/article/details/88055577