主要是学习项亮老师《推荐系统》一书与小破站里武晟然老师的课程《电影推荐系统设计》的相关学习笔记整理,其中不足,望笔者多多指正。
文章目录
TF_IDF算法原理
- TF(Term Frequency,TF)归一化的词频: T F i , j = n i , j n ∗ , j TF_{i,j}=\frac{n_{i,j}}{n_{*,j}} TFi,j=n∗,jni,j T F i , j , 词 语 i 在 文 档 j 中 出 现 的 频 率 , n i , j , 词 语 i 在 文 章 j 中 出 现 的 次 数 , n ∗ , j 文 档 j 的 总 次 数 。 TF_{i,j},词语i在文档j中出现的频率,n_{i,j},词语i在文章j中出现的次数,n_{*,j}文档j的总次数。 TFi,j,词语i在文档j中出现的频率,ni,j,词语i在文章j中出现的次数,n∗,j文档j的总次数。
- IDF(逆文档频率):
I D F i = log ( N + 1 N i + 1 ) I D F_{i}=\log \left(\frac{N+1}{N_{i}+1}\right) IDFi=log(Ni+1N+1)
N表示文档集中的文档总数, N i N_i Ni表示文档集中包含了词语i的文档数
实现引例
- 定义数据与预处理
#引入库
import numpy as np
import pandas as pd
#定义预处理数据
docA="The cat sat on my bed"
docB="The dog sat on my kness"
#词袋汇总
bowA=docA.split(" ")
bowB=docB.split(" ")
bowA
#构建词库
wordSet = set(bowA).union(set(bowB))
- 统计词数
# 统计词频
#利用统计词典保存词语出现的频率
wordDictA=dict.fromkeys(wordSet,0)
wordDictB=dict.fromkeys(wordSet,0)
#遍历文档统计词数
for word in bowA:
wordDictA[word] +=1
for word in bowB:
wordDictB[word] +=1
pd.DataFrame([wordDictA,wordDictB])
The | bed | cat | dog | kness | my | on | sat | |
---|---|---|---|---|---|---|---|---|
0 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | 1 |
1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 |
3.计算TF
def computeTF(wordDict,bow):
tfDict={
}
nbowCount = len(bow)
for word,count in wordDict.items():
tfDict[word]=count/nbowCount
return tfDict
tfA=computeTF(wordDictA,bowA)
tfB=computeTF(wordDictB,bowB)
tfA
{'The': 0.16666666666666666,
'cat': 0.16666666666666666,
'on': 0.16666666666666666,
'kness': 0.0,
'sat': 0.16666666666666666,
'bed': 0.16666666666666666,
'dog': 0.0,
'my': 0.16666666666666666}
- 计算IDF
def computeIDF( wordDictList ):
# 用一个字典对象保存idf结果,每个词作为key,初始值为0
idfDict = dict.fromkeys(wordDictList[0], 0)
N = len(wordDictList)
import math
for wordDict in wordDictList:
# 遍历字典中的每个词汇,统计Ni
for word, count in wordDict.items():
if count > 0:
# 先把Ni增加1,存入到idfDict
idfDict[word] += 1
# 已经得到所有词汇i对应的Ni,现在根据公式把它替换成为idf值
for word, ni in idfDict.items():
idfDict[word] = math.log10( (N+1)/(ni+1) )
return idfDict
idfs = computeIDF( [wordDictA, wordDictB] )
idfs
{'The': 0.0,
'cat': 0.17609125905568124,
'on': 0.0,
'kness': 0.17609125905568124,
'sat': 0.0,
'bed': 0.17609125905568124,
'dog': 0.17609125905568124,
'my': 0.0}
- 计算TF_IDF
def computeTFIDF( tf, idfs ):
tfidf = {
}
for word, tfval in tf.items():
tfidf[word] = tfval * idfs[word]
return tfidf
tfidfA = computeTFIDF( tfA, idfs )
tfidfB = computeTFIDF( tfB, idfs )
pd.DataFrame( [tfidfA, tfidfB] )
The | bed | cat | dog | kness | my | on | sat | |
---|---|---|---|---|---|---|---|---|
0 | 0.0 | 0.029349 | 0.029349 | 0.000000 | 0.000000 | 0.0 | 0.0 | 0.0 |
1 | 0.0 | 0.000000 | 0.000000 | 0.029349 | 0.029349 | 0.0 | 0.0 | 0.0 |