pytorch规约计算(累和、累积、均值、方差、标准差、P范数等)

目录

      • 一、什么是规约计算?
        • 1.累积、累和、所有元素的乘积、所有元素的和
        • 2.p-norm距离
        • 3.均值、中位数、众数、方差和标准差

一、什么是规约计算?

一般是指分组聚合计算,常见的由均值、方差等,该计算的特点是使分组内或所有的元素参与计算得到统计性的结果,常见的有如下几种:

1.累积、累和、所有元素的乘积、所有元素的和

# 累积
x = torch.Tensor([[2,3,4,5,6],[9,8,7,6,5]])
print(x)
print(torch.cumprod(x,dim=0))  # cumprod 元素累积
print(torch.cumprod(x,dim=1))
# 累和
print(torch.cumsum(x,dim=0)) # cumsum 元素累和  dim=0 指定行,行是可变的,列是不变的
print(torch.cumsum(x,dim=1)) # dim=1 指定列,也就是行不变,列之间的比较
# 计算所有元素乘积
print(torch.prod(x,dim=0))           # prod 元素积
print(torch.prod(x,dim=1))
# 计算所有元素的和
print(torch.sum(x,dim=0))            # sum 元素和
print(torch.sum(x,dim=1))
-------------------------------------------------------------------------------
result:
tensor([[2., 3., 4., 5., 6.],
        [9., 8., 7., 6., 5.]])
tensor([[ 2.,  3.,  4.,  5.,  6.],
        [18., 24., 28., 30., 30.]])
tensor([[2.0000e+00, 6.0000e+00, 2.4000e+01, 1.2000e+02, 7.2000e+02],
        [9.0000e+00, 7.2000e+01, 5.0400e+02, 3.0240e+03, 1.5120e+04]])
tensor([[ 2.,  3.,  4.,  5.,  6.],
        [11., 11., 11., 11., 11.]])
tensor([[ 2.,  5.,  9., 14., 20.],
        [ 9., 17., 24., 30., 35.]])
tensor([18., 24., 28., 30., 30.])
tensor([  720., 15120.])
tensor([11., 11., 11., 11., 11.])
tensor([20., 35.])

2.p-norm距离

# 距离公式常用来计算损失,默认值一般为欧氏距离
x = torch.Tensor([[1,2,3,4,5],[9,8,7,6,5]])
y = torch.Tensor([[1,2,3,4,5],[4,5,6,1,3]])
print(torch.dist(x,y,p=0))
print(torch.dist(x,y,p=1))
print(torch.dist(x,y,p=2))
print(torch.dist(x,y,np.inf))
# p-norm 范数  p = 1: 曼哈顿距离   p = 2: 欧式距离
print(torch.norm(x,p=1,dim=0))   # dim=0 指定行,行是可变的,列是不变的
print(torch.norm(x,p=1,dim=1))   # dim=1 指定列,也就是行不变,列之间的比较
print(torch.norm(x,p=2,dim=0))
print(torch.norm(x,p=2,dim=1))
-------------------------------------------------------------------------------
result:
tensor(5.)
tensor(16.)
tensor(8.)
tensor(5.)
tensor([10., 10., 10., 10., 10.])
tensor([15., 35.])
tensor([9.0554, 8.2462, 7.6158, 7.2111, 7.0711])
tensor([ 7.4162, 15.9687])

3.均值、中位数、众数、方差和标准差

# 均值
x = torch.Tensor([[2,3,4,5,6],[9,8,7,6,5]])
print(torch.mean(x))
print(torch.mean(x,dim=0))
print(torch.mean(x,dim=1))
# 中位数 : 指定dim将返回两个Tensor,第一个是Tensor中位数,第二个使Tensor索引
print(torch.median(x))
print(torch.median(x,dim=1))
# 众数: 在一组数据中,出现次数最多的数
print(torch.mode(x))
# 方差
print(torch.var(x))
print(torch.var(x,dim=0))
-------------------------------------------------------------------------------
result:
tensor(5.5000)
tensor([5.5000, 5.5000, 5.5000, 5.5000, 5.5000])
tensor([4., 7.])
tensor(5.)
torch.return_types.median(
values=tensor([4., 7.]),
indices=tensor([2, 2]))
torch.return_types.mode(
values=tensor([2., 5.]),
indices=tensor([0, 4]))
tensor(4.7222)
tensor([24.5000, 12.5000,  4.5000,  0.5000,  0.5000])

你可能感兴趣的:(PyTorch的攀登年华,pytorch,线性代数,矩阵,python)