주로 Xiang Liang의 저서 "Recommendation System"과 Xiaopozhan의 Wu Shengran 교사의 "Design of Movie Recommendation System"과정의 관련 연구 노트를 연구하는 데, 결함이 있으면 저자가 저를 바로 잡을 수 있기를 바랍니다.
기사 디렉토리
TF_IDF 알고리즘 원리
- TF (Term Frequency, TF) 정규화 된 항 주파수 : TF i, j = ni, jn ∗, j TF_ {i, j} = \ frac {n_ {i, j}} {n _ {*, j}}T FI , J=엔* , J엔I , J TF i, j, 문서 j, ni, j에서 단어 i의 발생 빈도, 기사 j에서 단어 i의 발생 횟수, n ∗, j 문서 j의 총 수. TF_ {i, j}, 문서 j에서 단어 i의 발생 빈도, n_ {i, j}, 기사 j에서 단어 i의 발생 횟수, n _ {*, j} 문서 j에서 총 횟수 .T FI , J,단어 즉 I 의 텍스트 파일 J 에 전류 의 주파수 레이트 , N-I , J, 워드 언어 전 에서 텍스트 장 J 의 현재 의 시간 수 , N- 형* , J텍스트 파일 J 의 총 시간 수 .
- IDF (逆 文档 频率) :
IDF i = log (N + 1 N i + 1) ID F_ {i} = \ log \ left (\ frac {N + 1} {N_ {i} +1} \ right)I D F나는=싸다 g(엔나는+1엔+(1))
N은 문서 세트의 총 문서 수를 나타냅니다.N i N_i엔나는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])
그만큼 | 침대 | 고양이 | 개 | kness | 나의 | 의 위에 | 수능 | |
---|---|---|---|---|---|---|---|---|
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] )
그만큼 | 침대 | 고양이 | 개 | kness | 나의 | 의 위에 | 수능 | |
---|---|---|---|---|---|---|---|---|
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 |