python - Python 中的自然语言处理 : Obtain word names from SelectKBest after vectorizing

标签 python nlp vectorization

我似乎无法找到我的确切问题的答案。谁能帮忙?

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

我在文本上做了词袋:

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。我错过了什么?

一个

最佳答案

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

方式 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 For Feature Selection

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

关于python - Python 中的自然语言处理 : Obtain word names from SelectKBest after vectorizing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52561244/

相关文章:

nlp - 如何在没有IOB标签的情况下使用Hugging Face的变形器管道重构文本实体?

r - read.xls-读取长度可变的工作表列表及其名称

python - 长异常链的优雅替代品?

python - unicode 文字数组

python - 如何从 pandas 数据框中的文本字符串中提取所有形容词?

python - 使用 numpy 更新节点值而不使用 for 循环

c++ - 如何在 C++ 中混合原子和非原子操作?

python - 为 dask 数据框列创建 dask 列表

python解码fernet key

java - 使用词边界和 POS 将句子拆分为固定大小的 block