下面介绍随机森林处理鸢尾花数据的python实践,不清楚随机森林原理的科研参考我的笔记https://blog.csdn.net/qq_43468729/article/details/84722248
开始撸代码~~
首先导入相关包并进行数据预处理
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.ensemble import RandomForestClassifier
def iris_type(s):
it = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}
return it[s.decode('utf-8')]
# '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 = '..\\8.Regression\\8.iris.data' # 数据文件路径
data = np.loadtxt(path, dtype=float, delimiter=',', converters={4: iris_type})
x_prime, y = np.split(data, (4,), axis=1)
feature_pairs = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
plt.figure(figsize=(10, 9), facecolor='#FFFFFF')
接着随机对特征集中取两个特征进行建模
x = x_prime[:, pair]
# 随机森林 200颗树 以熵下降最快为准则 深度为4
clf = RandomForestClassifier(n_estimators=200, criterion='entropy', max_depth=4)
rf_clf = clf.fit(x, y.ravel())
此处随机森林的参数可以选择以叶子结点的样本数为条件,这里选择的是决策树的深度
画图:
y_hat = rf_clf.predict(x)
y = y.reshape(-1)
c = np.count_nonzero(y_hat == y) # 统计预测正确的个数
print ('特征: ', iris_feature[pair[0]], ' + ', iris_feature[pair[1]],)
print ('\t预测正确数目:', c,)
print ('\t准确率: %.2f%%' % (100 * float(c) / float(len(y))))
# 显示
cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
y_hat = rf_clf.predict(x_test) # 预测值
y_hat = y_hat.reshape(x1.shape) # 使之与输入的形状相同
plt.subplot(2, 3, i+1)
plt.pcolormesh(x1, x2, y_hat, cmap=cm_light) # 预测值
plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', cmap=cm_dark) # 样本
plt.xlabel(iris_feature[pair[0]], fontsize=14)
plt.ylabel(iris_feature[pair[1]], fontsize=14)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.grid()
由于设置了200颗数,四个特征两两组合有六种情况,运算的速度稍微有点慢
最后可以得到如下数据 从图中可以看到 选择 花瓣长度 + 花瓣宽度特征预测最为准确
特征: 花萼长度 + 花萼宽度
预测正确数目: 125
准确率: 83.33%
特征: 花萼长度 + 花瓣长度
预测正确数目: 144
准确率: 96.00%
特征: 花萼长度 + 花瓣宽度
预测正确数目: 146
准确率: 97.33%
特征: 花萼宽度 + 花瓣长度
预测正确数目: 145
准确率: 96.67%
特征: 花萼宽度 + 花瓣宽度
预测正确数目: 144
准确率: 96.00%
特征: 花瓣长度 + 花瓣宽度
预测正确数目: 145
准确率: 96.67%