pytorch logsumexp 用于不同形状的张量

问题描述 投票:0回答:1

我正在寻找将 torch.logsumexp 与两个不同形状的张量一起使用的方法。我目前手动实现了 logsumexp,如下所示:

import torch
# t1.shape = (4,1,3)
t1 = torch.tensor([[[ 2,  1,  4]],[[-8, 23, -7]],[[ 8, -3,  3]],[[-4,  4,  6]]]).float()

# t2.shape = (4,6,3)
t2 = torch.tensor([[[ 3, 2, 2],[-1,-5, 1],[ 1, 1, 2],[-6, 7,-7],[ 3,-7, 1],[ 1,-1, 2]],
                   [[ 2, 1, 1],[ 3, 3,-1],[-5, 2, 4],[ 4, 3,-9],[ 1, 5, 1],[ 8,-5,-6]],
                   [[ 4, 6, 4],[ 1, 7,-7],[ 8, 8, 6],[-2, 1,-1],[ 9, 5, 9],[ 9, 2,-7]],
                   [[ 2,-6, 1],[-9, 9, 8],[ 3, 3, 2],[-3, 7, 4],[-6, 8,-5],[ 2, 4,-2]]]).float()

# t3.shape = (1,6,3)
t3 = torch.tensor([[[-1,-1, 0],[ 2, 2,-2],[ 3,-1, 0],[ 1, 0, 1],[ 2, 0,-1],[ 1,-2, 3]]]).float()

exp1 = torch.exp(t1)+torch.exp(t2)
log1 = torch.log(exp1)

exp2 = torch.exp(t1)+torch.exp(t3)
log2 = torch.log(exp2)

我想对 t1 和 t2 以及 t1 和 t3 执行 logsumexp。由于exp和log操作,我的代码在数值上非常不稳定,所以我希望使用torch.logsumexp()。

有什么方法可以对 t1、t2 和 t3 张量使用 torch.logsumexp() 吗?或者有什么办法让它数值稳定?

logging pytorch tensor exp
1个回答
0
投票

我找到了一种方法来执行此操作。我可以简单地使用

torch.logaddexp
(docs):

import torch
# t1.shape = (4,1,3)
t1 = torch.tensor([[[ 2,  1,  4]],[[-8, 23, -7]],[[ 8, -3,  3]],[[-4,  4,  6]]]).float()

# t2.shape = (4,6,3)
t2 = torch.tensor([[[ 3, 2, 2],[-1,-5, 1],[ 1, 1, 2],[-6, 7,-7],[ 3,-7, 1],[ 1,-1, 2]],
                   [[ 2, 1, 1],[ 3, 3,-1],[-5, 2, 4],[ 4, 3,-9],[ 1, 5, 1],[ 8,-5,-6]],
                   [[ 4, 6, 4],[ 1, 7,-7],[ 8, 8, 6],[-2, 1,-1],[ 9, 5, 9],[ 9, 2,-7]],
                   [[ 2,-6, 1],[-9, 9, 8],[ 3, 3, 2],[-3, 7, 4],[-6, 8,-5],[ 2, 4,-2]]]).float()

# t3.shape = (1,6,3)
t3 = torch.tensor([[[-1,-1, 0],[ 2, 2,-2],[ 3,-1, 0],[ 1, 0, 1],[ 2, 0,-1],[ 1,-2, 3]]]).float()

res1 = torch.logaddexp(t1, t2)
res2 = torch.logaddexp(t1, t3)
© www.soinside.com 2019 - 2024. All rights reserved.