首页 > 解决方案 > Python中的NLP:向量化后从SelectKBest中获取词名

问题描述

我似乎无法找到我的确切问题的答案。任何人都可以帮忙吗?

我的数据框的简化描述(“df”):它有 2 列:一个是一堆文本(“Notes”),另一个是指示解析时间是否高于平均水平的二进制变量(“y” )。

我在文本上做了词袋:

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(lowercase=True, stop_words="english")
matrix = vectorizer.fit_transform(df["Notes"])

我的矩阵是 6290 x 4650。获取单词名称(即特征名称)没有问题:

feature_names = vectorizer.get_feature_names()
feature_names

接下来,我想知道这 4650 中哪一个与高于平均分辨率的时间最相关;并减少我可能想在预测模型中使用的矩阵。我进行卡方检验以找到最重要的 20 个单词。

from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
selector = SelectKBest(chi2, k=20)
selector.fit(matrix, y)
top_words = selector.get_support().nonzero()

# Pick only the most informative columns in the data.
chi_matrix = matrix[:,top_words[0]]

现在我被困住了。我如何从这个简化的矩阵(“chi_matrix”)中得到单词?我的功能名称是什么?我正在尝试这个:

chi_matrix.feature_names[selector.get_support(indices=True)].tolist()

或者

chi_matrix.feature_names[features.get_support()]

这些给了我一个错误:未找到 feature_names。我错过了什么?

一种

标签: pythonnlpvectorization

解决方案


在弄清楚我真正想要做什么(感谢丹尼尔)并进行更多研究之后,我找到了其他几种方法来实现我的目标。

方式 1 - https://glowingpython.blogspot.com/2014/02/terms-selection-with-chi-square.html

from sklearn.feature_extraction.text import CountVectorizer
vectorizer = CountVectorizer(lowercase=True,stop_words='english')
X = vectorizer.fit_transform(df["Notes"])

from sklearn.feature_selection import chi2
chi2score = chi2(X,df['AboveAverage'])[0]

wscores = zip(vectorizer.get_feature_names(),chi2score)
wchi2 = sorted(wscores,key=lambda x:x[1]) 
topchi2 = zip(*wchi2[-20:])
show=list(topchi2)
show

方式 2 - 这是我使用的方式,因为它对我来说最容易理解并产生了一个很好的输出,列出了单词、chi2 分数和 p 值。此处的另一个线程:用于特征选择的 Sklearn Chi2

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_selection import SelectKBest, chi2

vectorizer = CountVectorizer(lowercase=True,stop_words='english')
X = vectorizer.fit_transform(df["Notes"])

y = df['AboveAverage']

# Select 10 features with highest chi-squared statistics
chi2_selector = SelectKBest(chi2, k=10)
chi2_selector.fit(X, y)

# Look at scores returned from the selector for each feature
chi2_scores = pd.DataFrame(list(zip(vectorizer.get_feature_names(), chi2_selector.scores_, chi2_selector.pvalues_)), 
                                       columns=['ftr', 'score', 'pval'])
chi2_scores

推荐阅读