下面介紹隨機森林處理鳶尾花數據的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%