我有一个数据框,其中包含一个名为“Phrase”的列。我试图在本专栏中找到20个最常用的单词。我使用以下代码执行此操作:
print(pd.Series(' '.join(film['Phrase']).lower().split()).value_counts()[:20])
这给了我以下输出:
s 16981
film 6689
movie 5905
nt 3970
one 3609
like 3071
story 2520
rrb 2438
lrb 2098
good 2043
characters 1882
much 1862
time 1747
comedy 1721
even 1597
little 1575
funny 1522
way 1511
life 1484
make 1396
我后来需要为每个单词创建矢量计数。我这样做是使用以下代码:
vectorizer = CountVectorizer()
vectorizer.fit(film['Phrase'])
print(vectorizer.vocabulary_)
我不会显示整个输出,但矢量计数与上面的输出不同。例如,对于“电影”这个词它是9308,对于'好'它是6131而对于'make'它是8655.为什么会发生这种情况?值计数方法只计算使用该单词的每一列而不是计算单词的每个出现次数吗?我误解了CountVectorizer功能在做什么吗?
vectorizer.vocabulary_
不返回单词频率,但根据文档:
术语到特征索引的映射
这意味着数据中的每个单词都会映射到一个索引,该索引存储在vectorizer.vocabulary_
中。
这是一个例子来说明正在发生的事情:
from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
df = pd.DataFrame({"a":["we love music","we love piano"]})
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(df['a'])
print(vectorizer.vocabulary_)
>>> {'we': 3, 'love': 0, 'music': 1, 'piano': 2}
该向量化识别数据中的4个单词,并为每个单词分配从0到3的索引。现在,您可能会问:“但为什么我甚至关心这些指数呢?”因为一旦完成矢量化,您需要跟踪矢量化对象中单词的顺序。例如,
X.toarray()
>>> array([[1, 1, 0, 1],
[1, 0, 1, 1]], dtype=int64)
使用词汇词典,你可以告诉第一列对应“爱”,第二列对应“音乐”,第三列对应“钢琴”,第四列对应“我们”。
注意,这也对应于vectorizer.get_feature_names()
中单词的顺序
vectorizer.get_feature_names()
>>> ['love', 'music', 'piano', 'we']
如@MaximeKan所述,CountVectorizer()
不计算每个项的频率,但我们可以从get_feature_names()
的transform()和vectorizer
属性的稀疏矩阵输出计算它。
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(film['Phrase'])
{x:y for x,y in zip(vectorizer.get_feature_names(), X.sum(0).getA1())}
工作范例:
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> corpus = [
... 'This is the first document.',
... 'This document is the second document.',
... 'And this is the third one.',
... 'Is this the first document?',
... ]
>>> vectorizer = CountVectorizer()
>>> X = vectorizer.fit_transform(corpus)
在有必要之前不要使用.toarray()
,因为它需要更多的内存大小和计算时间。我们可以直接使用稀疏矩阵得到和。
>>> list(zip(vectorizer.get_feature_names(), X.sum(0).getA1()))
[('and', 1),
('document', 4),
('first', 2),
('is', 4),
('one', 1),
('second', 1),
('the', 4),
('third', 1),
('this', 4)]