1. 程式人生 > >【Machine Learning】使用隨機森林進行特徵選擇

【Machine Learning】使用隨機森林進行特徵選擇

一、特徵選擇

        在我們做特徵工程時,當我們提取完特徵後,可能存在並不是所有的特徵都能分類起到作用的問題,這個時候就需要使用特徵選擇的方法選出相對重要的特徵用於構建分類器。此外,使用特徵選擇這一步驟也大大減少了訓練的時間,而且模型的擬合能力也不會出現很大的降低問題。

        在特徵選擇的許多方法中,我們可以使用隨機森林模型中的特徵重要屬性來篩選特徵,並得到其與分類的相關性。由於隨機森林存在的固有隨機性,該模型可能每次給予特徵不同的重要性權重。但是通過多次訓練該模型,即每次通過選取一定量的特徵與上次特徵中的交集進行保留,以此迴圈一定次數,從而我們最後可以得到一定量對分類任務的影響有重要貢獻的特徵。

二、程式碼示例

# -*- coding: utf-8 -*-

import numpy as np
from sklearn.ensemble import RandomForestClassifier
import pickle
import matplotlib.pyplot as plt

with open('training_df.pkl', 'rb') as f:
    df = pickle.load(f)
print("data loaded")

y = df["y"]                                   #獲取標籤列
X = df.drop("y", axis=1)                      #剩下的所有特徵

for i in range(10):                           #這裡我們進行十次迴圈取交集
    tmp = set()
    rfc = RandomForestClassifier(n_jobs=-1)
    rfc.fit(X, y)
    print("training finished")

    importances = rfc.feature_importances_
    indices = np.argsort(importances)[::-1]   # 降序排列
    for f in range(X.shape[1]):
        if f < 50:                            #選出前50個重要的特徵
            tmp.add(X.columns[indices[f]])
        print("%2d) %-*s %f" % (f + 1, 30, X.columns[indices[f]], importances[indices[f]]))

    selected_feat_names &= tmp
    print(len(selected_feat_names), "features are selected")

plt.title("Feature Importance")
plt.bar(range(X.shape[1]),
        importances[indices],
        color='lightblue',
        align='center')
plt.xticks(range(X.shape[1]),
           X.columns[indices],
           rotation=90)
plt.xlim([-1, X.shape[1]])
plt.tight_layout()
plt.show()
 

with open(r'selected_feat_names.pkl', 'wb') as f:
    pickle.dump(list(selected_feat_names), f)