Iris data set classification-random forest

Random forest

Iris data set classification-decision tree
https://blog.csdn.net/weixin_42567027/article/details/107487428

Bagging + decision tree = random forest

Bagging

Bagging (bagging method):

  1. The Bootstraping method is used to randomly select n training samples from the original sample set, and k rounds of extraction are performed to obtain k training sets. (K training sets are independent of each other, and elements can be repeated)
  2. For k training sets, train k models
  3. Classification problem: the classification result is generated by voting; regression problem: the mean value of the prediction results of k models is used as the final prediction result.

data set

Insert picture description here

Code

// An highlighted block
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier

# 'sepal length', 'sepal width', 'petal length', 'petal width'
iris_feature = u'花萼长度', u'花萼宽度', u'花瓣长度', u'花瓣宽度'

if __name__ == "__main__":
    # 字体颜色:黑体 FangSong/KaiTi
    mpl.rcParams['font.sans-serif'] = [u'SimHei'] 
    mpl.rcParams['axes.unicode_minus'] = False

    '''加载数据'''
    data = pd.read_csv('F:\pythonlianxi\shuju\iris.data', header=None)
    #样本集,标签集
    x_prime = data[range(4)]
    y = pd.Categorical(data[4]).codes
    x = x_prime.iloc[:, 2:4]
    print('开始训练模型....')

    '''训练随机森林'''
    # 200棵树,深度为3
    clf = RandomForestClassifier(n_estimators=200, criterion='entropy', max_depth=10)
    clf.fit(x, y.ravel())
    #print(clf.oob_score_,)
    #测试数据
    #y_test_hat = clf.predict(x_test)      # 测试数据
    #print(y_test_hat)
    
    # 横纵坐标的采样值
    N, M = 50, 50  
    x1_min, x2_min = x.min()
    x1_max, x2_max = x.max()
    t1 = np.linspace(x1_min, x1_max, N)
    t2 = np.linspace(x2_min, x2_max, M)
     # 生成网格采样点
    x1, x2 = np.meshgrid(t1, t2) 
     # 测试点
    x_show = np.stack((x1.flat, x2.flat), axis=1) 
    
    #图形添加颜色
    cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
    cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
     # 预测值
    y_show_hat = clf.predict(x_show) 
    # 使之与输入的形状相同
    y_show_hat = y_show_hat.reshape(x1.shape)  
    
    '''绘图'''
    plt.figure(facecolor='w')
    plt.pcolormesh(x1, x2, y_show_hat, cmap=cm_light)  # 预测值的显示
    #第两列,第三列的特征
    plt.scatter(x[2], x[3], c=y.ravel(), edgecolors='k', s=40, cmap=cm_dark)  
    plt.xlabel(iris_feature[2], fontsize=15)
    plt.ylabel(iris_feature[3], fontsize=15)
    plt.xlim(x1_min, x1_max)
    plt.ylim(x2_min, x2_max)
    plt.grid(True)
    plt.title(u'鸢尾花数据的决策树分类', fontsize=17)
    plt.show()

    '''测试样本'''
    # 训练集上的预测结果
    y_hat = clf.predict(x)
    y = y.reshape(-1)
    c = np.count_nonzero(y_hat == y)  # 统计预测正确的个数
    print('\t预测正确数目:', c)
    print('\t准确率: %.2f%%' % (100 * float(c) / float(len(y))))

experiment analysis

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42567027/article/details/107488666