torch.median#
- torch.median(input) Tensor #
返回
input
中值的中位数。注意
当
input
张量包含偶数个元素时,中位数不是唯一的。在这种情况下,将返回两个中位数中较低的一个。要计算两个中位数的平均值,请改用q=0.5
的torch.quantile()
。警告
此函数产生确定性的(子)梯度,与
median(dim=0)
不同。- 参数
input (Tensor) – 输入张量。
示例
>>> a = torch.randn(1, 3) >>> a tensor([[ 1.5219, -1.5212, 0.2202]]) >>> torch.median(a) tensor(0.2202)
- torch.median(input, dim=-1, keepdim=False, *, out=None)
返回一个命名元组
(values, indices)
,其中values
包含input
在dim
维度上每行的中位数,而indices
包含在dim
维度上找到的中位数值的索引。默认情况下,
dim
是input
张量的最后一个维度。如果
keepdim
为True
,则输出张量的大小与input
相同,除了在dim
维度上,它们的大小为 1。否则,dim
将被挤压(参见torch.squeeze()
),导致输出张量比input
少一个维度。注意
当
input
张量在dim
维度上包含偶数个元素时,中位数不是唯一的。在这种情况下,将返回两个中位数中较低的一个。要计算input
中两个中位数的平均值,请改用q=0.5
的torch.quantile()
。警告
indices
不一定包含找到的每个中位数值的第一次出现,除非该值是唯一的。具体的实现细节取决于设备。通常不要期望在 CPU 和 GPU 上运行得到相同的结果。出于同样的原因,不要期望梯度是确定的。示例
>>> a = torch.randn(4, 5) >>> a tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) >>> torch.median(a, 1) torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3]))