2017-10-09 54 views
0

我有一個numpy數組,包含1和-1的形狀(1000,)序列。我需要爲這個樣本的10%添加一些隨機噪聲。噪聲將是給定值的符號的簡單切換(例如,如果最初爲1,則爲-1)。我目前的解決方案如下:如何更改隨機選擇的數組子集的值?

# create an array of the indices of the values we are going to change 
noisy_index = np.random.choice(1000, size=100, replace=False) 

# multiply by -1 to change sign of these randomly selected values 
mult = np.multiply(correct_labels[noisy_index], -1) 

# delete these values from the original dataset 
labels_subset = np.delete(correct_labels, noisy_index) 

# concatenate the modified values to get back complete (and now noisy) dataset 
correct_labels_noisy = np.concatenate((labels_subset, mult), axis=0) 

兩個問題:1)這是做什麼,我描述它應該做什麼? 2)有沒有更直接和更詳細的方法?

回答

2

最簡單的將被乘以-1的選擇的值和分配回相應的索引與:

correct_labels[noisy_index] *= -1 

correct_labels = np.random.choice([1,-1], size=10) 
print('original labels: ', correct_labels) 
​ 
noisy_index = np.random.choice(10, size=3, replace=False) 
correct_labels[noisy_index] *= -1 
print('modified labels: ', correct_labels) 

#original labels: [ 1 -1 -1 1 -1 -1 -1 -1 -1 1] 
#modified labels: [ 1 -1 -1 1 1 -1 1 -1 -1 -1] 
#        ^ ^ ^

print('noisy index: ', noisy_index) 
# noisy index: [6 4 9]