PyTorch torch.median Function


Pytorch torch 参考手册PyTorch torch Reference Manual

torch.medianIt is a function in PyTorch used to return the median of a tensor. The median is the middle value after sorting the data.

Function Definition

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

Usage Example

Example

import torch

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

# Return the median of all elements
print("Global median:", torch.median(x))

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

The output result is:

全局中位数: tensor(3)
dim=0 中位数: torch.return_types.median(values=tensor([1, 1, 2]), indices=tensor([0, 1, 0]))

Pytorch torch 参考手册PyTorch torch Reference Manual

Other Extensions