使用PyTorch计算中位数/中值

一、中位数(【统计学】专有名词)

        中位数(Median)又称中值,是按顺序排列的一组数据中居于中间位置的数,代表一个样本、种群或概率分布中的一个数值,其可将数值集合划分为相等的上下两部分。对于有限的数集,可以通过把所有观察值高低排序后找出正中间的一个作为中位数。如果观察值有偶数个,通常取最中间的两个数值的平均数作为中位数

二、第一种计算方式

        利用torch.median()方法计算,代码

import torch

a = torch.tensor([10, 10, 40, 20, 70, 40, 20, 50, 50, 70], dtype=torch.float)
b = torch.tensor([10, 20, 30, 40, 50, 60], dtype=torch.float)
c = torch.tensor([10, 20, 30, 40, 50], dtype=torch.float)

print(a.sort().values, a.median().item())
print(b.sort().values, b.median().item())
print(c.sort().values, c.median().item())

        输出

tensor([10., 10., 20., 20., 40., 40., 50., 50., 70., 70.]) 40.0
tensor([10., 20., 30., 40., 50., 60.]) 30.0
tensor([10., 20., 30., 40., 50.]) 30.0

        在观察值为偶数的情况下,将返回两个中位数中的较低值。

三、第二种计算方式

        利用torch.quantile()方法计算,代码

import torch

a = torch.tensor([10, 10, 40, 20, 70, 40, 20, 50, 50, 70], dtype=torch.float)
b = torch.tensor([10, 20, 30, 40, 50, 60], dtype=torch.float)
c = torch.tensor([10, 20, 30, 40, 50], dtype=torch.float)

print(a.sort().values, a.quantile(q=0.5).item())
print(b.sort().values, b.quantile(q=0.5).item())
print(c.sort().values, c.quantile(q=0.5).item())

        输出

tensor([10., 10., 20., 20., 40., 40., 50., 50., 70., 70.]) 40.0
tensor([10., 20., 30., 40., 50., 60.]) 35.0
tensor([10., 20., 30., 40., 50.]) 30.0

        在观察值为偶数的情况下,将返回两个中位数中的平均值。

四、参考

        中位数_百度百科

        torch.median

        torch.quantile

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2022年5月28日
下一篇 2022年5月28日

相关推荐