PyTorch:输出层和损失函数loss function

输出相关

[PyTorch:全局函数_输出相关]

Loss Functions

[loss-functions]

nn.L1Loss

Creates a criterion that measures the mean absolute error (MAE) between each element in the input xx and target yy .

nn.MSELoss

Creates a criterion that measures the mean squared error (squared L2 norm) between each element in the input xx and target yy .

nn.CrossEntropyLoss

This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class.

nn.CTCLoss

The Connectionist Temporal Classification loss.

nn.NLLLoss

The negative log likelihood loss.

nn.PoissonNLLLoss

Negative log likelihood loss with Poisson distribution of target.

nn.KLDivLoss

The Kullback-Leibler divergence loss measure

nn.BCELoss

Creates a criterion that measures the Binary Cross Entropy between the target and the output:

nn.BCEWithLogitsLoss

This loss combines a Sigmoid layer and the BCELoss in one single class.

nn.MarginRankingLoss

Creates a criterion that measures the loss given inputs x1x1 , x2x2 , two 1D mini-batch Tensors, and a label 1D mini-batch tensor yy (containing 1 or -1).

nn.HingeEmbeddingLoss

Measures the loss given an input tensor xx and a labels tensor yy (containing 1 or -1).

nn.MultiLabelMarginLoss

Creates a criterion that optimizes a multi-class multi-classification hinge loss (margin-based loss) between input xx (a 2D mini-batch Tensor) and output yy (which is a 2D Tensor of target class indices).

nn.SmoothL1Loss

Creates a criterion that uses a squared term if the absolute element-wise error falls below beta and an L1 term otherwise.

nn.SoftMarginLoss

Creates a criterion that optimizes a two-class classification logistic loss between input tensor xx and target tensor yy (containing 1 or -1).

nn.MultiLabelSoftMarginLoss

Creates a criterion that optimizes a multi-label one-versus-all loss based on max-entropy, between input xx and target yy of size (N, C)(N,C) .

nn.CosineEmbeddingLoss

Creates a criterion that measures the loss given input tensors x_1x1​ , x_2x2​ and a Tensor label yy with values 1 or -1.

nn.MultiMarginLoss

Creates a criterion that optimizes a multi-class classification hinge loss (margin-based loss) between input xx (a 2D mini-batch Tensor) and output yy (which is a 1D tensor of target class indices, 0 \leq y \leq \text{x.size}(1)-10≤y≤x.size(1)−1 ):

nn.TripletMarginLoss

Creates a criterion that measures the triplet loss given an input tensors x1x1 , x2x2 , x3x3 and a margin with a value greater than 00 .

nn.TripletMarginWithDistanceLoss

Creates a criterion that measures the triplet loss given input tensors aa , pp , and nn (representing anchor, positive, and negative examples, respectively), and a nonnegative, real-valued function (“distance function”) used to compute the relationship between the anchor and positive example (“positive distance”) and the anchor and negative example (“negative distance”).

参数

reduction (stringoptional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum''none': no reduction will be applied, 'mean': the weighted mean of the output is taken, 'sum': the output will be summed. Note: size_average and reduce are in the process of being deprecated, and in the meantime, specifying either of those two args will override reduction. Default: 'mean'

[CROSSENTROPYLOSS]

[pytorch loss function 总结]

BCELoss/BCEWithLogitsLoss和CrossEntropyLoss的区别

        BCEWithLogitsLoss = Sigmoid+BCELoss,当网络最后一层使用nn.Sigmoid时,就用BCELoss,当网络最后一层不使用nn.Sigmoid时,就用BCEWithLogitsLoss。
        BCELoss/BCEWithLogitsLoss用于单标签二分类或者多标签二分类,输出和目标的维度是(batch,C),batch是样本数量,C是类别数量,对于每一个batch的C个值,对每个值求sigmoid到0-1之间,所以每个batch的C个值之间是没有关系的,相互独立的,所以之和不一定为1。每个C值代表属于一类标签的概率。如果是单标签二分类,那输出和目标的维度是(batch,1)即可。

        另外torch.nn.BCELoss是一个类,其中的forward的具体实现调用的是函数F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)。

[torch.nn.modules.loss — PyTorch 2.1 documentation]

[TORCH.NN.FUNCTIONAL.BINARY_CROSS_ENTROPY]

        CrossEntropyLoss用于多类别分类,输出和目标的维度是(batch,C),batch是样本数量,C是类别数量,每一个C之间是互斥的,相互关联的,对于每一个batch的C个值,一起求每个C的softmax,所以每个batch的所有C个值之和是1,哪个值大,代表其属于哪一类。如果用于二分类,那输出和目标的维度是(batch,2)。

二分类输出层使用两个神经元和只使用一个神经元的区别

[深度学习:神经网络的输出层]

        二分类时一般把bert压缩成一维过sigmoid或者压缩成2维过softmax。压缩成2维时,Sigmoid(每1维都过sigmoid)和softmax输出的结果不同,第一个所有神经元之和可能大于1,第二个所有神经元输出的结果之和一定等于1。

[神经网络进行二分类时,输出层使用两个神经元和只使用一个神经元,模型的性能有何差异]

[二分类问题输出一个节点还是两个节点_IT莫莫的博客-CSDN博客]

训练算loss时1 使用一个神经元,是用sigmoid处理,最后通过0.5阈值判断0或者1,交叉熵损失函数用的是F.binary_cross_entropy。
2 使用两个神经元,是用softmax处理,并且交叉熵损失函数用的是CrossEntropyLoss。
两个神经元算loss时
elif self.config.problem_type == "single_label_classification":
    loss_fct = CrossEntropyLoss()
    loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))

Note: 这里加view[PyTorch:tensor-基本操作_view]数据和shape都没变化
logits(batch_size, num_labels)    labels(batch_size,)

评估Evaluation 或者 预测predict时
使用两个神经元时不需要过softmax,直接比较两个神经元大小,取argmax。
如:两个神经元评估算metric时
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(p: EvalPrediction):
    preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
    preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
    return metric.compute(predictions=preds, references=p.label_ids)
如:两个神经元predict时
predictions = trainer.predict(predict_dataset, metric_key_prefix="predict").predictions
predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1)

Note: 只使用一个神经元时,必须过sigmoid吧,不然没法和0.5比较。

示例

nn.CrossEntropyLoss的示例

import torch
from torch import nn

# Example of target with class indices
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
# input.size():  torch.Size([3, 5])
target = torch.empty(3, dtype=torch.long).random_(5)
# target.size():  torch.Size([3])
output = loss(input, target)
output.backward()

# Example of target with class probabilities
input = torch.randn(3, 5, requires_grad=True)
# input.size():  torch.Size([3, 5])
target = torch.randn(3, 5).softmax(dim=1)
# target.size():  torch.Size([3, 5])
output = loss(input, target)
output.backward()

nn.BCELOSS的示例

m = nn.Sigmoid()
loss = nn.BCELoss()
input = torch.randn(3, requires_grad=True)
target = torch.empty(3).random_(2)
output = loss(m(input), target)
output.backward()

nn.functional.binary_cross_entropy的示例

import torch.nn.functional as F

labels = dataloader["label"]
predictions = outputs.squeeze().contiguous()

loss = F.binary_cross_entropy(predictions, labels, reduction='mean')

input = torch.randn(3, 2, requires_grad=True)
target = torch.rand(3, 2, requires_grad=False)
loss = F.binary_cross_entropy(torch.sigmoid(input), target)
loss.backward()

from: -柚子皮-

ref: [torch.nn — PyTorch 2.0 documentation]

<think>好的,我现在需要回答用户关于PyTorch输出激活函数及其应用场景的问题。首先,我需要回忆一下相关的知识,并结合提供的引用内容来组织回答。用户提到了三个引用,其中引用[1]讨论了不同任务中的输出激活函数,引用[2]关于自定义激活函数,引用[3]则给出了一些PyTorch中的示例。 首先,我应该按照用户的要求,结构清晰地分点回答,每个任务类型(二元分类、多分类、回归)分别说明适用的激活函数、数学表达式、PyTorch实现代码应用场景。同时,需要确保所有数学表达式使用$...$格式,独立公式用$$...$$。还要生成相关问题,并在引用处正确标注。 接下来,我需要确认每个任务对应的激活函数是否正确。二元分类通常是sigmoid,多分类用softmax,回归可能不使用激活函数或者用线性。然后,检查引用内容是否支持这些信息。例如,引用[1]提到二元分类用sigmoid,多分类用softmax,回归用线性或恒等函数,这我的记忆一致。引用[3]中提到了tanh用于隐藏,而sigmoid用于输出,这适用于二元分类的情况。 然后,我需要为每个部分编写数学表达式。比如sigmoid函数是$\sigma(x) = \frac{1}{1 + e^{-x}}$,softmax是$S(z_i) = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}$,线性函数可能不需要激活,或者用恒等函数。这些表达式需要正确使用LaTeX格式,并确保独立公式单独成段。 接下来是PyTorch的代码示例。对于sigmoid,使用nn.Sigmoid();softmax用nn.Softmax(dim=1);回归可能用nn.Identity()。需要确保代码正确,并适当注释,比如在softmax中注意dim参数的选择。 应用场景部分需要简明扼要,例如二元分类用于垃圾邮件检测,多分类用于图像分类,回归用于房价预测。这些例子需要符合实际应用,同时参考引用中的内容。例如引用[1]中的二元分类多分类的应用场景,引用[3]中的示例。 在注意事项部分,需要提到激活函数的选择依据,如输出范围、概率分布需求等,以及自定义激活函数的可能性,这里可以引用[2]中的内容,说明虽然预定义函数常用,但有时自定义可能更好。 最后,生成的相关问题需要围绕主题展开,可能包括激活函数的选择依据、不同函数的优缺点、自定义方法、与损失函数的关系,以及回归任务中的其他激活函数。这些问题应该帮助用户进一步深入学习。 在检查过程中,需要确保所有引用标记正确,如[^1]、[^2]、[^3]分别对应到相应的引用内容。例如,在讨论二元分类时引用,在自定义激活函数时引用[^2]。 现在,组织这些内容,确保结构清晰,符合用户的要求,同时使用正确的中文表达,避免技术错误。</think>### PyTorch输出激活函数使用场景及示例 在PyTorch中,输出激活函数的选择取决于任务类型。以下是三类常见任务(二元分类、多分类、回归)的激活函数应用场景及代码示例: --- #### 1. 二元分类(Binary Classification) - **激活函数**:Sigmoid - **数学表达式**: $$\sigma(x) = \frac{1}{1 + e^{-x}}$$ 输出值范围为$(0,1)$,可解释为概率。 - **PyTorch实现**: ```python import torch.nn as nn model = nn.Sequential( nn.Linear(in_features=10, out_features=1), nn.Sigmoid() ) ``` - **应用场景**:垃圾邮件检测、医学诊断(患病/健康)[^1]。 --- #### 2. 多分类(Multi-class Classification) - **激活函数**:Softmax - **数学表达式**: $$S(z_i) = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}$$ 输出为$K$个类别的概率分布(为1)[^1]。 - **PyTorch实现**: ```python model = nn.Sequential( nn.Linear(in_features=10, out_features=5), # 假设5个类别 nn.Softmax(dim=1) # 注意dim参数指定计算维度 ) ``` - **应用场景**:图像分类(MNIST手写数字识别)、文本情感分析(多类别情感标签)。 --- #### 3. 回归(Regression) - **激活函数**:恒等函数(Identity,即无激活函数)或线性激活 - **数学表达式**: $$f(x) = x$$ 直接输出连续值,无需非线性变换。 - **PyTorch实现**: ```python model = nn.Sequential( nn.Linear(in_features=10, out_features=1), nn.Identity() # 可省略,默认无激活函数 ) ``` - **应用场景**:房价预测、温度预测等连续值输出任务[^1]。 --- ### 注意事项 1. **输出范围匹配**:Sigmoid适合概率输出,Softmax确保概率归一化,回归任务需避免限制输出范围。 2. **与损失函数配合**: - Sigmoid通常搭配`BCELoss`(二元交叉熵) - Softmax搭配`CrossEntropyLoss`(已集成Softmax) - 回归任务常用`MSELoss`(均方误差)[^1] 3. **自定义激活函数**:可通过继承`torch.autograd.Function`实现(如改进梯度特性)。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值