Pytorch中张量的4种乘法

496 阅读1分钟

点积

>>> a,b = torch.arange(4), torch.arange(4)
>>> a,b
(tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3]))
>>> torch.dot(a, b)
tensor(14)
>>>

点积要求两个向量必须具有相同的尺寸,我们也可以通过按元素乘法来得到点积

>>> torch.sum(a * b)
tensor(14)

与标量相乘

Tensor与标量k相乘,其实相当于Tensor与Tensor同尺寸且元素全为k的矩阵做点积累

>>> a = torch.ones(3,4)
>>> a
tensor([[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]])
>>> a * 2
tensor([[2., 2., 2., 2.],
        [2., 2., 2., 2.],
        [2., 2., 2., 2.]])

矩阵-向量积

在代码中使用张量表示矩阵-向量积,我们使用mv函数。 当我们为矩阵A和向量x调用torch.mv(A, x)时,会执行矩阵-向量积。 注意,A的列维数(沿轴1的长度)必须与x的维数(其长度)相同。

>>> A = torch.ones(3, 4, dtype=torch.float32)
>>> x = torch.arange(4, dtype=torch.float32)
>>> A.shape, x.shape
(torch.Size([3, 4]), torch.Size([4]))
>>> torch.mv(A, x)
tensor([6., 6., 6.])

矩阵乘法

对于矩阵乘法,我们使用mm函数,mm的意思是matmul

>>> A = torch.arange(12).reshape(3,4)
>>> B = torch.arange(12).reshape(4,3)
>>> torch.mm(A, B)
tensor([[ 42,  48,  54],
        [114, 136, 158],
        [186, 224, 262]])

矩阵A的列的维数必须和矩阵B行的维数相同