自然语言处理_tf-idf

python 复制代码
import pandas as pd
import math

1.数据预处理

python 复制代码
docA = "The cat sat on my face"
docB = "The dog sat on my bed"

wordsA = docA.split(" ")
wordsB = docB.split(" ")

wordsSet = set(wordsA).union(set(wordsB))
print(wordsSet)
复制代码
{'on', 'my', 'face', 'sat', 'dog', 'The', 'cat', 'bed'}

2.计算词的频数

python 复制代码
wordCountA = dict.fromkeys(wordsSet, 0)
wordCountB = dict.fromkeys(wordsSet, 0)

for word in wordsA:
    wordCountA[word] += 1
for word in wordsB:
    wordCountB[word] += 1

pd.DataFrame([wordCountA, wordCountB])    

| | on | my | face | sat | dog | The | cat | bed |
| 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 0 |

1 1 1 0 1 1 1 0 1

3.计算词的频率

python 复制代码
def computeTF(wordCount, docWords):
    tfDict = {}
    docCount = len(docWords)
    for word, count in wordCount.items():
        tfDict[word] = count / float(docCount)
    return tfDict

tfA = computeTF(wordCountA, wordsA)
tfB = computeTF(wordCountB, wordsB)
print("tfA ", tfA)
复制代码
tfA  {'on': 0.16666666666666666, 'my': 0.16666666666666666, 'face': 0.16666666666666666, 'sat': 0.16666666666666666, 'dog': 0.0, 'The': 0.16666666666666666, 'cat': 0.16666666666666666, 'bed': 0.0}

4.计算逆文档频率

python 复制代码
def computeIDF(docList):
    idfDict = {}
    doc_len = len(docList)
    
    idfDict = dict.fromkeys(docList[0].keys(), 0)
    
    for doc in docList:
        for word, count in doc.items():
            if count > 0:
                idfDict[word] += 1
      
    for word, count in idfDict.items():
        idfDict[word] = math.log10((doc_len + 1) / float(count + 1))
    return idfDict

idf = computeIDF([wordCountA, wordCountB])
print(idf)
复制代码
{'on': 0.0, 'my': 0.0, 'face': 0.17609125905568124, 'sat': 0.0, 'dog': 0.17609125905568124, 'The': 0.0, 'cat': 0.17609125905568124, 'bed': 0.17609125905568124}

5.计算 TF-IDF

python 复制代码
def computeTFIDF(tf, idf):
    tfidf = {}
    for word, tf in tf.items():
        tfidf[word] = tf * idf[word]
    return tfidf

tfidfA = computeTFIDF(tfA, idf)
tfidfB = computeTFIDF(tfB, idf)
pd.DataFrame([tfidfA, tfidfB])

| | on | my | face | sat | dog | The | cat | bed |
| 0 | 0.0 | 0.0 | 0.029349 | 0.0 | 0.000000 | 0.0 | 0.029349 | 0.000000 |

1 0.0 0.0 0.000000 0.0 0.029349 0.0 0.000000 0.029349
相关推荐
lingyubb21 小时前
做短视频配音,想找操作简单、效果好的 AI 配音软件,有哪些可选?
自然语言处理·语音识别·ai配音·多语种
逐步走向自律1 天前
运维手机应急 + 电脑多终端并行:2026 远程终端选型指南
人工智能·深度学习·机器学习·自然语言处理·数据科学
果霸大叔1 天前
AI网关第8篇:AI 代理与负载均衡--多模型实例如何调度?
人工智能·算法·自然语言处理·负载均衡·ai-native
合调于形1 天前
Jicsuanji shzjue《计算机视觉》词条汉语拼音字母标调拼写实测案例
人工智能·自然语言处理·人机交互·语音识别·学习方法
牧羊人.3331 天前
自然语言处理基础 03|门控循环单元 GRU
网络·人工智能·rnn·深度学习·自然语言处理·gru
哈__1 天前
260+异构同步链路:DDL语法自动翻译在大规模数据同步中的实现原理
人工智能·自然语言处理·机器翻译
Yyyyyy~2 天前
【NLP】文本预处理
人工智能·自然语言处理
小李同学_LHY2 天前
第一章:从人工智能到大语言模型:概念梳理与关系辨析
人工智能·语言模型·自然语言处理
牧羊人.3332 天前
自然语言处理基础 04|长短期记忆网络 LSTM
网络·人工智能·rnn·深度学习·学习·自然语言处理·lstm
空 白II3 天前
10.14 大语言模型研究简报:Google 发布 长上下文模型 Gemini 4 Argon
人工智能·自然语言处理