pytorch中涉及矩阵运算的函数主要有以下几种,下面将依次讲解其使用功能。 ## 1 最常见的*运算 在python中,常见的*u用于进行2个**标量**相乘,返回一个标量的结果。在pytorch中,也可以 用于进行**标量和向量**的乘法获得一个向量结果。 ```python import torch a = torch.ones(3, 4) print(a * 2) # 输出 tensor([[2., 2., 2., 2.], [2., 2., 2., 2.], [2., 2., 2., 2.]]) ``` ## 2 torch.mul操作 torch.mul可以说是*操作的亲戚,用于支持element-wised的乘法操作, 支持boardcast的操作,自动进行维度拓展。沿着维度为1的维度进行复制,得到两个唯独相同的矩阵再进行逐个元素相乘。 ``` # torch.mul和*的原理类似,也是element-wise的乘法 c = torch.arange(4).unsqueeze(0) print(c, c.size()) d = torch.arange(4).unsqueeze(1) print(d, d.size()) print(torch.mul(c, d)) # 输出 tensor([[0, 1, 2, 3]]) torch.Size([1, 4]) tensor([[0], [1], [2], [3]]) torch.Size([4, 1]) tensor([[0, 0, 0, 0], [0, 1, 2, 3], [0, 2, 4, 6], [0, 3, 6, 9]]) ``` ## 3 torch.mm操作 torch.mm(input, mat2, *, out=None) → Tensor torch.mm操作要求输入的矩阵都是2维矩阵,矩阵的维度符合矩阵运算规则。第一个矩阵的列等于第二个矩阵的行。 ```python # torch.mm 仅支持2维度矩阵乘法 e = torch.ones(2, 4) f = torch.ones(4, 2) print(torch.mm(e, f)) # 输出 tensor([[4., 4.], [4., 4.]]) ``` ### 4 torch.matmul操作 torch.matmul(input, other, *, out=None) → Tensor 情况1: 若mat1, mat2都是一维向量,则结果返回的是一个标量。 ```python # vector x vector tensor1 = torch.ones(3) tensor2 = torch.ones(3) torch.matmul(tensor1, tensor2) # 输出 tensor(3.) ``` 情况2: mat, mat2为标准的二维矩阵,支持矩阵乘法 ```python g = torch.ones(2, 3) h = torch.ones(3, 5) res = torch.matmul(g, h) print(res) print(res.size()) # 输出 ``` 情况3: mat1, mat2为矩阵和vector,在进行运算的时候,会默认给1维度的vector添加一个维度变成2维矩阵,再进行运算,之后把结果的维度去除,变成1维矩阵。 ```python # matrix x vector tensor1 = torch.randn(3, 4) tensor2 = torch.randn(4) torch.matmul(tensor1, tensor2).size() # 输出 torch.Size([3]) # matrix x vector tensor1 = torch.randn(3) tensor2 = torch.randn(3, 4) torch.matmul(tensor1, tensor2).size() # 输出 torch.Size([4]) ``` 情况4: 若至少有一个参与运算的矩阵的维度大于2,则进行batch矩阵乘法。这里会把矩阵的后两个维度视作矩阵维度(matrix dimensions),参与矩阵运算,其他维度视作batch维度,进行broadcast处理。 ```python # batched matrix x batched matrix tensor1 = torch.randn(10, 3, 4) tensor2 = torch.randn(10, 4, 5) torch.matmul(tensor1, tensor2).size() # 输出 torch.Size([10, 3, 5]) ``` ```python # batched matrix x broadcasted matrix tensor1 = torch.randn(10, 3, 4) tensor2 = torch.randn(4, 5) torch.matmul(tensor1, tensor2).size() # 输出 torch.Size([10, 3, 5]) ``` 最后编辑:2024年04月23日 ©著作权归作者所有 赞 0 分享
最新回复