I want to broadcast an pytorcc tensor of dimension (a,b,c) onto an array of dimension (b,c) to get an output of dimension (a,c) how do I do this?

huangapple go评论66阅读模式
英文:

I want to broadcast an pytorcc tensor of dimension (a,b,c) onto an array of dimension (b,c) to get an output of dimension (a,c) how do I do this?

问题

我有两个PyTorch张量,

A.shape = [416, 20, 3]
B.shape = [416, 20]

我想要产生

C = torch.matmul(A, B.unsqueeze(2))
C.shape = [416, 3]

也就是说,对于A中的每个416个20x3数组,找到B中相应的20x1数组,然后计算torch.matmul(A_i, B)。将这个3x1数组放在输出索引i处。如何使广播像这样工作?

英文:

I have two pytorch tensors,

A.shape = [416, 20, 3]
B.shape = [416,20]

I want to produce

C = matmul(A,B)
C.shape = [416,3]

Ie for each of the 416 20x3 arrays in A, find the corresponding 20X1 array in B and compute torch.matmul(A_i,B). Set that 3x1 array the i index of the output index. How do I make the broadcasting work out like this?

答案1

得分: 2

当有疑惑时,请使用 torch.einsum。

# 为了示例,生成两个随机张量
A = torch.normal(mean=0.0, std=1.0, size=(416, 20, 3))
B = torch.normal(mean=0.0, std=1.0, size=(416, 20))

C = torch.einsum('ijk,ij->ik', A, B)
print(C.shape)  # 输出 (416,3)
英文:

When in doubt, use torch.einsum

# generate two random tensors for illustration purpose
A = torch.normal(mean=0.0, std=1.0, size=(416,20,3))
B = torch.normal(mean=0.0, std=1.0, size=(416,20))

C = torch.einsum('ijk,ij->ik', A, B)
print(C.shape) # will output (416,3)

huangapple
  • 本文由 发表于 2023年3月1日 14:44:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定