损失函数#
分割损失函数#
DiceLoss#
- class monai.losses.DiceLoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, weight=None, soft_label=False)[source]#
计算两个张量之间的平均 Dice 损失。它支持多类别和多标签任务。将数据 input(BNHW[D],其中 N 为类别数)与真实标签 target(BNHW[D])进行比较。
注意,input 的 N 轴期望为每个类别的 logits 或概率。如果传入 logits 作为输入,必须设置 sigmoid=True 或 softmax=True,或指定 other_act。target 的同一轴可以是 1 或 N(one-hot 格式)。
smooth_nr 和 smooth_dr 参数分别是添加到并集计算的交集和并集分量中的值,用于平滑结果,这些值应较小。
原始论文
Milletari, F. et. al. (2016) V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation. 3DV 2016.
Wang, Z. et. al. (2023) Jaccard Metric Losses: Optimizing the Jaccard Index with Soft Labels. NeurIPS 2023.
Wang, Z. et. al. (2023) Dice Semimetric Losses: Optimizing the Dice Score with Soft Labels. MICCAI 2023.
- __init__(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, weight=None, soft_label=False)[source]#
- 参数:
include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。如果非背景分割相对于总图像尺寸较小,它们可能会被来自背景的信号淹没,因此在这些情况下排除它有助于收敛。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。squared_pred (
bool) – 是否在分母中使用目标和预测的平方版本。jaccard (
bool) – 是否计算 Jaccard 指数(软 IoU)而不是 Dice。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 添加到分子中的一个小常数,以避免零。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。batch (
bool) – 是否在除法前对 batch 维度上的交集和并集区域求和。默认为 False,在任何 reduction 之前,Dice 损失值是独立于 batch 中的每个项目计算的。weight (
Union[Sequence[float],float,int,Tensor,None]) – 应用于每个类别体素的权重。如果为 None,则不应用权重。输入可以是单个值(所有类别权重相同),也可以是值序列(序列长度应与类别数量相同。如果不包含include_background,则类别数量不应包括背景类别 0)。值应不小于 0。默认为 None。soft_label (
bool) – 目标是否包含非二进制值(软标签)。如果为 True,将使用损失的软标签公式。
- 引发异常:
TypeError – 当
other_act不是Optional[Callable]时。ValueError – 当 [
sigmoid=True,softmax=True,other_act is not None] 中有超过 1 个为真时。参数不兼容。
- forward(input, target)[source]#
- 参数:
input (
Tensor) – 形状应为 BNH[WD],其中 N 为类别数。target (
Tensor) – 形状应为 BNH[WD] 或 B1H[WD],其中 N 为类别数。
- 引发异常:
AssertionError – 当输入和目标(如果设置了 one-hot 转换)形状不同时。
ValueError – 当
self.reduction不在 [“mean”, “sum”, “none”] 之中时。
示例
>>> from monai.losses.dice import * # NOQA >>> import torch >>> from monai.losses.dice import DiceLoss >>> B, C, H, W = 7, 5, 3, 2 >>> input = torch.rand(B, C, H, W) >>> target_idx = torch.randint(low=0, high=C - 1, size=(B, H, W)).long() >>> target = one_hot(target_idx[:, None, ...], num_classes=C) >>> self = DiceLoss(reduction='none') >>> loss = self(input, target) >>> assert np.broadcast_shapes(loss.shape, input.shape) == input.shape
- 返回类型:
Tensor
MaskedDiceLoss#
- class monai.losses.MaskedDiceLoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, weight=None, soft_label=False)[source]#
在 DiceLoss 之前添加一个额外的 masking 过程,接受一个指示区域的二进制掩码([0, 1]),input 和 target 将由该区域掩码:掩码为 1 的区域将保持原始值,掩码为 0 的区域将转换为 0。然后将 input 和 target 输入到正常的 DiceLoss 计算中。这样做的效果是确保只有掩码区域参与损失计算和梯度计算。
- __init__(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, weight=None, soft_label=False)[source]#
参数遵循
monai.losses.DiceLoss。
GeneralizedDiceLoss#
- class monai.losses.GeneralizedDiceLoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, w_type=square, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, soft_label=False)[source]#
计算在以下论文中定义的广义 Dice 损失
Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning loss function for highly unbalanced segmentations. DLMIA 2017.
- __init__(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, w_type=square, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, soft_label=False)[source]#
- 参数:
include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。w_type (
UnionType[Weight,str]) – {"square","simple","uniform"} 将真实体积转换为权重因子的函数类型。默认为"square"。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 添加到分子中的一个小常数,以避免零。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。batch (
bool) – 是否在除法前对 batch 维度上的交集和并集区域求和。默认为 False,从 batch 中的每个项目计算交集除以并集。如果为 True,则先对 batch 进行类加权交集和并集区域的求和。soft_label (
bool) – 目标是否包含非二进制值(软标签)。如果为 True,将使用损失的软标签公式。
- 引发异常:
TypeError – 当
other_act不是Optional[Callable]时。ValueError – 当 [
sigmoid=True,softmax=True,other_act is not None] 中有超过 1 个为真时。参数不兼容。
GeneralizedWassersteinDiceLoss#
- class monai.losses.GeneralizedWassersteinDiceLoss(dist_matrix, weighting_mode='default', reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05)[source]#
计算在以下论文中定义的广义 Wasserstein Dice 损失
Fidon L. et al. (2017) Generalised Wasserstein Dice Score for Imbalanced Multi-class Segmentation using Holistic Convolutional Networks. BrainLes 2017.
或者在以下文献的附录中定义的其变体(使用选项 weighting_mode=”GDL”)
Tilborghs, S. et al. (2020) Comparative study of deep learning methods for the automatic segmentation of lung, lesion and lesion type in CT scans of COVID-19 patients. arXiv preprint arXiv:2007.15546
- __init__(dist_matrix, weighting_mode='default', reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05)[source]#
- 参数:
dist_matrix (
UnionType[ndarray,Tensor]) – 二维张量或二维 numpy 数组;类别间距离矩阵。classes. (它必须具有 C x C 的维度,其中 C 为类别数量)
weighting_mode (
str) –{
"default","GDL"} 指定如何对特定类别的误差总和进行加权。默认为"default"。"default":(推荐)使用原始加权方法,如在...Fidon L. et al. (2017) Generalised Wasserstein Dice Score for Imbalanced Multi-class Segmentation using Holistic Convolutional Networks. BrainLes 2017.
"GDL":使用类似 GDL 的加权方法,如在以下论文的附录中...Tilborghs, S. et al. (2020) Comparative study of deep learning methods for the automatic segmentation of lung, lesion and lesion type in CT scans of COVID-19 patients. arXiv preprint arXiv:2007.15546
reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 添加到分子中的一个小常数,以避免零。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。
- 引发异常:
ValueError – 当
dist_matrix不是方阵时。
示例
import torch import numpy as np from monai.losses import GeneralizedWassersteinDiceLoss # Example with 3 classes (including the background: label 0). # The distance between the background class (label 0) and the other classes is the maximum, equal to 1. # The distance between class 1 and class 2 is 0.5. dist_mat = np.array([[0.0, 1.0, 1.0], [1.0, 0.0, 0.5], [1.0, 0.5, 0.0]], dtype=np.float32) wass_loss = GeneralizedWassersteinDiceLoss(dist_matrix=dist_mat) pred_score = torch.tensor([[1000, 0, 0], [0, 1000, 0], [0, 0, 1000]], dtype=torch.float32) grnd = torch.tensor([0, 1, 2], dtype=torch.int64) wass_loss(pred_score, grnd) # 0
- forward(input, target)[source]#
- 参数:
input (
Tensor) – 形状应为 BNH[WD]。target (
Tensor) – 形状应为 BNH[WD]。
- 返回类型:
Tensor
- wasserstein_distance_map(flat_proba, flat_target)[source]#
根据标签空间 M 上的距离矩阵,计算扁平化预测与扁平化标签(真实值)之间的体素级 Wasserstein 距离。这对应于以下论文中的公式 6
Fidon L. et al. (2017) Generalised Wasserstein Dice Score for Imbalanced Multi-class Segmentation using Holistic Convolutional Networks. BrainLes 2017.
- 参数:
flat_proba (
Tensor) – 输入(预测)张量的概率。flat_target (
Tensor) – 目标张量。
- 返回类型:
Tensor
DiceCELoss#
- class monai.losses.DiceCELoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction='mean', smooth_nr=1e-05, smooth_dr=1e-05, batch=False, weight=None, lambda_dice=1.0, lambda_ce=1.0, label_smoothing=0.0)[source]#
计算 Dice 损失和交叉熵损失,并返回这两个损失的加权和。Dice 损失的详细信息显示在
monai.losses.DiceLoss中。交叉熵损失的详细信息显示在torch.nn.CrossEntropyLoss和torch.nn.BCEWithLogitsLoss()中。在此实现中,不支持两个已弃用的参数size_average和reduce,以及参数ignore_index。- __init__(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction='mean', smooth_nr=1e-05, smooth_dr=1e-05, batch=False, weight=None, lambda_dice=1.0, lambda_ce=1.0, label_smoothing=0.0)[source]#
- 参数:
loss. (reduction 和 weight 同时用于两种损失,而其他参数仅用于 dice)
loss。
include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数,仅用于 DiceLoss,不需要为 CrossEntropyLoss 和 BCEWithLogitsLoss 指定激活函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数,仅用于 DiceLoss,不需要为 CrossEntropyLoss 和 BCEWithLogitsLoss 指定激活函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。仅用于 DiceLoss,不用于 CrossEntropyLoss 和 BCEWithLogitsLoss。squared_pred (
bool) – 是否在分母中使用目标和预测的平方版本。jaccard (
bool) – 是否计算 Jaccard 指数(软 IoU)而不是 Dice。reduction (
str) –{
"mean","sum"} 指定应用于输出的归约方式。默认为"mean"。Dice 损失至少应归约空间维度,这与交叉熵损失不同,因此这里不能使用none选项。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 添加到分子中的一个小常数,以避免零。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。batch (
bool) – 是否在除法前对 batch 维度上的交集和并集区域求和。默认为 False,在任何 reduction 之前,Dice 损失值是独立于 batch 中的每个项目计算的。weight (
Optional[Tensor,None]) – 用于 CrossEntropyLoss 的每个类别的重缩放权重。或用作 BCEWithLogitsLoss 的 pos_weight 的正样本权重。有关更多信息,请参见torch.nn.CrossEntropyLoss()或torch.nn.BCEWithLogitsLoss()。该权重也用于 DiceLoss。lambda_dice (
float) – Dice 损失的权衡权重值。该值应不小于 0.0。默认为 1.0。lambda_ce (
float) – 交叉熵损失的权衡权重值。该值应不小于 0.0。默认为 1.0。label_smoothing (
float) – [0, 1] 范围内的值。如果 > 0,标签将按给定因子进行平滑以减少过拟合。默认为 0.0。
DiceFocalLoss#
- class monai.losses.DiceFocalLoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction='mean', smooth_nr=1e-05, smooth_dr=1e-05, batch=False, gamma=2.0, weight=None, lambda_dice=1.0, lambda_focal=1.0, alpha=None)[source]#
计算 Dice 损失和 Focal 损失,并返回这两个损失的加权和。Dice 损失的详细信息显示在
monai.losses.DiceLoss中。Focal 损失的详细信息显示在monai.losses.FocalLoss中。gamma和lambda_focal仅用于 focal 损失。include_background、weight、reduction和alpha同时用于两种损失,其他参数仅用于 dice 损失。- __init__(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, squared_pred=False, jaccard=False, reduction='mean', smooth_nr=1e-05, smooth_dr=1e-05, batch=False, gamma=2.0, weight=None, lambda_dice=1.0, lambda_focal=1.0, alpha=None)[source]#
- 参数:
include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数,仅用于 DiceLoss,不需要为 FocalLoss 指定激活函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数,仅用于 DiceLoss,不需要为 FocalLoss 指定激活函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。仅用于 DiceLoss,不用于 FocalLoss。squared_pred (
bool) – 是否在分母中使用目标和预测的平方版本。jaccard (
bool) – 是否计算 Jaccard 指数(软 IoU)而不是 Dice。reduction (
str) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 添加到分子中的一个小常数,以避免零。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。batch (
bool) – 是否在除法前对 batch 维度上的交集和并集区域求和。默认为 False,在任何 reduction 之前,Dice 损失值是独立于 batch 中的每个项目计算的。gamma (
float) – Focal 损失定义中指数 gamma 的值。weight (
Union[Sequence[float],float,int,Tensor,None]) – 应用于每个类别体素的权重。如果为 None,则不应用权重。输入可以是单个值(所有类别权重相同),也可以是值序列(序列长度应与类别数量相同)。lambda_dice (
float) – Dice 损失的权衡权重值。该值应不小于 0.0。默认为 1.0。lambda_focal (
float) – Focal 损失的权衡权重值。该值应不小于 0.0。默认为 1.0。alpha (
Optional[float,None]) – alpha 平衡 Focal 损失定义中 alpha 的值。该值应在 [0, 1] 范围内。默认为 None。
GeneralizedDiceFocalLoss#
- class monai.losses.GeneralizedDiceFocalLoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, w_type=square, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, gamma=2.0, weight=None, lambda_gdl=1.0, lambda_focal=1.0)[source]#
计算广义 Dice 损失和 Focal 损失,并返回它们的加权平均值。广义 Dice 损失和 Focal 损失的详细信息可在
monai.losses.GeneralizedDiceLoss和monai.losses.FocalLoss中获取。- 参数:
include_background (bool, optional) – 如果为 False,则从计算中排除通道索引 0(背景类别)。默认为 True。
to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (bool, optional) – 如果为 True,则对预测应用 sigmoid 函数。默认为 False。
softmax (bool, optional) – 如果为 True,则对预测应用 softmax 函数。默认为 False。
other_act (Optional[Callable], optional) – 用于执行其他激活层的可调用函数,默认为
None。例如:other_act = torch.tanh。仅用于 GeneralizedDiceLoss,不用于 FocalLoss。w_type (Union[Weight, str], optional) – {
"square","simple","uniform"}。将真实体积转换为权重因子的函数类型。默认为"square"。reduction (Union[LossReduction, str], optional) – {
"none","mean","sum"}。指定应用于输出的归约方式。默认为"mean"。 -"none":不应用归约。 -"mean":输出的总和将除以输出中的元素数量。 -"sum":输出将被求和。smooth_nr (float, optional) – 添加到分子中的一个小常数,以避免零。默认为 1e-5。
smooth_dr (float, optional) – 添加到分母中的一个小常数,以避免 nan。默认为 1e-5。
batch (bool, optional) – 是否在除法前对 batch 维度上的交集和并集区域求和。默认为 False,即为 batch 中的每个项目计算这些区域。
gamma (float, optional) – Focal 损失定义中指数 gamma 的值。默认为 2.0。
weight (Optional[Union[Sequence[float], float, int, torch.Tensor]], optional) – 应用于每个类别体素的权重。如果为 None,则不应用权重。输入可以是单个值(所有类别权重相同),也可以是值序列(序列长度应与类别数量相同)。默认为 None。
lambda_gdl (float, optional) – 广义 Dice 损失的权衡权重值。该值应不小于 0.0。默认为 1.0。
lambda_focal (float, optional) – Focal 损失的权衡权重值。该值应不小于 0.0。默认为 1.0。
- 引发异常:
ValueError – 如果 lambda_gdl 或 lambda_focal 小于 0。
FocalLoss#
- class monai.losses.FocalLoss(include_background=True, to_onehot_y=False, gamma=2.0, alpha=None, weight=None, reduction=mean, use_softmax=False)[source]#
FocalLoss 是 BCEWithLogitsLoss 的扩展,用于降低高置信度正确预测所带来的损失权重。
重新实现了以下论文中描述的 Focal Loss
[“Focal Loss for Dense Object Detection”](https://arxiv.org/abs/1708.02002), T. Lin et al., ICCV 2017
“AnatomyNet: Deep learning for fast and fully automated whole-volume segmentation of head and neck anatomy”, Zhu et al., Medical Physics 2018
示例
>>> import torch >>> from monai.losses import FocalLoss >>> from torch.nn import BCEWithLogitsLoss >>> shape = B, N, *DIMS = 2, 3, 5, 7, 11 >>> input = torch.rand(*shape) >>> target = torch.rand(*shape) >>> # Demonstrate equivalence to BCE when gamma=0 >>> fl_g0_criterion = FocalLoss(reduction='none', gamma=0) >>> fl_g0_loss = fl_g0_criterion(input, target) >>> bce_criterion = BCEWithLogitsLoss(reduction='none') >>> bce_loss = bce_criterion(input, target) >>> assert torch.allclose(fl_g0_loss, bce_loss) >>> # Demonstrate "focus" by setting gamma > 0. >>> fl_g2_criterion = FocalLoss(reduction='none', gamma=2) >>> fl_g2_loss = fl_g2_criterion(input, target) >>> # Mark easy and hard cases >>> is_easy = (target > 0.7) & (input > 0.7) >>> is_hard = (target > 0.7) & (input < 0.3) >>> easy_loss_g0 = fl_g0_loss[is_easy].mean() >>> hard_loss_g0 = fl_g0_loss[is_hard].mean() >>> easy_loss_g2 = fl_g2_loss[is_easy].mean() >>> hard_loss_g2 = fl_g2_loss[is_hard].mean() >>> # Gamma > 0 causes the loss function to "focus" on the hard >>> # cases. IE, easy cases are downweighted, so hard cases >>> # receive a higher proportion of the loss. >>> hard_to_easy_ratio_g2 = hard_loss_g2 / easy_loss_g2 >>> hard_to_easy_ratio_g0 = hard_loss_g0 / easy_loss_g0 >>> assert hard_to_easy_ratio_g2 > hard_to_easy_ratio_g0
- __init__(include_background=True, to_onehot_y=False, gamma=2.0, alpha=None, weight=None, reduction=mean, use_softmax=False)[源码]#
- 参数:
include_background (
bool) – 如果为 False,则通道索引 0(背景类别)将从损失计算中排除。如果为 False,则在使用 softmax 时 alpha 无效,除非 alpha 是一个序列(显式类别权重)。to_onehot_y (
bool) – 是否将标签 y 转换为 one-hot 格式。默认为 False。gamma (
float) – Focal 损失定义中指数 gamma 的值。默认为 2。alpha (
Union[float,Sequence[float],None]) – alpha 平衡 Focal 损失定义中 alpha 的值。该值应在 [0, 1] 之间。如果提供了序列,其长度必须与类别数量相匹配(如果 include_background=False,则不包括背景类)。默认为 None。weight (
Union[Sequence[float],float,int,Tensor,None]) – 应用于每个类别体素的权重。如果为 None,则不应用权重。输入可以是单个值(所有类别权重相同),也可以是值序列(序列长度应与类别数量相同。如果不包含include_background,则类别数量不应包括背景类别 0)。值应不小于 0。默认为 None。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
use_softmax (
bool) – 是否使用 softmax 将原始 logits 转换为概率。如果为 True,则使用 softmax;如果为 False,则使用 sigmoid。默认为 False。
示例
>>> import torch >>> from monai.losses import FocalLoss >>> pred = torch.tensor([[1, 0], [0, 1], [1, 0]], dtype=torch.float32) >>> grnd = torch.tensor([[0], [1], [0]], dtype=torch.int64) >>> fl = FocalLoss(to_onehot_y=True) >>> fl(pred, grnd)
- forward(input, target)[源码]#
- 参数:
input (
Tensor) – 形状应为 BNH[WD],其中 N 是类别数量。输入应为原始 logits,因为它将在 forward 函数中通过 sigmoid/softmax 进行转换。target (
Tensor) – 形状应为 BNH[WD] 或 B1H[WD],其中 N 为类别数。
- 引发异常:
ValueError – 当输入和目标(如果设置了 one-hot 转换则在转换后)形状不同时。
ValueError – 当
self.reduction不在 [“mean”, “sum”, “none”] 之中时。ValueError – 当
self.weight是一个序列且其长度不等于类别数量时。ValueError – 当
self.weight是或包含小于 0 的值时。
- 返回类型:
Tensor
TverskyLoss#
- class monai.losses.TverskyLoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, alpha=0.5, beta=0.5, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, soft_label=False)[源码]#
计算 Tversky 损失,定义见
Sadegh 等人 (2017) “Tversky loss function for image segmentation using 3D fully convolutional deep networks.” (https://arxiv.org/abs/1706.05721)
Wang, Z. et. al. (2023) Dice Semimetric Losses: Optimizing the Dice Score with Soft Labels. MICCAI 2023.
- __init__(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, alpha=0.5, beta=0.5, reduction=mean, smooth_nr=1e-05, smooth_dr=1e-05, batch=False, soft_label=False)[源码]#
- 参数:
include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。to_onehot_y (
bool) – 是否将 y 转换为 one-hot 格式。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数。other_act (
Optional[Callable,None]) – 如果不想使用 sigmoid 或 softmax,可使用其他可调用函数来执行激活层,默认为None。例如:other_act = torch.tanh。alpha (
float) – 假阳性的权重beta (
float) – 假阴性的权重reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 添加到分子中的一个小常数,以避免零。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。batch (
bool) – 是否在除法前对 batch 维度上的交集和并集区域求和。默认为 False,在任何 reduction 之前,Dice 损失值是独立于 batch 中的每个项目计算的。soft_label (
bool) – 目标是否包含非二进制值(软标签)。如果为 True,将使用损失的软标签公式。
- 引发异常:
TypeError – 当
other_act不是Optional[Callable]时。ValueError – 当 [
sigmoid=True,softmax=True,other_act is not None] 中有超过 1 个为真时。参数不兼容。
ContrastiveLoss#
- class monai.losses.ContrastiveLoss(temperature=0.5, batch_size=-1)[源码]#
计算对比损失(Contrastive loss),定义见
Chen, Ting, et al. “A simple framework for contrastive learning of visual representations.” International conference on machine learning. PMLR, 2020. (https://pmlr.com.cn/v119/chen20j.html)
BarlowTwinsLoss#
- class monai.losses.BarlowTwinsLoss(lambd=0.005)[源码]#
Barlow Twins 代价函数接收神经网络从两个扭曲视图中提取的表示,并试图使两个表示的互相关矩阵趋向于单位矩阵。这鼓励神经网络以最少的冗余学习相似的表示。此代价函数特别适用于多模态学习,以处理来自两种模态的表示。最常见的用例是无监督学习,其中数据增强用于生成同一样本的 2 个扭曲视图,从而迫使编码器提取用于下游任务的有用特征。
Zbontar, Jure, et al. “Barlow Twins: Self-Supervised Learning via Redundancy Reduction” International conference on machine learning. PMLR, 2020. (https://pmlr.com.cn/v139/zbontar21a/zbontar21a.pdf)
HausdorffDTLoss#
- class monai.losses.HausdorffDTLoss(alpha=2.0, include_background=False, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean, batch=False)[源码]#
基于距离变换计算通道维度的二元 Hausdorff 损失。它支持多类别和多标签任务。数据 input(BNHW[D],其中 N 是类别数)与真值 target(BNHW[D])进行比较。
注意,input 的 N 轴期望为每个类别的 logits 或概率。如果传入 logits 作为输入,必须设置 sigmoid=True 或 softmax=True,或指定 other_act。target 的同一轴可以是 1 或 N(one-hot 格式)。
原始论文:Karimi, D. et. al. (2019) Reducing the Hausdorff Distance in Medical Image Segmentation with Convolutional Neural Networks, IEEE Transactions on medical imaging, 39(2), 499-513
- __init__(alpha=2.0, include_background=False, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean, batch=False)[源码]#
- 参数:
alpha (
float) – 计算损失时用于变换距离的指数。默认为 2.0。include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。如果非背景分割相对于总图像尺寸较小,它们可能会被来自背景的信号淹没,因此在这些情况下排除它有助于收敛。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
batch (
bool) – 是否在除法前对 batch 维度上的交集和并集区域求和。默认为 False,即在进行任何 reduction 之前,损失值是为 batch 中的每个项目独立计算的。
- 引发异常:
TypeError – 当
other_act不是Optional[Callable]时。ValueError – 当 [
sigmoid=True,softmax=True,other_act is not None] 中有超过 1 个为真时。参数不兼容。
- distance_field(img)#
生成距离变换。
- 参数:
img (np.ndarray) – 输入掩码,格式为 NCHWD 或 NCHW。
- 返回:
距离场。
- 返回类型:
np.ndarray
- forward(input, target)[源码]#
- 参数:
input (
Tensor) – 形状应为 BNHW[D],其中 N 是类别数量。target (
Tensor) – 形状应为 BNHW[D] 或 B1HW[D],其中 N 是类别数量。
- 引发异常:
ValueError – 如果输入不是 2D (NCHW) 或 3D (NCHWD)。
AssertionError – 当输入和目标(如果设置了 one-hot 转换)形状不同时。
ValueError – 当
self.reduction不在 [“mean”, “sum”, “none”] 之中时。
示例
>>> import torch >>> from monai.losses.hausdorff_loss import HausdorffDTLoss >>> from monai.networks.utils import one_hot >>> B, C, H, W = 7, 5, 3, 2 >>> input = torch.rand(B, C, H, W) >>> target_idx = torch.randint(low=0, high=C - 1, size=(B, H, W)).long() >>> target = one_hot(target_idx[:, None, ...], num_classes=C) >>> self = HausdorffDTLoss(reduction='none') >>> loss = self(input, target) >>> assert np.broadcast_shapes(loss.shape, input.shape) == input.shape
- 返回类型:
Tensor
SoftclDiceLoss#
- class monai.losses.SoftclDiceLoss(iter_=3, smooth_nr=1.0, smooth_dr=1.0, smooth=0.0001, include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean)[源码]#
计算 Soft clDice 损失,定义见
Shit 等人 (2021) “clDice – A Novel Topology-Preserving Loss Function for Tubular Structure Segmentation.” (https://arxiv.org/abs/2003.07311)
数据 input(BNHW[D],其中 N 是类别数)与真值 target(BNHW[D])进行比较。注意 input 的 N 轴期望是每个类别的 logits 或概率,如果传入 logits 作为输入,必须设置 sigmoid=True 或 softmax=True,或者指定 other_act。并且 target 的相同轴可以是 1 或 N(one-hot 格式)。
- __init__(iter_=3, smooth_nr=1.0, smooth_dr=1.0, smooth=0.0001, include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean)[源码]#
- 参数:
iter – 骨架化迭代次数。必须是非负整数。默认为 3。
smooth_nr (
float) – 加到分子上的一个小常数,以避免零。默认为 1.0。smooth_dr (
float) – 加到分母上的一个小常数,以避免 nan。默认为 1.0。smooth (
float) – 加到调和平均数分母上的一个小常数,以避免 nan。默认为 1e-4。include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。如果非背景分割相对于总图像尺寸较小,它们可能会被来自背景的信号淹没,因此在这些情况下排除它有助于收敛。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
- 引发异常:
TypeError – 当
other_act不是Optional[Callable]时。TypeError – 当
iter_不是int时。ValueError – 当
iter_是负整数时。ValueError – 当
smooth不是正值时。ValueError – 当 [
sigmoid=True,softmax=True,other_act is not None] 中有超过 1 个为真时。参数不兼容。
SoftDiceclDiceLoss#
- class monai.losses.SoftDiceclDiceLoss(iter_=3, alpha=0.5, smooth_nr=1.0, smooth_dr=1.0, smooth=0.0001, include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean)[源码]#
计算 Dice 损失和 clDice 损失,并返回这两项损失的加权和。Dice 损失的详细信息显示在
monai.losses.DiceLoss中。clDice 损失的详细信息显示在monai.losses.SoftclDiceLoss中。- 改编自
Shit 等人 (2021) “clDice – A Novel Topology-Preserving Loss Function for Tubular Structure Segmentation.” (https://arxiv.org/abs/2003.07311)
- __init__(iter_=3, alpha=0.5, smooth_nr=1.0, smooth_dr=1.0, smooth=0.0001, include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean)[源码]#
- 参数:
iter – 骨架化迭代次数,用于 clDice。必须是非负整数。默认为 3。
alpha (
float) – cldice 组件的加权因子。总损失 = (1 - alpha) * dice + alpha * cldice。默认为 0.5。smooth_nr (
float) – 加到分子上的一个小常数,以避免零,Dice 和 clDice 均使用。默认为 1.0。smooth_dr (
float) – 加到分母上的一个小常数,以避免 nan,Dice 和 clDice 均使用。默认为 1.0。smooth (
float) – 加到 clDice 中调和平均数分母上的一个小常数,以避免 nan。默认为 1e-4。注意:这与独立 DiceLoss 的默认值 (1e-5) 不同,是为了遵循 clDice 的惯例。include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。如果非背景分割相对于总图像尺寸较小,它们可能会被来自背景的信号淹没,因此在这些情况下排除它有助于收敛。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
- 引发异常:
TypeError – 当
other_act不是Optional[Callable]时。ValueError – 当
alpha不在[0, 1]范围内时。ValueError – 当 [
sigmoid=True,softmax=True,other_act is not None] 中有超过 1 个为真时。参数不兼容。
NACLLoss#
- class monai.losses.NACLLoss(classes, dim, kernel_size=3, kernel_ops='mean', distance_type='l1', alpha=0.1, sigma=1.0)[源码]#
邻域感知校准损失(Neighbor-Aware Calibration Loss, NACL)主要用于开发图像分割中的校准模型。NACL 计算带有线性惩罚的标准交叉熵损失,强制 logit 分布与周围像素的软类别比例相匹配。
Murugesan, Balamurali, et al. “Trust your neighbours: Penalty-based constraints for model calibration.” International Conference on Medical Image Computing and Computer-Assisted Intervention, MICCAI 2023. https://arxiv.org/abs/2303.06268
Murugesan, Balamurali, et al. “Neighbor-Aware Calibration of Segmentation Networks with Penalty-Based Constraints.” https://arxiv.org/abs/2401.14487
- __init__(classes, dim, kernel_size=3, kernel_ops='mean', distance_type='l1', alpha=0.1, sigma=1.0)[源码]#
- 参数:
classes (
int) – 类别数量dim (
int) – 数据维度(支持 2d 和 3d)kernel_size (
int) – 空间核的大小kernel_ops (
str) – 空间核类型,可以是"mean"或"gaussian"。默认为"mean"。distance_type (
str) – 空间核与预测 logits 之间的 l1/l2 距离。默认为"l1"。alpha (
float) – 交叉熵和 logit 约束之间的权重。默认为 0.1。sigma (
float) – 高斯滤波器的 sigma,当kernel_ops="gaussian"时使用。默认为 1.0。
- 引发异常:
ValueError – 如果
kernel_ops不是"mean"或"gaussian"。ValueError – 如果
dim不是 2 或 3。ValueError – 如果
distance_type不是"l1"或"l2"。
- forward(inputs, targets)[源码]#
计算标准交叉熵损失,并利用邻域感知 logit 惩罚对其进行约束。
- 参数:
inputs (
Tensor) – 形状应为 BNH[WD],其中 N 是类别数量。targets (
Tensor) – 形状应为 BH[WD]。
- 返回:
损失值。
- 返回类型:
torch.Tensor
示例
>>> import torch >>> from monai.losses import NACLLoss >>> B, N, H, W = 8, 3, 64, 64 >>> input = torch.rand(B, N, H, W) >>> target = torch.randint(0, N, (B, H, W)) >>> criterion = NACLLoss(classes = N, dim = 2) >>> loss = criterion(input, target)
MCCLoss#
- class monai.losses.MCCLoss(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean, smooth_nr=0.0, smooth_dr=1e-05, batch=False)[源码]#
计算两个张量之间的 Matthews 相关系数 (MCC) 损失。
与仅使用 TP、FP 和 FN 的 Dice 和 Tversky 损失不同,MCC 损失考虑了混淆矩阵的所有四个条目(TP、TN、FP、FN),使其对于背景占主导地位的类别不平衡分割任务非常有效。损失计算为
1 - MCC,其中MCC = (TP * TN - FP * FN) / sqrt((TP+FP)(TP+FN)(TN+FP)(TN+FN))。软混淆矩阵条目计算如下:
TP = sum(input * target)TN = sum((1 - input) * (1 - target))FP = sum(input * (1 - target))FN = sum((1 - input) * target)
数据 input(BNHW[D],其中 N 是类别数)与真值 target(BNHW[D])进行比较。
注意,input 的 N 轴期望为每个类别的 logits 或概率。如果传入 logits 作为输入,必须设置 sigmoid=True 或 softmax=True,或指定 other_act。target 的同一轴可以是 1 或 N(one-hot 格式)。
原始论文
Abhishek, K. and Hamarneh, G. (2021) Matthews Correlation Coefficient Loss for Deep Convolutional Networks: Application to Skin Lesion Segmentation. IEEE ISBI, pp. 225-229. (https://doi.org/10.1109/ISBI48211.2021.9433782)
- __init__(include_background=True, to_onehot_y=False, sigmoid=False, softmax=False, other_act=None, reduction=mean, smooth_nr=0.0, smooth_dr=1e-05, batch=False)[源码]#
- 参数:
include_background (
bool) – 如果为 False,则从计算中排除通道索引 0(背景类别)。如果非背景分割相对于总图像尺寸较小,它们可能会被来自背景的信号淹没,因此在这些情况下排除它有助于收敛。to_onehot_y (
bool) – 是否将target转换为 one-hot 格式,使用从 input 推断出的类别数量(input.shape[1])。默认为 False。sigmoid (
bool) – 如果为 True,则对预测应用 sigmoid 函数。softmax (
bool) – 如果为 True,则对预测应用 softmax 函数。other_act (
Optional[Callable,None]) – 用于执行其他激活层的可调用函数,默认为None。例如:other_act = torch.tanh。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 添加到分子中的一个小常数,以避免零。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。batch (
bool) – 是否在计算 MCC 之前对 batch 维度上的混淆矩阵条目求和。默认为 False,即在进行任何 reduction 之前,MCC 是为 batch 中的每个项目独立计算的。
- 引发异常:
TypeError – 当
other_act不是Optional[Callable]时。ValueError – 当 [
sigmoid=True,softmax=True,other_act is not None] 中有超过 1 个为真时。参数不兼容。
- forward(input, target)[源码]#
- 参数:
input (
Tensor) – 形状应为 BNH[WD],其中 N 为类别数。target (
Tensor) – 形状应为 BNH[WD] 或 B1H[WD],其中 N 为类别数。
- 引发异常:
AssertionError – 当输入和目标(如果设置了 one-hot 转换)形状不同时。
ValueError – 当
self.reduction不在 [“mean”, “sum”, “none”] 之中时。
示例
>>> from monai.losses.mcc_loss import MCCLoss >>> import torch >>> B, C, H, W = 7, 1, 3, 2 >>> input = torch.rand(B, C, H, W) >>> target = torch.randint(low=0, high=2, size=(B, C, H, W)).float() >>> self = MCCLoss(reduction='none') >>> loss = self(input, target)
- 返回类型:
Tensor
配准损失(Registration Losses)#
BendingEnergyLoss#
- class monai.losses.BendingEnergyLoss(normalize=False, reduction=mean)[源码]#
使用中心有限差分,基于
pred的二阶微分计算弯曲能量。有关更多信息,请参阅 Project-MONAI/tutorials。
- 改编自
DeepReg (DeepRegNet/DeepReg)
- __init__(normalize=False, reduction=mean)[源码]#
- 参数:
normalize (
bool) – 是否通过除以空间大小来使计算大致上对图像比例(即向量场采样分辨率)保持不变。默认为 False。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
DiffusionLoss#
- class monai.losses.DiffusionLoss(normalize=False, reduction=mean)[源码]#
使用中心有限差分,基于
pred的一阶微分计算扩散。关于原始论文,请参考:VoxelMorph: A Learning Framework for Deformable Medical Image Registration, Guha Balakrishnan, Amy Zhao, Mert R. Sabuncu, John Guttag, Adrian V. Dalca IEEE TMI: Transactions on Medical Imaging. 2019. eprint arXiv:1809.05231.有关更多信息,请参阅 Project-MONAI/tutorials。
- 改编自
VoxelMorph (voxelmorph/voxelmorph)
- __init__(normalize=False, reduction=mean)[源码]#
- 参数:
normalize (
bool) – 是否通过除以空间大小来使计算大致上对图像比例(即向量场采样分辨率)保持不变。默认为 False。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
- forward(pred)[源码]#
- 参数:
pred (
Tensor) – 预测的密集位移场 (DDF),形状为 BCH[WD],其中 C 是空间维度数。注意,扩散损失仅在 DDF 沿所有空间维度的大小大于 2 时才能计算。- 引发异常:
ValueError – 当
self.reduction不在 [“mean”, “sum”, “none”] 之中时。ValueError – 当
pred不是 3-d、4-d 或 5-d 时。ValueError – 当
pred的任何空间维度的大小小于或等于 2 时。ValueError – 当
pred的通道数与空间维度数不匹配时。
- 返回类型:
Tensor
LocalNormalizedCrossCorrelationLoss#
- class monai.losses.LocalNormalizedCrossCorrelationLoss(spatial_dims=3, kernel_size=3, kernel_type='rectangular', reduction=mean, smooth_nr=0.0, smooth_dr=1e-05)[源码]#
局部平方零归一化互相关(Local squared zero-normalized cross-correlation)。
损失基于 y_true/y_pred 上的移动核/窗口,在窗口内计算 zncc 的平方。核可以是矩形/三角形/高斯窗口。最终损失是所有窗口上的平均损失。
- 改编自
voxelmorph/voxelmorph DeepReg (DeepRegNet/DeepReg)
- 参数:
spatial_dims (
int) – 空间维度数,{1,2,3}。默认为 3。kernel_size (
int) – 核空间大小,必须为奇数。kernel_type (
str) – {"rectangular","triangular","gaussian"}。默认为"rectangular"。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 加到分子上的一个小常数,以避免 nan。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。
- 返回:
- 计算出的损失值。输出范围约为 [-1, 0],其中
值越接近 -1 表示相关性越高(匹配越好)
值越接近 0 表示相关性越低(匹配越差)
此损失应在优化过程中被最小化
- 返回类型:
torch.Tensor
注意
实现计算了平方归一化互相关系数并对其取反,将相关性最大化问题转化为适合标准 PyTorch 优化器的损失最小化问题。
- 解释
损失 ≈ -1:图像之间完美相关
损失 ≈ 0:图像之间没有相关性
更低(更负)的值表示更好的对齐
GlobalMutualInformationLoss#
- class monai.losses.GlobalMutualInformationLoss(kernel_type='gaussian', num_bins=23, sigma_ratio=0.5, reduction=mean, smooth_nr=1e-07, smooth_dr=1e-07)[源码]#
通过 Parzen 窗法实现可微分的全局互信息损失。
- 参考
https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Algorithm 1
- __init__(kernel_type='gaussian', num_bins=23, sigma_ratio=0.5, reduction=mean, smooth_nr=1e-07, smooth_dr=1e-07)[源码]#
- 参数:
kernel_type (
str) –{
"gaussian","b-spline"}"gaussian":改编自 DeepReg 参考:https://dspace.mit.edu/handle/1721.1/123142, Section 3.1, equation 3.1-3.5, Algorithm 1。"b-spline":基于 Mattes 等人 [1,2] 的方法,并改编自 ITK .. rubric:: 参考文献- [1] “Nonrigid multimodality image registration”
D. Mattes, D. R. Haynor, H. Vesselle, T. Lewellen and W. Eubank Medical Imaging 2001: Image Processing, 2001, pp. 1609-1620.
- [2] “PET-CT Image Registration in the Chest Using Free-form Deformations”
D. Mattes, D. R. Haynor, H. Vesselle, T. Lewellen and W. Eubank IEEE Transactions in Medical Imaging. Vol.22, No.1, January 2003. pp.120-128.
num_bins (
int) – 灰度级的 bin 数量sigma_ratio (
float) – 高斯函数的超参数reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
smooth_nr (
float) – 加到分子上的一个小常数,以避免 nan。smooth_dr (
float) – 添加到分母中的一个小常数,以避免 nan。
- forward(pred, target)[源码]#
- 参数:
pred (
Tensor) – 形状应为 B[NDHW]。target (
Tensor) – 形状应与 pred 形状相同。
- 引发异常:
ValueError – 当
self.reduction不在 [“mean”, “sum”, “none”] 之中时。- 返回类型:
Tensor
重建损失(Reconstruction Losses)#
SSIMLoss#
- class monai.losses.ssim_loss.SSIMLoss(spatial_dims, data_range=1.0, kernel_type=gaussian, win_size=11, kernel_sigma=1.5, k1=0.01, k2=0.03, reduction=mean)[源码]#
计算基于结构相似度指标 (SSIM) 的损失函数。
- 欲了解更多信息,请访问
- SSIM 参考文献
Wang, Zhou, et al. “Image quality assessment: from error visibility to structural similarity.” IEEE transactions on image processing 13.4 (2004): 600-612.
- __init__(spatial_dims, data_range=1.0, kernel_type=gaussian, win_size=11, kernel_sigma=1.5, k1=0.01, k2=0.03, reduction=mean)[源码]#
- 参数:
spatial_dims (
int) – 输入图像的空间维度数。data_range (
float) – 输入图像的数值范围。(通常为 1.0 或 255)kernel_type (
UnionType[KernelType,str]) – 核类型,可以是“gaussian”或“uniform”。win_size (
UnionType[int,Sequence[int]]) – 核的窗口大小kernel_sigma (
UnionType[float,Sequence[float]]) – 高斯核的标准差。k1 (
float) – 用于亮度分母的稳定性常数k2 (
float) – 用于对比度分母的稳定性常数reduction (
UnionType[LossReduction,str]) – {"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。 -"none": 不应用归约。 -"mean": 输出的总和将除以输出中的元素数量。 -"sum": 输出将被求和。
- forward(input, target)[源码]#
- 参数:
input (
Tensor) – 预测图像的 batch,形状为 (batch_size, channels, spatial_dim1, spatial_dim2[, spatial_dim3])target (
Tensor) – 目标图像的 batch,形状为 (batch_size, channels, spatial_dim1, spatial_dim2[, spatial_dim3])
- 返回类型:
Tensor- 返回:
1 减去 ssim 指数(请记住,这旨在作为一个损失函数)
示例
import torch # 2D data x = torch.ones([1,1,10,10])/2 y = torch.ones([1,1,10,10])/2 print(SSIMLoss(spatial_dims=2)(x,y)) # pseudo-3D data x = torch.ones([1,5,10,10])/2 # 5 could represent number of slices y = torch.ones([1,5,10,10])/2 print(SSIMLoss(spatial_dims=2)(x,y)) # 3D data x = torch.ones([1,1,10,10,10])/2 y = torch.ones([1,1,10,10,10])/2 print(SSIMLoss(spatial_dims=3)(x,y))
PatchAdversarialLoss#
- class monai.losses.PatchAdversarialLoss(reduction=mean, criterion=least_squares, no_activation_leastsq=False)[源码]#
对 Patch 判别器或多尺度 Patch 判别器计算对抗损失。警告:由于可能使用不同的准则,判别器的输出不能传递给最终激活层。这在损失函数内部已经处理了。
- 参数:
reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
criterion (
str) – 您想在判别器输出上使用的准则(hinge、least_squares 或 bce)。根据准则的不同,将使用不同的激活层。在调用损失函数之前,请确保不要将输出通过激活层。no_activation_leastsq (
bool) – 如果为 True,则最小二乘情况下的激活层被移除。
- forward(input, target_is_real, for_discriminator)[源码]#
- 参数:
input (
UnionType[Tensor,list]) – 多尺度 Patch 判别器或 Patch 判别器的输出;为一个张量列表或一个张量;它们不应该已经通过了激活层。target_is_real (
bool) – 输入是对应于真实图像还是虚假图像的判别器输出for_discriminator (
bool) – 这是为判别器还是生成器损失计算的。在后一种情况下,target_is_real 被设置为 True,因为生成器希望输入被视为真实的。
- 返回:如果 reduction 为 None,则返回一个列表,其中包含每个判别器的损失张量(如果是多尺度判别器激活),或者如果只有一个判别器,则返回损失张量。否则,返回跨张量和判别器的求和或平均损失。
返回的类型
- 返回类型:
UnionType[Tensor,list[Tensor]]
PerceptualLoss#
- class monai.losses.PerceptualLoss(spatial_dims, network_type=alex, is_fake_3d=True, fake_3d_ratio=0.5, cache_dir=None, pretrained=True, pretrained_path=None, pretrained_state_dict_key=None, channel_wise=False)[source]#
使用来自预训练深度神经网络特征的感知损失。该函数支持基于以下内容预训练的网络:使用 Zhang 等人提出的 LPIPS 方法的 ImageNet,“The unreasonable effectiveness of deep features as a perceptual metric.” https://arxiv.org/abs/1801.03924;Mei 等人的 RadImagenet,“RadImageNet: An Open Radiologic Deep Learning Research Dataset for Effective Transfer Learning” https://pubs.rsna.org/doi/full/10.1148/ryai.210315;Chen 等人的 MedicalNet,“Med3D: Transfer Learning for 3D Medical Image Analysis” https://arxiv.org/abs/1904.00625;以及 Torchvision 的 ResNet50: https://pytorch.ac.cn/vision/main/models/generated/torchvision.models.resnet50.html 。
伪 3D 实现基于 2.5D 方法,我们计算所有三个轴上切片的 2D 感知损失并取平均值。完整的 3D 方法使用 3D 网络来计算感知损失。MedicalNet 网络仅与 3D 输入兼容,并支持通道维度的损失计算。
- 参数:
spatial_dims (
int) – 空间维度的数量。network_type (
str) – 感知损失的网络类型。可选:- “alex” - “vgg” - “squeeze” - “radimagenet_resnet50” - “medicalnet_resnet10_23datasets” - “medicalnet_resnet50_23datasets” - “resnet50”is_fake_3d (
bool) – 如果为 True,则使用 2.5D 方法进行 3D 感知损失计算。fake_3d_ratio (
float) – 在 2.5D 方法中每个轴使用的切片比例。cache_dir (
Optional[str,None]) – 用于保存预训练网络权重的缓存目录路径。pretrained (
bool) – 是否加载预训练权重。此参数仅在使用 LIPIS 或 Torchvision 的网络时有效。默认为True。pretrained_path (
Optional[str,None]) – 如果 pretrained 为 True,用户可以通过此参数指定要加载的权重文件。此参数仅在"network_type"为 “resnet50” 时有效。默认为 None。pretrained_state_dict_key (
Optional[str,None]) – 如果 pretrained_path 不为 None,则此参数用于提取预期的状态字典。此参数仅在"network_type"为 “resnet50” 时有效。默认为 None。channel_wise (
bool) – 如果为 True,则按通道返回损失。否则对通道进行平均。默认为False。
- 引发异常:
NotImplementedError – 如果
spatial_dims不为 2 或 3。ValueError – 如果将 MedicalNet 网络与
spatial_dims=2或is_fake_3d=True一起使用。ValueError – 如果将
channel_wise=True与非 MedicalNet 网络一起使用。ValueError – 如果
network_type不在支持的选项中。
JukeboxLoss#
- class monai.losses.JukeboxLoss(spatial_dims, fft_signal_size=None, fft_norm='ortho', reduction=mean)[source]#
基于快速傅里叶变换 (FFT) 的幅度计算谱分量。
- 基于
Dhariwal 等人,“Jukebox: A generative model for music.” https://arxiv.org/abs/2005.00341
- 参数:
spatial_dims (
int) – 空间维度的数量。fft_signal_size (
Optional[tuple[int],None]) – 变换维度中的信号大小。更多信息请参阅 torch.fft.fftn()。fft_norm (
str) – {"forward","backward","ortho"} 指定 FFT 中的归一化模式。更多信息请参阅 torch.fft.fftn()。reduction (
UnionType[LossReduction,str]) –{
"none","mean","sum"} 指定应用于输出的归约方式。默认为"mean"。"none":不应用归约。"mean":输出的总和将除以输出中的元素数量。"sum":输出将被求和。
SURELoss#
- class monai.losses.SURELoss(perturb_noise=None, eps=None)[source]#
为给定算子计算 Stein 无偏风险估计 (SURE) 损失。
这是一种可微分损失函数,可用于训练/指导算子(例如神经网络),适用于有伪地面真值但没有参考地面真值的情况。例如,在 MRI 重建中,伪地面真值是零填充重建,参考地面真值是全采样重建。通常,由于缺乏全采样数据,参考地面真值不可用。
原始 SURE 损失由 [1] 提出。用于指导基于扩散模型的 MRI 重建的 SURE 损失由 [2] 提出。
参考
[1] Stein, C.M.: Estimation of the mean of a multivariate normal distribution. Annals of Statistics
[2] B. Ozturkler 等人. SMRD: SURE-based Robust MRI Reconstruction with Diffusion Models. (https://arxiv.org/pdf/2310.01799.pdf)
- __init__(perturb_noise=None, eps=None)[source]#
- 参数:
perturb_noise (torch.Tensor, 可选) – 噪声向量,形状为
(B (B, 2, H, W)
C (B, 2, H, W)
H (B, 2, H, W)
input (对于实数)
is (形状)
input
is
eps (float, 可选) – 扰动标量。默认为 None。
- forward(operator, x, y_pseudo_gt, y_ref=None, complex_input=False)[source]#
- 参数:
operator (函数) – 接收输入并返回输出张量的算子函数
compute (张量 x,我们将使用它来)
specifically (计算散度。更多)
a (我们将通过以下方式扰动输入 x)
output (以及参考)
output
x (torch.Tensor) – 输入到算子的形状为 (B, C, H, W) 的张量
2 (W) 用于计算 L2 损失。C=1 或) – 对于复数输入,形状为 (B, 2, H, W),即
input (B, 2, H, W)
is (形状)
y_pseudo_gt (与...形状相同) – 伪地面真值张量,形状为
(B – 对于复数
C – 对于复数
H – 对于复数
2 – 对于复数
input
is
is
y_ref (torch.Tensor, 可选) – 参考输出张量
y_pseudo_gt
- 返回:
SURE 损失标量。
- 返回类型:
sure_loss (torch.Tensor)
损失包装器 (Loss Wrappers)#
MultiScaleLoss#
- class monai.losses.MultiScaleLoss(loss, scales=None, kernel='gaussian', reduction=mean)[source]#
这是一个包装类。它在将输入和目标传入包装好的损失函数之前,会在不同尺度上对其进行平滑处理。
- 改编自
DeepReg (DeepRegNet/DeepReg)
- __init__(loss, scales=None, kernel='gaussian', reduction=mean)[source]#
- 参数:
loss (
_Loss) – 要包装的损失函数。scales (
Optional[list,None]) – 缩放因子的列表或 None,如果为 None,则不应用任何缩放。kernel (
str) – 平滑内核的类型,可以是"gaussian"或"cauchy"。默认为"gaussian"。reduction (
UnionType[LossReduction,str]) – 指定应用于输出的缩减方式:"none"|"mean"|"sum"。默认为"mean"。
- 引发异常:
ValueError – 如果
kernel不是"gaussian"或"cauchy"。ValueError – 如果
reduction不是"mean","sum", 或"none"。
MaskedLoss#
- class monai.losses.MaskedLoss(loss, *loss_args, **loss_kwargs)[source]#
这是损失函数的包装类。它允许将额外的加权掩码应用于输入和目标。
DeepSupervisionLoss#
- class monai.losses.DeepSupervisionLoss(loss, weight_mode='exp', weights=None)[source]#
围绕主要损失函数的包装类,用于接收来自深度监督网络的张量列表。最终损失计算为每个深度监督级别加权损失的总和。
- __init__(loss, weight_mode='exp', weights=None)[source]#
- 参数:
loss (
_Loss) – 主要损失实例,例如 DiceLoss()。weight_mode (
str) – {"same","exp","two"} 指定每个图像级别的权重计算。默认为"exp"。 -"same": 所有权重等于 1。 -"exp": 指数递减的权重,以 2 的幂递减:1, 0.5, 0.25, 0.125 等。 -"two": 下层具有相等的较小权重:1, 0.5, 0.5, 0.5, 0.5 等。weights (
Optional[list[float],None]) – 应用于每个深度监督子损失的权重列表,如果提供,无论 weight_mode 如何,都将使用此权重。
- forward(input, target)[source]#
- 参数:
input (
UnionType[None,Tensor,list[Tensor]]) – 单个张量或来自深度监督网络输出的张量列表。target (
Tensor) – 目标张量。
- 返回:
计算出的深度监督损失。
- 返回类型:
torch.Tensor
- 引发异常:
ValueError – 如果
input为 None。