classify labels to -1 or 1

Viewed 28

I have a tensor with values between -1 and 1 . How can I get a new tensor such that where were negative values now there will be one and where were positive numbers now there will be 1? (efficiently)

Namely,

tensor1 = [-0.1, 0.5, 0.08]
new_tensor = [-1, 1, 1]

and zero will be -1 or 1

2 Answers

With numpy it is trivial:

import numpy as np
tensor1 = [-0.1, 0.5, 0.08]
new_tensor = np.sign(tensor1)
new_tensor[new_tensor==0] = 1

I would use numpy.where for this task following way

import numpy as np
tensor1 = np.array([-0.1, 0.5, 0.08])
new_tensor = np.where(tensor1<0,-1,1)
print(new_tensor)

output

[-1  1  1]

Note this will asign 1 to 0 if you wish to assign -1 to 0 then alter condition to tensor1<=0

Related