2017-10-19 2 views
0

에서 임의로 선택하는 방법은, ground_truth을 목록의 목록 (평가의도는 정말 매트릭스)를 가지고있다. 나는 비 제로 항목의 20 %를 만들고 싶어 = 0. 나의 초기 접근 방식은 다음과 같습니다는 2 차원 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 

그래서 내 솔루션은 1D로 내 매트릭스를 평평하게하는 오류를 제공합니다 배열을 선택하고 0이 아닌 항목의 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입니까? I는'np.where (ground_truth)을 실행할 때'I이 결과를 얻을'(배열 ([0, 0, 1, 1, 2, DTYPE = INT64) 배열 ([1, 2, 1, 2, 0] , dtype = int64))'. 두 개의 분리 된 길이 5의 배열. 왜 그럴까요? – Moondra

+0

@Moondra 그것은 0이 아닌 요소의 행 인덱스 (첫 번째 요소)와 열 인덱스 (두 번째 요소)를 제공합니다. [numpy.where] (https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html). – Psidom

+0

감사합니다 !!!!!! –