簡體   English   中英

從給定的元素列表生成隨機的numpy數組,每個元素至少重復一次

[英]Generate random numpy array from a given list of elements with at least one repetition of each element

我想創建的陣列(比如output_list從給定numpy的)(比方說input_list )重新采樣,使得從每個元素之后input_list在存在output_list至少一次。 output_list的長度將始終> input_list.的長度input_list.

我嘗試了幾種方法,現在正在尋找一種更快的方法。 不幸的是, numpyrandom.choice不能保證至少存在一個元素。

步驟1:產生資料

import string
import random
import numpy as np

size = 150000
chars = string.digits + string.ascii_lowercase
input_list= [
            "".join(
                [random.choice(chars) for i in range(5)]
            ) for j in range(dict_data[1]['unique_len'])]

選項1:讓我們嘗試numpyrandom.choice ,其概率分布均勻。

output_list = np.random.choice(
    input_list,
    size=output_size,
    replace=True,
    p=[1/input_list.__len__()]*input_list.__len__()
    )
assert set(input_list).__len__()==set(output_list).__len__(),\
    "Output list has fewer elements than input list"

這引起了斷言:

輸出列表的元素少於輸入列表的元素

選項2讓我們將隨機數填充到input_list ,然后將其隨機播放。

output_list = np.concatenate((np.array(input_list),np.random.choice(
    input_list,
    size=output_size-input_list.__len__(),
    replace=True,
    p=[1/input_list.__len__()]*input_list.__len__()
)),axis=None)

np.random.shuffle(output_list)
assert set(input_list).__len__()==set(output_list).__len__(),\
    "Output list has fewer elements than input list"

盡管這不會引起任何斷言,但我正在尋找一種比此算法或使用numpy的內置函數更快的解決方案。

謝謝你的幫助。

lenI為輸入列表長度, lenO為輸出列表長度。

1)從源列表中進行均勻隨機選擇的lenO - lenI次迭代

2)然后將所有輸入列表追加到輸出列表的末尾

3)然后對Fisher-Yates進行lenI次迭代,以均勻分布最后一個元素。

import random
src = [1, 2, 3, 4]
lD = 10
lS = len(src)
dst = []
for _ in range(lD - lS):
    dst.append(src[random.randint(0, lS-1)])
dst.extend(src)
print(dst)
for i in range(lD - 1, lD - lS - 1, -1):
    r = random.randint(0, lD - 1)
    dst[r], dst[i] = dst[i], dst[r]
print(dst)

>>[4, 3, 1, 3, 4, 3, 1, 2, 3, 4]
>>[4, 3, 1, 3, 4, 3, 1, 3, 4, 2]

這是具有線性復雜度的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM