1

I begin to practice Pytorch ,try to use torch.mm() method。

Below is my code

import torch 
import numpy as np
from torch.autograd import Variable
num_x = np.array([[1.0, 2.0]
                  ,[3.0,4.0]])

tensor_x = torch.from_numpy(num_x)
x = Variable(tensor_x,requires_grad = True)
s = Variable(torch.DoubleTensor([0.01,0.02]),requires_grad = True)
print(s)
s = s.mm(x)
print(s)

Unfortunately,there is a runtime error

*RuntimeError                              Traceback (most recent call last)
<ipython-input-58-e8a58ffb2545> in <module>()
      9 s = Variable(torch.DoubleTensor([0.01,0.02]),requires_grad = True)
     10 print(s)
---> 11 s = s.mm(x)
     12 print(s)
RuntimeError: matrices expected, got 1D, 2D tensors at /pytorch/aten/src/TH/generic/THTensorMath.cpp:131*

How can I fix this problem。 your reply is appreciated

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
林宏銘
  • 13
  • 1
  • 3
  • are you trying to do matrix multiplication? Try reading https://stackoverflow.com/questions/44524901/how-to-do-product-of-matrices-in-pytorch – Banks Feb 07 '20 at 04:47

2 Answers2

1

try reshape you need to change shape of s to (1,2) to make possible matrix multiplication operation with (2,2) tensor

>>> s.reshape(1,2).mm(x)
tensor([[0.0700, 0.1000]], dtype=torch.float64, grad_fn=<MmBackward>)

Or give right shape when initializing s

>>> s = Variable(torch.DoubleTensor([[0.01,0.02]]),requires_grad = True)
>>> s.mm(x)
tensor([[0.0700, 0.1000]], dtype=torch.float64, grad_fn=<MmBackward>)
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
0

or so:

>>> s @ x
tensor([0.0700, 0.1000], dtype=torch.float64, grad_fn=<SqueezeBackward3>)
Sum Zbrod
  • 301
  • 2
  • 4
  • 3
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – He3lixxx Jul 07 '21 at 22:48