tux:

idx = np.random.choice(2, size=your_shape, p=[r, 1-r])


Thank you very much for your reply! Based on your reply,I think this may be the right  answer to my question.
s = x.data.size()
t = torch.from_numpy(numpy.random.choice([-1, 1], size=s, p=[0.5, 0.5])).type_as(x)
x = x.data.mul(t)