微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。