用特定索引中numpy数组的其他值替换特定值的Python方法
我已经看到了问题每个部分的答案。例如用特定索引中numpy数组的其他值替换特定值的Python方法,python,arrays,numpy,Python,Arrays,Numpy,我已经看到了问题每个部分的答案。例如np。其中(arr,b,c)将arr中的所有b转换为c。或者arr[arr==b]=c也会这样做。但是,我在一个numpy数组中有1000个标签,labels\u test,包括1个和6个。我想将30%的正确标签翻转到错误的标签上,以生成错误的数据集。因此,我创建了以下应该更改的索引列表 l = [np.random.choice(1000) for x in range(100)] (I am not sure if each index is repeat
np。其中(arr,b,c)
将arr中的所有b转换为c。或者arr[arr==b]=c
也会这样做。但是,我在一个numpy数组中有1000个标签,labels\u test
,包括1个和6个。我想将30%的正确标签翻转到错误的标签上,以生成错误的数据集。因此,我创建了以下应该更改的索引列表
l = [np.random.choice(1000) for x in range(100)] (I am not sure if each index is repeated once)
我想要像这样的东西
np.put(labels_test, l, if labels_test[l] ==1, then 6 and if labels_test[l] ==6, then 1`
我们可以为以下玩具示例执行此操作:
np.random.seed(1)
labels_test = [np.random.choice([1,6]) for x in range(20)]
[6, 6, 1, 1, 6, 6, 6, 6, 6, 1, 1, 6, 1, 6, 6, 1, 1, 6, 1, 1]
这里有一个方法:
>>> labels_test = np.random.choice([1, 6], 20)
>>> ind = np.random.choice(labels_test.shape[0], labels_test.shape[0]//3, replace=False)
>>> labels_test
array([1, 6, 1, 1, 6, 1, 1, 1, 6, 1, 1, 1, 6, 6, 6, 6, 6, 1, 1, 1])
>>> labels_test[ind] = 7 - labels_test[ind]
>>> labels_test
array([1, 6, 1, 6, 6, 6, 1, 1, 6, 1, 6, 1, 1, 6, 1, 6, 6, 1, 1, 6])
通过不进行替换的采样,可以精确翻转30%(四舍五入到最接近的整数)。根据您的要求,一个合适的替代方案可能是选择概率为0.3的每个标签。没有任何通用方法可以做到这一点。我的意思是,如果我们有更多的标签(0,1,2,…,9),并且希望对所有标签都这样做,或者百分比改变。