1. 程式人生 > >利用隨機森林進行特徵選擇

利用隨機森林進行特徵選擇

例子是wine資料集: http://archive.ics.uci.edu/ml/machine-learning-databases/wine/ 之所以可以利用隨即森立來進行特徵篩選是由於決策樹的特性,因此我們可以利用所有決策樹得到的平均不純度(基尼係數)衰減來量化特徵的重要性。根據重要性可以剔除相關度很低的特徵,精簡模型。 接下來直接進入程式碼:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#載入資料,必要的時候可以檢視下資料的情況
source_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'
data = pd.read_csv(source_url,header=None,prefix='x') data.columns = ['cluster','Alcohol','Malic acid','Ash','Alcalinity of ash','Magnesium','Total phenols','Flavanoids','Nonflavanoid phenols','Proanthocyanins','Color intensity','Hue','OD280/OD315 of diluted wines','Proline'] #print(data.info())
#print(data.head()) #print(data.tail()) #print(data.describe())
#由於data第一列為資料集分好的標籤,先剔除。
x = data.iloc[:,1:].values
# print(x.shape)
y = data.iloc[:,0].values
from sklearn.ensemble import RandomForestClassifier
RFC = RandomForestClassifier(n_estimators=15000,n_jobs= -1 ,random_state=0)
RFC.fit(x,y)
#構造隨機森林,擬合數據。

n_estimators:森林中樹的數量 n_jobs:整數,可選(預設= 1)適合和預測並行執行的作業數。如果為-1,則將作業數設定為核心數。 關於詳細引數,可以自行檢視文件。

import_level = RFC.feature_importances_ #這個方法可以調取關於特徵重要程度
x_columns = data.columns[1:]
index = np.argsort(import_level)[::-1]
for each in range(x.shape[1]):
    print('The important level of '+ x_columns[each]+ ':      '+ str(import_level[index[each]]))
#對於最後需要逆序,個人的理解是做了類似決策樹回溯的取值。從葉子收斂到根,根部重要程度高於葉子。
#最後在視覺化以下圖
plt.figure(figsize=(10,6))
plt.title('紅酒資料集中各個特徵的重要程度',fontsize = 18)
plt.ylabel('import level',fontsize = 15,rotation = 90)
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
for i in range(x_columns.shape[0]):
    plt.bar(i,import_level[index[i]],color = 'orange',align = 'center')
    plt.xticks(np.arange(x_columns.shape[0]),x_columns,rotation = 90,fontsize = 15)

這裡寫圖片描述