>  기사  >  기술 주변기기  >  일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

王林
王林앞으로
2023-09-22 12:09:03730검색

특성 중요도 분석은 예측 시 각 특성(변수 또는 입력)의 유용성이나 가치를 이해하는 데 사용됩니다. 모델 출력에 가장 큰 영향을 미치는 가장 중요한 특징을 식별하는 것이 목표이며, 머신러닝에서 자주 사용되는 방법입니다.

일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

특성 중요도 분석이 중요한 이유는 무엇인가요?

수십 또는 수백 개의 특성이 포함된 데이터 세트가 있는 경우 각 특성은 기계 학습 모델의 성능에 기여할 수 있습니다. 그러나 모든 기능이 동일하게 생성되는 것은 아닙니다. 일부는 중복되거나 관련성이 없을 수 있으며, 이로 인해 모델링 복잡성이 증가하고 과적합이 발생할 수 있습니다.

기능 중요도 분석은 가장 유용한 기능을 식별하고 이에 집중할 수 있으므로 다음과 같은 이점이 있습니다. 1. 통찰력 제공: 특징의 중요성을 분석함으로써 데이터의 어떤 특징이 결과에 가장 큰 영향을 미치는지에 대한 통찰력을 얻을 수 있으므로 데이터의 성격을 더 잘 이해하는 데 도움이 됩니다. 2. 모델 최적화: 주요 기능을 식별함으로써 모델 성능을 최적화하고 불필요한 컴퓨팅 및 스토리지 오버헤드를 줄이며 모델의 훈련 및 예측 효율성을 향상시킬 수 있습니다. 3. 특징 선택: 특징 중요도 분석은 예측력이 가장 높은 특징을 선택하는 데 도움이 되므로 모델의 정확도와 일반화 능력이 향상됩니다. 4. 모델 설명: 특성 중요도 분석은 모델의 예측 결과를 설명하고, 모델 이면의 패턴과 인과 관계를 밝히고, 모델의 해석성을 향상시키는 데도 도움이 됩니다. 함께

  • 더 빠른 학습 및 추론
  • 향상된 해석 가능성
  • Python에서 기능 중요도 분석의 몇 가지 방법을 자세히 살펴보겠습니다.
  • Feature 중요도 분석 방법

1. Permutation Importance PermutationImportance

이 방법은 각 특성의 값을 무작위로 배열한 후 모델 성능 저하 정도를 모니터링합니다. 감소량이 클수록 특성이 더 중요하다는 의미입니다
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. 내장된 특성 중요도(coef_ 또는 feature_importances_)

선형 회귀 및 랜덤 포레스트와 같은 일부 모델은 다음을 수행할 수 있습니다. 특성 중요도 점수를 직접 출력합니다. 이는 최종 예측에 대한 각 기능의 기여도를 보여줍니다.

일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

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

한 번에 하나의 특징을 반복적으로 제거하고 정확성을 평가합니다.

일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

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. 상관 분석

다시 작성해야 할 것은: 특성과 대상 변수 간의 상관 관계를 계산하는 것입니다. 상관 관계가 높을수록 특성이 더 중요합니다

일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

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. 재귀적 특징 제거

재귀적으로 특징을 제거하고 모델 성능에 어떤 영향을 미치는지 확인하세요. 제거 시 더 큰 방울이 발생하는 기능이 더 중요합니다.

일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

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입니다.

계산하다 one 데이터를 분할할 때 모든 트리에서 기능이 사용되는 횟수입니다. 분할이 많을수록 중요합니다

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')
일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

8. 분산 분산 분석

f_classif()를 사용하여 각 특성의 분산 f 값 분석을 얻습니다. f 값이 높을수록 특징과 목표 간의 상관 관계가 더 강해집니다.

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가지 Python 기능 중요도 분석 방법

9. 카이제곱 테스트

chi2() 함수를 사용하여 각 특성의 카이제곱 통계를 구합니다. 점수가 높은 기능은 대상 변수에 독립적일 가능성이 더 높습니다

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()

일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법

为什么不同的方法会检测到不同的特征?

由于不同的特征重要性方法,有时可以确定哪些特征是最重要的

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

有的使用不同特特征进行预测,监控精度下降

像XGBOOST或者回归模型使用内置重要性来进行特征的重要性排序

而PCA着眼于方差解释

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

线性模型偏向于处理线性关系,而树模型则更倾向于捕捉接近根节点的特征

3、交互作用:

有些方法可以获取特征之间的相互关系,而有些方法则不行,这会导致结果的不同

3、不稳定:

使用不同的数据子集,重要性值可能在同一方法的不同运行中有所不同,这是因为数据差异决定的

4、Hyperparameters:

通过调整超参数,例如主成分分析(PCA)组件或决策树的深度,也会对结果产生影响

所以不同的假设、偏差、数据处理和方法的可变性意味着它们并不总是在最重要的特征上保持一致。

选择特征重要性分析方法的一些最佳实践

  • 尝试多种方法以获得更健壮的视图
  • 聚合结果的集成方法
  • 更多地关注相对顺序,而不是绝对值
  • 差异并不一定意味着有问题,检查差异的原因会对数据和模型有更深入的了解

위 내용은 일반적으로 사용되는 9가지 Python 기능 중요도 분석 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 51cto.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제