PyTorch torch.mode Function


Pytorch torch 参考手册Pytorch torch Reference Manual

torch.modeIt is a function in PyTorch used to return the mode of a tensor. The mode is the value that appears most frequently in a set of data.

Function Definition

torch.mode(input, dim, keepdim=False)

Usage Example

Example

import torch

x = torch.tensor([1, 2, 2, 3, 3, 3])

# Return the mode
print("Mode:", torch.mode(x))

# Mode along dim=0
y = torch.tensor([[1, 2, 2], [1, 2, 3]])
print("dim=0 mode:", torch.mode(y, dim=0))

# Mode along dim=1
print("dim=1 mode:", torch.mode(y, dim=1))

The output result is:

众数: torch.return_types.mode(values=tensor(3), indices=tensor(4))
dim=0 众数: torch.return_types.mode(values=tensor([1, 2, 2]), indices=tensor([0, 0, 0]))
dim=1 众数: torch.return_types.mode(values=tensor([2, 3]), indices=tensor([1, 2]))

Pytorch torch 参考手册Pytorch torch Reference Manual

Other Extensions