pytorch中是否存在稀疏分类交叉熵的版本?

问题描述

我看到一个数独求解器CNN使用TensorFlow框架将稀疏的分类交叉熵用作损失函数,我想知道Pytorch是否有类似的函数?如果不能,我怎么可能使用Pytorch计算2d阵列的损耗?

解决方法

以下是使用 nn.CrossEntropyLoss 对大小为 1、宽度为 2、高度为 2 和 3 类的批次进行图像分割的示例。
图像分割是像素级的分类问题。当然你也可以使用 nn.CrossEntropyLoss 进行基本的图像分类。
问题中的数独问题可以看作是一个图像分割问题,其中您有 10 个类(10 个数字)(尽管神经网络不适合解决像数独这样已经具有高效精确分辨率算法的组合问题)。
nn.CrossEntropyLoss 直接接受地面实况标签作为 [0,N_CLASSES[ 中的整数(无需对标签进行单热编码)

import torch
from torch import nn
import numpy as np

# logits predicted
x = np.array([[
    [[1,0],[1,0]],# predict class 0 for pixel (0,0) and class 0 for pixel (0,1)
    [[0,1,[0,1]],# predict class 1 for pixel (1,0) and class 2 for pixel (1,1)
]])*5  # multiply by 5 to give bigger losses
print("logits map :")
print(x)

# ground truth labels
y = np.array([[
    [0,1],# must predict class 0 for pixel (0,0) and class 1 for pixel (0,1)
    [1,2],# must predict class 1 for pixel (1,1)
]])  
print("\nlabels map :")
print(y)

x=torch.Tensor(x).permute((0,3,2))  # shape of preds must be (N,C,H,W) instead of (N,W,C)
y=torch.Tensor(y).long() #  shape of labels must be (N,W) and type must be long integer

losses = nn.CrossEntropyLoss(reduction="none")(x,y)  # reduction="none" to get the loss by pixel 
print("\nLosses map :")
print(losses)
# notice that the loss is big only for pixel (0,1) where we predicted 0 instead of 1

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...