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}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值