1

I have my output tensor like this:

tensor([[0.1834, 0.8166],
        [0.3031, 0.6969],
        [0.3104, 0.6896],
        [0.3065, 0.6935],
        [0.3060, 0.6940],
        [0.2963, 0.7037],
        [0.2340, 0.7660],
        [0.2302, 0.7698],
        [0.2581, 0.7419],
        [0.2081, 0.7919]], grad_fn=<PowBackward0>)

I would like to first convert my output tensor to something like this:

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

where the value indicate the index of the larger value(for example, 0.8166 > 0.1834 so the first element is 1).

Any suggestions would by appreciated!

shuai wang
  • 27
  • 4

2 Answers2

0

To get the index with the largest value you should use torch.argmax.

Related PyTorch commands that can be used here are also:

  • torch.max: this command (when used with dim argument) returns the max value and the index of that value along the specified dimension.
  • torch.topk: returns the top k elements along a dimension. When k=1 works like torch.max.
Shai
  • 111,146
  • 38
  • 238
  • 371
0

That's literally just your_tensor.argmax(dim=1).

your_tensor.argmax(dim=1).float() if you truly need it to be float.

After that, the accuracy can be calculated as sum(my_tensor == target_tensor) / len(target_tensor), for example. (See also this question).

dx2-66
  • 2,376
  • 2
  • 4
  • 14