【问题标题】:Log-likelihood function in NumPyNumPy 中的对数似然函数
【发布时间】:2019-09-13 04:40:11
【问题描述】:

我关注了this tutorial 我对作者定义负对数似然损失函数的部分感到困惑。

def nll(input, target):
    return -input[range(target.shape[0]), target].mean()

loss_func = nll

这里,target.shape[0]64target 是一个长度为 64 的向量

tensor([5, 0, 4, 1, 9, 2, 1, 3, 1, 4, 3, 5, 3, 6, 1, 7, 2, 8, 6, 9, 4, 0, 9, 1, 1, 2, 4, 3, 2, 7, 3, 8, 6, 9, 0, 5, 6, 0, 7, 6, 1, 8, 7, 9, 3, 9, 8, 5, 9, 3, 3, 0, 7, 4, 9, 8, 0, 9, 4, 1, 4, 4, 6, 0]).

numpy 索引如何导致损失函数?另外,当方括号内有range()和另一个数组时,numpy数组的输出应该是什么?

【问题讨论】:

    标签: python numpy pytorch loss-function


    【解决方案1】:

    在教程中,inputtarget 都是 torch.tensor

    负对数似然损失计算如下:

    nll = -(1/B) * sum(logPi_(target_class)) # for all sample_i in the batch.
    
    

    地点:

    • B:批量大小
    • C:类数
    • Pi: 形状为 [num_classes,] 样本 i 的预测概率向量。由样本ilogit向量的softmax值得到。
    • logPiPi的对数,我们可以通过F.log_softmax(logit_i)得到。

    让我们把它分解为一个简单的例子:

    • input 应为 log_softmax 值,形状为 [B, C]
    • target 预计为地面实况类,形状为 [B, ]

    为了减少混乱,让我们使用B = 4C = 3

    import torch 
    
    B, C = 4, 3
    
    input = torch.randn(B, C)
    """
    >>> input
    tensor([[-0.5043,  0.9023, -0.4046],
            [-0.4370, -0.8637,  0.1674],
            [-0.5451, -0.5573,  0.0531],
            [-0.6751, -1.0447, -1.6793]])
    """
    
    target = torch.randint(low=0, high=C, size=(B, ))
    """
    >>> target
    tensor([0, 2, 2, 1])
    """
    
    # The unrolled version
    nll = 0
    nll += input[0][target[0]] # add -0.5043
    nll += input[1][target[1]] # add -0.1674
    nll += input[2][target[2]] # add  0.0531
    nll += input[3][target[3]] # add -1.0447
    nll *= (-1/B)
    print(nll)
    # tensor(0.3321)
    
    
    # The compact way using numpy indexing
    _nll = -input[range(0, B), target].mean()
    print(_nll)
    # tensor(0.3321)
    

    两种计算方式是相似的。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2019-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2017-02-10
      相关资源
      最近更新 更多