文檔去重(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, Tupleclass MinHash:def __init__(self, num_hashes: int = 100):self.num_hashes = num_hashesself.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 primereturn [(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_hashesfor word in document:for i, (a, b, c) in enumerate(self.hash_functions):hash_value = (a * hash(word) + b) % csignature[i] = min(signature[i], hash_value)return signaturedef 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_hashesdef deduplicate(self, documents: List[str], threshold: float = 0.5) -> List[str]:"""Deduplicate documents based on MinHash similarity."""# Preprocess documents into sets of wordsdoc_sets = [set(doc.lower().split()) for doc in documents]# Compute MinHash signatures for all documentssignatures = [self._minhash(doc_set) for doc_set in doc_sets]# Find unique documentsunique_docs = []for i, doc in enumerate(documents):is_duplicate = Falsefor j in range(len(unique_docs)):if self.jaccard_similarity(signatures[i], signatures[j]) >= threshold:is_duplicate = Truebreakif 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, Tupleclass SimHash:def __init__(self, hash_bits: int = 64):self.hash_bits = hash_bitsdef _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_bitsfor feature in features:feature_hash = self._string_hash(feature)for i in range(self.hash_bits):bitmask = 1 << iif feature_hash & bitmask:v[i] += 1else:v[i] -= 1fingerprint = 0for i in range(self.hash_bits):if v[i] >= 0:fingerprint |= 1 << ireturn fingerprintdef _hamming_distance(self, hash1: int, hash2: int) -> int:"""Compute the Hamming distance between two hashes."""xor = hash1 ^ hash2return 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 = Falsefor unique_doc, unique_hash in unique_docs:if self.compute_similarity(doc_hash, unique_hash) >= threshold:is_duplicate = Truebreakif 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.pswp.cn/web/44297.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/44297.shtml
英文地址,請注明出處:http://en.pswp.cn/web/44297.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據分析_計劃

我做大數據的有6年了&#xff0c;以前都是用sql&#xff0c;或者spark&#xff0c;java&#xff0c;scala&#xff0c;python去做。現在這些平臺搭建、維護、大多數都是搭建一次就完了&#xff0c;而且維護大多是大廠直接用云平臺去做。ETL也是就做一次就夠了&#xff0c;我們公…

基于JAVA+SpringBoot+Vue+Uni-app前后端分離的校園好物小紅書分享平臺小程序

?全網粉絲20W,csdn特邀作者、博客專家、CSDN新星計劃導師、java領域優質創作者,博客之星、掘金/華為云/阿里云/InfoQ等平臺優質作者、專注于Java技術領域和畢業項目實戰? &#x1f345;文末獲取項目下載方式&#x1f345; 一、項目背景介紹&#xff1a; 在快速數字化的時代背…

同三維T80004EA編解碼器視頻使用操作說明書:高清HDMI編解碼器,高清SDI編解碼器,4K超清HDMI編解碼器,雙路4K超高清編解碼器

同三維T80004EA編解碼器視頻使用操作說明書&#xff1a;高清HDMI編解碼器&#xff0c;高清SDI編解碼器&#xff0c;4K超清HDMI編解碼器&#xff0c;雙路4K超高清編解碼器 同三維T80004EA編解碼器視頻使用操作說明書&#xff1a;高清HDMI編解碼器&#xff0c;高清SDI編解碼器&am…

UniVue@v1.3.0版本發布

GitHub倉庫 發布版本倉庫&#xff1a;https://github.com/Avalon712/UniVue 開發版本倉庫&#xff1a;https://github.com/Avalon712/UniVue-Develop UniVue拓展框架UniVue源生成器倉庫&#xff1a;https://github.com/Avalon712/UniVue-SourceGenerator v1.3.0版本新增功能…

DangerWind-RPC-framework---四、SPI

SPI 即 Service Provider Interface &#xff0c;可以理解為專門提供給服務提供者或者擴展框架功能的開發者去使用的一個接口。SPI 將服務接口和具體的服務實現分離開來&#xff0c;將服務調用方和服務實現者解耦&#xff0c;能夠提升程序的擴展性、可維護性。修改或者替換服務…

etcd 實現分布式鎖

10 基于 Etcd 的分布式鎖實現原理及方案

如何通過兔子和窩窩的故事理解“在機器人學習和研究中的獲得成本與維護成本”(節選)

獲得成本 掌握一門課程&#xff0c;以最為簡單的學校成績過60為例&#xff0c;需要按要求提交材料&#xff0c;包括作業、報告、實驗和考試等&#xff0c;依據學分和考核要求的不同&#xff0c;需要對于花費時間和經歷進行完成。 維護成本 考完了&#xff0c;如果被動學習那…

docker拉取鏡像-配置阿里云鏡像加速

1、配置阿里云鏡像&#xff08;用于拉取鏡像加速&#xff09; sudo mkdir -p /etc/docker sudo tee /etc/docker/daemon.json <<-EOF {"registry-mirrors": ["https://xxxxxxxx.mirror.aliyuncs.com"] } EOF sudo systemctl daemon-reload sudo syst…

Docker 使用基礎(4)—存儲卷

&#x1f3ac;慕斯主頁&#xff1a;修仙—別有洞天 ??今日夜電波&#xff1a;秒針を噛む—ずっと真夜中でいいのに。 0:34━━━━━━?&#x1f49f;──────── 4:20 &#x1f504; ?? ? …

JVM堆內存的結構,YGC,FGC的原理

JVM堆內存結構&#xff1a; JVM堆內存可分為三個區域&#xff1a;新生代&#xff08;Young Generation&#xff09;、年老代&#xff08;Tenured Generation&#xff0c;也叫做Old Generation&#xff09;和永久代&#xff08;Permanent Generation&#xff0c;也叫做Method Ar…

linux 設置nginx開機自啟

1、關閉當前nginx運行 systemctl stop nginx 2、添加以下內容到nginx.service文件&#xff0c;注意nginx.pid文件的路徑&#xff0c;要替換哦&#xff01; vim /etc/systemd/system/nginx.service [Unit] DescriptionThe NGINX HTTP and reverse proxy server Afternetwork…

ArcGIS如何快速對齊兩個圖層

1、問題 如何讓兩個圖層快速對齊 2、使用捕捉工具 移動點或折點&#xff0c;使其與其他要素的折點、邊或端點精確重合。 可指定捕捉規則來控制是將輸入折點捕捉到指定距離范圍內的最近折點、邊還是端點。

MySQL數字相關數據處理函數

目錄 1. 隨機數生成 rand ( ) 2. 四舍五入 round&#xff08;&#xff09; 3. 舍去 truncate ( ) 4. 向上/下取整 5. 空處理 ifnull&#xff08; x , y &#xff09; 1. 隨機數生成 rand ( ) rand ( ) 生成 0 到 1 的隨機數&#xff1b; rand ( x ) 生成 0 到 1 的隨機數…

簡單理解Lua 協程(coroutine)

也許更好的閱讀體驗 協程簡單理解為可以暫停的線程&#xff0c;但是同一時刻只有一個協程可以處于運行狀態。 文章目錄 coroutine.create()coroutine.resume()coroutine.wrap()coroutine.yield()coroutine.resume()參數傳遞resume和yield之間互換數據 coroutine.create() lua…

403 禁止錯誤: 它是什么?如何修復?

您應該對403錯誤代碼很熟悉&#xff01;這種錯誤會導致流量損失&#xff0c;甚至錯失一些商業機會&#xff01; 什么&#xff1f;您在自己的網站上遇到了403錯誤&#xff1f;請立即修復它&#xff01;但是什么原因導致這種錯誤&#xff1f;該如何解決&#xff1f;這兩個問題都…

66種智能優化算法和改進優化算法優化BP神經網絡【開源代碼!】【文末福利IT學習資料】

前言 熟話說得好&#xff0c;創新點不夠&#xff0c;智能優化算法來湊&#xff0c;不要覺得羞恥&#xff0c;因為不僅我們這么干&#xff0c;很多外國人也這么干&#xff01;因為創新點實在太難想了&#xff0c;和優化算法結合下是最簡單的創新點了&#xff01; 之前給大家分享…

485通訊抗干擾,超時重發,不斷重連的程序架構

485通訊抗干擾,超時重發,不斷重連的編程思路 在工程中會遇到一種情況,當通信受到干擾之后,數據超時重發多次,無法被成功發出去,當恢復干擾后,之前發送的指令就被報錯清掉了,相當于串口掉線之后,即使短暫時間內通信連上,掉線之后發出的指令也不生效。 為了確保受到干…

OFDM符號周期

OFDM符號周期的確定 OFDM符號周期的確定是一個復雜的過程&#xff0c;需要考慮多個因素。以下是主要的考慮因素和確定步驟&#xff1a; 主要考慮因素 信道特性 多徑延遲擴展相干時間 系統要求 數據速率頻譜效率 硬件限制 采樣率計算復雜度 應用場景 移動性要求覆蓋范圍 …

spark shuffle寫操作——SortShuffleWriter

寫入的簡單流程&#xff1a; 1.生成ExternalSorter對象 2.將消息都是插入ExternalSorter對象中 3.獲取到mapOutputWriter&#xff0c;將中間產生的臨時文件合并到一個臨時文件 4.生成最后的data文件和index文件 可以看到寫入的重點類是ExternalSorter對象 ExternalSorter 基…

Vant Ui 最新訪問地址

Vant 4 - A lightweight, customizable Vue UI library for mobile web apps. 順帶一個頂部導航欄正常寫法 先使用吸頂為0&#xff0c;然后再寫nav-bar <van-sticky :offset-top"0"> <van-nav-bar class"top-title" title"村集體土地公示&q…