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

How to get feature importance in logistic regression using weights?

我有一个评论数据集,其 class 标签为 positive/negative。我正在对该评论数据集应用逻辑回归。首先,我正在转换成词袋。这里 sorted_data['Text']reviewsfinal_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 个特征。谁能告诉我如何获得它们?

调查给定特征/参数在线性 [=51= 中的“影响”或“重要性”的一种方法]化模型是考虑系数幅度

这是最基本的做法用于查找特征重要性或参数影响的其他技术 可以提供更多见解,例如使用 p 值bootstrap 分数,各种 "discriminative indices",等等


这里,你已经标准化了数据所以直接使用这个:

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

print(abs_weights)

如果您查看原始 weights,那么负系数意味着相应特征的较高值会将 class 化推向负 class。


编辑 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])

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

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