tf–idf算法解釋及其python代碼


tf–idf算法python代碼實現

這是我寫的一個tf-idf的簡單實現的代碼,我們知道tfidf=tf*idf,所以可以分別計算tf和idf值在相乘,首先我們創建一個簡單的語料庫,作為例子,只有四句話,每句表示一個文檔

  

copus=['我正在學習計算機','它正在吃飯','我的書還在你那兒','今天不上班']

  由於中文需要分詞,jieba分詞是python里面比較好用的分詞工具,所以選用jieba分詞,文末是jieba的鏈接。首先對文檔進行分詞:

  

import jieba
copus=['我正在學習計算機','它正在吃飯','我的書還在你那兒','今天不上班']
copus= [[word for word in jieba.cut(doc)] for doc in copus]
print(copus)

  輸出結果:

   

[['我', '正在', '學習', '計算機'], ['它', '正在', '吃飯'], ['我', '的', '書', '還', '在', '你', '那兒'], ['今天', '不', '上班']]

  文檔變成我們想要的格式了,然后開始詞頻統計,計算tf值,這里用Counter類來把每篇文檔都轉換成詞和詞頻的字典,其實就已經得到tf值了

   

tf = []
for doc in copus:
tf.append(Counter(doc))
print(tf)

  輸出結果:

   

[Counter({'我': 1, '正在': 1, '學習': 1, '計算機': 1}), Counter({'它': 1, '正在': 1, '吃飯': 1}), Counter({'的': 1, '書': 1, '你': 1, '在': 1, '那兒': 1, '我': 1, '還': 1}), Counter({'今天': 1, '不': 1, '上班': 1})]

  計算idf值

   

import math
from collections import defaultdict
idf = defaultdict(int)
for doc in tf:
    for word in doc:
        idf[word] += 1
for word in idf:
    idf[word] = math.log(len(idf)/(idf[word]+1))
print(idf)

  

  輸出結果:

   

defaultdict(<class 'int'>, {'的': 2.0149030205422647, '正在': 1.6094379124341003, '學習': 2.0149030205422647, '計算機': 2.0149030205422647, '今天': 2.0149030205422647, '書': 2.0149030205422647, '那兒': 2.0149030205422647, '它': 2.0149030205422647, '不': 2.0149030205422647, '在': 2.0149030205422647, '吃飯': 2.0149030205422647, '我': 1.6094379124341003, '你': 2.0149030205422647, '還': 2.0149030205422647, '上班': 2.0149030205422647})

  

  

剩下的事情就很簡單了,只需要把tf和idf相乘就可以了。

下面是一個tfidf的實現代碼

   

from collections import Counter,defaultdict
import jieba
import math
 
def file2list(file):
    '''
    把文件轉換成列表,並對數據進行簡單的預處理
    '''
    with open(file) as f:
        corpus = f.readlines()
        corpus = [[word.replace('\n','') for word in jieba.cut(line)] for line in corpus if line.strip()]
    return corpus
#c = file2list('E:\hei.txt')
def get_tf(corpus):
    return [Counter(doc) for doc in corpus]#用Counter函數把每篇文檔轉換成詞和詞頻的字典
def get_idf(tf_dict):
    idf = defaultdict(int)
    for doc in tf_dict:
        for word in doc:
            idf[word] += 1
    for word in idf:
        idf[word] = math.log(len(idf)/(idf[word]+1))#idf的公式
    return idf
 
def get_tfidf(doc_id,file):
    '''doc_id是語料庫中文檔的id,file是txt的路徑'''
    corpus = file2list(file)
    tf = get_tf(corpus)
    idf = get_idf(tf)
    if doc_id > len(tf):
        print("doc_id should smaller than %i"%len(tf))
    else:
        id_tf= tf[doc_id-1]
        for word in id_tf:
            id_tf[word] = id_tf[word]*idf[word]#計算tfidf值
        print(id_tf)

  

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM