classify labels to -1 or 1

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

  • answered 2022-05-04 11:09 Giovanni Tardini

    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
    

  • answered 2022-05-04 11:20 Daweo

    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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum