数学运算
一.torch.add()/minus()/multply()/divide()
建议直接使用运算符
add
a=torch.rand(3,4)
b=torch.rand(4)
print(a)
print(b)
print(torch.add(a,b))
minus
multply
a=torch.randn(1,2)
b=torch.rand(1,2)
c=torch.multiply(a,b)
print(a)
print(b)
print(c)
print(c.shape)
divide
二.matmul
矩阵相乘A[a,b],乘B[b,c],最终得到矩阵C[a,c],C的第一行第一列的值等于A的第一行乘以B的第一列的各个值相乘之和。
1.torch.mm
只适应于2D
2.torch.matmul推荐
a=torch.ones(2,2)
b=torch.full([2,2],6,dtype=torch.float32)
c=torch.matmul(a,b)
print(a)
print(b)
print(c)
[4,3,28,64]乘以[4,3,64,32],前面两维保持不变,后面两维按照2D的运算规则得[4,3,28,32]
[4,3,28,64]乘以[4,1,64,32],第二个满足broadcast,变成[4,3,64,32],然后再相乘。
a=torch.rand(4,3,28,64)
b=torch.rand(4,3,64,32)
c=torch.rand(4,1,64,32)
d=torch.matmul(a,b)
e=torch.matmul(a,c)
print(d.shape)
print(e.shape)
3.@
更加简练的方法,与上个同一原理
a=torch.rand(4,3,28,64)
b=torch.rand(4,3,64,32)
c=a@b
print(c.shape)
4.example
x=torch.rand(4,784)
w=torch.rand(512,784)
print((x@w.t()).shape)
我们降维时,将[4,784]乘矩阵[784,512]可得到[4,512],w不写成[784,512],是因为pytorch固定写成,先channe-out,再channel-in。
三.pow/exp/log
.pow()
a=torch.full([2,2],3)
print(a.pow(2))
torch.exp()
exp(a),求e的a次方。
a=torch.ones([2,2])
a=torch.exp(a)
print(a)
torch.log()
该log是以e为底数的
a=torch.ones([2,2])
a=torch.exp(a)
print(torch.log(a))
四.sqrt/rsqrt
.sqrt()
平方根
a=torch.full([2,2],3)
aa=a.pow(2)
print(aa.sqrt())
.rsqrt()
平方根的倒数
a=torch.full([2,2],3)
aa=a.pow(2)
print(aa.rsqrt())
五.approximation
1…floor()/.ceil()
.floor()向下取整,.ceil()向上取整
a=torch.tensor(3.14)
print(a.floor(),a.ceil())
2…trunc()/.frac()
.trunc()裁剪整数部分,.frac()裁剪小数部分
a=torch.tensor(3.14)
print(a.trunc())
print(a.frac())
3…round()
.round()四舍五入
a=torch.tensor(3.54)
print(a.round())
六…clamp()使用比较多
gradient clipping梯度裁剪
a=torch.rand(2,3)*15
print(a)
print(a.clamp(8))
print(a.clamp(5,8))
a.clamp(8),小于8的变成8
a.clamp(5,8)数在5到8之间,大于8的变成8,小于5的变成5。
属性统计
.norm()
1-norm:
P-norm:
.mean()/.sum()/.min()/.max()/.prod()
product,累乘
a=torch.arange(8).view(2,4).float()
print(a)
print(a.mean())
print(a.sum())
print(a.min())
print(a.max())
print(a.prod())
dim/keepdim
a[4,10]
a.max(dim=1)z
tensor(0.8,),tensor(3,)
第一个tensor是4个概率值,第二个tensor显示的是每个概率值所在的位置(索引),第一张是3的概率是0.8
对哪个dim进行max,拿个dim相当于被消掉了。keepdim是dim与原来保持一致,返回[4,1]
.argmax()/.argmin()
argmax()返回最大值的索引
a[4,10]
a.argmax(dim=1),则返回4个是每个概率值所在的位置(索引)
.argmin()返回最小值的索引,会把tensor打平,然后再看所在的索引,如果不想打平,直接看某一维度的,则参数(dim=)
a=torch.arange(8).view(2,4).float()
print(a)
print(a.argmax())
print(a.argmin())
.kthvalue()/.topk()
kthvalue()返回最小的k个数,相当于[4,10]得到[4,k]
topk()返回最大的k个数,相当于[4,10]得到[4,k]
compare
>,>=不是true和false,而是0和1。
torch.eq(a,b)判断a和b每个位置是否相等
torch.equal(a,b)返回true