Adding and multiplying matrices in PyTorch

Part 1

IN:

A = torch.tensor([1,2])

B = torch.tensor([[1,2],[2,4]])

print(A+B)

OUT:

tensor([[2, 4],
        [3, 6]])

Question:

Why doesn't Torch swear even though the matrices are of different sizes?


Part 2

IN:

A = torch.tensor([[2,2],[1,2],[2,4]])

B = torch.tensor([[-7,5],[2,-1]])

print(A*B)

OUT:

RuntimeError

Question:

And why can't I multiply the matrices A(3x2) and B (2x2)?

Author: S. Nick, 2020-05-05

1 answers

Because the operations + and * perform an element-by-element action. In the first case, you have a one-dimensional vector of length 2 added to each vector of length 2 of a two-dimensional vector of size (2, 2).

In the second case, both operands are two-dimensional, but they have different sizes, so they cannot be multiplied in any way element by element. To perform matrix multiplication by the "row by column" rule, do one of the following: methods:

AB = A.mm(B)

AB = torch.mm(A, B)

AB = torch.matmul(A, B)

AB = A @ B # Python 3.5+

Https://stackoverflow.com/a/44527447/7485582

 1
Author: Кирилл Малышев, 2020-05-05 20:29:10