python - 如何使用 Scikit Learn CountVectorizer 获取语料库中的词频?

标签 python scikit-learn

我正在尝试使用 scikit-learn 的 CountVectorizer 计算一个简单的词频。

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer

texts=["dog cat fish","dog cat cat","fish bird","bird"]
cv = CountVectorizer()
cv_fit=cv.fit_transform(texts)

print cv.vocabulary_
{u'bird': 0, u'cat': 1, u'dog': 2, u'fish': 3}

我期待它返回 {u'bird': 2, u'cat': 3, u'dog': 2, u'fish': 2}

最佳答案

cv.vocabulary_ 在这种情况下是一个字典,其中键是您找到的单词(特征),值是索引,这就是为什么它们是 0 , 1, 2, 3。只是运气不好,它看起来与您的计数相似:)

您需要使用 cv_fit 对象来获取计数

from sklearn.feature_extraction.text import CountVectorizer

texts = ["dog cat fish", "dog cat cat", "fish bird", "bird"]
cv = CountVectorizer()
cv_fit = cv.fit_transform(texts)

print(cv.get_feature_names())
print(cv_fit.toarray())
# ["bird", "cat", "dog", "fish"]
# [[0 1 1 1]
#  [0 2 1 0]
#  [1 0 0 1]
#  [1 0 0 0]]

数组中的每一行都是您的原始文档之一(字符串),每一列都是一个特征(词),元素是该特定词和文档的计数。您可以看到,如果对每一列求和,您将得到正确的数字

print(cv_fit.toarray().sum(axis=0))
# [2 3 2 2]

老实说,我建议使用 collections.Counter 或来自 NLTK 的东西,除非你有一些特定的理由使用 scikit-learn,因为它会更简单。

关于python - 如何使用 Scikit Learn CountVectorizer 获取语料库中的词频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27488446/

相关文章:

python - 当我尝试从列表中删除变量时,remove() 返回 None

python - Python FOR循环的疑问

scikit-learn - scikit学习: how to check coefficients significance

scikit-learn - 使用 sklearn 时的精确度和召回率误差

python - 修剪 sklearn 决策树以确保单调性

python - 如何知道特征影响模型预测的因素

python - 我在compose.yml中定义了一个命令,例如: “python manage.py runserver 0.0.0.0:8000”,它可以正常工作。但是当我 build

python - 为什么代码在收到响应后不执行

python - 将列从 float 转换为 int 时收到 KeyError

python - AttributeError : probability estimates are not available for loss ='hinge'