深度学习--统计与数据映射

范数

import torch

#范数norm   第一范数:绝对值求和 第二范数:平方和后求根号           norm使用要求是浮点数
a=torch.full([8],1.)    
#tensor([1., 1., 1., 1., 1., 1., 1., 1.])
b=a.view(2,4)
#tensor([[1., 1., 1., 1.],
#        [1., 1., 1., 1.]])

c=a.view(2,2,2)
#tensor([[[1., 1.],
#         [1., 1.]],
#
#        [[1., 1.],
#         [1., 1.]]])


a.norm(1),b.norm(1),c.norm(1)
#(tensor(8.), tensor(8.), tensor(8.))
a.norm(2),b.norm(2),c.norm(2)
#(tensor(2.8284), tensor(2.8284), tensor(2.8284))

b.norm(1,dim=1)
#tensor([4., 4.])
b.norm(2,dim=1)
#tensor([2., 2.])

c.norm(1,dim=0)
#tensor([[2., 2.],
#        [2., 2.]])
c.norm(2,dim=0)
#tensor([[1.4142, 1.4142],
#        [1.4142, 1.4142]])

统计API

#平均值mean 最大值max 最小值min 累乘prod 和sum
a=torch.arange(8).view(2,4).float()
a.min(),a.max(),a.mean(),a.prod(),a.sum()
#(tensor(0.), tensor(7.), tensor(3.5000), tensor(0.), tensor(28.))

#返回索引  最大argmax  最小argmin    会把数组拉成一维的坐标返回
a.argmax(),a.argmin()
#(tensor(7), tensor(0))

#topk取最大的几个值与坐标,最小的几个值和坐标    
#kthvalue取第k小的值与坐标

a=torch.rand(4,8)
#tensor([[0.3843, 0.6784, 0.8017, 0.9439, 0.3890, 0.3628, 0.7875, 0.5188],
#        [0.4975, 0.4088, 0.0875, 0.5642, 0.0414, 0.9302, 0.9502, 0.3015],
#        [0.6524, 0.2346, 0.4501, 0.0310, 0.4379, 0.9146, 0.3559, 0.4451],
#        [0.9268, 0.2702, 0.2949, 0.9351, 0.9238, 0.5367, 0.7425, 0.2148]])

a.topk(3,dim=1)
#torch.return_types.topk(
#values=tensor([[0.9439, 0.8017, 0.7875],
#        [0.9502, 0.9302, 0.5642],
#        [0.9146, 0.6524, 0.4501],
#        [0.9351, 0.9268, 0.9238]]),
#indices=tensor([[3, 2, 6],
#        [6, 5, 3],
#        [5, 0, 2],
#        [3, 0, 4]]))

a.topk(3,dim=1,largest=False)
#torch.return_types.topk(
#values=tensor([[0.3628, 0.3843, 0.3890],
#        [0.0414, 0.0875, 0.3015],
#        [0.0310, 0.2346, 0.3559],
#        [0.2148, 0.2702, 0.2949]]),
#indices=tensor([[5, 0, 4],
#        [4, 2, 7],
#        [3, 1, 6],
#        [7, 1, 2]]))


a.kthvalue(1,dim=1)
#torch.return_types.kthvalue(
#values=tensor([0.3628, 0.0414, 0.0310, 0.2148]),
#indices=tensor([5, 4, 3, 7]))

a.kthvalue(1,dim=0)
#torch.return_types.kthvalue(
#values=tensor([0.3843, 0.2346, 0.0875, 0.0310, 0.0414, 0.3628, 0.3559, 0.2148]),
#indices=tensor([0, 2, 1, 2, 1, 0, 2, 3]))


高阶操作

#高阶操作  where  和 gather
#torch.where(condition,x,y)   类似判断取值
cond=torch.tensor([0.6,0.4,0.6,0.6]).view(2,2)
a=torch.zeros(2,2)
b=torch.ones(2,2)
torch.where(cond>0.5,a,b)
#tensor([[0., 1.],
#        [0., 0.]])

#torch.gather(input,dim,index,out=None)  用于查表,就是做了一个映射
#input(猫,狗,鱼) 
#dim 维度
#index(1,0,1,2)
#则out可以输出为(狗,猫,狗,鱼)