2017-10-19 117 views
0

隨機選擇我有一個列表的列表(以及它真的是收視率的矩陣),ground_truth。我想使非零項目的20%= 0.我最初的做法是:如何從2D numpy的陣列

ground_truth = [[0,99,98],[0,84,97], [55,0,0]] 
ground_truth = np.array(ground_truth) 
np.random.choice(ground_truth) 

然而,這給出了錯誤

ValueError: a must be 1-dimensional 

所以我的解決辦法是我的矩陣壓扁成一維數組,然後隨機選取20%的非零項。

random_digits = np.random.choice(ground_truth.flatten()[ground_truth.flatten() > 0], 
           int(round(len(ground_truth.flatten()) * .2))) 

in: random_digits 
out: array([99, 97]) 

現在,我想將這些項目設置爲0,並將更改反映在我的原始矩陣中。我怎樣才能做到這一點?

回答

3
total_non_zeros = np.count_nonzero(ground_truth) 

# sample 1d index 
idx = np.random.choice(total_non_zeros, int(total_non_zeros * 0.2)) 

# subset non zero indices and set the value at corresponding indices to zero 
ground_truth[tuple(map(lambda x: x[idx], np.where(ground_truth)))] = 0 

ground_truth 
#array([[ 0, 99, 98], 
#  [ 0, 84, 0], 
#  [55, 0, 0]]) 
+0

到底是np.where幹什麼?當我運行'np.where(ground_truth)'我得到這樣的結果:'(陣列([0,0,1,1,2],D型細胞= int64類型),陣列([1,2,1,2,0] ,dtype = int64))'。兩個單獨的長度數組5.爲什麼是這樣? – Moondra

+0

@Moondra它給出非零元素的行索引(第一元件)和列索引(第二元件)。 [numpy.where](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html)。 – Psidom

+0

謝謝!!!!!! –