Add / substract between matrix and vector in pytorch
Add / substract between matrix and vector in pytorch
I want to do + / - / * between matrix and vector in pytorch.
How can I do with good performance?
I tried to use expand, but it's really slow (I am using big matrix with small vector).
a = torch.rand(2,3)
print(a)
0.7420 0.2990 0.3896
0.0715 0.6719 0.0602
[torch.FloatTensor of size 2x3]
b = torch.rand(2)
print(b)
0.3773
0.6757
[torch.FloatTensor of size 2]
a.add(b)
Traceback (most recent call last):
File "C:ProgramDataAnaconda3libsite-packagesIPythoncoreinteractiveshell.py", line 3066, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-17-a1cb1b03d031>", line 1, in <module>
a.add(b)
RuntimeError: inconsistent tensor size, expected r_ [2 x 3], t [2 x 3] and src [2] to have the same number of elements, but got 6, 6 and 2 elements respectively at c:miniconda2conda-bldpytorch-cpu_1519449358620worktorchlibthgeneric/THTensorMath.c:1021
Expected result:
0.7420-0.3773 0.2990-0.3773 0.3896-0.3773
0.0715-0.6757 0.6719-0.6757 0.0602-0.6757
1 Answer
1
what about reshaping?
In [2]: a = torch.rand(2,3)
...:
In [3]: a
Out[3]:
tensor([[ 0.2207, 0.1203, 0.7908],
[ 0.6702, 0.7557, 0.0708]])
In [4]: b = torch.rand(2)
...:
In [5]: b
Out[5]: tensor([ 0.5953, 0.7925])
In [6]: a.add(b.reshape(-1,1))
Out[6]:
tensor([[ 0.8160, 0.7156, 1.3861],
[ 1.4627, 1.5481, 0.8632]])
also check about the broadcasting: https://pytorch.org/docs/stable/notes/broadcasting.html
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Comments
Post a Comment