【问题标题】:How to apply countvectorizer to bigrams in a pandas dataframe如何将 countvectorizer 应用于熊猫数据框中的二元组
【发布时间】:2019-07-09 21:35:49
【问题描述】:

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



【问题讨论】:

  • 这是您拥有的数据类型以及您期望的结果的一个很好的例子 - 但如果您还包括您遇到的错误,那就更好了。

标签: nltk n-gram sklearn-pandas countvectorizer


【解决方案1】:

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

这与 CountVectorizer 所做的有点不同;

从功能说明:

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

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

因此,可以看出,它需要一个列表作为输入,其中每个术语都是一个“文档”。 这很可能是您遇到错误的原因,您看,您正在传递一个 pd.Series,其中每个术语都是一个元组列表。

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

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

否则,最好的解决方案是按原样对待它,一个包含项目列表的系列,必须计算/透视。

解决方法示例:

(如果你只使用文本语料库会容易得多)

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多