自然语言处理_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
相关推荐
java1234_小锋5 小时前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 热词评论查询功能实现
python·自然语言处理·flask
金井PRATHAMA10 小时前
主要分布在背侧海马体(dHPC)CA1区域(dCA1)的时空联合细胞对NLP中的深层语义分析的积极影响和启示
人工智能·神经网络·自然语言处理
Easy数模21 小时前
Word2Vec模型训练全流程解析:从数据预处理到实体识别应用
人工智能·机器学习·自然语言处理·word2vec
weixin_4224564421 小时前
第N8周:使用Word2vec实现文本分类
人工智能·自然语言处理·word2vec
_abab1 天前
图书推荐-由浅入深的大模型构建《从零构建大模型》
人工智能·语言模型·自然语言处理
初恋叫萱萱1 天前
Kimi K2 大语言模型技术特性与应用实践分析
人工智能·语言模型·自然语言处理
java1234_小锋1 天前
【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 主页-最近七天微博发布量实现
python·自然语言处理·flask
DO_Community2 天前
DigitalOcean 一键模型部署,新增支持百度开源大模型ERNIE 4.5 21B
人工智能·深度学习·百度·自然语言处理·开源
静心问道2 天前
BiLLM:突破大语言模型后训练量化的极限
人工智能·语言模型·自然语言处理
小哲慢慢来2 天前
Text2SQL智能问答系统开发(一)
python·自然语言处理