Learn practical skills, build real-world projects, and advance your career

Reduction Ops

The torch package contains data structures for multi-dimensional tensors and mathematical operations over these are defined. Additionally, it provides many utilities for efficient serializing of Tensors and arbitrary types, and other useful utilities.

  • function 1 - torch.argmax(input)
  • function 2 - torch.argmin(input)
  • function 3 - torch.amax(input, dim, keepdim=False, *, out=None)
  • function 4 - torch.amin(input, dim, keepdim=False, *, out=None)
  • function 5 - torch.mean(input)

Before we begin, let's install and import PyTorch

# Uncomment and run the appropriate command for your operating system, if required

# Linux / Binder
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# Windows
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# MacOS
# !pip install numpy torch torchvision torchaudio
# Import torch and other required modules
import torch

Function 1 - torch.argmax(input)

Returns the indices of the maximum value of all elements in the input tensor.

This is the second value returned by torch.max(). See its documentation for the exact semantics of this method.

If there are multiple minimal values then the indices of the first minimal value are returned.

a = torch.randn(4, 4)
a
tensor([[-0.3642, -0.8743, -0.7714,  0.2018],
        [ 1.9625,  0.7499,  1.4775,  0.1271],
        [ 1.1300, -1.6750, -0.1611,  0.8189],
        [-0.3695, -0.0941, -0.9290,  0.1859]])