merge&split
torch.cat函数 合并增加size
torch.stack函数 合并会增加维度
split函数与chunk 分割
import torch
a=torch.rand(5,32,8)
b=torch.rand(5,32,8)
print(torch.cat([a,b],0).shape)
print(torch.stack([a,b],0).shape)
a1,a2=a.split([2,3],0)#把5拆成2和3两个对象
print(a1.shape,a2.shape)
a3,a4=a.chunk(2,dim=2)#在第三个维度中拆分出2个相同对象
print(a3.shape,a4.shape) 
输出
torch.Size([10, 32, 8])
torch.Size([2, 5, 32, 8])
torch.Size([2, 32, 8]) torch.Size([3, 32, 8])
torch.Size([5, 32, 4]) torch.Size([5, 32, 4]) 
加法
add()与运算符'+'等效
import torch
a=torch.rand(3,4)
b=torch.rand(4)
print(a+b)#broadcast,加法
print(torch.add(a,b)) 
输出
tensor([[1.3737, 1.9019, 1.6215, 0.5376],
        [1.1492, 1.1726, 1.2129, 1.3834],
        [1.4665, 1.0665, 1.2932, 0.8242]])
tensor([[1.3737, 1.9019, 1.6215, 0.5376],
        [1.1492, 1.1726, 1.2129, 1.3834],
        [1.4665, 1.0665, 1.2932, 0.8242]]) 
乘法
matmul函数
* 是矩阵对应位置简单相乘
c=torch.tensor([[3.,3.],[3.,3.]])
d=torch.ones(2,2)
print(torch.matmul(c,d))#矩阵乘法
print(c@d)
e=torch.rand(4,784)
temp=torch.rand(512,784)#矩阵相乘条件:左列数=右行数
print((e@temp.t()).shape)#结果为[左行数,右列数]
f=torch.rand(4,3,28,64)
g=torch.rand(4,1,64,32)#broadcast为(4,3,64,32)
print(torch.matmul(f,g).shape)#matmul用于多维度张量乘法,实质是多组矩阵并行相乘, 
输出
tensor([[6., 6.],
        [6., 6.]])
tensor([[6., 6.],
        [6., 6.]])
torch.Size([4, 512])
torch.Size([4, 3, 28, 32]) 
乘方与对数
pow(),exp(),log()
h=torch.full([2,2],3)
print(h.pow(2))#x^2
print(h**2)#x^2
print(torch.exp(h))#e^x
print(torch.log(h))#lnx 
输出
tensor([[9, 9],
        [9, 9]])
tensor([[9, 9],
        [9, 9]])
tensor([[20.0855, 20.0855],
        [20.0855, 20.0855]])
tensor([[1.0986, 1.0986],
        [1.0986, 1.0986]]) 
clamp方法
grad=torch.rand(2,3)*15
print(grad.clamp(3,10))#clamp(),>10的元素置为10,<3的置为3 
输出
tensor([[ 3.0000,  6.1345,  9.5902],
        [10.0000,  5.2752,  3.0000]]) 
approximation近似
floor(),ceil(),round()
n=torch.tensor(3.14)
print(n.floor())#向下取整
print(n.ceil())#向上取整
print(n.round())#四舍五入 
输出
tensor(3.)
tensor(4.)
tensor(3.)







