TF-IDF from Scratch
บทความโดย อ.ดร.ณัฐโชติ พรหมฤทธิ์
ภาควิชาคอมพิวเตอร์
คณะวิทยาศาสตร์
มหาวิทยาลัยศิลปากร
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizerdocumentA = 'The cat sat on my face'
documentB = 'The dog sat on my bed'bagOfWordsA = documentA.split(' ')
bagOfWordsB = documentB.split(' ')bagOfWordsAbagOfWordsBuniqueWords = set(bagOfWordsA).union(set(bagOfWordsB))uniqueWordsnumOfWordsA = dict.fromkeys(uniqueWords, 0)numOfWordsAfor word in bagOfWordsA:
numOfWordsA[word] += 1numOfWordsAnumOfWordsB = dict.fromkeys(uniqueWords, 0)numOfWordsBfor word in bagOfWordsB:
numOfWordsB[word] += 1numOfWordsBdef computeTF(wordDict, bagOfWords):
tfDict = {}
bagOfWordsCount = len(bagOfWords)
for word, count in wordDict.items():
tfDict[word] = count / float(bagOfWordsCount)
return tfDicttfA = computeTF(numOfWordsA, bagOfWordsA)
tfB = computeTF(numOfWordsB, bagOfWordsB)tfAtfBdef computeIDF(documents):
import math
N = len(documents)
idfDict = dict.fromkeys(documents[0].keys(), 0)
for document in documents:
for word, val in document.items():
if val > 0:
idfDict[word] += 1
for word, val in idfDict.items():
idfDict[word] = math.log(N / float(val), 10)
return idfDictimport math
1/6*math.log(2/1, 10)idfs = computeIDF([numOfWordsA, numOfWordsB])idfsdef computeTFIDF(tfBagOfWords, idfs):
tfidf = {}
for word, val in tfBagOfWords.items():
tfidf[word] = val * idfs[word]
return tfidftfidfA = computeTFIDF(tfA, idfs)
tfidfB = computeTFIDF(tfB, idfs)df = pd.DataFrame([tfidfA, tfidfB])
dfvectorizer = TfidfVectorizer()
vectors = vectorizer.fit_transform([documentA, documentB])feature_names = vectorizer.get_feature_names()feature_namesdense = vectors.todense()denselist = dense.tolist()df = pd.DataFrame(denselist, columns=feature_names)
df