【问题标题】:Provide vocaburary of word with space to scikit-learn CountVectorizer为 scikit-learn CountVectorizer 提供带有空格的单词词汇表
【发布时间】:2016-10-18 18:52:24
【问题描述】:

参考这个post。我想知道我们如何为 CountVectorizer 模型提供带有空格的单词词汇表,例如distributed systems 还是 machine learning?这是一个例子:

import numpy as np
from itertools import chain

tags = [
  "python, tools",
  "linux, tools, ubuntu",
  "distributed systems, linux, networking, tools",
]

vocabulary = list(map(lambda x: x.split(', '), tags))
vocabulary = list(np.unique(list(chain(*vocabulary))))

我们可以将这个词汇表提供给模型

from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer(vocabulary=vocabulary)
print(vec.fit_transform(tags).toarray())

在这里,我失去了字数distributed systems(第一列)。结果如下:

[[0 0 0 1 1 0]
 [0 1 0 0 1 1]
 [0 1 1 0 1 0]]

我是否必须更改 token_pattern 或其他地方?

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    我认为基本上您已经预先定义了要分析的词汇表,并且您希望通过拆分 ', ' 来标记标签。

    您可以通过以下方式欺骗CountVectorizer

    from sklearn.feature_extraction.text import CountVectorizer
    vec = CountVectorizer(vocabulary=vocabulary, tokenizer=lambda x: x.split(', '))
    print(vec.fit_transform(tags).toarray())
    

    ,给出:

    [[0 0 0 1 1 0]
     [0 1 0 0 1 1]
     [1 1 1 0 1 0]]
    

    【讨论】:

    • 非常感谢@Zichen,这就是我要找的。使用tokenizer 使问题变得非常方便
    猜你喜欢
    • 2020-01-15
    • 2019-03-14
    • 2014-08-14
    • 2017-09-21
    • 2013-04-11
    • 2014-07-06
    • 2014-07-13
    • 2016-07-02
    • 2015-02-22
    相关资源
    最近更新 更多