1.CountVectorizer

首先我们看看CountVectorizer相关源码中的部分内容。

class CountVectorizer(_VectorizerMixin, BaseEstimator):"""Convert a collection of text documents to a matrix of token countsThis implementation produces a sparse representation of the counts usingscipy.sparse.csr_matrix.If you do not provide an a-priori dictionary and you do not use an analyzerthat does some kind of feature selection then the number of features willbe equal to the vocabulary size found by analyzing the data.Read more in the :ref:`User Guide <text_feature_extraction>`.

注释的前面两行就指出了CountVectorizer最核心的两点
Convert a collection of text documents to a matrix of token counts
CountVectorizer把一个文档转成一个包含词频的矩阵。
This implementation produces a sparse representation of the counts using scipy.sparse.csr_matrix.
最后的词频矩阵是用csr_matrix这种稀疏矩阵的表示方式来表示的。

用一个简单的demo测试一下

from sklearn.feature_extraction.text import CountVectorizerdef t1():cv = CountVectorizer()train = ["Chinese Beijing Chinese","Chinese Chinese Shanghai","Chinese Macao","Tokyo Japan Chinese"]cv_fit = cv.fit_transform(train)print(cv.get_feature_names())print(cv_fit)print(cv_fit.toarray())t1()

最后的输出结果

['beijing', 'chinese', 'japan', 'macao', 'shanghai', 'tokyo'](0, 1)  2(0, 0) 1(1, 1) 2(1, 4) 1(2, 1) 1(2, 3) 1(3, 1) 1(3, 5) 1(3, 2) 1
[[1 2 0 0 0 0][0 2 0 0 1 0][0 1 0 1 0 0][0 1 1 0 0 1]]

首先所有的文档中有6个词,所以最后get_feature_names得到的结果为6维列表。
cv_fit很明显可以看出来就是使用csr_matrix这种方式来存储的,(0,1)对应的是第一行第二个词即chinese,后面的2表示第一行chinese这个词出现了2次。
如果调用toarray方法,会将矩阵由稀疏表示转化为正常矩阵,因为所有文档中包含6个词,所以每一行文档会有6维。

2.TfidfVectorizer

class TfidfVectorizer(CountVectorizer):"""Convert a collection of raw documents to a matrix of TF-IDF features.Equivalent to :class:`CountVectorizer` followed by:class:`TfidfTransformer`.Read more in the :ref:`User Guide <text_feature_extraction>`.

TfidfVectorizer跟CountVectorizer的区别在于:
CountVectorizer返回的是词频,TfidfVectorizer返回的是tfidf值。

from sklearn.feature_extraction.text import TfidfVectorizerdef t2():tf = TfidfVectorizer(use_idf=True, smooth_idf=True, norm=None)train = ["Chinese Beijing Chinese","Chinese Chinese Shanghai","Chinese Macao","Tokyo Japan Chinese"]tf_fit = tf.fit_transform(train)print(tf.get_feature_names())print(tf_fit)print(tf_fit.toarray())t2()
['beijing', 'chinese', 'japan', 'macao', 'shanghai', 'tokyo'](0, 0)  1.916290731874155(0, 1) 2.0(1, 4)   1.916290731874155(1, 1) 2.0(2, 3)   1.916290731874155(2, 1) 1.0(3, 2)   1.916290731874155(3, 5) 1.916290731874155(3, 1) 1.0
[[1.91629073 2.         0.         0.         0.         0.        ][0.         2.         0.         0.         1.91629073 0.        ][0.         1.         0.         1.91629073 0.         0.        ][0.         1.         1.91629073 0.         0.         1.91629073]]

3.sklearn中idf的计算方法

TfidfVectorizer中计算tfidf值的核心代码调用如下

self._tfidf = TfidfTransformer(norm=norm, use_idf=use_idf,smooth_idf=smooth_idf,sublinear_tf=sublinear_tf)

进入到TfidfTransformer中,查看源码观察具体计算逻辑

    def __init__(self, norm='l2', use_idf=True, smooth_idf=True,sublinear_tf=False):self.norm = normself.use_idf = use_idfself.smooth_idf = smooth_idfself.sublinear_tf = sublinear_tfdef fit(self, X, y=None):"""Learn the idf vector (global term weights)Parameters----------X : sparse matrix, [n_samples, n_features]a matrix of term/token counts"""X = check_array(X, accept_sparse=('csr', 'csc'))if not sp.issparse(X):X = sp.csr_matrix(X)dtype = X.dtype if X.dtype in FLOAT_DTYPES else np.float64if self.use_idf:n_samples, n_features = X.shapedf = _document_frequency(X)df = df.astype(dtype, **_astype_copy_false(df))# perform idf smoothing if requireddf += int(self.smooth_idf)n_samples += int(self.smooth_idf)# log+1 instead of log makes sure terms with zero idf don't get# suppressed entirely.idf = np.log(n_samples / df) + 1self._idf_diag = sp.diags(idf, offsets=0,shape=(n_features, n_features),format='csr',dtype=dtype)return self

根据上面的代码不难看出,idf的具体计算方法为
当smooth_idf参数为true时
idf=log1+nd1+df+1idf = log \frac{1+n_d}{1+ df} + 1idf=log1+df1+nd​​+1
其中,ndn_dnd​为总文档数量,df为某个词出现的文档数量。
而当smooth_idf参数为false时
idf=lognddf+1idf = log \frac{n_d}{df} + 1idf=logdfnd​​+1

4.csr_matrix解析

前面说到了csr_matrix表示方法,顺便温习一下csr_matrix相关知识点。
csr_matrix(Compressed Sparse Row matrix)为稀疏矩阵的一种表示方式,对应的是csc_matric(Compressed Sparse Column marix)。

CSR方法采取按行压缩的办法, 将原始的矩阵用三个数组进行表示

def csr_data():from scipy import sparseimport numpy as npdata = np.array([1, 2, 3, 4, 5, 6])indices = np.array([0, 2, 2, 0, 1, 2])indptr = np.array([0, 2, 3, 6])matrix = sparse.csr_matrix((data, indices, indptr), shape=(3, 3))print(matrix)print()print(matrix.todense())csr_data()

结果为

  (0, 0) 1(0, 2) 2(1, 2) 3(2, 0) 4(2, 1) 5(2, 2) 6[[1 0 2][0 0 3][4 5 6]]

其中,data为所有的非零数值
indices为所有非零值的列索引
indptr为每行的非零数据起止索引

def csc_data():from scipy import sparseimport numpy as npdata = np.array([1, 2, 3, 4, 5, 6])indices = np.array([0, 2, 2, 0, 1, 2])indptr = np.array([0, 2, 3, 6])matrix = sparse.csc_matrix((data, indices, indptr), shape=(3, 3))print(matrix)print()print(matrix.todense())csc_data()

结果为

  (0, 0) 1(2, 0) 2(2, 1) 3(0, 2) 4(1, 2) 5(2, 2) 6[[1 0 4][0 0 5][2 3 6]]

csc_matrix与csr_matrix唯一的区别在于,csr的indptr是针对行,而csc的indptr是针对列。

sklearn中CountVectorizer与TfidfVectorizer区别相关推荐

  1. tfidf处理代码_tf idf公式及sklearn中TfidfVectorizer

    在文本挖掘预处理之向量化与Hash Trick中我们讲到在文本挖掘的预处理中,向量化之后一般都伴随着TF-IDF的处理,那么什么是TF-IDF,为什么一般我们要加这一步预处理呢?这里就对TF-IDF的 ...

  2. 理解sklearn.feature.text中的CountVectorizer和TfidfVectorizer

    """ 理解sklearn中的CountVectorizer和TfidfVectorizer """ from collections im ...

  3. word2vec预训练词向量+通俗理解word2vec+CountVectorizer+TfidfVectorizer+tf-idf公式及sklearn中TfidfVectorizer

    文章目录 文分类实(一) word2vec预训练词向量 2 数据集 3 数据预处理 4 预训练word2vec模型 canci 通俗理解word2vec 独热编码 word2vec (Continuo ...

  4. CountVectorizer,Tf-idfVectorizer和word2vec构建词向量的区别

    CountVectorizer和Tf-idfVectorizer构建词向量都是通过构建字典的方式,比如在情感分析问题中,我需要把每一个句子(评论)转化为词向量,这两种方法是如何构建的呢?拿CountV ...

  5. 一个例子来使用sklearn中的TfidfVectorizer

    TfidfVectorizer 作用 将文本进行向量化表示. 原理 这里的tf(term frequency)是词的频数,idf(inverse document frequency)是这个词的逆文档 ...

  6. sklearn中的k_means和KMeans区别

    sklearn中的k_means和KMeans区别 1.KMeans的缺点 2.sklearn.KMeans参数 3.sklearn.KMeans属性 KMeans **: 1.k点中心个数的确定,很 ...

  7. sklearn中一些参数

    转载:http://www.cnblogs.com/chenyaling/p/7826229.html 1.监督学习 1.1.广义线性模型 1.1.1.普通最小二乘法  class sklearn.l ...

  8. 自然语言典型工具TextBlob、Gensim、Polyglot,关键词抽取(jieba、TF-IDF、textrank)和特征提取(CountVectorizer、TfidfVectorizer)

    一.自然语言处理的典型工具 自然语言处理的三项基本技术为单词切分.句法分析.语义理解. 1. TextBlob TextBlob是自然语言处理的python库.它为常见的自然语言处理提供一个简单地AP ...

  9. sklearn中的朴素贝叶斯

    1 概述 1.1 真正的概率分类器 在许多分类算法应用中,特征和标签之间的关系并非是决定性的.如想预测一个人究竟是否能在泰坦尼克号海难中生存下来,可以建一棵决策树来学习训练集.在训练中,其中一个人的特 ...

  10. sklearn中GBDT的一些参数、属性、方法的理解

    文章目录 GBDT 分类器 引入 重要参数 loss learning_rate subsample n_estimators criterion max_depth min_samples_leaf ...

最新文章

  1. PHP 常用字符串处理代码片段
  2. 怎么添加项目到SVN上面
  3. EXC_BAD_ACCESS调试
  4. boost::phoenix::if_相关的测试程序
  5. 快速傅里叶变换(FFT)——按频率抽取DIF的基
  6. thinkphp 前端页面js接收后端传过来的数据
  7. 清华硕士分享思维导图:机器学习所需的数学基础
  8. win7 32 php+mysql+apache环境_win7 搭建PHP环境(php+mysql+apache)
  9. python中如何创建一个空列表_Python创建空列表的字典2种方法详解
  10. 十五、Oracle学习笔记:序列(用于表字段值自增)
  11. 第三届“传智杯”全国大学生IT技能大赛(初赛B组)
  12. NDK之FFmpeg视频解码
  13. 产品经理项目从0-1工作简要流程
  14. linux scl,scl命令
  15. 北京最最最牛的IT公司都在这了
  16. c语言ab43错误的是,ab测试大并发错误
  17. 详述数据中心内部通风的几种形态
  18. 「文末送书」如何让数据分析不脱离业务?
  19. Win32 OpenGL 编程(1)Win32下的OpenGL编程必须步骤
  20. Unity3D 实现背包系统

热门文章

  1. 正则表达式,时间戳和日期互相转换
  2. php UUID 分布式生成用不重复的随机数方法
  3. Linux下解压RAR软件下载和解压.zip和.rar文件
  4. excel数据导入到 mysql 中
  5. ubuntu下iptables的用法
  6. JEECG支付服务窗平台与服务窗接口对接文档
  7. JavaScript技巧写法
  8. poj1691 Painting A Board
  9. 【心得】Web设计师应参考的技术
  10. AS3 的 2D向量类(Vector2D)