范数
1-范数: ∥ x ∥ 1 = ∑ i = 1 N ∣ x i ∣ \left \| x \right \|_1=\sum_{i=1}^N\left| x_i \right| ∥x∥1=∑i=1N∣xi∣ 即向量元素绝对值之和。
import torch
a = torch.full([8],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 = a.float() # 需要转化为float,否则报错Can only calculate the mean of floating types. Got Long instead
b = b.float()
c = c.float()
# 第一范式
a.norm(1) # tensor(8.)
b.norm(1) # tensor(8.)
c.norm(1) # tensor(8.)
2-范数: ∥ x ∥ 2 = ∑ i = 1 N x i 2 \left \| x \right \|_2=\sqrt{\sum_{i=1}^Nx_i^2} ∥x∥2=∑i=1Nxi2,即向量元素绝对值的平方和再开方。
a.norm(2) # tensor(2.8284)
b.norm(2) # tensor(2.8284)
c.norm(2) # tensor(2.8284)
# 在第一个维度上,1-范数
b.norm(1,dim=1) # tensor([4., 4.])
# 在第一个维度上,2-范数
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]])
mean、sum、min、max、prod
a = torch.arange(8).view(2,4).float()
# tensor([[0., 1., 2., 3.],
# [4., 5., 6., 7.]])
a.min() # tensor(0.) 最小值
a.max() # tensor(7.) 最大值
a.mean() # tensor(3.5000) 平均值
a.sum() # tensor(28.) 累加
a.prod() # tensor(0.) 累乘
a.argmax() # tensor(7) 最大值的索引,将数据打平之后的索引
a.argmin() # tensor(0) 最小值的索引,将数据打平之后的索引
a = torch.randn(4,10)
a.argmax(dim=1) # tensor([0, 1, 4, 9]) 返回维度的最大数的索引
# 更简单的做法,直接返回最大值和对应的索引
a.max(dim=1)
# torch.return_types.max(
# values=tensor([1.7486, 0.8279, 1.1447, 2.9224]),
# indices=tensor([0, 1, 4, 9]))
topk
a = torch.rand(4,10)
# tensor([[0.1952, 0.0522, 0.0049, 0.5136, 0.8603, 0.8427, 0.8195, 0.9584, 0.2865,
# 0.3642],
# [0.1997, 0.4595, 0.3956, 0.6997, 0.1752, 0.6585, 0.4618, 0.8720, 0.4493,
# 0.8950],
# [0.3413, 0.3944, 0.4641, 0.5972, 0.7680, 0.6328, 0.0565, 0.6384, 0.8459,
# 0.1884],
# [0.8966, 0.7085, 0.9635, 0.8404, 0.3393, 0.1922, 0.2011, 0.9136, 0.9064,
# 0.6741]])
# top3
a.topk(3, dim=1) # 在10这个维度中,获取前三个最大的值,并返回对应的索引
# torch.return_types.topk(
# values=tensor([[0.9584, 0.8603, 0.8427],
# [0.8950, 0.8720, 0.6997],
# [0.8459, 0.7680, 0.6384],
# [0.9635, 0.9136, 0.9064]]),
# indices=tensor([[7, 4, 5],
# [9, 7, 3],
# [8, 4, 7],
# [2, 7, 8]]))
# 最小3个
a.topk(3, dim=1, largest = False)
# 第8小的(相当于第3大),方法只能算第几小,不能算第几大
a.kthvalue(8,dim=1)
# torch.return_types.kthvalue(
# values=tensor([0.8427, 0.6997, 0.6384, 0.9064]),
# indices=tensor([5, 3, 7, 8]))
逻辑运算
a = torch.rand(2,3)
# tensor([[0.3328, 0.8201, 0.0464],
# [0.6762, 0.1728, 0.4123]])
a>0
# tensor([[True, True, True],
# [True, True, True]])
b = torch.ones(2,3)
torch.eq(a,b)
# tensor([[False, False, False],
# [False, False, False]])
torch.equal(a,b)
# False