如何在朴素贝叶斯中获得特征重要性?

2024-04-26 04:39:24 发布

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

我有一个评论的数据集,它有一个正面/负面的类标签。我正在将Naive Bayes应用到评论数据集。首先,我要变成一袋文字。这里排序的数据['Text']是评论,而最终计数是稀疏矩阵

count_vect = CountVectorizer() 
final_counts = count_vect.fit_transform(sorted_data['Text'].values)

我正在把数据分成训练和测试数据集。

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

我应用朴素贝叶斯算法如下

optimal_alpha = 1
NB_optimal = BernoulliNB(alpha=optimal_aplha)

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

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

# evaluate accuracy
acc = accuracy_score(y_test, pred) * 100
print('\nThe accuracy of the NB classifier for k = %d is %f%%' % (optimal_aplha, acc))

这里X_测试是一个测试数据集,pred变量给出X_测试中的向量是正类还是负类。

X U测试形状为(54626行,82343维)

pred的长度为54626

我的问题是我想得到每个向量中概率最高的单词,这样我就可以通过单词知道为什么它预测为正类或负类。因此,如何得到每个向量中概率最高的词呢?


Tags: the数据texttestcount评论optimal向量
2条回答

通过使用coefs_feature_log_prob_属性,可以从fit模型中获取每个单词的重要信息。例如

neg_class_prob_sorted = NB_optimal.feature_log_prob_[0, :].argsort()
pos_class_prob_sorted = NB_optimal.feature_log_prob_[1, :].argsort()

print(np.take(count_vect.get_feature_names(), neg_class_prob_sorted[:10]))
print(np.take(count_vect.get_feature_names(), pos_class_prob_sorted[:10]))

为每门课打印出十个最具预测性的单词。

试试这个:

pred_proba = NB_optimal.predict_proba(X_test)
words = np.take(count_vect.get_feature_names(), pred_proba.argmax(axis=1))

相关问题 更多 >