I'd like to get a location with elements of the tensor array.

Asked 2 years ago, Updated 2 years ago, 65 views

I'd like to get an index of the tensor array, but it doesn't work, so please let me know. I'd like to extract only the following shape and the maximum element 1 is present.

tensor([[1., 0., 0., 0., 0.], → 0 in this case.
    [1., 0., 0., 0., 0., 0.],
    [1., 0., 0., 0., 0., 0.],
    ...,
    [0., 0., 1., 0., 0., 0.],
    [0., 0., 1., 0., 0., 0.],
    [0., 0., 1., 0., 0., 0.]]) → 2 in this case

Code
 

import numpy as np
import torch                                                                                   
npzfile=np.load("C:/Users/namae/Desktop/myo-python-1.0.4/myo-armband-nn-master/data/train_set.npz")
x = npzfile ['x']
y=npzfile['y']                                                                                     
x = x.astype (np.float32)
x=torch.from_numpy(x).clone()
x = torch.tensor(x)
x = x.clone().detach()
y = y.astype(np.float32)
y=torch.from_numpy(y).clone()
print(y)

python numpy pytorch

2022-09-29 22:16

2 Answers

x=torch.tensor([[1., 0, 0, 0, 0, 0.],
    [1., 0., 0., 0., 0., 0.],
    [1., 0., 0., 0., 0., 0.],
    [0., 0., 1., 0., 0., 0.],
    [0., 0., 1., 0., 0., 0.],
    [0., 0., 1., 0., 0., 0.]])

x.max(dim=1)[1]
# US>tensor([0,0,0,2,2,2])


2022-09-29 22:16

Use argmax().

x=torch.tensor([[1., 0, 0, 0, 0, 0.],
                  [1., 0., 0., 0., 0., 0.],
                  [1., 0., 0., 0., 0., 0.],
                  [0., 0., 1., 0., 0., 0.],
                  [0., 0., 1., 0., 0., 0.],
                  [0., 0., 1., 0., 0., 0.]])

x.argmax(1)
# US>tensor([0,0,0,2,2,2])


2022-09-29 22:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.