Hello Kevin!



 Keverino:

I have a tensor with [batch_size, 4]
Andi Want the value of the 2nd dimension to be somehting like  [0,0,1,0], where the one corresponds to the max value in this tensor.
Any ideas?


I am assuming that you want your result tensor to have the
same shape as your input tensor, [batch_size, 4], with
the largest value in each row replaced by 1 and the lesser
values replaced by 0.
How about (1.e6 * t).softmax (1)?
(No, no, no …   Bad idea!  Don’t listen to me!!!)
I don’t know of any good, one-step way of doing this.  You have
to call argmax() (or do something equivalent) and then “one-hot”
your result.  The commonly-suggested way to “one-hot” (that as
far as I know is the best way) is to use scatter().
Try this:
import torch
torch.manual_seed (1414)
t = torch.randn (8, 4)
a = t.argmax (1)
m = torch.zeros (t.shape).scatter (1, a.unsqueeze (1), 1.0)
print ('\n', t, '\n\n', a, '\n\n', m)

Running this, I get
tensor([[ 0.1868,  1.2265,  1.0181,  0.6943],
       [ 0.1075, -0.3540,  0.1766, -0.4940],
       [ 3.0013,  1.8697, -0.0673, -1.3875],
       [-0.0560, -0.6007, -0.0410, -0.6681],
       [-0.2963,  0.1108,  0.2250, -0.5483],
       [-0.1541, -1.1390,  0.4984, -0.4016],
       [-0.3887, -0.1821,  0.4817,  0.4268],
       [ 0.8756,  2.0755,  0.2577,  0.8941]])

tensor([1, 2, 0, 2, 2, 2, 2, 1])

tensor([[0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 1., 0.],
       [0., 0., 1., 0.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.]])

(This is a sufficiently commonly requested manipulation that
I’m surprised that there isn’t a built-in function for it – at
least I haven’t found one.)
Happy One-Hotting!
K. Frank