日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

tfidf算法 python_tf–idf算法解释及其python代码实现(下)

發布時間:2023/12/10 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 tfidf算法 python_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(, {'的': 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)

總結

以上是生活随笔為你收集整理的tfidf算法 python_tf–idf算法解释及其python代码实现(下)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。