老卫带你学---sklearn的CountVectorizer()类解析

它主要是把新的文本转化为特征矩阵,只不过,这些特征是已经确定过的。而这个特征序列是前面的fit_transfome()输入的语料库确定的特征。见例子:

>>>from sklearn.feature_extraction.text import CountVectorizer
>>>vec=CountVectrizer()
>>>vec.transform(['Something completely new.']).toarray()

错误返回 ,sklearn.exceptions.NotFittedError: CountVectorizer - Vocabulary wasn’t fitted.表示没有对应的词汇表,这个文本无法转换。其实就是没有建立vocabulary表,没法对文本按照矩阵索引来统计词的个位数

corpus = [
     'This is the first document.',
    'This is the second second document.',
   'And the third one.',
   'Is this the first document?']
X = vec.fit_transform(corpus)
X.toarray(

vocabulary列表

>>>vec.get_feature_names()
 ['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']

得到的稀疏矩阵是

array([[0, 1, 1, 1, 0, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 2, 1, 0, 1],
       [1, 0, 0, 0, 1, 0, 1, 1, 0],
       [0, 1, 1, 1, 0, 0, 1, 0, 1]], dtype=int64)

建立vocabulary后可以用transform()来对新文本进行矩阵化了

>>>vec.transform(['this is']).toarray()
 array([[0, 0, 0, 1, 0, 0, 0, 0, 1]], dtype=int64)
>>>vec.transform(['too bad']).toarray()
array([[0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int64)

简单分析’this is’在vocabulary表里面,则对应词统计数量,形成矩阵。而’too bad’在vocabulary表中没有这两词,所以矩阵都为0.

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值