[英]Multiply rows of matrix by vector elementwise in pytorch?
I would like to do the below but using PyTorch . 我想执行以下操作,但要使用PyTorch 。
The below example and description is from this post . 以下示例和说明来自此文章 。
I have a numeric matrix with 25 columns and 23 rows, and a vector of length 25. How can I multiply each row of the matrix by the vector without using a for loop? 我有一个25列23行的数字矩阵,以及一个长度为25的向量。如何在不使用for循环的情况下将矩阵的每一行乘以向量?
The result should be a 25x23 matrix (the same size as the input), but each row has been multiplied by the vector. 结果应该是25x23的矩阵(与输入大小相同),但是每一行都已乘以向量。
Example Code in R (source: reproducible example from @hatmatrix's answer ): R中的示例代码(来源:可复制的示例,来自@hatmatrix的答案 ):
matrix <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
vector <- 1:5
Desired output: 所需的输出:
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 4 6 8 10
[3,] 3 6 9 12 15
What is the best way of doing this using Pytorch? 使用Pytorch的最佳方法是什么?
The answer was so trivial that I overlooked it. 答案是如此微不足道,以至于我忽略了它。
For simplicity I used a smaller vector and matrix in this answer. 为简单起见,我在此答案中使用了较小的向量和矩阵。
X = torch.tensor([[3, 5],[5, 5],[1, 0]])
y = torch.tensor([7,4])
X*y
# or alternatively
y*X
output: 输出:
tensor([[21, 20],
[35, 20],
[ 7, 0]])
tensor([[21, 20],
[35, 20],
[ 7, 0]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.