如何更改随机选择的数组子集的值?

时间:2017-10-09 01:30:31

标签: python-3.x numpy

我有一个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)是否有更简单,更简洁的方法?

1 个答案:

答案 0 :(得分: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]