英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论