不同形状张量的pytorch logsumexp



我正在寻找将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((吗?或者有没有办法使它在数值上稳定?

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

torch.logadexp

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)

最新更新