自然语言处理_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
相关推荐
layneyao2 小时前
AI与自然语言处理(NLP):从BERT到GPT的演进
人工智能·自然语言处理·bert
IT古董4 小时前
【漫话机器学习系列】249.Word2Vec自然语言训练模型
机器学习·自然语言处理·word2vec
大模型最新论文速读14 小时前
在Text-to-SQL任务中应用过程奖励模型
数据库·人工智能·sql·深度学习·语言模型·自然语言处理
L_cl16 小时前
【NLP 71、常见大模型的模型结构对比】
自然语言处理
知来者逆19 小时前
AI 在模仿历史语言方面面临挑战:大型语言模型在生成历史风格文本时的困境与研究进展
人工智能·深度学习·语言模型·自然语言处理·chatgpt
qq_189370491 天前
自然语言处理NLP中的连续词袋(Continuous bag of words,CBOW)方法、优势、作用和程序举例
人工智能·自然语言处理·连续词袋
学算法的程霖1 天前
TGRS | FSVLM: 用于遥感农田分割的视觉语言模型
人工智能·深度学习·目标检测·机器学习·计算机视觉·自然语言处理·遥感图像分类
TextIn智能文档云平台1 天前
PDF文档解析新突破:图表识别、公式还原、手写字体处理,让AI真正读懂复杂文档!
图像处理·人工智能·算法·自然语言处理·pdf·ocr
nenchoumi31191 天前
LLM 论文精读(四)LLM Post-Training: A Deep Dive into Reasoning Large Language Models
人工智能·语言模型·自然语言处理
Jamence1 天前
多模态大语言模型arxiv论文略读(六十九)
神经网络·语言模型·自然语言处理