유방암 데이터셋에서 변환 중요도 분석

Beginner

This tutorial is from open-source community. Access the source code

소개

이 실습에서는 sklearn.inspectionpermutation_importance 함수를 사용하여 위스콘신 유방암 데이터셋에 순열 중요도를 적용하는 방법을 보여줍니다. 랜덤 포레스트 분류기를 사용하여 데이터를 분류하고 테스트 세트에서 정확도를 계산합니다. 또한 계층적 군집화를 사용하여 특징의 다중 공선성을 처리하는 방법도 보여줍니다.

VM 팁

VM 시작이 완료되면 왼쪽 상단 모서리를 클릭하여 Notebook 탭으로 전환하여 연습용 Jupyter Notebook에 접근합니다.

때때로 Jupyter Notebook 이 로드되는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한으로 인해 작업의 유효성 검사를 자동화할 수 없습니다.

학습 중 문제가 발생하면 Labby 에게 문의하십시오. 세션 후 피드백을 제공하면 문제를 신속하게 해결해 드리겠습니다.

랜덤 포레스트 분류기 학습

먼저 위스콘신 유방암 데이터셋을 불러와서 학습용과 테스트용 데이터셋으로 분할합니다. 그런 다음 학습 데이터셋으로 랜덤 포레스트 분류기를 학습하고 테스트 데이터셋에서 정확도를 평가합니다.

data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)
print("Accuracy on test data: {:.2f}".format(clf.score(X_test, y_test)))

특징 중요도 시각화

트리 기반 특징 중요도와 순열 중요도를 시각화합니다. 순열 중요도 플롯은 특징을 섞으면 정확도가 최대 0.012 만큼 감소한다는 것을 보여주는데, 이는 특징 중 중요한 것이 없다는 것을 시사합니다. 이는 위에서 계산된 높은 테스트 정확도와 모순됩니다. 몇몇 특징은 중요해야 합니다. 순열 중요도는 학습 과정에서 모델이 각 특징에 얼마나 의존하는지 보여주기 위해 학습 데이터셋에서 계산됩니다.

result = permutation_importance(clf, X_train, y_train, n_repeats=10, random_state=42)
perm_sorted_idx = result.importances_mean.argsort()

tree_importance_sorted_idx = np.argsort(clf.feature_importances_)
tree_indices = np.arange(0, len(clf.feature_importances_)) + 0.5

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 8))
ax1.barh(tree_indices, clf.feature_importances_[tree_importance_sorted_idx], height=0.7)
ax1.set_yticks(tree_indices)
ax1.set_yticklabels(data.feature_names[tree_importance_sorted_idx])
ax1.set_ylim((0, len(clf.feature_importances_)))
ax2.boxplot(
    result.importances[perm_sorted_idx].T,
    vert=False,
    labels=data.feature_names[perm_sorted_idx],
)
fig.tight_layout()
plt.show()

Handle Multicollinear Features

When features are collinear, permuting one feature will have little effect on the model's performance because it can get the same information from a correlated feature. One way to handle multicollinear features is by performing hierarchical clustering on the Spearman rank-order correlations, picking a threshold, and keeping a single feature from each cluster. First, we plot a heatmap of the correlated features.

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 8))
corr = spearmanr(X).correlation

## Ensure the correlation matrix is symmetric
corr = (corr + corr.T) / 2
np.fill_diagonal(corr, 1)

## We convert the correlation matrix to a distance matrix before performing
## hierarchical clustering using Ward's linkage.
distance_matrix = 1 - np.abs(corr)
dist_linkage = hierarchy.ward(squareform(distance_matrix))
dendro = hierarchy.dendrogram(
    dist_linkage, labels=data.feature_names.tolist(), ax=ax1, leaf_rotation=90
)
dendro_idx = np.arange(0, len(dendro["ivl"]))

ax2.imshow(corr[dendro["leaves"], :][:, dendro["leaves"]])
ax2.set_xticks(dendro_idx)
ax2.set_yticks(dendro_idx)
ax2.set_xticklabels(dendro["ivl"], rotation="vertical")
ax2.set_yticklabels(dendro["ivl"])
fig.tight_layout()
plt.show()

다중 공선성 특징 처리

특징들이 공선성이 있을 때, 한 특징을 섞어도 상관관계가 있는 다른 특징으로부터 같은 정보를 얻을 수 있기 때문에 모델의 성능에 미치는 영향이 작습니다. 다중 공선성 특징을 처리하는 한 가지 방법은 Spearman 순위 상관관계에 대한 계층적 군집화를 수행하고 임계값을 선택한 후 각 군집에서 하나의 특징만 선택하는 것입니다. 먼저 상관관계가 있는 특징의 히트맵을 그립니다.

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 8))
corr = spearmanr(X).correlation

## 상관 행렬이 대칭이 되도록 합니다.
corr = (corr + corr.T) / 2
np.fill_diagonal(corr, 1)

## 계층적 군집화를 수행하기 전에 상관 행렬을 거리 행렬로 변환합니다.
## Ward 의 연결을 사용하여 계층적 군집화를 수행합니다.
distance_matrix = 1 - np.abs(corr)
dist_linkage = hierarchy.ward(squareform(distance_matrix))
dendro = hierarchy.dendrogram(
    dist_linkage, labels=data.feature_names.tolist(), ax=ax1, leaf_rotation=90
)
dendro_idx = np.arange(0, len(dendro["ivl"]))

ax2.imshow(corr[dendro["leaves"], :][:, dendro["leaves"]])
ax2.set_xticks(dendro_idx)
ax2.set_yticks(dendro_idx)
ax2.set_xticklabels(dendro["ivl"], rotation="vertical")
ax2.set_yticklabels(dendro["ivl"])
fig.tight_layout()
plt.show()

요약

이 실험에서는 랜덤 포레스트 분류기를 사용하여 위스콘신 유방암 데이터 세트에서 특징 중요도를 계산하기 위해 변환 중요도를 사용하는 방법을 보여주었습니다. 계층적 군집화를 사용하여 다중 공선성 특징을 처리하는 방법도 보여주었습니다.