日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

利用随机森林对特征重要性进行评估(含实例+代码讲解)

發布時間:2023/12/8 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 利用随机森林对特征重要性进行评估(含实例+代码讲解) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這部分主要講解一下如何使用,需要看原理的小伙伴,可以到我之前的博客:

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.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash','Alcalinity of ash', 'Magnesium', 'Total phenols','Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins','Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] wine_data


我們來大致看下這時一個怎么樣的數據集:

import numpy as np np.unique(wine_data['Class label'])


可見我們的數據集只有三個類別。

檢查一下數據是否有空數組:

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


幫我們選好了三列數據!

總結

以上是生活随笔為你收集整理的利用随机森林对特征重要性进行评估(含实例+代码讲解)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。