本篇主要记录一下一些基础的pytorch知识,一些基本的统计操作

常用API

1.norm 范数

1范数
2 范数

# 1.norm 范数
# 不同于正则化(normalize)
# 在数学上,范数包括向量范数和矩阵范数,向量范数表征向量空间中向量的大小,矩阵范数表征矩阵引起变化的大小
a = torch.full([8], 1)
b = a.view(2, 4)
c = a.view(2, 2, 2)
b
'''
Out[37]: 
tensor([[1, 1, 1, 1],
        [1, 1, 1, 1]])
'''
c
'''
Out[38]: 
tensor([[[1, 1],
         [1, 1]],
        [[1, 1],
         [1, 1]]])
'''
# 默认类型是long,norm不支持
a = a.float()
b = b.float()
c = c.float()
# 1范数是Σ∣x∣,即对所以元素的绝对值求和
a.norm(1), b.norm(1), c.norm(1)
# Out[47]: (tensor(8.), tensor(8.), tensor(8.))
# 2范数表示向量元素的平方和再开平方
a.norm(2), b.norm(2), c.norm(2)
# Out[48]: (tensor(2.8284), tensor(2.8284), tensor(2.8284))
# 在1维求 一范数
b.norm(1, dim=1)
# Out[49]: tensor([4., 4.])
# 在1维求 二范数
b.norm(2, dim=1)
# Out[50]: tensor([2., 2.])
c.norm(1, dim=0)
'''
Out[51]: 
tensor([[2., 2.],
        [2., 2.]])
'''
# 每个tensor的对应位置求范数
c.norm(2, dim=0)
'''
Out[53]: 
tensor([[1.4142, 1.4142],
        [1.4142, 1.4142]])
'''

2.求最大最小值等

# 2.mean sum min max prod
a = torch.arange(8).view(2, 4).float()
'''
Out[55]: 
tensor([[0., 1., 2., 3.],
        [4., 5., 6., 7.]])
'''
# product 累乘
a.min(), a.max(), a.mean(), a.prod()
# Out[56]: (tensor(0.), tensor(7.), tensor(3.5000), tensor(0.))
a.sum()
# Out[57]: tensor(28.)
# 求最大最小值所在位置
# 会先打平成一维,如果想要求特定维数的最小/大值位置可以加上dim参数
a.argmax(), a.argmin()
# Out[58]: (tensor(7), tensor(0))
# 这里的输出的意义是在第一维上最大值的索引是3,第二维同样是3
a.argmax(dim=1)
# Out[59]: tensor([3, 3])
# 下面是对 dim 和 keepdim参数的一些说明
a.max(dim=1)
# 可以看到输出的说明非常清晰,indices和上面argmax求得的是一样的
'''
Out[61]: 
torch.return_types.max(
values=tensor([3., 7.]),
indices=tensor([3, 3]))
'''
# 以a为例,仍然保留和a一样的维度信息,0维还在
a.max(dim=1, keepdim=True)
'''
Out[63]: 
torch.return_types.max(
values=tensor([[3.],
        [7.]]),
indices=tensor([[3],
        [3]]))
'''

3.第几大!

# 3.kthvalue,topk
# top-k很容易理解,输出前几大的(自动按降序输出)
a
a.topk(3, dim=1)
# largest=False表示倒序输出
a.topk(3, dim=1, largest=False)
'''
Out[65]: 
tensor([[0., 1., 2., 3.],
        [4., 5., 6., 7.]])
a.topk(3, dim=1)
Out[66]: 
torch.return_types.topk(
values=tensor([[3., 2., 1.],
        [7., 6., 5.]]),
indices=tensor([[3, 2, 1],
        [3, 2, 1]]))

'''
# kthvalue 输出第几小的,只输出一个(每维),且只能从小
a.kthvalue(3, dim=1)
'''
Out[67]: 
torch.return_types.kthvalue(
values=tensor([2., 6.]),
indices=tensor([2, 2]))
'''

4.比较

# 4.比较
# >,<,>=,<=,==,!=
# torch.eq(a, b)
# 以上的返回值都是 byteTensor 即0/1
# 只有equal返回值是True/False
# torch.equal(a, b)