当前位置: 首页 > article >正文

自然语言处理_tf-idf

import pandas as pd
import math

1.数据预处理

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.计算词的频数

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])    
onmyfacesatdogThecatbed
011110110
111011101

3.计算词的频率

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.计算逆文档频率

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

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])
onmyfacesatdogThecatbed
00.00.00.0293490.00.0000000.00.0293490.000000
10.00.00.0000000.00.0293490.00.0000000.029349

http://www.kler.cn/a/314952.html

相关文章:

  • 必修 -- 常用笔试题
  • Database Advantages (数据库系统的优点)
  • Docker compose部署portainer
  • Mysql数据库里的SSH连接
  • redis7.x源码分析:(1) sds动态字符串
  • 优化时钟网络之时钟抖动
  • Java 入门指南:Java 8 新特性 —— Stream 流
  • JavaScript 插入元素到数组三个方法代码示例
  • celery 结合 rabbitmq 使用时,celery 消费者执行时间太久发送 ack 消息失败
  • 【研发日记】嵌入式处理器技能解锁(六)——ARM的Cortex-M4内核
  • 【js常用函数封装】获取年龄,根据身份证获取年龄,性别,生日
  • 算法笔试-编程练习-好题-07
  • 《MmAP : Multi-Modal Alignment Prompt for Cross-Domain Multi-Task Learning》中文校对版
  • Homebrew安装与切换下载源
  • 单例模式(饿汉式-懒汉式)
  • leetcode:3232. 判断是否可以赢得数字游戏(python3解法)
  • FastDFS架构和原理
  • RabbitMQ:交换机详解(Fanout交换机、Direct交换机、Topic交换机)
  • Linux实用命令 df和du命令
  • 数据结构之‘栈’
  • 面向对象程序设计
  • VisionPro - 基础 - 模板匹配技术-Search/PMAlign/PatMax(6)-纹理屏蔽和重叠匹配
  • Redis面试真题总结(四)
  • 多模态交互才是人机交互的未来
  • MoFA: 迈向AIOS
  • 【QGIS入门实战精品教程】6.1:QGIS根据属性条件查询数据(SQL表达式)