CountVectorizer和TfidfVectorizer学习笔记(详细)

1.CountVectorizer()

这个函数的作用是:生产 文档 - 词频 矩阵,如:
CountVectorizer和TfidfVectorizer学习笔记(详细)_第1张图片

1.1 导入

from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer
1.2 调用
  • 实例化
#只列出常用的参数
contv = CountVectorizer(encoding=u'utf-8', decode_error=u'strict',
lowercase=True,  stop_words=None,token_pattern=u'(?u)\b\w\w+\b', ngram_range=(1, 1), analyzer=u'word', max_df=1.0, min_df=1,max_features=None, vocabulary=None, binary=False, dtype=<type 'numpy.int64'>)
  • 训练-传入数据
texts: 文档集合
cv_fit=contv.fit_transform(texts)
  • 调用结果
print(cv_fit)   
print(cv_fit.toarray())    # 文档-词频 矩阵
print(contv.vocabulary_)   # 词库

1.3 参数解释

lowercase : boolean,True by default:统计 词频(tf) 前,先将所有单词 转化为 小写。这个参数一般为True
stop_words : string {‘english’}, list, or None (default):如果是‘english’, 则使用默认的内置英语停用词库。如果是 list,那么最后形成的 词库 将不包含 list 中的所有的stop word。如果是None, 则不处理停顿词。
token_pattern : string:正则表达式'(?u)\\b\\w\\w+\\b',默认筛选长度大于等于 2 的字母和数字混合字符,参数analyzer 设置为 word 时才有效。
如果想保留一个字符,可以将 pattern 改为 '(?u)\\b\\w*\\w*\\b'
ngram_range : tuple (min_n, max_n):默认是ngram_range=(1, 1),该范围之内的 n 元 feature 都会被提取出来!这个参数要根据自己的需求调整
analyzer : string, {‘word’, ‘char’, ‘char_wb’} or callable:特征基于 wordn-grams 还是character n-grams 
max_df : float in range [0.0, 1.0] or int, default=1.0 设置最大 词频阈值, 大于这个词频 的 词 都不会包含在 词库 中,小数表示占所有词数的百分比。该参数只适用于 自己没有指定词库的情况下
min_df : float in range [0.0, 1.0] or int, default=1 设置最小 词频阈值, 小这个词频 的 词 都不会包含在 词库 中,小数表示占所有词数的百分比。该参数只适用于 自己没有指定词库的情况下
max_features : int or None, default=None:选择 词频 最大的 max_features个特征(单词)。有效的前提是参数vocabulary设置成Node,即自己没有指定 词库。
vocabulary : 字典 or iterable, optional:自定义的词库,如果不是None,则只计算自定义 词库中的词的词频。
binary : boolean, default=False:如果是True,词频 的值只有01,表示单词 出现和不出现 在词库中
dtype, default=np.int64 : Type of the matrix returned by fit_transform() or transform()

1.4 例子1

例子参考sklearn函数CountVectorizer()和TfidfVectorizer()计算方法介绍

from sklearn.feature_extraction.text import CountVectorizer
texts=["orange banana apple grape app",  "banana apple apple",  "grape app",  "orange apple"] 
# doc0: "orange banana apple grape app"
# doc1: "banana apple apple"
# doc2:  "grape app"
# doc3: "orange apple"
cv = CountVectorizer()   ## 实例化(不传入任何参数)
cv_fit=cv.fit_transform(texts)  ## 训练-传入数据texts
print(cv.vocabulary_)   ## 调取结果
print(cv_fit)
print(cv_fit.toarray())

输出结果:

## 函数自动生成的词库是根据 首字母 顺序,将texts中所有单词进行排序从0,1,2...排起,apple首字母为a所以排第一,banana首字母为b所以排第二
{'orange': 4, 'banana': 2, 'apple': 1, 'grape': 3, 'app': 0}
(0, 4)	1
(0, 2)	1 ## (0, 2)  1  中 0 表示 doc0 "orange banana apple grape app", 2 对应上面的 'banana': 2, 1表示出现频次 1。即 doc0 中 banana 出现了一次
(0, 1)	1
(0, 3)	1
(0, 0)	1
(1, 2)	1
(1, 1)	2
(2, 3)	1
(2, 0)	1
(3, 4)	1
(3, 1)	1
[[1 1 1 1 1]   # 对于doc0,按 {'orange': 4, 'banana': 2, 'apple': 1, 'grape': 3, 'app': 0} 中的顺序统计 词频,如 doc0 中 app 出现 1次, apple 出现 1次,banana 出现 1 次, grape 出现 1 次, orange 出现 1 次
 [0 2 1 0 0] 
 [1 0 0 1 0]  # 对于doc2,按 {'orange': 4, 'banana': 2, 'apple': 1, 'grape': 3, 'app': 0} 中的顺序统计 词频,如 doc2 中 app 出现 1次, apple 出现 0 次,banana 出现 0 次, grape 出现 1 次, orange 出现 0 次
 [0 1 0 0 1]]

1.5 例子2

这个例子是传入中文的文本,对于中文文本,这个函数会直接过滤掉只有一个的中文 如:我 , 上, 走,坑等,解决方法是 改写torken_patten 为:’(?u)\b\w*\w*\b’,大家可以试试采用默认的torken_patten 会怎么样呢

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer

text = ["今天 上 NLP 课程",  "今天 的 课程 有 意思" ,  "数据 课程 也有 意思"]

vocabulary = ["今天", "上" , "NLP", "课程", "的", "有", "意思",  "数据", "也"]

contv = CountVectorizer(vocabulary=vocabulary, stop_words=[], min_df=0, token_pattern='(?u)\\b\\w*\\w*\\b', lowercase=False) # 实例化
contv1 = contv.fit_transform(text)  # 训练-传入数据
print(contv1)   #调取结果
print(contv1.toarray())
print(contv.vocabulary_)

输出:

{'今天': 0, '上': 1, 'NLP': 2, '课程': 3, '的': 4, '有': 5, '意思': 6, '数据': 7, '也': 8}

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

2.TfidfVectorizer()

对于 tf-idf 的原理,大家可以看看这个句子的向量表达,写的还是很详细的^^
但是:这个函数所用的公式有点不一样:
原来公式:
CountVectorizer和TfidfVectorizer学习笔记(详细)_第2张图片
TfidfVectorizer() 用的公式:
CountVectorizer和TfidfVectorizer学习笔记(详细)_第3张图片
平滑参数=True之后:
CountVectorizer和TfidfVectorizer学习笔记(详细)_第4张图片

2.1 导入

from sklearn.feature_extraction.text import TfidfVectorizer

2.2 实例化

tfidf = TfidfVectorizer()

2.2 训练-导入数据

tf_fit=tfidf.fit_transform(texts)

2.3 调用结果

print(tfidf.vocabulary_)  #词库
print(tfidf.idf_)   # 词库中单词的 idf 值
print(tfidf_fit.toarray())  # tf-idf文档-词频 矩阵
print(tf_fit)

2.4 参数解释

这里面很多参数与 CountVectorizer()是相似的,这里只说道常用的几个参数

norm:'l1', 'l2', or None,optional, 默认为 l2, 表示对 TF-IDF文档-词频矩阵 的 每一行进行归一化
use_idf:boolean, optional,当为 True 时,计算 TF-IDF文档-词频矩阵, 当为 False 时 计算
文档-词频矩阵,相当于 CountVectorizer()
smooth_idf:boolean,optional,当为 True 时 就是:平滑参数=True之后的公式,默认是 True
sublinear_tf:boolean, optional, 当为 True, tf(d,w) 变成 1 + log[tf(d,w)]

2.5 例子

例子参考sklearn函数CountVectorizer()和TfidfVectorizer()计算方法介绍

from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer

texts=["orange banana apple grape app","banana apple apple","grape app", 'orange apple']
# doc0: "orange banana apple grape app"
# doc1: "banana apple apple"
# doc2:  "grape app"
# doc3: "orange apple"

cv = TfidfVectorizer(norm=None) # 实例化, 不对TF-IDF文档-词频矩阵 作归一化
cv_fit=cv.fit_transform(texts)   # 训练-导入数据
print('词库')
print(cv.vocabulary_)
print('IDF值')
print(cv.idf_)  # 计算 单词的 idf_值
print('文档-词频 矩阵')
print([[1 1 1 1 1]   # 对于doc0,按 {'orange': 4, 'banana': 2, 'apple': 1, 'grape': 3, 'app': 0} 中的顺序统计 词频,如 doc0 中 app 出现 1次, apple 出现 1次,banana 出现 1 次, grape 出现 1 次, orange 出现 1 次
       [0 2 1 0 0] 
       [1 0 0 1 0]  # 对于doc2,按 {'orange': 4, 'banana': 2, 'apple': 1, 'grape': 3, 'app': 0} 中的顺序统计 词频,如 doc2 中 app 出现 1次, apple 出现 0 次,banana 出现 0 次, grape 出现 1 次, orange 出现 0 次
       [0 1 0 0 1]])
print('TF-IDF文档-词矩阵')
print(cv_fit.toarray())
print(cv_fit)

输出词库

词库
{'orange': 4, 'banana': 2, 'apple': 1, 'grape': 3, 'app': 0}

计算 词库中单词 的 idf 值 # 注意默认是平滑的
N:总文档个数是 4
N(app)= 2, app 出现在 两个文档中
N(apple)=3,apple 出现在 三个文档 中
N(banana)=2, banana 出现在 两个 文档中
N (grape) = 2
N (orange) = 2
CountVectorizer和TfidfVectorizer学习笔记(详细)_第5张图片
看程序输出结果:是一致的

IDF值
[1.51082562 1.22314355 1.51082562 1.51082562 1.51082562]
文档-词频 矩阵
[[1 1 1 1 1]
 [0 2 1 0 0] 
 [1 0 0 1 0]      
 [0 1 0 0 1]] 

计算 tf-idf文档-词频 矩阵
先看第一行:
CountVectorizer和TfidfVectorizer学习笔记(详细)_第6张图片
再看第二行:
在这里插入图片描述
在看第三行:
在这里插入图片描述
最后一行:
CountVectorizer和TfidfVectorizer学习笔记(详细)_第7张图片
看程序输出结果: 是一致的

TF-IDF文档-词矩阵
[[1.51082562 1.22314355 1.51082562 1.51082562 1.51082562]
 [0.         2.4462871  1.51082562 0.         0.        ]
 [1.51082562 0.         0.         1.51082562 0.        ]
 [0.         1.22314355 0.         0.         1.51082562]]
print(cv.fit)
(0, 0)	1.5108256237659907  # doc0 中 app 的 idf
(0, 3)	1.5108256237659907  # doc0 中 apple 的 idf
(0, 1)	1.2231435513142097
(0, 2)	1.5108256237659907
(0, 4)	1.5108256237659907
(1, 1)	2.4462871026284194
(1, 2)	1.5108256237659907
(2, 0)	1.5108256237659907
(2, 3)	1.5108256237659907
(3, 1)	1.2231435513142097
(3, 4)	1.5108256237659907

采用 l2 正则化会怎样呢?

其余不变,只是 tf-idf文档-词频 矩阵 归一化了

cv = TfidfVectorizer()
cv_fit=cv.fit_transform(texts)
print(cv.vocabulary_)
print(cv.idf_)
print(cv_fit.toarray())
print(cv_fit)

输出

词库
{'orange': 4, 'banana': 2, 'apple': 1, 'grape': 3, 'app': 0}

IDF值
[1.51082562 1.22314355 1.51082562 1.51082562 1.51082562]

文档-词频 矩阵
[[1 1 1 1 1]
 [0 2 1 0 0] 
 [1 0 0 1 0]      
 [0 1 0 0 1]] 
 
TF-IDF文档-词矩阵
[[0.46346838 0.3752176  0.46346838 0.46346838 0.46346838]
 [0.         0.8508161  0.52546357 0.         0.        ]
 [0.70710678 0.         0.         0.70710678 0.        ]
 [0.         0.62922751 0.         0.         0.77722116]]

cv_fit
  (0, 0)	0.46346837948164166
  (0, 3)	0.46346837948164166
  (0, 1)	0.3752175967124194
  (0, 2)	0.46346837948164166
  (0, 4)	0.46346837948164166
  (1, 1)	0.8508160982744233
  (1, 2)	0.5254635733493682
  (2, 0)	0.7071067811865475
  (2, 3)	0.7071067811865475
  (3, 1)	0.6292275146695526
  (3, 4)	0.7772211620785797

以 tf-idf文档-词频 矩阵中的 1.51082562为例,进行正则化
CountVectorizer和TfidfVectorizer学习笔记(详细)_第8张图片

你可能感兴趣的:(NLP自学笔记,自然语言处理,深度学习)