06_TF-IDF算法代碼示例

TF-IDF算法代碼示例0.引入依賴1.定義數據和預處理2.進行詞數統計3.計算詞頻 TF4.計算逆文檔頻率 IDF5.計算 TF-IDFpython


TF-IDF算法代碼示例

0.引入依賴

import numpy as np # 數值計算、矩陣運算、向量運算
import pandas as pd # 數值分析、科學計算

1.定義數據和預處理

# 定義文檔
docA = 'The cat sat on my bed'
docB = 'The dog sat on my knees'

# 切割文檔
bowA = docA.split(' ')
bowB = docB.split(' ')
# bowA # ['The', 'cat', 'sat', 'on', 'my', 'bed']
# bowB # ['The', 'dog', 'sat', 'on', 'my', 'knees']

# 構建詞庫
wordSet = set(bowA).union(set(bowB))
# wordSet # {'The', 'bed', 'cat', 'dog', 'knees', 'my', 'on', 'sat'}

2.進行詞數統計

# 用字典來保存詞出現的次數
wordDictA = dict.fromkeys(wordSet, 0)
wordDictB = dict.fromkeys(wordSet, 0)
wordDictA
wordDictB

# 遍歷文檔,統計詞數
for word in bowA:
    wordDictA[word] += 1
for word in bowB:
    wordDictB[word] += 1

pd.DataFrame([wordDictA, wordDictB])

輸出結果以下:算法

3.計算詞頻 TF

def computeTF(wordDict, bow):
    # 用一個字典對象保存 TF,把全部對應於 bow 文檔裏的 TF都計算出來
    tfDict = {}
    nbowCount = len(bow)

    for word, count in wordDict.items():
        tfDict[word] = count / nbowCount
    return tfDict

# 測試
tfA = computeTF(wordDictA, bowA)
tfB = computeTF(wordDictB, bowB)
print(tfA)
print(tfB)

輸出結果以下:app

    {'on'0.16666666666666666'dog'0.0'cat'0.16666666666666666'The'0.16666666666666666'knees'0.0'my'0.16666666666666666'sat'0.16666666666666666'bed'0.16666666666666666}
    {'on'0.16666666666666666'dog'0.16666666666666666'cat'0.0'The'0.16666666666666666'knees'0.16666666666666666'my'0.16666666666666666'sat'0.16666666666666666'bed'0.0}

4.計算逆文檔頻率 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

輸出結果以下:測試

    {'on'0.0,
     'dog'0.17609125905568124,
     'cat'0.17609125905568124,
     'The'0.0,
     'knees'0.17609125905568124,
     'my'0.0,
     'sat'0.0,
     'bed'0.17609125905568124}

5.計算 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])

輸出結果以下:spa

相關文章
相關標籤/搜索