文档去重(TF-IDF,MinHash, SimHash)

2个doc有些相似有些不相似,如何衡量这个相似度;

直接用Jaccard距离,计算量太大

TF-IDF: TF*IDF

TF:该词在该文档中的出现次数,

IDF:该词在所有文档中的多少个文档出现是DF,lg(N/(1+DF))

MinHash

代码:

import random
from typing import List, Set, Tuple

class MinHash:
    def __init__(self, num_hashes: int = 100):
        self.num_hashes = num_hashes
        self.hash_functions = self._generate_hash_functions()

    def _generate_hash_functions(self) -> List[Tuple[int, int, int]]:
        """Generate hash functions of the form (a*x + b) % c."""
        max_prime = 2**31 - 1  # Mersenne prime
        return [(random.randint(1, max_prime), random.randint(0, max_prime), max_prime)
                for _ in range(self.num_hashes)]

    def _minhash(self, document: Set[str]) -> List[int]:
        """Compute MinHash signature for a document."""
        signature = [float('inf')] * self.num_hashes
        for word in document:
            for i, (a, b, c) in enumerate(self.hash_functions):
                hash_value = (a * hash(word) + b) % c
                signature[i] = min(signature[i], hash_value)
        return signature

    def jaccard_similarity(self, sig1: List[int], sig2: List[int]) -> float:
        """Estimate Jaccard similarity from MinHash signatures."""
        return sum(s1 == s2 for s1, s2 in zip(sig1, sig2)) / self.num_hashes

    def deduplicate(self, documents: List[str], threshold: float = 0.5) -> List[str]:
        """Deduplicate documents based on MinHash similarity."""
        # Preprocess documents into sets of words
        doc_sets = [set(doc.lower().split()) for doc in documents]
        
        # Compute MinHash signatures for all documents
        signatures = [self._minhash(doc_set) for doc_set in doc_sets]
        
        # Find unique documents
        unique_docs = []
        for i, doc in enumerate(documents):
            is_duplicate = False
            for j in range(len(unique_docs)):
                if self.jaccard_similarity(signatures[i], signatures[j]) >= threshold:
                    is_duplicate = True
                    break
            if not is_duplicate:
                unique_docs.append(doc)
        
        return unique_docs

100个hash函数;

在某个hash函数上,1个doc里的所有word,在该函数上的hash值,其中最小的那个,记下来;

该doc得到100个最小hash值,该100维向量,作为其signature;

2个doc的相似度,就是100个维度里的相等数目,除以100;

SimHash

MinHash和SimHash_minhash simhash-CSDN博客

海量文本去重(允许一定的噪声);文档里权重最大的前N个词(或词组)进行Hash编码,1正0负乘以词的权重,N个词的向量按位相加,再反编码(正1负0),得到该文档的编码;两篇文档的距离用编码的海明距离,小于Bar(例如3)则认为二者相似;

import hashlib
from typing import List, Tuple

class SimHash:
    def __init__(self, hash_bits: int = 64):
        self.hash_bits = hash_bits

    def _string_hash(self, text: str) -> int:
        """Create a hash for a given string."""
        return int(hashlib.md5(text.encode('utf-8')).hexdigest(), 16)

    def _create_shingles(self, text: str, k: int = 2) -> List[str]:
        """Create k-shingles from the text."""
        return [text[i:i+k] for i in range(len(text) - k + 1)]

    def _compute_simhash(self, features: List[str]) -> int:
        """Compute the SimHash of a list of features."""
        v = [0] * self.hash_bits
        
        for feature in features:
            feature_hash = self._string_hash(feature)
            for i in range(self.hash_bits):
                bitmask = 1 << i
                if feature_hash & bitmask:
                    v[i] += 1
                else:
                    v[i] -= 1
        
        fingerprint = 0
        for i in range(self.hash_bits):
            if v[i] >= 0:
                fingerprint |= 1 << i
        
        return fingerprint

    def _hamming_distance(self, hash1: int, hash2: int) -> int:
        """Compute the Hamming distance between two hashes."""
        xor = hash1 ^ hash2
        return bin(xor).count('1')

    def compute_similarity(self, hash1: int, hash2: int) -> float:
        """Compute the similarity between two SimHashes."""
        distance = self._hamming_distance(hash1, hash2)
        return 1 - (distance / self.hash_bits)

    def deduplicate(self, documents: List[str], threshold: float = 0.9) -> List[Tuple[str, int]]:
        """Deduplicate documents based on SimHash similarity."""
        unique_docs = []
        
        for doc in documents:
            shingles = self._create_shingles(doc.lower())
            doc_hash = self._compute_simhash(shingles)
            
            is_duplicate = False
            for unique_doc, unique_hash in unique_docs:
                if self.compute_similarity(doc_hash, unique_hash) >= threshold:
                    is_duplicate = True
                    break
            
            if not is_duplicate:
                unique_docs.append((doc, doc_hash))
        
        return unique_docs

# Example usage
if __name__ == "__main__":
    simhash = SimHash(hash_bits=64)
    
    documents = [
        "The quick brown fox jumps over the lazy dog",
        "The quick brown fox jumps over the sleeping dog",
        "The lazy dog is sleeping",
        "A completely different document"
    ]
    
    unique_docs = simhash.deduplicate(documents, threshold=0.7)
    
    print("Original documents:")
    for doc in documents:
        print(f"- {doc}")
    
    print("\nUnique documents:")
    for doc, _ in unique_docs:
        print(f"- {doc}")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/779028.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

适合宠物饮水机的光电传感器有哪些

如今&#xff0c;随着越来越多的人选择养宠物&#xff0c;宠物饮水机作为一种便捷的饮水解决方案日益受到欢迎。为了确保宠物随时能够获得足够的水源&#xff0c;宠物饮水机通常配备了先进的光电液位传感器技术。 光电液位传感器在宠物饮水机中起着关键作用&#xff0c;主要用…

Java技术栈总结:kafka篇

一、# 基础知识 1、安装 部署一台ZooKeeper服务器&#xff1b;安装jdk&#xff1b;下载kafka安装包&#xff1b;上传安装包到kafka服务器上&#xff1a;/usr/local/kafka;解压缩压缩包&#xff1b;进入到config目录&#xff0c;修改server.properties配置信息&#xff1a; #…

SpringBoot+mail 轻松实现各类邮件自动推送

一、简介 在实际的项目开发过程中&#xff0c;经常需要用到邮件通知功能。例如&#xff0c;通过邮箱注册&#xff0c;邮箱找回密码&#xff0c;邮箱推送报表等等&#xff0c;实际的应用场景非常的多。 早期的时候&#xff0c;为了能实现邮件的自动发送功能&#xff0c;通常会…

Java | Leetcode Java题解之第218题天际线问题

题目&#xff1a; 题解&#xff1a; class Solution {public List<List<Integer>> getSkyline(int[][] buildings) {PriorityQueue<int[]> pq new PriorityQueue<int[]>((a, b) -> b[1] - a[1]);List<Integer> boundaries new ArrayList&l…

html+js+css做的扫雷

做了个扫雷&#x1f4a3; 88大小 源代码在文章最后 界面 先点击蓝色开局按钮 然后就可以再扫雷的棋盘上玩 0代表该位置没有雷 其他数字代表周围雷的数量 源代码 <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8&qu…

第5章 认证授权:需求分析,Security介绍(OAuth2,JWT),用户认证,微信扫码登录,用户授权

1 模块需求分析 1.1 什么是认证授权 截至目前&#xff0c;项目已经完成了课程发布功能&#xff0c;课程发布后用户通过在线学习页面点播视频进行学习。如何去记录学生的学习过程呢&#xff1f;要想掌握学生的学习情况就需要知道用户的身份信息&#xff0c;记录哪个用户在什么…

编写优雅Python代码的20个最佳实践

想要让你的代码像艺术品一样既实用又赏心悦目吗&#xff1f;今天我们就来聊聊如何通过20个小技巧&#xff0c;让你的Python代码从平凡走向优雅&#xff0c;让同行看了都忍不住点赞&#xff01; **温馨提示&#xff1a;更多的编程资料&#xff0c;领取方式在&#xff1a; 1. 拥…

【Python文件】操作终极指南:高效管理和处理文件系统的必备技能

目录 ​编辑 1. 文件的基础操作 1.1 打开/关闭文件 ​编辑 示例代码 文件对象 使用with语句打开文件 2. 读文件 2.1 使用read方法读取文件 2.2 使用readline方法读取文件 2.3 使用readlines方法读取文件 2.4 使用for循环读取文件 3. 写文件 3.1 使用write方法写文…

Podman 深度解析

目录 引言Podman 的定义Podman 的架构Podman 的工作原理Podman 的应用场景Podman 在 CentOS 上的常见命令实验场景模拟总结 1. 引言 随着容器化技术的发展&#xff0c;Docker 已成为容器管理的代名词。然而&#xff0c;由于 Docker 的一些局限性&#xff0c;如需要守护进程和 …

基于java+springboot+vue实现的大学生就业需求分析系统(文末源码+Lw)233

摘 要 信息数据从传统到当代&#xff0c;是一直在变革当中&#xff0c;突如其来的互联网让传统的信息管理看到了革命性的曙光&#xff0c;因为传统信息管理从时效性&#xff0c;还是安全性&#xff0c;还是可操作性等各个方面来讲&#xff0c;遇到了互联网时代才发现能补上自…

jmeter-beanshell学习3-beanshell获取请求报文和响应报文

前后两个报文&#xff0c;后面报文要用前面报文的响应结果&#xff0c;这个简单&#xff0c;正则表达式或者json提取器&#xff0c;都能实现。但是如果后面报文要用前面请求报文的内容&#xff0c;感觉有点难。最早时候把随机数写在自定义变量&#xff0c;前后两个接口都用这个…

HTML5使用<progress>进度条、<meter>刻度条

1、<progress>进度条 定义进度信息使用的是 progress 标签。它表示一个任务的完成进度&#xff0c;这个进度可以是不确定的&#xff0c;只是表示进度正在进行&#xff0c;但是不清楚还有多少工作量没有完成&#xff0c;也可以用0到某个最大数字&#xff08;如&#xff1…

如何搜索查找ICLR论文

记录有几个查找顶级会议文章的网址&#xff0c;不止ICLR ICLR 2024 还会有visualization模式&#xff1a; ICLR 2024 virtual 这个网站也很棒 Paper Copilot ICLR 2024 当然还有一个用图表示各论文相关关系的网站&#xff1a; connected papers

ROS——坐标系管理、监听与广播、常用可视化工具

坐标系管理 TF功能包 小海龟追踪实验 ros版本(20.04)的tf安装命令: sudo apt-get install ros-noetic-turtle-tf 解决因python版本出现的无法生成跟随海龟&#xff1a; sudo ln -s /usr/bin/python3 /usr/bin/python ( -s 软链接,符号链接) ln命令&#xff08;英文全拼&#…

Matplotlib Artist 1 概览

Matplotlib API中有三层 matplotlib.backend_bases.FigureCanvas&#xff1a;绘制区域matplotlib.backend_bases.Renderer&#xff1a;控制如何在FigureCanvas上绘制matplotlib.artist.Artist&#xff1a;控制render如何进行绘制 开发者95%的时间都是在使用Artist。Artist有两…

【MYSQL】InnoDB引擎为什么选可重复读作为默认隔离级别

InnoDB引擎为什么选可重复读作为默认隔离级别 一般的DBMS系统&#xff0c;默认都会使用读提交&#xff08;Read-Comitted&#xff0c;RC&#xff09;作为默认隔离级别&#xff0c;如Oracle、SQL Server等&#xff0c;而MySQL却使用可重复读&#xff08;Read-Repeatable&#x…

MySQL 9.0 创新版发布,大失所望。。

大家好&#xff0c;我是程序员鱼皮。2024 年 7 月 1 日&#xff0c;MySQL 发布了 9.0 创新版本。区别于我们大多数开发者常用的 LTS&#xff08;Long-Term Support&#xff09;长期支持版本&#xff0c;创新版本的发布会更频繁、会更快地推出新的特性和变更&#xff0c;可以理解…

白嫖A100活动-入门篇-1.Linux+InterStudio

进入InterStudio 这节课是为了让大家熟悉使用InterStudio平台&#xff0c;以便后续开发 InterStudio平台是算力平台&#xff0c;可以通过平台使用A100,还可以使用“书生”团队集成好的环境、工具&#xff0c;快速部署LLMs. 进入平台&#xff1a; 记得报名&#xff0c;获得免…

快排的非递归实现

前提 快排的递归实现&#xff0c;在深度过深时会存在栈溢出的风险&#xff0c;所以我们需要掌握快排的非递归写法 快排的实现 单趟实现 上次我们使用了hoare的快排单趟写法&#xff0c;所以这次我们使用前后指针法. 前后指针法 初始状态下&#xff0c;初始化prev为left,cu…

Android Studio Run窗口中文乱码解决办法

Android Studio Run窗口中文乱码解决办法 问题描述&#xff1a; AndroidStudio 编译项目时Run窗口中文乱码&#xff0c;如图&#xff1a; 解决方法&#xff1a; 依次打开菜单&#xff1a;Help--Edit Custom VM Options&#xff0c;打开studio64.exe.vmoptions编辑框&#xf…