【问题标题】:Dot Product of Tensors with Different Shapes in PyTorchPyTorch中不同形状张量的点积
【发布时间】:2018-11-20 07:48:39
【问题描述】:
p=torch.randn(2,3)
q=torch.randn(3,4,5)

我想进行点积,得到形状为(2,4,5)的结果。

PyTorch 如何做到这一点?

【问题讨论】:

标签: matrix-multiplication pytorch tensor


【解决方案1】:

多维矩阵乘法的两种解法:

演示:

import torch

p=torch.randn(2,3)
q=torch.randn(3,4,5)

# Solution 1: Reshaping to use 2-dimensional torch.mm()
res1 = torch.mm(p, q.resize(3, 4 * 5)).resize_(2, 4, 5)
print(res1.shape)
# torch.Size([2, 4, 5])

# Solution 2: Using explicit torch.einsum()
res2 = torch.einsum("ab,bcd->acd", (p, q))
print(res2.shape)
# torch.Size([2, 4, 5])

# Checking if results are equal:
print((res1 == res2).all())
# tensor(1, dtype=torch.uint8)

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2022-12-12
    • 2019-02-21
    • 2022-01-16
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多