Issue
I currently have a tensor that looks like this (numbers randomly selected), which I will call x:
tensor([[ 1., -5.],
[ 2., -4.],
[ 3., 2.],
[ 4., 1.],
[ 5., 2.]])
I also have another 2D tensor (call it i)
tensor([[-1., 1.],
[ 1., -1.]], requires_grad=True)
I hope to pytorch.matmul i to each row in x. Is there a way for me to achieve this?
Below is my attempt:
apply_i = lambda x: torch.matmul(x, i)
final = pytorch.tensor([apply_i(a) for a in x])
It throws an error saying "only one element tensors can be converted to Python scalars". Does not work even when I remove the square bracket.
Any help would be appreciated!
Solution
import torch
x = torch.tensor([[ 1., -5.],
[ 2., -4.],
[ 3., 2.],
[ 4., 1.],
[ 5., 2.]])
change your code:
i = torch.tensor([[-1., 1.],
[ 1., -1.]], requires_grad=True)
apply_i = lambda x: torch.matmul(x, i)
# final = torch.tensor([apply_i(a) for a in x])
final = [apply_i(a) for a in x]
final = torch. stack(final)
Answered By - BarzanHayati
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.