【问题标题】:pytorch logsumexp for tensors with different shapespytorch logsumexp 用于不同形状的张量
【发布时间】:2021-02-26 15:37:35
【问题描述】:

我正在寻找将 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()。

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

【问题讨论】:

    标签: logging pytorch tensor exp


    【解决方案1】:

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

    torch.logaddexp

    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)
    

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 1970-01-01
      • 2022-12-12
      • 2019-02-21
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-08-27
      • 2021-07-22
      相关资源
      最近更新 更多