自然语言处理_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
相关推荐
柯儿的天空1 小时前
Mem0深度解析:给你的ai agent加上长期记忆,让ai从“健忘“到“过目不忘“
人工智能·gpt·自然语言处理·ai作画·aigc·ai编程·agi
懒麻蛇2 小时前
用大语言模型生成心理学范式 2.0
人工智能·语言模型·自然语言处理
AI产品备案3 小时前
生成式人工智能(大语言模型)上线备案表【模版分享+填报指南】
人工智能·语言模型·自然语言处理
龙腾AI白云3 小时前
如何利用大语言模型的能力进行实体关系抽取
人工智能·语言模型·自然语言处理·tornado
Spliceㅤ6 小时前
项目:基于qwen的点餐系统
开发语言·人工智能·python·机器学习·自然语言处理
有为少年6 小时前
ArXiv 2603 | 用神经元胞自动机训练语言模型:合成数据能超越自然语言吗?
人工智能·语言模型·自然语言处理
韭菜盖饭7 小时前
大模型常见八股集合(带答案)
语言模型·自然语言处理·面试·transformer
AI精钢7 小时前
Agent Harness,正在成为新的 MLOps
人工智能·自然语言处理·语音识别·mlops·ai agent·agentops·ai engineering
人工智能培训7 小时前
如何利用大语言模型的能力进行实体关系抽取
大数据·人工智能·深度学习·语言模型·自然语言处理·大模型·数字孪生
jinanwuhuaguo8 小时前
OpenClaw v2026.3.22-beta.1 深度技术分析报告:从单智能体操作系统到多智能体协作平台的范式跃迁
运维·人工智能·语言模型·自然语言处理·visual studio code·openclaw