当前位置:   article > 正文

2021-09-29 Scikit-learn中CountVectorizer类的使用_countvectorizer的作用

countvectorizer的作用

CountVectorizer会将文本中的词语转换为词频矩阵,它通过fit_transform()函数计算各个词语出现的次数,通过get_feature_names()可获取词袋中所有文本的关键字,通过toarray()可看到词频矩阵的结果。

TfidfTransformer类用于将词频矩阵转化为每个词语的TF-IDF值,通过fit_transform()函数。

  1. from sklearn.feature_extraction.text import CountVectorizer
  2. from sklearn.feature_extraction.text import TfidfTransformer
  3. corpus=[
  4. 'this is the first document',
  5. 'this is the second second document',
  6. 'and And and the third one'
  7. ]
  8. vectorizer=CountVectorizer()
  9. vectorizer.fit(corpus)
  10. x=vectorizer.transform(corpus)
  11. word=vectorizer.get_feature_names()
  12. word_1=vectorizer.vocabulary_
  13. print(word)
  14. #['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
  15. print(word_1)
  16. #{'this': 8, 'is': 3, 'the': 6, 'first': 2, 'document': 1, 'second': 5, 'and': 0, 'third': 7, 'one': 4} key:词,value:词在词袋列表中的索引值。
  17. print(x.toarray())
  18. #[[0 1 1 1 0 0 1 0 1]
  19.  [0 1 0 1 0 2 1 0 1]
  20.  [3 0 0 0 1 0 1 1 0]] 文本中有多少个词就有多少列,有几个文本就有几行。
  21. tf=TfidfTransformer()
  22. y=tf.fit_transform(x)
  23. print(y.toarray())
  24. # [[0. 0.43306685 0.56943086 0.43306685 0. 0.
  25. 0.33631504 0. 0.43306685]
  26. [0. 0.30833187 0. 0.30833187 0. 0.81083871
  27. 0.2394472 0. 0.30833187]
  28. [0.89052427 0. 0. 0. 0.29684142 0.
  29. 0.17531933 0.29684142 0. ]]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/361102
推荐阅读
相关标签
  

闽ICP备14008679号