自然语言处理_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
相关推荐
小言从不摸鱼17 分钟前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
AI进修生6 小时前
全新WordPress插件简化成功之路
人工智能·语言模型·自然语言处理
勤劳兔码农6 小时前
文本分类实战项目:如何使用NLP构建情感分析模型
自然语言处理·分类·数据挖掘
知来者逆7 小时前
讨论人机交互研究中大语言模型的整合与伦理问题
人工智能·gpt·语言模型·自然语言处理·人机交互
i嗑盐の小F7 小时前
【IEEE出版,高录用 | EI快检索】第二届人工智能与自动化控制国际学术会议(AIAC 2024,10月25-27)
图像处理·人工智能·深度学习·算法·自然语言处理·自动化
i嗑盐の小F8 小时前
【IEEE&ACM Fellow、CCF组委】第三届人工智能与智能信息处理国际学术会议(AIIIP 2024)
人工智能·深度学习·算法·机器学习·自然语言处理·信号处理
鲸可落8 小时前
【Finetune】(一)、transformers之BitFit微调
语言模型·自然语言处理·大语言模型·教程·预训练·finetune·代码实战
大耳朵爱学习10 小时前
大模型预训练的降本增效之路——从信息密度出发
人工智能·深度学习·机器学习·自然语言处理·大模型·llm·大语言模型
loongloongz10 小时前
联合条件概率 以及在语言模型中的应用
人工智能·语言模型·自然语言处理·概率论