主頁 > 移動端開發 > 當整個串列很長(10000)時,識別所有串列對的最快方法,它們的差異低于給定閾值

當整個串列很長(10000)時,識別所有串列對的最快方法,它們的差異低于給定閾值

2022-10-28 23:13:38 移動端開發

嗨,大家。很抱歉打擾你。

我有這個任務,我有一個存盤在一個串列中的哈希編碼串列,其中包含 30 個位置,值為 0 和 1。總的來說,我有超過 10000 個這樣的 30 大小(0/1)哈希碼,我想找到所有對這種哈希碼的差異低于給定閾值(例如 0、1、5),在這種情況下,這對將被視為“相似”哈希碼。

我已經在python3中使用雙“for回圈”實作了這一點(見下面的代碼),但我覺得它不夠高效,因為這似乎是一個O(N!),當N = 10000或時它確實很慢更大。

我的問題是有沒有更好的方法可以加快尋找相似哈希對的速度?理想情況下,我想在 O(N) 中?

注意效率我的意思是在給定的情況下找到相似的對而不是生成哈希編碼(這僅用于演示)。

我已經深入研究了這個問題,我找到的所有答案都是關于使用某種收集工具來查找相同的對,但在這里我有一個更一般的情況,即在給定閾值的情況下,這些對也可能是相似的。

我提供了生成示例散列編碼的代碼和我正在使用的當前低效程式。我希望你會發現這個問題很有趣,希望一些更好/更聰明/高級的程式員可以幫我解決這個問題。提前致謝。

import random
import numpy as np

# HashCodingSize = 10
# Just use this to test the program
HashCodingSize = 100
# HashCodingSize = 1000
# What can we do when we have the list over 10000, 100000 size ? 
# This is where the problem is 
# HashCodingSize = 10000
# HashCodingSize = 100000

#Generating "HashCodingSize" of list with each element has size of 30
outputCodingAllPy = []
for seed in range(HashCodingSize):
    random.seed(seed)
    listLength = 30
    numZero = random.randint(1, listLength)
    numOne = listLength - numZero
    my_list = [0] * numZero   [1] * numOne
    random.shuffle(my_list)
    # print(my_list)
    outputCodingAllPy.append(my_list)

#Covert to np array which is better than python3 list I suppose?
outputCodingAll = np.asarray(outputCodingAllPy)
print(outputCodingAll)
print("The N is", len(outputCodingAll))

hashDiffThreshold = 0
#hashDiffThreshold = 1
#hashDiffThreshold = 5
loopRange = range(outputCodingAll.shape[0])
samePairList = []

#This is O(n!) I suppose, is there better way ? 
for i in loopRange:
    for j in loopRange:
        if j > i:
            if (sum(abs(outputCodingAll[i,] - outputCodingAll[j,])) <= hashDiffThreshold):
                print("The pair (",  str(i), ", ", str(j), ") ")
                samePairList.append([i, j])

print("Following pairs are considered the same given the threshold ", hashDiffThreshold)
print(samePairList)

uj5u.com熱心網友回復:

如果您只需要 30 位向量,那么將其表示為 32 位整數中的 30 位會更好。那么兩個“向量”之間的漢明距離就是xor兩個整數的位數。計算整數中非零位數的有效演算法。這些可以很容易地使用numpy.

所以演算法是:

  • 生成HashCodingSize0 到 (1<<30)-1 之間的隨機整數。那是一條線numpy.random.randint()
  • 對于每個值與陣列進行異或運算(參見 參考資料numpy.bitwise_xor),計算每個異或輸出值中的位數(向量化位計數演算法之一),并找到位計數小于或等于的索引hashDiffThreshold

這仍然是 O(n^2),但只是 python 中的一個回圈;回圈中的每個操作都在一個長度為 n 的向量上進行numpy呼叫。

uj5u.com熱心網友回復:

只要您listLength在計算機上的整數大小范圍內,我就會改用整數。然后,您可以xor將這些值(使用廣播一次對所有值進行異或)來獲得不同的位數,對這些位求和,然后用于nonzero查找符合哈希差異要求的索引。例如:

import numpy as np
import random

HashCodingSize = 10
listLength = 30
outputCodingAll = np.array([random.choice(range(2**listLength)) for _ in range(HashCodingSize)])
# sample result
# array([995834408, 173548139, 717311089,  87822983, 813938401, 
#        363814224, 970707528, 907497995, 337492435, 361696322])

distance = bit_count(outputCodingAll[:, np.newaxis] ^ outputCodingAll)
# sample result
# array([[ 0, 10, 15, 18, 14, 18,  8, 12, 18, 16],
#        [10,  0, 13, 14, 16, 24, 14, 14, 16, 18],
#        [15, 13,  0, 23, 13, 15, 15, 17, 19, 15],
#        [18, 14, 23,  0, 18, 16, 18, 12, 12, 14],
#        [14, 16, 13, 18,  0, 16, 12, 14, 14, 14],
#        [18, 24, 15, 16, 16,  0, 14, 16, 12,  6],
#        [ 8, 14, 15, 18, 12, 14,  0, 12, 18, 14],
#        [12, 14, 17, 12, 14, 16, 12,  0, 14, 14],
#        [18, 16, 19, 12, 14, 12, 18, 14,  0, 12],
#        [16, 18, 15, 14, 14,  6, 14, 14, 12,  0]], dtype=int32)

hashDiffThreshold = 10
samePairList = np.transpose(np.nonzero(distance < hashDiffThreshold))
# sample result
# array([[0, 0],
#        [0, 6],
#        [1, 1],
#        [2, 2],
#        [3, 3],
#        [4, 4],
#        [5, 5],
#        [5, 9],
#        [6, 0],
#        [6, 6],
#        [7, 7],
#        [8, 8],
#        [9, 5],
#        [9, 9]], dtype=int64)

請注意,結果重復對(例如 [5, 9] 和 [9, 5]),因為它們都作為第一個和第二個運算元進行了測驗)。它還包括針對自身測驗的每個值(顯然是0)。如果需要,可以輕松過濾掉這些結果。

請注意,如果要將任何值轉換為串列,1并且0可以將數字格式化為長度的二進制字串listLength并將每個字符映射到 int,例如

list(map(int, f'{outputCodingAll[0]:0{listLength}b}'))
# sample output
# [0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1]

此代碼使用此答案bit_count中的函式

def bit_count(arr):
    # Make the values type-agnostic (as long as it's integers)
    t = arr.dtype.type
    mask = t(-1)
    s55 = t(0x5555555555555555 & mask)  # Add more digits for 128bit support
    s33 = t(0x3333333333333333 & mask)
    s0F = t(0x0F0F0F0F0F0F0F0F & mask)
    s01 = t(0x0101010101010101 & mask)
    
    arr = arr - ((arr >> 1) & s55)
    arr = (arr & s33)   ((arr >> 2) & s33)
    arr = (arr   (arr >> 4)) & s0F
    return (arr * s01) >> (8 * (arr.itemsize - 1))

uj5u.com熱心網友回復:

此版本利用整數的按位運算。將 numpy 二進制表示轉換為整數的方法是從這個答案https://stackoverflow.com/a/59273656/11040577中獲得的。

基準測驗結果表明,新方法比原來的方法快得多:

N = 1000, 0.194 秒 VS 3.332 秒
N = 10000, 17.417 秒 VS 338.628 秒

import random
import numpy as np
from time import perf_counter


def generate_codings(
        HashCodingSize=100,
        listLength=30
) -> np.ndarray:

    # Generating "HashCodingSize" of list with each element has size of 30
    outputCodingAllPy = []
    for seed in range(HashCodingSize):
        random.seed(seed)
        numZero = random.randint(1, listLength)
        numOne = listLength - numZero
        my_list = [0] * numZero   [1] * numOne
        random.shuffle(my_list)
        # print(my_list)
        outputCodingAllPy.append(my_list)
    # Covert to np array which is better than python3 list I suppose?
    outputCodingAll = np.asarray(outputCodingAllPy)
    return outputCodingAll


def find_pairs_by_threshold(
        coding_all: np.ndarray,
        hashDiffThreshold=0
) -> np.ndarray:

    loopRange = range(coding_all.shape[0])
    samePairList = []

    #This is O(n!) I suppose, is there better way ?
    for i in loopRange:
        for j in loopRange:
            if j > i:
                if (sum(abs(coding_all[i,] - coding_all[j,])) <= hashDiffThreshold):
                    # print("The pair (",  str(i), ", ", str(j), ") ")
                    samePairList.append([i, j])

    return np.array(samePairList)


def bits_to_int(bits: np.ndarray) -> np.ndarray:
    """
    https://stackoverflow.com/a/59273656/11040577
    :param bits:
    :return:
    """
    assert len(bits.shape) == 2
    # number of columns is needed, not bits.size
    m, n = bits.shape
    # -1 reverses array of powers of 2 of same length as bits
    a = 2**np.arange(n)[::-1]
    # this matmult is the key line of code
    return bits @ a


def find_pairs_by_threshold_fast(
        coding_all_bits: np.ndarray,
        listLength=30,
        hashDiffThreshold=0
) -> np.ndarray:

    xor_outer_matrix = np.bitwise_xor.outer(coding_all_bits, coding_all_bits)

    # counting number of differences
    diff_count_matrix = np.bitwise_and(xor_outer_matrix, 1)
    for i in range(1, listLength):
        diff_count_matrix  = np.right_shift(np.bitwise_and(xor_outer_matrix, 2**i), i)

    same_pairs = np.transpose(np.where(diff_count_matrix <= hashDiffThreshold))

    # filtering out diagonal values
    same_pairs = same_pairs[same_pairs[:, 0] != same_pairs[:, 1]]

    # filtering out duplicates above diagonal
    same_pairs.sort(axis=1)
    same_pairs = np.unique(same_pairs, axis=0)

    return same_pairs


if __name__ == "__main__":

    list_length = 30
    hash_diff_threshold = 0

    for hash_coding_size in (100, 1000, 10000):

        # let's generate samples
        output_coding_all = generate_codings(hash_coding_size, list_length)
        print("The N is", len(output_coding_all))

        # find_pairs_by_threshold bench
        start_time = perf_counter()
        same_pairs_etalon = find_pairs_by_threshold(output_coding_all, hash_diff_threshold)
        end_time = perf_counter()
        print(f"find_pairs_by_threshold() took {end_time-start_time} secs...")
        print("Following pairs are considered the same given the threshold ", same_pairs_etalon)

        # find_pairs_by_threshold_fast bench
        # first, we should convert binary representations to int
        start_time = perf_counter()
        output_coding_all_bits = bits_to_int(output_coding_all)
        end_time = perf_counter()
        print(f"it took {end_time-start_time} secs to convert numpy array binary to ints...")

        start_time = perf_counter()
        same_pairs_fast = find_pairs_by_threshold_fast(output_coding_all_bits, list_length, hash_diff_threshold)
        end_time = perf_counter()
        print(f"find_pairs_by_threshold_fast() took {end_time-start_time} secs...")

        # check if the results are the same
        print(f"Two lists of pairs found by different methods are identical: {(same_pairs_fast == same_pairs_etalon).all()}")

第一個非常消耗記憶體的版本:

outer_not_equal = np.not_equal.outer(outputCodingAll, outputCodingAll)

diff_count_matrix = outer_not_equal.sum((1, 3)) // outputCodingAll.shape[1]

samePairNumpy = np.transpose(np.where(diff_count_matrix <= hashDiffThreshold))

# filtering out diagonal values
samePairNumpy = samePairNumpy[samePairNumpy[:, 0] != samePairNumpy[:, 1]]

# filtering out duplicates above diagonal
samePairNumpy.sort(axis=1)
samePairNumpy = np.unique(samePairNumpy, axis=0)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522503.html

標籤:Pythonpython-3.x表现for循环哈希

上一篇:將資料幀拆分為更小的資料幀的最有效方法

下一篇:mongodb。如何將字串映射到另一個集合中的整數

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more