# Creat a tensor with random number of 1 and -1

In order to add noise to the XNOR-Net, I need to modify the trained weights which contains only 1 and -1. So I think the problem is how to generate a tensor with random number of 1 and -1, and then multiply this tensor with the trained weights. The solution of mine is following:

`````` def add_noise_to_weights(m):
s = m.data.size()
n = m.data.nelement()
r = round(n*0.01) #0.01 is the noise ratio
idx = torch.randperm(t.nelement())
t = t.view(-1)[idx].view(t.size())
m.data = m.data.mul(t)
return m
``````

Despite it works, the code is too complicated, so could you guys have some simply solutions?

If I understand correctly, you just want to generate a tensor which contains -1 and 1 values ?

Would something like this work for you ?

``````a = torch.Tensor([-1, 1])
idx = np.random.randint(2, size=your_shape)
noise = a[idx]
``````

Edit :
Furthermore, if you want to have some control on the number of 1 or -1 in your tensor, I would suggest:

``````a = torch.Tensor([-1, 1])
idx = np.random.choice(2, size=your_shape, p=[r, 1-r])
noise = a[idx]
``````

``````s = x.data.size()