2017-01-27 33 views
1

有一個0-1矩陣,我需要從該矩陣中抽取M個不同的1值的條目。有這種需求有效的Python實現嗎?基準線方法是在每次迭代過程中進行M次迭代,如果它的值爲1,則隨機取樣1,然後保留它並保存它的位置,否則繼續此迭代直到找到值爲1的入口;並繼續下一次迭代。這似乎不是一個好的啓發式。矩陣中的樣本條目滿足給定的要求

+0

你在這裏工作?什麼是矩陣?列表清單?一些'numpy'數據結構? –

+0

確實需要一次一個嗎? http://stackoverflow.com/q/17385419/6876009或者快速獲取所有http://stackoverflow.com/q/432112/6876009 – f5r5e5d

+0

@ junapa.arrivillaga的列表,它是一個二維numpy數組,從圖像生成,只有白色和黑色。 – user288609

回答

0

我選擇了間接指數從numpy.nonzero

通過ndx_ndx名單上使用pop()方法來獲得一個(間接)索引輸入數組不用更換回

最終ndx_ndx會當你有被清空得到所有的那些

import numpy as np 


ary = np.random.randint(2, size=(20, 20)) 

# get the indices of all of the ones 

ndx_ary_ones = np.nonzero(ary) 

# make a range list for pointing into ndx_ary_ones 

ndx_ndx = list(range(len(ndx_ary_ones[0]))) 

# randomize the order 

np.random.shuffle(ndx_ndx) 

# pop the last ndx_ndx 

a_ran_ndx_ndx = ndx_ndx.pop() 

# get the index tuple for the one in ary that we removed from ndx_ndx 

a_ran_one_ndx = (ndx_ary_ones[0][a_ran_ndx_ndx], 
       ndx_ary_ones[1][a_ran_ndx_ndx]) 

# testing... 

print('ary', ary, '\n') 
print('ndx_ary_ones ', *ndx_ary_ones, sep = '\n') 
print('\n','ndx_ndx[0:10] ', ndx_ndx[0:10], '\n') 

for _ in range (10): 
    a_ran_ndx_ndx = ndx_ndx.pop() 
    a_ran_one_ndx = (ndx_ary_ones[0][a_ran_ndx_ndx], 
        ndx_ary_ones[1][a_ran_ndx_ndx]) 
    print(a_ran_one_ndx, ary[a_ran_one_ndx]) 

ary [[0 0 0 ..., 1 1 1] 
[0 1 1 ..., 1 1 1] 
[1 0 0 ..., 1 0 1] 
..., 
[1 1 0 ..., 1 0 1] 
[1 1 0 ..., 1 1 1] 
[1 0 0 ..., 0 0 1]] 

ndx_ary_ones 
[ 0 0 0 ..., 19 19 19] 
[ 3 5 7 ..., 14 15 19] 

ndx_ndx[0:10] [121, 43, 146, 69, 64, 3, 29, 186, 98, 30] 

(7, 12) 1 
(8, 18) 1 
(0, 3) 1 
(10, 2) 1 
(18, 18) 1 
(17, 7) 1 
(15, 14) 1 
(4, 11) 1 
(10, 1) 1 
(4, 4) 1 
0

我們能夠做到以如下方式組成:第一獲得矩陣A,其中A [X,Y] = 1的所有的(X,Y)的元組(索引)。有k個這樣的指數。現在滾動一個K邊無偏骰子M次(我們可以使用函數randint(1,k)從均勻分佈中抽取樣本來模擬)。如果你想要更換樣品(矩陣的相同位置可以選擇多次),那麼可以用M個函數調用完成。否則,對於有替換的樣品(不允許重複),您需要跟蹤已選擇的位置,並在下次投擲潛水之前從陣列中刪除這些索引。

相關問題