如何将 countvectorizer 应用于 pandas 数据框中的双字母组

How to apply countvectorizer to bigrams in a pandas dataframe

我正在尝试将 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
....



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

这与 CountVectorizer 所做的有点不同;

来自功能描述:

Convert a collection of text documents to a matrix of token counts

case使用的官方例子是:

>>> 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]]

因此,如您所见,它将一个列表作为输入,其中每个术语都是 "document"。 这可能是您收到错误的原因,您看,您正在传递一个 pd.Series,其中每个术语都是一个元组列表。

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

如果您有原始的 corpus/text,您可以轻松地在其上实现 CountVectorizer(使用 ngram 参数)以获得所需的结果。

否则,最好的解决方案是按原样处理,一个带有项目列表的系列,必须是 counted/pivoted。

解决方法示例:

(如果直接使用文本语料库会容易很多)

希望对您有所帮助!