如何将countvectorizer应用于熊猫数据框中的双字母

时间:2019-02-15 17:39:46

标签: nltk n-gram sklearn-pandas countvectorizer

我正在尝试将 countvectorizer 应用于包含双字母组的数据帧,以将其转换为频率矩阵,该矩阵显示每个双字母组在每一行中出现的次数,但我不断收到错误消息。

这是我尝试使用的

cereal['bigrams'].head()

0    [(best, thing), (thing, I), (I, have),....
1    [(eat, it), (it, every), (every, morning),...
2    [(every, morning), (morning, my), (my, brother),...
3    [(I, have), (five, cartons), (cartons, lying),...
.........
bow = CountVectorizer(max_features=5000, ngram_range=(2,2))
train_bow = bow.fit_transform(cereal['bigrams'])
train_bow

Expected results


      (best,thing) (thing, I) (I, have)  (eat,it) (every,morning)....
0           1          1          1         0           0
1           0          0          0         1           1
2           0          0          0         0           1
3           0          0          1         0           0
....



1 个答案:

答案 0 :(得分:0)

我看到您正在尝试将pd.Series转换为每个术语的计数表示形式。

与CountVectorizer的功能有些不同;

根据功能描述:

  

将文本文档的集合转换为令牌计数矩阵

案例使用的官方示例是:

>>> 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)
>>> print(vectorizer.get_feature_names())
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
>>> print(X.toarray())  
[[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]

因此,正如人们所看到的,它将每个术语都是“文档”的列表作为输入。 那很可能是导致错误的原因,您看到的是,您传递的是pd.Series,其中每个术语是一个元组列表。

要使用CountVectorizer,您必须将输入转换为正确的格式。

如果您拥有原始语料库/文本,则可以在其顶部轻松实现CountVectorizer(使用ngram参数)以获得所需的结果。

否则,最好的解决方案是按原样对待包含一系列项目的序列,必须对它们进行计数/透视。

示例解决方法:

enter image description here

(如果您只是使用文本语料库,将会容易得多)

希望有帮助!