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

Python中進行特征重要性分析的九個常用方法

人工智能 機器學習
特征重要性分析用于了解每個特征(變量或輸入)對于做出預測的有用性或價值。目標是確定對模型輸出影響最大的最重要的特征,它是機器學習中經(jīng)常使用的一種方法。

特征重要性分析用于了解每個特征(變量或輸入)對于做出預測的有用性或價值。目標是確定對模型輸出影響最大的最重要的特征,它是機器學習中經(jīng)常使用的一種方法。

為什么特征重要性分析很重要?

如果有一個包含數(shù)十個甚至數(shù)百個特征的數(shù)據(jù)集,每個特征都可能對你的機器學習模型的性能有所貢獻。但是并不是所有的特征都是一樣的。有些可能是冗余的或不相關(guān)的,這會增加建模的復雜性并可能導致過擬合。

特征重要性分析可以識別并關(guān)注最具信息量的特征,從而帶來以下幾個優(yōu)勢:

  • 改進的模型性能
  • 減少過度擬合
  • 更快的訓練和推理
  • 增強的可解釋性

下面我們深入了解在Python中的一些特性重要性分析的方法。

特征重要性分析方法

1、排列重要性 PermutationImportance

該方法會隨機排列每個特征的值,然后監(jiān)控模型性能下降的程度。如果獲得了更大的下降意味著特征更重要

from sklearn.datasets import load_breast_cancer
 from sklearn.ensemble import RandomForestClassifier
 from sklearn.inspection import permutation_importance 
 from sklearn.model_selection import train_test_split
 import matplotlib.pyplot as plt
 
 cancer = load_breast_cancer()
 
 X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state=1)
 
 rf = RandomForestClassifier(n_estimators=100, random_state=1)
 rf.fit(X_train, y_train) 
 
 baseline = rf.score(X_test, y_test)
 result = permutation_importance(rf, X_test, y_test, n_repeats=10, random_state=1, scoring='accuracy')
 
 importances = result.importances_mean
 
 # Visualize permutation importances
 plt.bar(range(len(importances)), importances)
 plt.xlabel('Feature Index')
 plt.ylabel('Permutation Importance')
 plt.show()

2、內(nèi)置特征重要性(coef_或feature_importances_)

一些模型,如線性回歸和隨機森林,可以直接輸出特征重要性分數(shù)。這些顯示了每個特征對最終預測的貢獻。

from sklearn.datasets import load_breast_cancer
 from sklearn.ensemble import RandomForestClassifier
 
 X, y = load_breast_cancer(return_X_y=True)
 
 rf = RandomForestClassifier(n_estimators=100, random_state=1)
 rf.fit(X, y)
 
 importances = rf.feature_importances_
 
 # Plot importances
 plt.bar(range(X.shape[1]), importances)
 plt.xlabel('Feature Index') 
 plt.ylabel('Feature Importance')
 plt.show()

3、Leave-one-out

迭代地每次刪除一個特征并評估準確性。

from sklearn.datasets import load_breast_cancer
 from sklearn.model_selection import train_test_split
 from sklearn.ensemble import RandomForestClassifier
 from sklearn.metrics import accuracy_score
 import matplotlib.pyplot as plt
 import numpy as np
 
 # Load sample data
 X, y = load_breast_cancer(return_X_y=True)
 
 # Split data into train and test sets
 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) 
 
 # Train a random forest model
 rf = RandomForestClassifier(n_estimators=100, random_state=1)
 rf.fit(X_train, y_train)
 
 # Get baseline accuracy on test data
 base_acc = accuracy_score(y_test, rf.predict(X_test))
 
 # Initialize empty list to store importances
 importances = []
 
 # Iterate over all columns and remove one at a time
 for i in range(X_train.shape[1]):
    X_temp = np.delete(X_train, i, axis=1)
    rf.fit(X_temp, y_train)
    acc = accuracy_score(y_test, rf.predict(np.delete(X_test, i, axis=1)))
    importances.append(base_acc - acc)
     
 # Plot importance scores    
 plt.bar(range(len(importances)), importances)
 plt.show()

4、相關(guān)性分析

計算各特征與目標變量之間的相關(guān)性。相關(guān)性越高的特征越重要。

import pandas as pd
 from sklearn.datasets import load_breast_cancer
 
 X, y = load_breast_cancer(return_X_y=True)
 df = pd.DataFrame(X, columns=range(30))
 df['y'] = y
 
 correlations = df.corrwith(df.y).abs()
 correlations.sort_values(ascending=False, inplace=True)
 
 correlations.plot.bar()

5、遞歸特征消除 Recursive Feature Elimination

遞歸地刪除特征并查看它如何影響模型性能。刪除時會導致更大下降的特征更重要。

from sklearn.ensemble import RandomForestClassifier
 from sklearn.feature_selection import RFE
 import pandas as pd
 from sklearn.datasets import load_breast_cancer
 import matplotlib.pyplot as plt
 
 X, y = load_breast_cancer(return_X_y=True)
 df = pd.DataFrame(X, columns=range(30))
 df['y'] = y
 
 rf = RandomForestClassifier()
 
 rfe = RFE(rf, n_features_to_select=10) 
 rfe.fit(X, y)
 
 print(rfe.ranking_)

輸出為[6 4 11 12 7 11 18 21 8 16 10 3 15 14 19 17 20 13 11 11 12 9 11 5 11]

6、XGBoost特性重要性

計算一個特性用于跨所有樹拆分數(shù)據(jù)的次數(shù)。更多的分裂意味著更重要。

import xgboost as xgb
 import pandas as pd
 from sklearn.datasets import load_breast_cancer
 import matplotlib.pyplot as plt
 
 X, y = load_breast_cancer(return_X_y=True)
 df = pd.DataFrame(X, columns=range(30))
 df['y'] = y
 
 model = xgb.XGBClassifier()
 model.fit(X, y)
 
 importances = model.feature_importances_
 importances = pd.Series(importances, index=range(X.shape[1])) 
 importances.plot.bar()

7、主成分分析 PCA

對特征進行主成分分析,并查看每個主成分的解釋方差比。在前幾個組件上具有較高負載的特性更為重要。

from sklearn.decomposition import PCA
 import pandas as pd
 from sklearn.datasets import load_breast_cancer
 import matplotlib.pyplot as plt
 
 X, y = load_breast_cancer(return_X_y=True)
 df = pd.DataFrame(X, columns=range(30))
 df['y'] = y
 
 pca = PCA()
 pca.fit(X)
 
 plt.bar(range(pca.n_components_), pca.explained_variance_ratio_) 
 plt.xlabel('PCA components')
 plt.ylabel('Explained Variance')

8、方差分析 ANOVA

使用f_classif()獲得每個特征的方差分析f值。f值越高,表明特征與目標的相關(guān)性越強。

from sklearn.feature_selection import f_classif
 import pandas as pd
 from sklearn.datasets import load_breast_cancer
 import matplotlib.pyplot as plt
 
 X, y = load_breast_cancer(return_X_y=True)
 df = pd.DataFrame(X, columns=range(30))
 df['y'] = y
 
 fval = f_classif(X, y)
 fval = pd.Series(fval[0], index=range(X.shape[1]))
 fval.plot.bar()

9、卡方檢驗

使用chi2()獲得每個特征的卡方統(tǒng)計信息。得分越高的特征越有可能獨立于目標。

from sklearn.feature_selection import chi2
 import pandas as pd
 from sklearn.datasets import load_breast_cancer
 import matplotlib.pyplot as plt
 
 X, y = load_breast_cancer(return_X_y=True)
 df = pd.DataFrame(X, columns=range(30))
 df['y'] = y
 
 chi_scores = chi2(X, y)
 chi_scores = pd.Series(chi_scores[0], index=range(X.shape[1]))
 chi_scores.plot.bar()

為什么不同的方法會檢測到不同的特征?

不同的特征重要性方法有時可以識別出不同的特征是最重要的,這是因為:

1、他們用不同的方式衡量重要性:

有的使用不同特特征進行預測,監(jiān)控精度下降

像XGBOOST或者回國模型使用內(nèi)置重要性來進行特征的重要性排列

而PCA著眼于方差解釋

2、不同模型有不同模型的方法:

線性模型傾向于線性關(guān)系、樹模型傾向于接近根的特征

3、交互作用:

有的方法可以獲取特征之間的相互左右,而有一些則不行,這就會導致結(jié)果的差異

3、不穩(wěn)定:

使用不同的數(shù)據(jù)子集,重要性值可能在同一方法的不同運行中有所不同,這是因為數(shù)據(jù)差異決定的

4、Hyperparameters:

通過調(diào)整超參數(shù),如PCA組件或樹深度,也會影響結(jié)果

所以不同的假設(shè)、偏差、數(shù)據(jù)處理和方法的可變性意味著它們并不總是在最重要的特征上保持一致。

選擇特征重要性分析方法的一些最佳實踐

  • 嘗試多種方法以獲得更健壯的視圖
  • 聚合結(jié)果的集成方法
  • 更多地關(guān)注相對順序,而不是絕對值
  • 差異并不一定意味著有問題,檢查差異的原因會對數(shù)據(jù)和模型有更深入的了解
責任編輯:華軒 來源: DeepHub IMBA
相關(guān)推薦

2021-04-16 20:46:21

PythonXGBoost 特征

2009-12-25 15:00:48

WPF軟件

2009-11-25 17:36:38

PHP函數(shù)includ

2018-11-06 09:31:34

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

2019-09-27 09:56:31

軟件技術(shù)硬件

2009-09-28 13:23:00

CCNA學習方法CCNA

2009-08-05 15:26:23

需求分析

2023-10-24 11:07:57

2010-07-30 16:28:06

2009-09-14 15:50:17

CCNA學習方法

2021-02-04 06:30:26

Python編程語言

2013-08-08 10:10:06

備份策略全備份增量備份

2020-08-27 07:00:00

代碼軟件應(yīng)用程序

2017-12-29 10:14:48

IT項目

2024-08-27 11:35:49

2011-07-05 18:30:44

站內(nèi)優(yōu)化

2024-06-24 21:18:48

2011-07-03 19:58:34

SEO

2016-08-29 20:31:17

2009-03-03 17:25:41

點贊
收藏

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