自然语言处理_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
相关推荐
CCPC不拿奖不改名19 小时前
python基础面试编程题汇总+个人练习(入门+结构+函数+面向对象编程)--需要自取
开发语言·人工智能·python·学习·自然语言处理·面试·职场和发展
isAchilles20 小时前
NLP入门:分词化与词表映射详解
人工智能·自然语言处理
赋创小助手20 小时前
超微2U高密度服务器AS-2126HS-TN评测(双AMD EPYC 9005 Turin)
运维·服务器·人工智能·深度学习·神经网络·自然语言处理·架构
Rabbit_QL21 小时前
【LLM背景】语言模型简史:从概率统计到通用智能接口
人工智能·语言模型·自然语言处理
分享牛21 小时前
LangChain4j从入门到精通-3-聊天与语言模型
人工智能·语言模型·自然语言处理
renhongxia121 小时前
多模型协作定律:大型语言模型模型集成的缩放极限
人工智能·信息可视化·语言模型·自然语言处理·数据分析
SCKJAI21 小时前
突破边界,智联未来:赋能远程控制新体验
人工智能·机器学习·计算机视觉·自然语言处理·自动驾驶
肥猪猪爸1 天前
NLP中BIO标签浅析
人工智能·深度学习·神经网络·机器学习·自然语言处理·nlp
蓝海星梦1 天前
【强化学习】深度解析 GSPO:解决 GRPO 中优化目标与奖励不匹配的问题
论文阅读·人工智能·自然语言处理·大语言模型·强化学习
范桂飓1 天前
Transformer 大模型架构深度解析(1)NLP 自然语言处理文本表示方法
人工智能·深度学习·自然语言处理·transformer