PyTorch torch.mode 函数
torch.mode 是 PyTorch 中用于返回张量的众数的函数。众数是一组数据中出现次数最多的值。
函数定义
torch.mode(input, dim, keepdim=False)
使用示例
实例
import torch
x = torch.tensor([1, 2, 2, 3, 3, 3])
# 返回众数
print("众数:", torch.mode(x))
# 沿 dim=0 众数
y = torch.tensor([[1, 2, 2], [1, 2, 3]])
print("dim=0 众数:", torch.mode(y, dim=0))
# 沿 dim=1 众数
print("dim=1 众数:", torch.mode(y, dim=1))
x = torch.tensor([1, 2, 2, 3, 3, 3])
# 返回众数
print("众数:", torch.mode(x))
# 沿 dim=0 众数
y = torch.tensor([[1, 2, 2], [1, 2, 3]])
print("dim=0 众数:", torch.mode(y, dim=0))
# 沿 dim=1 众数
print("dim=1 众数:", torch.mode(y, dim=1))
输出结果为:
众数: 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 参考手册