自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

用 XGBoost 在 Python 中進(jìn)行特征重要性分析和特征選擇

開發(fā) 后端
使用諸如梯度增強(qiáng)之類的決策樹方法的集成的好處是,它們可以從訓(xùn)練有素的預(yù)測模型中自動提供特征重要性的估計。

 

本文轉(zhuǎn)載自微信公眾號「Python中文社區(qū)」,作者沂水寒城。轉(zhuǎn)載本文請聯(lián)系Python中文社區(qū)公眾號。

使用諸如梯度增強(qiáng)之類的決策樹方法的集成的好處是,它們可以從訓(xùn)練有素的預(yù)測模型中自動提供特征重要性的估計。

在本文中,您將發(fā)現(xiàn)如何使用Python中的XGBoost庫來估計特征對于預(yù)測性建模問題的重要性,閱讀這篇文章后,您將知道:

  • 如何使用梯度提升算法計算特征重要性。
  • 如何繪制由XGBoost模型計算的Python中的特征重要性。
  • 如何使用XGBoost計算的特征重要性來執(zhí)行特征選擇。

梯度提升中的特征重要性

使用梯度增強(qiáng)的好處是,在構(gòu)建增強(qiáng)后的樹之后,檢索每個屬性的重要性得分相對簡單。通常,重要性提供了一個分?jǐn)?shù),該分?jǐn)?shù)指示每個特征在模型中構(gòu)建增強(qiáng)決策樹時的有用性或價值。用于決策樹的關(guān)鍵決策使用的屬性越多,其相對重要性就越高。

此重要性是針對數(shù)據(jù)集中的每個屬性明確計算得出的,從而可以對屬性進(jìn)行排名并進(jìn)行相互比較。單個決策樹的重要性是通過每個屬性拆分點(diǎn)提高性能指標(biāo)的數(shù)量來計算的,并由節(jié)點(diǎn)負(fù)責(zé)的觀察次數(shù)來加權(quán)。性能度量可以是用于選擇拆分點(diǎn)的純度(基尼系數(shù)),也可以是其他更特定的誤差函數(shù)。然后,將特征重要性在模型中所有決策樹之間平均。有關(guān)如何在增強(qiáng)型決策樹中計算特征重要性的更多技術(shù)信息,請參見《統(tǒng)計學(xué)習(xí)的要素:數(shù)據(jù)挖掘,推理和預(yù)測》(第367頁)第10.13.1節(jié)“預(yù)測變量的相對重要性”。另外,請參見Matthew Drury對StackOverflow問題“ Boosting的相對變量重要性”的回答,在此他提供了非常詳細(xì)和實(shí)用的答案。

手動繪制特征重要性

訓(xùn)練有素的XGBoost模型會自動計算出您的預(yù)測建模問題中的特征重要性。這些重要性分?jǐn)?shù)可在訓(xùn)練模型的feature_importances_成員變量中獲得。例如,可以按如下所示直接打印它們:

  1. print(model.feature_importances_) 

我們可以將這些得分直接繪制在條形圖上,以直觀表示數(shù)據(jù)集中每個特征的相對重要性。例如:

 

  1. # plot 
  2. pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_) 
  3. pyplot.show() 

 

我們可以通過在皮馬印第安人發(fā)病的糖尿病數(shù)據(jù)集上訓(xùn)練XGBoost模型并根據(jù)計算出的特征重要性創(chuàng)建條形圖來證明這一點(diǎn)。

下載數(shù)據(jù)集并將其放置在當(dāng)前工作目錄中。

數(shù)據(jù)集文件:

https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.csv

數(shù)據(jù)集詳細(xì)信息:

https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.names

 

  1. # plot feature importance manually 
  2. from numpy import loadtxt 
  3. from xgboost import XGBClassifier 
  4. from matplotlib import pyplot 
  5. load data 
  6. dataset = loadtxt('pima-indians-diabetes.csv', delimiter=","
  7. # split data into X and y 
  8. X = dataset[:,0:8] 
  9. y = dataset[:,8] 
  10. # fit model no training data 
  11. model = XGBClassifier() 
  12. model.fit(X, y) 
  13. # feature importance 
  14. print(model.feature_importances_) 
  15. # plot 
  16. pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_) 
  17. pyplot.show() 

 

注意:由于算法或評估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會有所不同??紤]運(yùn)行該示例幾次并比較平均結(jié)果。

首先運(yùn)行此示例將輸出重要性分?jǐn)?shù)。

 

  1. [ 0.089701    0.17109634  0.08139535  0.04651163  0.10465116  0.2026578 0.1627907   0.14119601] 

我們還獲得了相對重要性的條形圖。

該圖的缺點(diǎn)是要素按其輸入索引而不是其重要性排序。我們可以在繪制之前對特征進(jìn)行排序。

值得慶幸的是,有一個內(nèi)置的繪圖函數(shù)可以幫助我們。

使用內(nèi)置XGBoost特征重要性圖XGBoost庫提供了一個內(nèi)置函數(shù),可以按重要性順序繪制要素。該函數(shù)稱為plot_importance(),可以按以下方式使用:

  1. # plot feature importance 
  2. plot_importance(model) 
  3. pyplot.show() 

例如,以下是完整的代碼清單,其中使用內(nèi)置的plot_importance()函數(shù)繪制了Pima Indians數(shù)據(jù)集的特征重要性。

  1. # plot feature importance using built-in function 
  2. from numpy import loadtxt 
  3. from xgboost import XGBClassifier 
  4. from xgboost import plot_importance 
  5. from matplotlib import pyplot 
  6. load data 
  7. dataset = loadtxt('pima-indians-diabetes.csv', delimiter=","
  8. # split data into X and y 
  9. X = dataset[:,0:8] 
  10. y = dataset[:,8] 
  11. # fit model no training data 
  12. model = XGBClassifier() 
  13. model.fit(X, y) 
  14. # plot feature importance 
  15. plot_importance(model) 
  16. pyplot.show() 

注意:由于算法或評估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會有所不同。考慮運(yùn)行該示例幾次并比較平均結(jié)果。

運(yùn)行該示例將為我們提供更有用的條形圖。

您可以看到,要素是根據(jù)它們在F0至F7的輸入數(shù)組(X)中的索引自動命名的。手動將這些索引映射到問題描述中的名稱,可以看到該圖顯示F5(體重指數(shù))具有最高的重要性,而F3(皮膚褶皺厚度)具有最低的重要性。

XGBoost特征重要性評分的特征選擇

特征重要性評分可用于scikit-learn中的特征選擇。這是通過使用SelectFromModel類完成的,該類采用一個模型,并且可以將數(shù)據(jù)集轉(zhuǎn)換為具有選定要素的子集。此類可以采用預(yù)訓(xùn)練的模型,例如在整個訓(xùn)練數(shù)據(jù)集上進(jìn)行訓(xùn)練的模型。然后,它可以使用閾值來確定要選擇的特征。當(dāng)您在SelectFromModel實(shí)例上調(diào)用transform()方法以一致地選擇訓(xùn)練數(shù)據(jù)集和測試數(shù)據(jù)集上的相同要素時,將使用此閾值。

在下面的示例中,我們首先訓(xùn)練,然后分別在整個訓(xùn)練數(shù)據(jù)集和測試數(shù)據(jù)集上評估XGBoost模型。使用從訓(xùn)練數(shù)據(jù)集計算出的特征重要性,然后將模型包裝在SelectFromModel實(shí)例中。我們使用它來選擇訓(xùn)練數(shù)據(jù)集上的特征,從選定的特征子集中訓(xùn)練模型,然后在測試集上評估模型,并遵循相同的特征選擇方案。

例如:

  1. select features using threshold 
  2. selection = SelectFromModel(model, threshold=thresh, prefit=True
  3. select_X_train = selection.transform(X_train) 
  4. # train model 
  5. selection_model = XGBClassifier() 
  6. selection_model.fit(select_X_train, y_train) 
  7. # eval model 
  8. select_X_test = selection.transform(X_test) 
  9. y_pred = selection_model.predict(select_X_test) 

出于興趣,我們可以測試多個閾值,以根據(jù)特征重要性選擇特征。具體來說,每個輸入變量的特征重要性,從本質(zhì)上講,使我們能夠按重要性測試每個特征子集,從所有特征開始,到具有最重要特征的子集結(jié)束。

下面提供了完整的代碼清單:

  1. # use feature importance for feature selection 
  2. from numpy import loadtxt 
  3. from numpy import sort 
  4. from xgboost import XGBClassifier 
  5. from sklearn.model_selection import train_test_split 
  6. from sklearn.metrics import accuracy_score 
  7. from sklearn.feature_selection import SelectFromModel 
  8. load data 
  9. dataset = loadtxt('pima-indians-diabetes.csv', delimiter=","
  10. # split data into X and y 
  11. X = dataset[:,0:8] 
  12. Y = dataset[:,8] 
  13. # split data into train and test sets 
  14. X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=7) 
  15. # fit model on all training data 
  16. model = XGBClassifier() 
  17. model.fit(X_train, y_train) 
  18. # make predictions for test data and evaluate 
  19. y_pred = model.predict(X_test) 
  20. predictions = [round(value) for value in y_pred] 
  21. accuracy = accuracy_score(y_test, predictions) 
  22. print("Accuracy: %.2f%%" % (accuracy * 100.0)) 
  23. # Fit model using each importance as a threshold 
  24. thresholds = sort(model.feature_importances_) 
  25. for thresh in thresholds: 
  26.  # select features using threshold 
  27.  selection = SelectFromModel(model, threshold=thresh, prefit=True
  28.  select_X_train = selection.transform(X_train) 
  29.  # train model 
  30.  selection_model = XGBClassifier() 
  31.  selection_model.fit(select_X_train, y_train) 
  32.  # eval model 
  33.  select_X_test = selection.transform(X_test) 
  34.  y_pred = selection_model.predict(select_X_test) 
  35.  predictions = [round(value) for value in y_pred] 
  36.  accuracy = accuracy_score(y_test, predictions) 
  37.  print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (thresh, select_X_train.shape[1], accuracy*100.0)) 

請注意,如果您使用的是XGBoost 1.0.2(可能還有其他版本),則XGBClassifier類中存在一個錯誤,該錯誤會導(dǎo)致錯誤:

  1. KeyError: 'weight' 

這可以通過使用自定義XGBClassifier類來解決,該類為coef_屬性返回None。下面列出了完整的示例。

  1. # use feature importance for feature selection, with fix for xgboost 1.0.2 
  2. from numpy import loadtxt 
  3. from numpy import sort 
  4. from xgboost import XGBClassifier 
  5. from sklearn.model_selection import train_test_split 
  6. from sklearn.metrics import accuracy_score 
  7. from sklearn.feature_selection import SelectFromModel 
  8.   
  9. # define custom class to fix bug in xgboost 1.0.2 
  10. class MyXGBClassifier(XGBClassifier): 
  11.  @property 
  12.  def coef_(self): 
  13.   return None 
  14.   
  15. load data 
  16. dataset = loadtxt('pima-indians-diabetes.csv', delimiter=","
  17. # split data into X and y 
  18. X = dataset[:,0:8] 
  19. Y = dataset[:,8] 
  20. # split data into train and test sets 
  21. X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=7) 
  22. # fit model on all training data 
  23. model = MyXGBClassifier() 
  24. model.fit(X_train, y_train) 
  25. # make predictions for test data and evaluate 
  26. predictions = model.predict(X_test) 
  27. accuracy = accuracy_score(y_test, predictions) 
  28. print("Accuracy: %.2f%%" % (accuracy * 100.0)) 
  29. # Fit model using each importance as a threshold 
  30. thresholds = sort(model.feature_importances_) 
  31. for thresh in thresholds: 
  32.  # select features using threshold 
  33.  selection = SelectFromModel(model, threshold=thresh, prefit=True
  34.  select_X_train = selection.transform(X_train) 
  35.  # train model 
  36.  selection_model = XGBClassifier() 
  37.  selection_model.fit(select_X_train, y_train) 
  38.  # eval model 
  39.  select_X_test = selection.transform(X_test) 
  40.  predictions = selection_model.predict(select_X_test) 
  41.  accuracy = accuracy_score(y_test, predictions) 
  42.  print("Thresh=%.3f, n=%d, Accuracy: %.2f%%" % (thresh, select_X_train.shape[1], accuracy*100.0)) 

注意:由于算法或評估程序的隨機(jī)性,或者數(shù)值精度的差異,您的結(jié)果可能會有所不同??紤]運(yùn)行該示例幾次并比較平均結(jié)果。

運(yùn)行此示例將打印以下輸出。

  1. Accuracy: 77.95% 
  2. Thresh=0.071, n=8, Accuracy: 77.95% 
  3. Thresh=0.073, n=7, Accuracy: 76.38% 
  4. Thresh=0.084, n=6, Accuracy: 77.56% 
  5. Thresh=0.090, n=5, Accuracy: 76.38% 
  6. Thresh=0.128, n=4, Accuracy: 76.38% 
  7. Thresh=0.160, n=3, Accuracy: 74.80% 
  8. Thresh=0.186, n=2, Accuracy: 71.65% 
  9. Thresh=0.208, n=1, Accuracy: 63.78% 

我們可以看到,模型的性能通常隨所選特征的數(shù)量而降低。

在此問題上,需要權(quán)衡測試集精度的特征,我們可以決定采用較不復(fù)雜的模型(較少的屬性,例如n = 4),并接受估計精度的適度降低,從77.95%降至76.38%。

這可能是對這么小的數(shù)據(jù)集的洗禮,但是對于更大的數(shù)據(jù)集并使用交叉驗(yàn)證作為模型評估方案可能是更有用的策略。

 

責(zé)任編輯:武曉燕 來源: Python中文社區(qū)
相關(guān)推薦

2023-09-18 15:54:56

Python機(jī)器學(xué)習(xí)

2024-08-27 11:35:49

2017-09-19 22:36:39

XGBoostLR 算法

2009-12-25 15:00:48

WPF軟件

2009-08-05 15:26:23

需求分析

2024-08-13 11:59:07

2009-11-25 17:36:38

PHP函數(shù)includ

2023-02-26 18:46:35

機(jī)器學(xué)習(xí)數(shù)據(jù)集算法

2018-11-06 09:31:34

物聯(lián)網(wǎng)分析AoT物聯(lián)網(wǎng)

2024-05-30 16:37:29

2021-06-05 08:04:26

機(jī)器學(xué)習(xí)CARTOptimal

2021-12-22 23:12:19

物聯(lián)網(wǎng)隱私安全

2021-04-09 10:02:29

機(jī)器學(xué)習(xí)人工智能計算機(jī)

2019-09-27 09:56:31

軟件技術(shù)硬件

2023-09-08 07:01:08

機(jī)器學(xué)習(xí)監(jiān)控ML

2020-04-27 21:44:39

物聯(lián)網(wǎng)開發(fā)物聯(lián)網(wǎng)IOT

2020-08-26 10:42:15

IIoT智能工廠工業(yè)物聯(lián)網(wǎng)

2009-09-14 15:50:17

CCNA學(xué)習(xí)方法

2021-11-22 11:40:05

人工智能物聯(lián)網(wǎng)商業(yè)

2021-12-20 11:02:13

勒索軟件攻擊網(wǎng)絡(luò)安全
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號