获取转换后用于分类的最重要特征的名称

2024-04-19 07:54:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中遇到了一个分类问题。我想找出分类中最重要的特征是什么。 我的数据是混合的,有些列是分类值,有些不是分类值。 我正在使用OneHotEncoderNormalizer应用转换:

columns_for_vectorization = ['A', 'B', 'C', 'D', 'E']
columns_for_normalization = ['F', 'G', 'H']

transformerVectoriser = ColumnTransformer(transformers=[('Vector Cat', OneHotEncoder(handle_unknown = "ignore"), columns_for_vectorization),
                                                        ('Normalizer', Normalizer(), columns_for_normalization)],
                                          remainder='passthrough') # Default is to drop untransformed columns

之后,我将拆分数据并进行转换:

x_train, x_test, y_train, y_test = train_test_split(features, results, test_size = 0.25, random_state=0)

x_train = transformerVectoriser.fit_transform(x_train)
x_test = transformerVectoriser.transform(x_test)

然后,我训练我的模型:

clf = RandomForestClassifier(max_depth = 5, n_estimators = 50, random_state = 0)
model = clf.fit(x_train, y_train)

我正在打印最好的功能:

print(model.feature_importances_)

我得到的结果如下:

[1.40910562e-03 1.46133832e-03 4.05058130e-03 3.92205197e-03
 2.13243521e-03 5.78555893e-03 1.51927254e-03 1.14987114e-03
 ...
 6.37840204e-04 7.21061812e-04 5.77726129e-04 5.32382587e-04]

问题是,一开始,我有8个特性,但由于转换,我有20多个特性(因为分类数据) 我该怎么办? 我如何知道什么是最重要的开始特征


Tags: columns数据testfor分类trainrandom特征
2条回答

尝试以下操作以获取“Vector Cat”transformer处理过的功能的名称:

VectorCatNames = list(transformerVectoriser.transformers_[0][1]['Vector Cat'].get_feature_names(columns_for_vectorization))

然后,最终功能的名称可以另存为:

feature_names = VectorCatNames + columns_for_normalization

github gist似乎表示可以通过以下方法获得拟合/变换后的列:

numeric_features = X.select_dtypes(np.number).columns

enc_cat_features = transformerVectorizer.named_transformers_['Vector cat'].get_feature_names()
labels = np.concatenate([numeric_features, enc_cat_features])
transformed_df_X = pd.DataFrame(preprocessor.transform(X_train).toarray(), columns=labels)
# To access your data - transformed_df_X
# To access your columns - transformed_df_X.columns

如果由于“subscriptable”错误而无法通过ColumnTransformer使其正常工作,则可以直接在OneHotEncoder对象上执行此操作

通常我也会在事后处理这些名称,因为OneHotEncoder会自动给出难看的名称

无论如何,一旦您可以访问X.columns东西,您就可以对功能重要性做任何您喜欢的事情。我用功能名称绘制它们的示例代码使用了permutation_importance,但显然feature_importance给出了相同的结构,因此您可能会有一些运气,这对您来说很有用

from sklearn.inspection import permutation_importance
import matplotlib.pyplot as plt

def plot_feature_importance(model, X_train, y_train, feature_names):
   result = permutation_importance(model, X_train, y_train, n_repeats=10)
   perm_sorted_idx = result.importances_mean.argsort()

   fig, ax2 = plt.subplots(1, 1, figsize=(5, 15))
   ax2.boxplot(result.importances[perm_sorted_idx].T, vert=False,
               labels=feature_names[perm_sorted_idx])
   fig.tight_layout()
   plt.show()

在带有随机林的UCI ML horse colic集合上,这给了我一个带有分类&;数字名称如下:

Box plot showing features AbdomenClass4, RectTemp, AbdominalDistension3, CapillaryRefillTime1, PeripheralPulse3 as key features

相关问题 更多 >