我是靠谱客的博主 开心泥猴桃,最近开发中收集的这篇文章主要介绍CountVectorizer解决 报错empty vocabulary,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

在使用CountVectorizer的时候,出现了错误ValueError: empty vocabulary; perhaps the documents only contain stop words。先看下出现问题的代码:

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
df = pd.DataFrame(['1 2 3 4', '2 3'])
cv.fit(df[0])

上述代码会报错,原因是,创建CountVectorizer实例时,有一个默认参数analyzer=‘word’,在该参数作用下,词频矩阵构建过程会默认过滤所有的单字token,所以上面的’1 2 3 4’以空格分隔以后全是单字,也就全被过滤了,所以就empty vocabulary了。

修改代码,之后继续测试

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
df = pd.DataFrame(['12 23 34 45', '23 34'])
cv.fit(df[0])
cv.transform(df[0]).toarray()

array([[1, 1, 1, 1],
       [0, 1, 1, 0]])

但是这样我们就没办法处理单字符,接下来看看如何对analyer进行修改,我们看下函数的介绍

analyzer : string, {'word', 'char', 'char_wb'} or callable
       Whether the feature should be made of word or character n-grams.
       Option 'char_wb' creates character n-grams only from text inside
       word boundaries; n-grams at the edges of words are padded with space.
   
       If a callable is passed it is used to extract the sequence of features
       out of the raw, unprocessed input.

从上面看到,CountVectorizer提供了三种方式,word,char和char_wb,我们再看下char

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
df = pd.DataFrame(['ab cd ef g h', 'cd ef g'])
cv = CountVectorizer(analyzer='char')
cv.fit(df[0])
cv.transform(df[0]).toarray()
cv.vocabulary_

输出结果为:

array([[4, 1, 1, 1, 1, 1, 1, 1, 1],
       [2, 0, 0, 1, 1, 1, 1, 1, 0]])
{'a': 1, 'b': 2, ' ': 0, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}

对于char_wb,我自己没他搞懂,看来暂时没有找到通过analyer解决word和char同时使用的方法,之后继续查找资料了解可以通过正则的方式来解决,具体解决代码如下

from sklearn.feature_extraction.text import CountVectorizer
import pandas as pd
df = pd.DataFrame(['ab cd ef g h', 'cd ef g'])
cv = CountVectorizer(analyzer='word',token_pattern=u"(?u)\b\w+\b")
cv.fit(df[0])
cv.transform(df[0]).toarray()
cv.vocabulary_

输出结果如下:

array([[1, 1, 1, 1, 1],
       [0, 1, 1, 1, 0]])
{'ab': 0, 'cd': 1, 'ef': 2, 'g': 3, 'h': 4}

最后

以上就是开心泥猴桃为你收集整理的CountVectorizer解决 报错empty vocabulary的全部内容,希望文章能够帮你解决CountVectorizer解决 报错empty vocabulary所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(98)

评论列表共有 0 条评论

立即
投稿
返回
顶部