2017-10-19 23 views
0

私はリストのリストを持っています(実際には格付けの行列です)、ground_truthです。しかし、これはエラーに2dのnumpyの配列からランダムに選択する方法

ValueError: a must be 1-dimensional 

を与えるだから私のソリューションは、1Dに私の行列を平坦化することである

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

:私は= 0.私の最初のアプローチは、非ゼロ項目の20%を作りたいです次に、非ゼロ項目の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は何をしていますか? '(array([0、0,1,1,2)、dtype = int64)、array([1、2、1、2、0])を実行すると、' np.where(ground_truth) 、dtype = int64)) 'となります。長さ5の2つの別々の配列。なぜですか? – Moondra

+0

@Moondraこれは、非ゼロ要素の行インデックス(最初の要素)と列インデックス(2番目の要素)を与えます。 [numpy.where](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html)。 – Psidom

+0

ありがとう!!!!!! –

関連する問題