【机器学习】词袋模型TF-IDF算法

一、词袋模型

  • Bag-of-words model (BoW model) 最早出现在自然语言处理和信息检索领域.。该模型忽略掉文本的语法和语序等要素,将其仅仅看作是若干个词汇的集合,将文档中每个单词的出现都视为是独立的。
  • 词袋模型能够把一段文字或一个文档转化为向量表示,它不考虑句子中单词的顺序,只考虑词表(vocabulary)中单词在这个句子中的出现次数。具体的说,词袋模型将每段文字或文档都转化为一个与词汇表一样长的向量,向量的每个元素存储该位置对于的词出现的次数。
  • 由于每个文档中一般只会出现的词汇表中的很少一部分词,因此会有很多的单词没有出现过,这些词被标记为0。所以,向量中大多数的元素就会为0。
  • scikit-learn中BOW模型的API
from sklearn.feature_extraction.text import CountVectorizer
#一个语料库
corpus = [
    'This is the first document.',
    'This document is the second document.',
    'And this is the third one.',
    'Is this the first document?',
]
vectorizer = CountVectorizer()

X = vectorizer.fit_transform(corpus)
print("词汇:索引",vectorizer.vocabulary_)
print("句子的向量:")
print(X.toarray())#元素为每个词出现的次数
输出:
	词汇:索引
		 {'this': 8, 'is': 3, 'the': 6, 'first': 2, 'document': 1, 'second': 5, 'and': 0, 'third': 7, 'one': 4}
	句子的向量:
		[[0 1 1 1 0 0 1 0 1]
		 [0 2 0 1 0 1 1 0 1]
		 [1 0 0 1 1 0 1 1 1]
		 [0 1 1 1 0 0 1 0 1]]
  • 在上面词袋模型中,我们是使用单个的单词来构建词向量,这样的序列被称为1元组(1-gram)或单元组(unigram)模型。除了一元组以外,我们还可以构建n元组(n-gram)。n元组模型中的n取值与特定的应用场景有关,如在反垃圾邮件中,n的值为3或4是可以获得比较好的效果。下面举例说明一下n元组,如在"the weather is sweet"这句话中,
    • 1元组:“the”、“weather”、“is”、“sweet”。
    • 2元组:“the weather”、“weather is”、“is sweet”。
  • 在sklearn中,可以设置CountVecorizer中的ngram_range参数来构建不同的n元组模型,默认ngram_range=(1,1)。
from sklearn.feature_extraction.text import CountVectorizer
#一个语料库
corpus = [
    'This is the first document.',
    'This document is the second document.',
    'And this is the third one.',
    'Is this the first document?',
]
vectorizer = CountVectorizer(ngram_range=(2,2))

X = vectorizer.fit_transform(corpus)
print("词汇:索引",vectorizer.vocabulary_)
print("句子的向量:")
print(X.toarray())#元素为每个词出现的次数
输出:
	词汇:索引
		 {'this is': 11, 'is the': 3, 'the first': 6, 'first document': 2, 'this document': 10, 'document is': 1, 'the second': 7, 'second document': 5, 'and this': 0, 'the third': 8, 'third one': 9, 'is this': 4, 'this the': 12}
	句子的向量:
		[[0 0 1 1 0 0 1 0 0 0 0 1 0]
		 [0 1 0 1 0 1 0 1 0 0 1 0 0]
		 [1 0 0 1 0 0 0 0 1 1 0 1 0]
		 [0 0 1 0 1 0 1 0 0 0 0 0 1]]

二、TF-IDF算法

  • 词频-逆文档频率(TF-IDF,term frequency-inverse document frequency):是一种用于信息检索与数据挖掘的常用加权技术,常用于挖掘文章中的关键词。算法简单高效,常被工业用于最开始的文本数据清洗。
  • TF-IDF有两层意思:
    • "词频"(Term Frequency,缩写为TF):它表示的是在某个文档中每个词出现的频率,公式如下: 词 频 ( T F ) = 某 个 词 在 文 档 中 出 现 的 次 数 词频(TF)=某个词在文档中出现的次数 (TF)=考虑到文章有长短之分,为了便于不同文章的比较,进行**"词频"标准化**:

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值