python繪製隨機森林重要度排序條形圖,以及把重要度之和前0.9顯示出來,用於觀察
前面的話:因爲項目原因,需要特徵選擇,隨機森林有自帶的重要度屬性,但是我需要觀察前0.9(此處理解爲能包含重要度之和爲0.9的前幾項特徵爲比較重要的,例如:20個特徵可以包含重要度之和0.9,八個特徵包含重要度0.1,那麼可以把這8個進行篩選)
先附上繪製後的條新圖(因爲項目保密性,具體特徵只截取部分名稱,橫座標是重要度,縱座標是特徵名稱):
對這個圖簡單說明一下:
1.橫座標是重要度,縱座標是特徵名稱
2.按照重要度排序,藍色爲末尾重要度之和爲0.1的特徵,紅色爲餘下0.9的特徵,在此也就可以理解爲最重要部分
3.每一條重要度後都加了標籤用於顯示具體數值
下面附上代碼:(一個函數)
def plot_feature_importances(feature_importances,title,feature_names,change):
print('feature_importances',feature_importances)
print('names',feature_names)
# feature_importances = 100.0*(feature_importances/max(feature_importances))
# print('feature_importances',feature_importances)
# 將得分從小到大排序
index_sorted = np.argsort(feature_importances)
print('index_sorted',index_sorted)
#特徵名稱排序
chara= change
for col in range(0,i):
chara[col] = feature_names[index_sorted[col]]
print(chara)
# 讓y座標軸上的標籤居中顯示
pos = np.arange(index_sorted.shape[0])+0.5
print(pos)
plt.figure(figsize=(16,16))
#0.9的分割數據
index1 = [i] * i
index2 = [i] * i
feature_importances = np.append(feature_importances,0)
print('feature_importances',feature_importances)
sum = 0
for col in range(0,i):
k = feature_importances[index_sorted[i-col-1]]
sum =sum+ k
index1[col] = index_sorted[i-col-1]
if (sum >= 0.9):
break
s =0
for col in range(0,i):
k = feature_importances[index_sorted[col]]
print(k)
s =s+ k
index2[col] = index_sorted[col]
if (s >= 0.1):
break
print('小於0.1',index2)
index1 = np.flipud(index1)
print('大於0.9',index1)
plt.barh(pos,feature_importances[index2],align='center')
plt.barh(pos,feature_importances[index1],align='center',color="red")
plt.yticks(pos,chara)
plt.xlabel('Relative Importance')
plt.title(title)
xlabel = feature_importances[index_sorted]
ylabel = pos
for x1, y1 in zip(xlabel,ylabel):
# 添加文本時添加偏移量使其顯示更加美觀
x1 = np.around(x1, decimals=3)
# print("座標",y1,x1)
plt.text(x1+0.00005, y1, '%.3f' % x1)
plt.show()
使用方法 plot_feature_importances(imports,'隨機森林特徵重要度排序',al,ad),四個參數,分別爲:
1.imports:一個list,每個特徵的重要度,不需要提前排序,plot_feature_importances函數中有排序算法
2.繪製圖片的title,這裏叫作 '隨機森林特徵重要度排序'
3.al,ad:一個list,都是每個特徵的名字,這裏需要和imports一一對應,比如: 第一個特徵爲A,重要度爲0.1,第二個特徵爲B,重要度爲0.9,則imports爲[0.1,0.9],al = ad 爲[A,B],即可使用繪圖代碼
最後,具體用到的包沒有標註,需要手動加入包