simhash原理及使用
1. 簡介
simhash是一種局部敏感hash。那什么叫局部敏感呢,假定兩個字符串具有一定的相似性,在hash之后,仍然能保持這種相似性,就稱之為局部敏感hash。普通的hash是不具有這種屬性的。simhash被Google用來在海量文本中去重。
2. 原理
算法過程大概如下:
3. 距離計算
通過simhash,我們要度量兩個文檔的相似度就可以通過度量它們的simhash值相似度。度量兩個simhash值相似度一般使用海明距離。
二進制串A和二進制串B的海明距離 就是A異或B后二進制中1的個數。
舉例如下:
A = 100111; B = 101010; hamming_distance(A, B) = count_1(A xor B) = count_1(001101) = 3A和B的海明距離是否小于等于n,這個n值根據經驗一般取值為3。
4. Python使用
使用simhash。
(1) 查看simhash值
>>> from simhash import Simhash >>> print '%x' % Simhash(u'I am very happy'.split()).value 9f8fd7efdb1ded7fSimhash()接收一個token序列,或者叫特征序列。
(2)計算兩個simhash值距離
>>> hash1 = Simhash(u'I am very happy'.split()) >>> hash2 = Simhash(u'I am very sad'.split()) >>> print hash1.distance(hash2) 5(3)建立索引
simhash被用來去重。如果兩兩分別計算simhash值,數據量較大的情況下肯定hold不住。有專門的數據結構,參考:http://www.cnblogs.com/maybe2030/p/5203186.html#_label4
from simhash import Simhash, SimhashIndex # 建立索引 data = {u'1': u'How are you I Am fine . blar blar blar blar blar Thanks .'.lower().split(),u'2': u'How are you i am fine .'.lower().split(),u'3': u'This is simhash test .'.lower().split(), } objs = [(id, Simhash(sent)) for id, sent in data.items()] index = SimhashIndex(objs, k=10) # k是容忍度;k越大,檢索出的相似文本就越多 # 檢索 s1 = Simhash(u'How are you . blar blar blar blar blar Thanks'.lower().split()) print index.get_near_dups(s1) # 增加新索引 index.add(u'4', s1)Ref
http://yanyiwu.com/work/2014/01/30/simhash-shi-xian-xiang-jie.html
http://blog.csdn.net/madujin/article/details/53152619
http://leons.im/posts/a-python-implementation-of-simhash-algorithm/
總結
以上是生活随笔為你收集整理的simhash原理及使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 智能家居开源平台——Home Assis
- 下一篇: chrome升级后无法访问iframe页