利用随机森林对特征重要性进行评估(含实例+代码讲解)
生活随笔
收集整理的這篇文章主要介紹了
利用随机森林对特征重要性进行评估(含实例+代码讲解)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這部分主要講解一下如何使用,需要看原理的小伙伴,可以到我之前的博客:
https://blog.csdn.net/wzk4869/article/details/126379073?spm=1001.2014.3001.5501
這里只介紹用基尼指數來評價的方法:
sklearn已經幫我們封裝好了一切,我們只需要調用其中的函數即可。
一、導入數據集
import pandas as pd url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data' wine_data = pd.read_csv(url, header = None) wine_data
我們加入列名:
我們來大致看下這時一個怎么樣的數據集:
可見我們的數據集只有三個類別。
檢查一下數據是否有空數組:
wine_data.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 178 entries, 0 to 177 Data columns (total 14 columns):# Column Non-Null Count Dtype --- ------ -------------- ----- 0 Class label 178 non-null int64 1 Alcohol 178 non-null float642 Malic acid 178 non-null float643 Ash 178 non-null float644 Alcalinity of ash 178 non-null float645 Magnesium 178 non-null int64 6 Total phenols 178 non-null float647 Flavanoids 178 non-null float648 Nonflavanoid phenols 178 non-null float649 Proanthocyanins 178 non-null float6410 Color intensity 178 non-null float6411 Hue 178 non-null float6412 OD280/OD315 of diluted wines 178 non-null float6413 Proline 178 non-null int64 dtypes: float64(11), int64(3)除去class label之外共有13個特征,數據集的大小為178。常規做法,將數據集分為訓練集和測試集。
from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier x, y = wine_data.iloc[:, 1:].values, wine_data.iloc[:, 0].values x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0) feat_labels = df.columns[1:] forest = RandomForestClassifier(n_estimators=10000, random_state=0, n_jobs=-1) forest.fit(x_train, y_train)這樣一來隨機森林就訓練好了,其中已經把特征的重要性評估也做好了,我們拿出來看下。
importances = forest.feature_importances_ indices = np.argsort(importances)[::-1] for f in range(x_train.shape[1]):print("%2d) %-*s %f" % (f + 1, 30, feat_labels[indices[f]], importances[indices[f]]))輸出的結果為:
1) 10 0.1824832) 13 0.1586103) 7 0.1509484) 12 0.1319875) 1 0.1065896) 11 0.0782437) 6 0.0607188) 4 0.0320339) 2 0.025400 10) 9 0.022351 11) 5 0.022078 12) 8 0.014645 13) 3 0.013916要篩選出重要性比較高的變量的話,這么做就可以:
threshold = 0.15 x_selected = x_train[:, importances > threshold] x_selected
幫我們選好了三列數據!
總結
以上是生活随笔為你收集整理的利用随机森林对特征重要性进行评估(含实例+代码讲解)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 二维码的纠错码原理及如何纠错(2)
- 下一篇: 夜深模拟器不能连接 adb shell