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

mer*_*kle 5 machine-learning scikit-learn logistic-regression sklearn-pandas

我有一个评论数据集,其类别标签为正面/负面。我正在对该评论数据集应用逻辑回归。首先,我正在转换成词袋。这里sorted_data['Text']评论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)
Run Code Online (Sandbox Code Playgroud)

将数据集拆分为训练和测试

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)
Run Code Online (Sandbox Code Playgroud)

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

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))
Run Code Online (Sandbox Code Playgroud)

我的体重是

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
Run Code Online (Sandbox Code Playgroud)

我想获得特征重要性,即;前 100 个具有高权重的特征。谁能告诉我如何获得它们?

mak*_*kis 10

调查“的一种方式影响”或“重要的线性分类模型给定的特征/参数”是考虑大小的的系数

这是最基本的做法其他用于查找特征重要性或参数影响的技术可以提供更多洞察,例如使用p 值引导分数、各种“判别指数”等。


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

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

print(abs_weights)
Run Code Online (Sandbox Code Playgroud)

如果您查看原始数据,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])
Run Code Online (Sandbox Code Playgroud)