Pytorch基础入门2
目录
- 3:Tensor运算
- 3.1 A.add() && A.add_()
- 3.2 torch.stack
3:Tensor运算
函数 | 作用 |
---|---|
torch.abs(A) | 绝对值 |
torch.add(A,B) | 相加,A和B既可以是Tensor也可以是标量 |
torch.clamp(A,max,min) | 裁剪,A中的数据若小于min或大于max,则变成min或max,即保证范围在[min,max] |
torch.div(A,B) | 相除,A%B,A和B既可以是Tensor也可以是标量 |
torch.mul(A,B) | 点乘,A*B,A和B既可以是Tensor也可以是标量 |
torch.pow(A,n) | 求幂,A的n次方 |
torch.mm(A,B.T) | 矩阵叉乘,注意与torch.mul之间的区别 |
torch.mv(A,B) | 矩阵与向量相乘,A是矩阵,B是向量,这里的B需不需要转置都是可以的 |
A.item() | 将Tensor转化为基本数据类型,注意Tensor中只有一个元素的时候才可以使用,一般用于在Tensor中取出数值 |
A.numpy() | 将Tensor转化为Numpy类型 |
A.size() | 查看尺寸 |
A.shape | 查看尺寸 |
A.dtype | 查看数据类型 |
A.view() | 重构张量尺寸,类似于Numpy中的reshape |
A.transpose(0,1) | 行列交换 |
A[1:],A[-1,-1]=100 | 切面,类似Numpy中的切面 |
A.zero_() | 归零化 |
torch.stack((A,B),sim=-1) | 拼接,升维 |
torch.diag(A) | 取A对角线元素形成一个一维向量 |
torch.diag_embed(A) | 将一维向量放到对角线中,其余数值为0的Tensor |
3.1 A.add() && A.add_()
所有的带_符号的函数都会对原数据进行修改
import torcha = torch.zeros(3)
print (a)
a.add(1)
print (a)
a.add_(1)
print(a)
输出结果为:
tensor([0., 0., 0.])
tensor([0., 0., 0.])
tensor([1., 1., 1.])
3.2 torch.stack
stack为拼接函数,函数的第一个参数为需要拼接的Tensor,第二个参数为细分到哪个维度
import torchA=torch.IntTensor([[1,2,3],[4,5,6]])
B=torch.IntTensor([[7,8,9],[10,11,12]])
C1=torch.stack((A,B),dim=0) # or C1=torch.stack((A,B))
C2=torch.stack((A,B),dim=1)
C3=torch.stack((A,B),dim=2)
C4=torch.stack((A,B),dim=-1)
print(C1)
print(C2)
print(C3)
print(C4)
结果如下:
tensor([[[ 1, 2, 3],[ 4, 5, 6]],[[ 7, 8, 9],[10, 11, 12]]], dtype=torch.int32)
tensor([[[ 1, 2, 3],[ 7, 8, 9]],[[ 4, 5, 6],[10, 11, 12]]], dtype=torch.int32)
tensor([[[ 1, 7],[ 2, 8],[ 3, 9]],[[ 4, 10],[ 5, 11],[ 6, 12]]], dtype=torch.int32)
tensor([[[ 1, 7],[ 2, 8],[ 3, 9]],[[ 4, 10],[ 5, 11],[ 6, 12]]], dtype=torch.int32)