最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

pytorch - Element wise multiplication of scalars with matrix - Stack Overflow

programmeradmin1浏览0评论

In this example, I want to multiply each of the 10 (batch size) 3x3 matrices with the corresponding scalar. Is there a better solution without having to unsqueeze twice?

import torch

# Create a batch of scalars (e.g., 10 scalars)
batch_size = 10
scalars = torch.randn(batch_size)  # Shape: (10,)

# Create a batch of 3x3 second-order tensors (e.g., 10 matrices of size 3x3)
tensors = torch.randn(batch_size, 3, 3)  # Shape: (10, 3, 3)

# Do we really have to unsqueeze twice to perform element wise multiplication?
result = scalars.unsqueeze(1).unsqueeze(2) * tensors  # Shape (10, 3, 3)

In this example, I want to multiply each of the 10 (batch size) 3x3 matrices with the corresponding scalar. Is there a better solution without having to unsqueeze twice?

import torch

# Create a batch of scalars (e.g., 10 scalars)
batch_size = 10
scalars = torch.randn(batch_size)  # Shape: (10,)

# Create a batch of 3x3 second-order tensors (e.g., 10 matrices of size 3x3)
tensors = torch.randn(batch_size, 3, 3)  # Shape: (10, 3, 3)

# Do we really have to unsqueeze twice to perform element wise multiplication?
result = scalars.unsqueeze(1).unsqueeze(2) * tensors  # Shape (10, 3, 3)
Share Improve this question edited Feb 6 at 7:30 DarkBee 15.6k8 gold badges70 silver badges115 bronze badges asked Feb 6 at 7:24 MathieuMathieu 3287 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 1

You can use different syntax to create a broadcastable view. All of the following are equivalent.

result = scalars.unsqueeze(1).unsqueeze(2) * tensors
result = scalars.view(-1, 1, 1) * tensors
result = scalars[:,None,None] * tensors
发布评论

评论列表(0)

  1. 暂无评论