如何使用权重在逻辑回归中获得特征重要性?

时间:2018-07-22 07:34:34

标签: machine-learning scikit-learn logistic-regression sklearn-pandas

我有一个评论集,其类别标签为正/负。我正在将Logistic回归应用于该评论数据集。首先,我要转换为单词包。此处 sorted_data ['文本'] 评论,而 final_counts 稀疏矩阵

count_vect = CountVectorizer() 
final_counts = count_vect.fit_transform(sorted_data['Text'].values)
standardized_data = StandardScaler(with_mean=False).fit_transform(final_counts)

将数据集分为训练和测试

X_1, X_test, y_1, y_test = cross_validation.train_test_split(final_counts, labels, test_size=0.3, random_state=0)
X_tr, X_cv, y_tr, y_cv = cross_validation.train_test_split(X_1, y_1, test_size=0.3)

我正在如下应用逻辑回归算法

optimal_lambda = 0.001000
log_reg_optimal = LogisticRegression(C=optimal_lambda)

# fitting the model
log_reg_optimal.fit(X_tr, y_tr)

# predict the response
pred = log_reg_optimal.predict(X_test)

# evaluate accuracy
acc = accuracy_score(y_test, pred) * 100
print('\nThe accuracy of the Logistic Regression for C = %f is %f%%' % (optimal_lambda, acc))

我的体重是

weights = log_reg_optimal.coef_ .   #<class 'numpy.ndarray'>

array([[-0.23729528, -0.16050616, -0.1382504 , ...,  0.27291847,
         0.35857267,  0.41756443]])
(1, 38178) #shape of weights

我想了解功能的重要性,即;高权重的前100个功能。谁能告诉我如何获得它们?

2 个答案:

答案 0 :(得分:1)

研究线性分类模型中给定特征/参数的“ 影响力”或“ 重要性”的一种方法是考虑幅值系数的strong>。

这是最基本的方法其他用于发现特征重要性或参数影响的技术可以提供更多的见解,例如使用 p值自举得分,各种“判别指标”,等


在这里,您已经对数据进行了标准化,因此直接使用此功能

weights = log_reg_optimal.coef_
abs_weights = np.abs(weights)

print(abs_weights)

如果您查看原始的weights,则负系数表示相应特征的较高值会将分类推向负类。


编辑1

显示如何获取功能名称的示例:

import numpy as np

#features names
names_of_variables =np.array(['a','b','c','d'])

#create random weights and get the magnitude
weights = np.random.rand(4)
abs_weights = np.abs(weights)

#get the sorting indices
sorted_index = np.argsort(abs_weights)[::-1]

#check if the sorting indices are correct
print(abs_weights[sorted_index])

#get the index of the top-2 features
top_2 = sorted_index[:2]

#get the names of the top 2 most important features
print(names_of_variables[top_2])

答案 1 :(得分:1)

如果使用的是逻辑回归模型,则可以使用递归特征消除(RFE)方法来选择重要特征,并从预测变量列表中过滤出多余特征。 scikit-learn库中提供了此功能。您可以参考以下链接以获取详细信息:https://machinelearningmastery.com/feature-selection-machine-learning-python/

此方法根据重要性对功能进行排名,您可以选择进行进一步分析所需的前n个功能。

相关问题