Shi*_*att 7 conv-neural-network pytorch loss-function
我看到一个数独求解器 CNN 使用稀疏分类交叉熵作为使用 TensorFlow 框架的损失函数,我想知道 Pytorch 是否有类似的函数?如果不是,我如何可能使用 Pytorch 计算 2d 数组的损失?
下面是使用nn.CrossEntropyLoss进行图像分割的示例,其中批量大小为 1、宽度 2、高度 2 和 3。
图像分割是像素级的分类问题。当然,您也可以使用 nn.CrossEntropyLoss 进行基本图像分类。
问题中的数独问题可以看作是一个图像分割问题,其中有 10 个类别(10 个数字)(尽管神经网络不适合解决像数独这样的组合问题,因为数独已经具有高效的精确分辨率算法)。
nn.CrossEntropyLoss 直接接受真实标签作为 [0, N_CLASSES[ 中的整数(无需对标签进行 onehot 编码):
import torch
from torch import nn
import numpy as np
# logits predicted
x = np.array([[
[[1,0,0],[1,0,0]], # predict class 0 for pixel (0,0) and class 0 for pixel (0,1)
[[0,1,0],[0,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,0) and class 2 for pixel (1,1)
]])
print("\nlabels map :")
print(y)
x=torch.Tensor(x).permute((0,3,1,2)) # shape of preds must be (N, C, H, W) instead of (N, H, W, C)
y=torch.Tensor(y).long() # shape of labels must be (N, H, 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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14761 次 |
最近记录: |