自然语言处理_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
相关推荐
小道士写程序16 小时前
自然语言处理NLP - 第8章 词向量与神经网络:从手工特征到学习表示
神经网络·学习·自然语言处理
Jialu.1 天前
中文 NLP 模型部署实战:FastAPI 接口 + Streamlit 看板
人工智能·python·自然语言处理·fastapi
LlmCraft|大模型工程实践1 天前
01-NLP入门-什么是自然语言处理
人工智能·自然语言处理
LlmCraft|大模型工程实践2 天前
03 文本向量化:词袋模型与 TF-IDF
自然语言处理·nlp·tf-idf
大模型任我行2 天前
蚂蚁:金融文档解析新范式
人工智能·语言模型·自然语言处理·金融·论文笔记
小白说大模型2 天前
基于 Qwen3.8-Max 构建 AI 合同精审系统:文档解析、多轮条款分析 Pipeline 工程实战
数据库·人工智能·spring·机器学习·自然语言处理
Asa121382 天前
Science Advances|大语言模型增强宏基因组酶功能注释
人工智能·语言模型·自然语言处理
傲笑风2 天前
【openvino】tinybert基于openvino服务化部署(四)
人工智能·python·自然语言处理·nlp·bert·openvino
啊阿狸不会拉杆2 天前
《自然语言处理:基于大语言模型的方法》第1章 绪论 读书笔记
人工智能·自然语言处理·nlp·easyui·智能体