欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

理解并实现PyTorch中的交叉熵损失函数(附带Python代码)

最编程 2024-02-02 09:04:08
...

1.调用

首先,torch的交叉熵损失函数调用方式为:

torch.nn.functional.cross_entropy(input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean')

一般会写成:

import torch.nn.functional as F
F.cross_entropy(input, target)

2.参数说明

  • 输入张量)–(N, C), 其中C = 类别数;或在 2D 损失的情况下输入尺寸为(N, C, H, W) ,或在K≥1 在 K 维损失的情况下输入尺寸为 (N, C, d1, d2, ..., dK) 

  • target张量)-(N),其中每个值是 0target[i]≤​​​​​​​C-1, 或者在 K≥1 对于 K 维损失,目标张量的尺寸为(N, d1, d2, ..., dK)

  • weight ( Tensor , optional ) – 对每个类别的手动重新缩放权重。如果给定,则必须是大小为C的张量

  • size_average ( bool , optional ) – 不推荐使用。默认情况下,损失是批次中每个损失元素的平均值。请注意,对于某些损失,每个样本有多个元素。如果该字段size_average 设置为False,则对每个小批量的损失求和。当 reduce 为 时忽略False。默认:True

  • ignore_index ( int , optional ) – 指定一个被忽略且对输入梯度没有贡献的目标值。当size_average为 时 True,损失在未忽略的目标上取平均值。默认值:-100

  • reduce ( bool , optional ) – 不推荐使用。默认情况下,损失对每个小批量的观察进行平均或求和,取决于size_average。当reduceis 时False,返回每个批次元素的损失并忽略size_average。默认:True

  • reduce ( string optional ) – 指定应用于输出的缩减: 'none''mean''sum''none': 不会应用减少, 'mean': 输出的总和将除以输出中的元素数, 'sum': 输出将被求和。注意:size_average 和reduce正在被弃用,同时,指定这两个参数中的任何一个都将覆盖reduction. 默认:'mean'

3.举例说明

代码:

import torch
import torch.nn.functional as F
input = torch.randn(3, 5, requires_grad=True)
target = torch.randint(5, (3,), dtype=torch.int64)
loss = F.cross_entropy(input, target)
loss.backward()

变量输出:


input:
tensor([[-0.6314,  0.6876,  0.8655, -1.8212,  0.0963],
        [-0.5437,  0.2778, -0.1662, -0.0784, -0.6565],
        [-0.1164,  0.3882,  0.2487, -0.5318,  0.3943]], requires_grad=True)
target:
tensor([1, 0, 0])
loss:
tensor(1.6557, grad_fn=<NllLossBackward>)

4.注意

python里的torch.nn.functional.cross_entropy函数的实现是:

def cross_entropy(input, target, weight=None, size_average=None, ignore_index=-100,
                  reduce=None, reduction='mean'):
    if size_average is not None or reduce is not None:
        reduction = _Reduction.legacy_get_string(size_average, reduce)
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)

注意1:输入张量不需要经过softmax,直接从fn层拿出来的张量就可以送入交叉熵中,因为在交叉熵中已经对输入input做了softmax了。

注意2:不用对label进行one_hot编码,因为nll_loss函数已经实现了类似one-hot过程,不同之处是当class = [1, 2, 3]时要处理成从0开始[0, 1, 2]。

这里把官方网站的地址也放这里:torch.nn.functional — PyTorch master documentationhttps://pytorch.org/docs/1.2.0/nn.functional.html#torch.nn.functional.cross_entropy

整理不易,欢迎一键三连!!!