PyTorch学习笔记(四)损失函数

损失函数 DiceLoss 的 Pytorch 实现 Pytorch 实现 def dice_loss(preds, targets): """ preds: tensor of shape (N, C) targets: tensor of shape (N, C) """ assert preds.shape == targets.shape preds = preds.float() targets = targets.float() numer 阅读详情

Environment

  • OS: macOS Mojave
  • Python version: 3.7
  • PyTorch version: 1.4.0
  • IDE: PyCharm


0. 写在前面

损失函数用于描述模型预测与真实值之间的差异。严格意义上来说,损失函数(loss function)是对于单个样本实例而言的,而代价函数(cost function)的对于训练数据集而言的

  • 损失函数 Loss = f ( y ^ , y ) \text{Loss} = f(\hat{y}, y) Loss=f(y^​,y)
  • 代价函数 Cost = ∑ i N f ( y ^ , y ) \text{Cost} = \sum_i^N f(\hat{y}, y) Cost=∑iN​f(y^​,y) 或 Cost = 1 N ∑ i N f ( y ^ , y ) \text{Cost} = \frac{1}{N} \sum_i^N f(\hat{y}, y) Cost=N1​∑iN​f(y^​,y)

但实际表述中并不严格区分二者。此外,最终要优化的函数为目标函数为代价函数加上正则项

  • 目标函数 Obj = Cost + Regularization \text{Obj} = \text{Cost} + \text{Regularization} Obj=Cost+Regularization

PyTorch 在 torch.nn 模块中提供了 18 种常用的损失函数的类,它们被定义为 torch.nn.Module 的子类,通过重写 forward 方法,在其中调用 torch.nn.functional 中的函数实现。

from torch.nn import Module, CrossEntropyLoss

issubclass(CrossEntropyLoss, Module)  # True

实例化这些类时,都需要传入一个参数 reduction

  • 默认值为 mean,计算 Cost = 1 N ∑ i N f ( y ^ , y ) \text{Cost} = \frac{1}{N} \sum_i^N f(\hat{y}, y) Cost=N1​∑iN​f(y^​,y)
  • 若传入 sum,则计算 Cost = ∑ i N f ( y ^ , y ) \text{Cost} = \sum_i^N f(\hat{y}, y) Cost=∑iN​f(y^​,y)
  • 若传入 none,则计算 Loss = f ( y ^ , y ) \text{Loss} = f(\hat{y}, y) Loss=f(y^​,y)
from torch.nn import L1Loss

l1_loss = L1Loss(reduction='mean')

这里小小地学习一下这些损失函数的类,有些尚未在应用到,日后方便查询 ✅

1. L1Loss

L1Loss 类,计算 inputs 和 target 之差的绝对值, l o s s = ∣ y ^ − y ∣ loss = |\hat{y} - y| loss=∣y^​−y∣

import torch
from torch.nn import L1Loss

# create data
inputs = torch.tensor([1, 5, 3, 9, 7], dtype=torch.float)
target = torch.tensor([4, 2, 6, 0, 8], dtype=torch.float)

l1_loss = L1Loss(reduction='none')
print(l1_loss(inputs, target))
# tensor([3., 3., 3., 9., 1.])

2. SmoothL1Loss

SmoothL1Loss 类,平滑 L1 损失函数,计算公式为
l o s s = { 1 2 ( y ^ − y ) 2 ,  if ∣ y ^ − y ∣ < 1 ∣ y ^ − y ∣ − 1 2 , otherwise loss = \begin{cases} \frac{1}{2} (\hat{y} - y)^2, \text{ if} |\hat{y} - y| < 1 \\ |\hat{y} - y| - \frac{1}{2}, \text{otherwise} \end{cases} loss={21​(y^​−y)2, if∣y^​−y∣<1∣y^​−y∣−21​,otherwise​

import torch
from torch.nn import SmoothL1Loss

# create data
inputs = torch.tensor([1, 5, 3, 9, 7.6], dtype=torch.float)
target = torch.tensor([4, 2, 6, 0, 8], dtype=torch.float)

smooth_l1_loss = SmoothL1Loss(reduction='none')
print(smooth_l1_loss(inputs, target))
# tensor([2.5000, 2.5000, 2.5000, 8.5000, 0.0800])

3. MSELoss

MSELoss 类,计算 inputs 和 target 之差的平方, l o s s = ( y ^ − y ) 2 loss = (\hat{y} - y)^2 loss=(y^​−y)2

import torch
from torch.nn import MSELoss

# create data
inputs = torch.tensor([1, 5, 3, 9, 7], dtype=torch.float)
target = torch.tensor([4, 2, 6, 0, 8], dtype=torch.float)

l2_loss = MSELoss(reduction='none')

print(l2_loss(inputs, target))

4. BCELoss

BCELoss 类,计算二分类交叉熵,要求输入 inputs 的值范围在 [ 0 , 1 ] [0, 1] [0,1]

import torch
from torch.nn import BCELoss

# create data
inputs = torch.tensor([
    [1, 3],
    [4, 2]
], dtype=torch.float)
target = torch.tensor([
    [1, 0],
    [1, 0]
], dtype=torch.float)

binary_crossentropy_loss = BCELoss(
    weight=None,
    reduction='none'
)

# 用 sigmoid 将输入压缩至 0 到 1
print(binary_crossentropy_loss(torch.sigmoid(inputs), target))
# tensor([[0.3133, 3.0486],
#         [0.0181, 2.1269]])

5. BCEWithLogitsLoss

在 BCELoss 类中,要求输入 inputs 的值范围在 [ 0 , 1 ] [0, 1] [0,1],因此需要额外调用 torch.sigmoid 计算二分类交叉熵。

使用 BCEWithLogitsLoss 类则不用额外调用 torch.sigmoid。计算公式为
l o s s = − ( y log ⁡ σ ( y ^ ) + ( 1 − y ) log ⁡ ( 1 − σ ( y ^ ) ) ) loss = -(y \log{\sigma(\hat{y})} + (1 - y) \log{(1 - \sigma(\hat{y}))}) loss=−(ylogσ(y^​)+(1−y)log(1−σ(y^​)))

import torch
from torch.nn import BCEWithLogitsLoss

# create data
inputs = torch.tensor([
    [1, 3],
    [4, 2]
], dtype=torch.float)
target = torch.tensor([
    [1, 0],
    [1, 0]
], dtype=torch.float)

bce_with_logits_loss = BCEWithLogitsLoss(
    weight=None,
    reduction='none',
    pos_weight=None  # 正样本的权重
)
print(bce_with_logits_loss(inputs, target))
# tensor([[0.3133, 3.0486],
#         [0.0181, 2.1269]])

6. CrossEntropyLoss

CrossEntropyLoss 类,将 LogSoftmax 和 NLLLoss 结合,计算交叉熵损失。可以参考这篇博文 Pytorch详解NLLLoss和CrossEntropyLoss。

import torch
from torch.nn import CrossEntropyLoss

# create data
inputs = torch.tensor([
    [1, 2],
    [1, 3],
    [1, 3]
], dtype=torch.float)
target = torch.tensor([0, 1, 1], dtype=torch.long)

cross_entropy_loss = CrossEntropyLoss(
    weight=None,  # 为各类别的损失设置权重
    ignore_index=-1,  # 忽略某个类别
    reduction='none'
)
print(cross_entropy_loss(inputs, target))
# tensor([1.3133, 0.1269, 0.1269])

传入 weight 参数

import torch
from torch.nn import CrossEntropyLoss

# create data
inputs = torch.tensor([
    [1, 2],
    [1, 3],
    [1, 3]
], dtype=torch.float)
target = torch.tensor([0, 1, 1], dtype=torch.long)

# 设置 weight,如下表示:表示标签为 0 的样本权重为 1,标签为 1 的权重为 2
weight = torch.tensor([1, 2], dtype=torch.float)
cross_entropy_loss = CrossEntropyLoss(weight, reduction='none')
print(cross_entropy_loss(inputs, target))
# tensor([1.3133, 0.2539, 0.2539]) 

7. NLLLoss

NLLLoss 类,取出真实标签对应的预测分数,并取相反数

import torch
from torch.nn import NLLLoss

# create data
inputs = torch.tensor([
    [1, 2],
    [1, 3],
    [1, 3]
], dtype=torch.float)
target = torch.tensor([0, 1, 1], dtype=torch.long)

nll = NLLLoss(
    weight=None,
    ignore_index=-1,
    reduction='none'
)
print(nll(inputs, target))
# tensor([-1., -3., -3.])

8. PoisonNLLLoss

PoisonNLLLoss 类,对于泊松分布目标的负对数似然损失,计算公式

若参数 log_input 为 True,则 l o s s = e y ^ − y × y ^ loss = e^{\hat{y}} - y \times \hat{y} loss=ey^​−y×y^​

若参数 log_input 为 False,则 l o s s = y ^ − y × log ⁡ ( y ^ + e p s ) loss = \hat{y} - y \times \log{(\hat{y} + eps)} loss=y^​−y×log(y^​+eps)

import torch
from torch.nn import PoissonNLLLoss

# create data
inputs = torch.tensor([
    [0.3, 0.7],
    [0.6, 0.4]
], dtype=torch.float)
target = torch.tensor([
    [1, 0],
    [1, 0]
], dtype=torch.long)

poison_nll_loss = PoissonNLLLoss(
    log_input=True,  # 指示是否输入的预测值已取了对数
    full=False,  # 计算所有 loss,默认为 False
    eps=1e-8,  # 修正项,避免 log_input=False 时对 0 取对数
    reduction='none'
)

print(poison_nll_loss(inputs, target))
# tensor([[1.0499, 2.0138],
#         [1.2221, 1.4918]])

9. KLDivLoss

KLDivLoss 类,计算 KL 散度(KL Divergence),即相对熵

相对熵的理论公式为
D K L ( P ∣ Q ) = E x ∼ p [ P ( x ) Q ( x ) ] = E x ∼ p [ log ⁡ P ( x ) − log ⁡ Q ( x ) ] D_{KL}(P|Q) = E_{x \sim p} [\frac{P(x)}{Q(x)}] = E_{x \sim p} [\log{P(x)} - \log{Q(x)}] DKL​(P∣Q)=Ex∼p​[Q(x)P(x)​]=Ex∼p​[logP(x)−logQ(x)]

但 PyTorch 中的计算为
l o s s = y ( log ⁡ y − y ^ ) loss = y (\log{y} - \hat{y}) loss=y(logy−y^​)

意味着,在输入 y ^ \hat{y} y^​ 之前要先计算其 log-probability,可以使用 LogSoftmax 实现

import torch
from torch.nn import KLDivLoss, LogSoftmax

# create data
inputs = torch.tensor([
    [0.5, 0.3, 0.2],
    [0.2, 0.3, 0.5]
])
target = torch.tensor([
    [0.9, 0.05, 0.05],
    [0.1, 0.7, 0.2]
])

# log-probability
inputs = LogSoftmax(dim=1)(inputs)

# reduction 还可以传入 'batchmean',之后版本的 reduction='mean' 的效果将变为与 reduction='batchmean' 相同
kl_div_loss = KLDivLoss(reduction='none')

print(kl_div_loss(inputs, target))
# tensor([[ 0.7510, -0.0928, -0.0878],
#         [-0.1063,  0.5482, -0.1339]])

10. MarginRankingLoss

MarginRankingLoss 类,描述两个向量之间的相似度,常用于排序任务

计算公式: l o s s = m a x { 0 , − y × ( y 1 ^ − y 2 ^ ) + m a r g i n ) } loss = max\{0, -y \times (\hat{y_1} - \hat{y_2}) + margin)\} loss=max{0,−y×(y1​^​−y2​^​)+margin)}

import torch
from torch.nn import MarginRankingLoss

# create data
y1 = torch.tensor([
    [1],
    [2],
    [3]
], dtype=torch.float)
y2 = torch.tensor([
    [2],
    [2],
    [2]
], dtype=torch.float)
y_true = torch.tensor([1, 1, -1], dtype=torch.float)

margin_ranking_loss = MarginRankingLoss(
    margin=0.0,  # 边界值,\hat{y_1} 和 \hat{y_2} 之间的差异值
    reduction='none'
)

# 返回一个 n x n 的 loss 矩阵,
# 第一行表示 y1 中的第一个元素和 y2 中的每一个元素计算的结果,
# 第二行表示 y1 中的第二个元素和 y2 中的每一个元素计算的结果,以此类推。
print(margin_ranking_loss(y1, y2, y_true))
# tensor([[1., 1., 0.],
#         [0., 0., 0.],
#         [0., 0., 1.]])

11. HingeEmbeddingLoss

HingeEmbeddingLoss 类,计算预测与真实之间的相似性,常用于非线性 embedding 和半监督学习。

计算公式:
l o s s = { y ^                          , i f    y = 1 m a x { 0 , Δ − y ^ }    , i f    y = − 1 loss = \begin{cases} \hat{y} \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ , if \ \ y = 1 \\ max\{ 0, \Delta - \hat{y} \} \ \ , if \ \ y = -1 \end{cases} loss={y^​                        ,if  y=1max{0,Δ−y^​}  ,if  y=−1​

import torch
from torch.nn import HingeEmbeddingLoss

# create data
# 输入 inputs 应为两个预测之差的绝对值
inputs = torch.tensor([[1., .8, .5]])
target = torch.tensor([[1, 1, -1]])

hinge_embedding_loss = HingeEmbeddingLoss(margin=1.0, reduction='none')
print(hinge_embedding_loss(inputs, target))
# tensor([[1.0000, 0.8000, 0.5000]])

12. MultiLabelMarginLoss

MultiLabelMarginLoss 类,多标签边界损失。计算公式为
l o s s = ∑ i j m a x { 0 , 1 − ( x [ y [ j ] ] − x [ i ] ) } x.size ( 0 ) loss = \sum_{ij} \frac{max\{ 0, 1 - (x[y[j]] - x[i]) \}}{\text{x.size}(0)} loss=ij∑​x.size(0)max{0,1−(x[y[j]]−x[i])}​
where i = 0 i = 0 i=0 to x.size ( 0 ) − 1 \text{x.size}(0)-1 x.size(0)−1, j = 0 j = 0 j=0 to y.size ( 0 ) − 1 \text{y.size}(0)-1 y.size(0)−1, 0 ≤ y [ j ] ≥ x.size ( 0 ) − 1 0 \leq y[j] \geq \text{x.size}(0)-1 0≤y[j]≥x.size(0)−1, and i ≠ y [ j ] i \not= y[j] i​=y[j] for all i i i and j j j.

import torch
from torch.nn import MultiLabelMarginLoss

# create data
inputs = torch.tensor([[0.1, 0.2, 0.4, 0.8]])
target = torch.tensor([[0, 3, -1, -1]], dtype=torch.long)

multi_label_margin_loss = MultiLabelMarginLoss(reduction='none')
print(multi_label_margin_loss(inputs, target))
# tensor([0.8500])

手动计算

import torch

# create data
inputs = torch.tensor([[0.1, 0.2, 0.4, 0.8]])
target = torch.tensor([[0, 3, -1, -1]], dtype=torch.long)

input_ = inputs[0]
item1 = (1 - (input_[0] - input_[1])) + (1 - (input_[0] - input_[2]))
item2 = (1 - (input_[3] - input_[1])) + (1 - (input_[3] - input_[2]))

print((item1 + item2) / input_.size(0))
# tensor([0.8500])

13. SoftMarginLoss

SoftMarginLoss 类,二分类 logistic 损失函数,计算公式
l o s s = log ⁡ ( 1 + e ( − y × y ^ ) ) loss = \log{(1 + e^{(-y \times \hat{y})})} loss=log(1+e(−y×y^​))

import torch
from torch.nn import SoftMarginLoss

# create data
inputs = torch.tensor([
    [0.3, 0.7],
    [0.5, 0.5]
])
target = torch.tensor([
    [-1, 1],
    [1, -1]
], dtype=torch.float)

soft_margin_loss = SoftMarginLoss(reduction='none')
print(soft_margin_loss(inputs, target))
# tensor([[0.8544, 0.4032],
#         [0.4741, 0.9741]])

14. MultiLabelSoftMarginLoss

MultiLabelSoftMarginLoss 类,SoftMarginLoss 的多标签版本,计算公式
l o s s = − 1 C ∑ i [ y i log ⁡ ( 1 1 + e − y i ^ ) + ( 1 − y i ) log ⁡ ( e − y i ^ 1 + e − y i ^ ) ] loss = -\frac{1}{C} \sum_i \left[ y_i \log{(\frac{1}{1 + e^{-\hat{y_i}}})} + (1 - y_i) \log{(\frac{e^{-\hat{y_i}}}{1 + e^{-\hat{y_i}}})} \right] loss=−C1​i∑​[yi​log(1+e−yi​^​1​)+(1−yi​)log(1+e−yi​^​e−yi​^​​)]
其中, C C C 为标签数, y i y_i yi​ 表示某一个标签的真实值, y i ^ \hat{y_i} yi​^​ 表示某一个标签的预测值。

import torch
from torch.nn import MultiLabelSoftMarginLoss

# create data
inputs = torch.tensor([[0.3, 0.7, 0.8]])
target = torch.tensor([[0, 1, 1]], dtype=torch.float)

multi_label_soft_margin_loss = MultiLabelSoftMarginLoss(weight=None, reduction='none')
print(multi_label_soft_margin_loss(inputs, target))
# tensor([0.5429])

手动计算

import torch

# create data
inputs = torch.tensor([[0.3, 0.7, 0.8]])
target = torch.tensor([[0, 1, 1]], dtype=torch.float)

C = 3
i_0 = torch.log(torch.exp(-inputs[0][0]) / (1 + torch.exp(-inputs[0][0])))
i_1 = torch.log(1 / (1 + torch.exp(-inputs[0][1])))
i_2 = torch.log(1 / (1 + torch.exp(-inputs[0][2])))
res = -(1 / C) * (i_0 + i_1 + i_2)
print(res)
# tensor([0.5429])

15. CosineEmbeddingLoss

CosineEmbeddingLoss 类,采用余弦相似度计算两个输入的相似性,常用于非线性 embedding 和半监督学习。计算公式
l o s s = { 1 − cos ⁡ ( x 1 , x 2 )                            , i f    y = 1 m a x { 0 , cos ⁡ ( x 1 , x 2 ) − m a r g i n }    , i f    y = − 1 loss = \begin{cases} 1 - \cos{(x_1, x_2)} \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ , if \ \ y = 1 \\ max\{ 0, \cos{(x_1, x_2)} - margin \} \ \ , if \ \ y = -1 \end{cases} loss={1−cos(x1​,x2​)                          ,if  y=1max{0,cos(x1​,x2​)−margin}  ,if  y=−1​

import torch
from torch.nn import CosineEmbeddingLoss

# create data
inputs1 = torch.tensor([
    [.3, .5, .7],
    [.3, .5, .7]
])
inputs2 = torch.tensor([
    [.1, .3, .5],
    [.1, .3, .5]
])
target = torch.tensor([1, -1], dtype=torch.float)

cosine_embedding_loss = CosineEmbeddingLoss(
    margin=0.0,  # 边界值,可取值范围为 [-1, 1],推荐 [0, 0.5]
    reduction='none'
)
print(cosine_embedding_loss(inputs1, inputs2, target))
# tensor([0.0167, 0.9833])

手动计算

import torch
from torch.nn import CosineEmbeddingLoss

# create data
inputs1 = torch.tensor([
    [.3, .5, .7],
    [.3, .5, .7]
])
inputs2 = torch.tensor([
    [.1, .3, .5],
    [.1, .3, .5]
])
target = torch.tensor([1, -1], dtype=torch.float)


def cosine(a, b):
    numerator = a @ b
    denominator = torch.norm(a, 2) * torch.norm(b, 2)
    return numerator / denominator


res_y_pos = 1 - cosine(inputs1[0], inputs2[0])  # y = 1
res_y_neg = max(0, cosine(inputs1[1], inputs2[1]))  # y = -1
print(res_y_pos, res_y_neg)
# tensor(0.0167) tensor(0.9833)

16. MultiMarginLoss

MultiMarginLoss 类,计算多分类任务的合页损失,计算公式
l o s s = 1 C ∑ i ( m a x { 0 , m a r g i n − x [ y ] + x [ i ] } ) p loss = \frac{1}{C} \sum_i (max\{ 0, margin - x[y] + x[i] \})^p loss=C1​i∑​(max{0,margin−x[y]+x[i]})p
其中, C C C 为多分类的类别数

import torch
from torch.nn import MultiMarginLoss

# create data
inputs = torch.tensor([
    [0.1, 0.2, 0.7],
    [0.2, 0.5, 0.3]
])
target = torch.tensor([1, 2], dtype=torch.long)

multi_margin_loss = MultiMarginLoss(
    p=1,  # 指数部分的值,可传入 1 或 2
    margin=1.0,  # 边界值
    weight=None,  # 各类别损失的权重
    reduction='none'
)
print(multi_margin_loss(inputs, target))
# tensor([0.8000, 0.7000])

手动计算

import torch

# create data
inputs = torch.tensor([
    [0.1, 0.2, 0.7],
    [0.2, 0.5, 0.3]
])
target = torch.tensor([1, 2], dtype=torch.long)

# 对于第一个样本实例
inputs_ = inputs[0]
margin = 1

i_0 = margin - (inputs_[1] - inputs_[0])  # > 0
i_2 = margin - (inputs_[1] - inputs_[2])  # > 0
res = (i_0 + i_2) / inputs_.size(0)
print(res)
# tensor(0.8000)

17. TripletMarginLoss

TripletMarginLoss 类,计算三元组损失,常用于人脸识别。计算公式
L ( a , p , n ) = m a x { d ( a i , p i ) − d ( a i , n i ) + m a r g i n , 0 } L(a, p, n) = max\{ d(a_i, p_i) - d(a_i, n_i) + margin, 0 \} L(a,p,n)=max{d(ai​,pi​)−d(ai​,ni​)+margin,0}
其中, d ( x , y ) = ∣ ∣ x − y ∣ ∣ p d(x, y) = ||x - y||_p d(x,y)=∣∣x−y∣∣p​

在这里插入代码片import torch
from torch.nn import TripletMarginLoss

# create data
anchor = torch.tensor([[1.]])
pos = torch.tensor([[2.]])
neg = torch.tensor([[0.5]])

triplet_margin_loss = TripletMarginLoss(
    margin=1.0,  # 边界值
    p=2.0,  # 范数的阶,默认为 2
    eps=1e-06,
    swap=False,
    reduction='none'
)
print(triplet_margin_loss(anchor, pos, neg))
# tensor([1.5000])

手动计算

(1. - 2.)**2 - np.sqrt((1. - .5)**2) + 1  # 1.5

18. CTCLoss

计算 CTC (Connectionist Temporal Classificatoin) 损失,用于时序类数据的分类问题。

from torch.nn import CTCLoss

CTCLoss(
    blank=0, # blank label
    reduction='mean',
    zero_infinity=False # 无穷大的值或梯度置零
)

时序建模方面有待进一步了解…

pytorch学习笔记十一:损失函数 一、损失函数是什么 损失函数:衡量模型输出与真实标签之间的差异。与损失函数有关的还有代价函数和目标函数。 损失函数(Loss Function):计算一个样本的差异,Loss=f(y^,y)Loss=f\left ( \hat{y},y \right )Loss=f(y^​,y) 代价函数(Cost Function):计算整个训练集loss的一个平均值,cost=1N∑iNf(y^,y)cos t= \frac{1}{N}\sum_{i}^{N}f\left ( \hat{y},y \right )co 阅读详情

相关推荐

【损失函数】【pytorch】损失函数与pytorch,详细解释

在 PyTorch 中,你也可以创建自定义的损失函数。通常,你需要继承。

wq6qeg88的博客 733

Pytorch中Softmax和LogSoftmax的使用

目录 一、函数解释 二、代码示例 三、整体代码 一、函数解释 1.Softmax函数常用的用法是指定参数dim就可以: (1)dim=0:对每一列的所有元素进行softmax运算,并使得每一列所有元素和为1。 (2)dim=1:对每一行的所有元素进行softmax运算,并使得每一行所有元素和为1。 class Softmax(Module): r"""Applies th...

黄笳倞的博客 1万+

pytorch 如何自定义损失函数

我是大佬们的搬运工 在做神经网络的时候,一般情况我们可以直接调用pytorch提供的函数损失函数,例如: class torch.nn.MSELoss(size_average=True) 调用方式: creterion=torch.nn.MSELoss() loss=creterion(x,y) 想要自定义损失函数,就要按照损失函数的格式来编写 观察自带的损失函数...

qq_24407657的博客 6062

pycharm 如何画损失函数

学习如何自己画损失函数

qq_43661900的博客 997

unity 在透明物体上投射阴影

unity版本:2019.4.16 创建一个shader,代码如下: Shader "ChuckLee/ARShadow" { Properties { _ShadowColor("Shadow Color", Color) = (0.1, 0.1, 0.1, 0.53) } SubShader { Tags{ "RenderType" = "Transparent" "Queue" = "Geometry+1" } Blend SrcAlpha OneMinusSrcAlph

Abel02的博客 2953

音频降采样系数

如果需要把8K, 16K, 32K, 48K采样率的音频数据降为4K的音频数据, 最简单的方法根据降频倍数来取点, 但是线性度不好. 另一种线性度好一点的方法是: 取适当个数的点数, 各点乘以各自点的系数, 然后相加取平均值. 降频倍数与系数的关系如下: 2倍:     {0.3, 0.4, 0.3} 4倍:    {0.15, 0.2, 0.3, 0.2, 0.15} 8倍:   {0

joans123的专栏 4645

Loss损失函数

本博客记录一下遇到的各种损失,如想了解各种损失及其代码,也可查看mmdet项目的loss部分 适用于多分类任务,交叉熵属于分类损失中常见的一种损失,-ylogP取平均,概率P为1时,损失为0。在bert的mlm预训练任务中使用了ignore_index入参,可仅根据部分位置(15%mask处)计算损失。在实际计算时,标签转为one-hot,y=0的位置-ylogP为0,不参与损失计算,可参考如下链接中的红色示例交叉熵损失和二元交叉熵损失_飞机火车巴雷特的博客-优快云博客_交叉熵损失计算过程为:

北落师门XY的博客 3567

Android应用开发从零到一:基于Kotlin与Jetpack Compose的完整实践指南

移动应用开发的核心在于构建一个架构清晰、可维护且可扩展的应用基础。理解应用架构的原理,如关注点分离和数据驱动UI,是实现高质量应用的关键技术价值。在现代Android开发中,Kotlin语言凭借其空安全特性和协程,能有效提升代码的健壮性与开发效率。Jetpack Compose作为声明式UI框架,代表了UI开发的未来方向,与Kotlin协程深度集成,简化了复杂交互界面的构建。这些技术共同服务于个人任务管理、企业工具等多种应用场景。本文以构建一个完整的个人任务管理应用为例,系统阐述从环境搭建、UI构建、数据持

weixin_32667955的博客 313

Pytorch nn.CosineEmbeddingLoss() 学习

cosine损失 1. 余弦相似度的计算 pytorch存在一个计算两个向量的余弦相似度的方法,torch.cosine_similarity 输入:(N,D)(N, D)(N,D)和(N,D)(N, D)(N,D),返回(N)(N)(N)。 2. cosine损失的计算 Pytorch自带的Loss为:CosineEmbeddingLoss 公式: 详情见官方文档 3.代码实现 这里用两种不同的方式实现了cosine loss的功能。 import torch import torch.nn as nn

weixin_44385551的博客 1万+

别慌!Oracle MOS登录页面大变样?5分钟搞定新旧账号登录全流程

本文详细解析Oracle MOS登录页面改版后的新旧账号登录流程,帮助用户快速适应账号体系变革。针对传统MOS账号和OCI账号的不同应用场景,提供5分钟内完成无缝切换的实用指南,包括登录步骤、书签设置和密码管理策略,助力数据库管理用户高效访问Oracle技术支持资源。

weixin_30275415的博客 514

数据科学常见模型总结(二)-倾向性得分匹配模型

PSM的核心思想是从未受干预的用户群体中,找到和干预对象一模一样的用户,这样就可以把因果效应归因到干预上。

wudelong0112的专栏 4888

PyTorch教程(1)张量以及张量操作

PyTorch有各种组件: Torch有与NumPy类似的功能,但是支持GPU。 torch.autograd提供了用于实现任意标量值函数的自动微分的类、方法和函数。它只需要对现有代码进行最小的更改。你只需要声明class:‘Tensor’,它的梯度应该用requires_grad=True关键字计算。 NN是PyTorch中的一个神经网络库 Optim提供用于函数最小化和最大化的优化算法。 Multiprocessing是一个用于在多个张量之间共享内存的有用库。 Utils有加载数据的实用函数;它还有其

weixin_43229348的博客 2395

保姆级教程:在ROS Noetic下,手把手教你将自定义A*全局规划器打包成插件(附避坑指南)

本文提供了一份详细的ROS Noetic下自定义A*全局规划器插件开发指南,涵盖从环境准备、算法优化到插件配置与调试的全流程。通过实战案例和避坑技巧,帮助开发者高效实现机器人导航中的全局路径规划,特别适合需要优化ROS导航栈的开发者。

weixin_29168675的博客 284

pytorch如何定义损失函数,如何定义优化器,如何反向传播,如何更新梯度。pytorch如何用GPU运行程序。GPU如何用部分网络训练好的参数=PyTorch学习笔记(四)

数据: 通常来说,先要将数据用python包来加载到numpy里面,再转换成torch.tensor。 对于图像-pliiow/opencv 对于声音-scipy/librosa 对于文本-用python加载就可以 torchvision:用于载入图像的包。 torchvision.datasets:图片转换包。 torch.utils.data.Dataloader:图像转换包。 ...

wacebb的博客 1203

高云FPGA系列教程(8):ARM串口数据接收(中断和轮询方式)

GW1NSR-4C ARM部分共有2个串口外设,都挂载在APB1总线上,最高支持波特率921.6Kbit/s,无奇偶校验位,8位数据位,1位停止位,支持高速测试模式 HSTM(High Speed Test Mode),即每个时钟周期输出1位数据,可以在短时间内传输大量数据。官方手册上没有描述发送和接收缓存FIFO的深度,所以不确定是否支持缓存。

whik1194的博客 1684

SMPLify-x-master | 复现记录

由于毕业设计中将会用到smpl模型,而smplify方法的各环境依赖版本比较老,复现不太容易,因此便进行了smplifyx方法使用smplx的方法。由于在过程中遇到较多坑,因此进行记录和分享。

qq_44916003的博客 5100

Pytorch学习之十九种损失函数

损失函数通过torch.nn包实现, 1 基本用法 criterion = LossCriterion() #构造函数有自己的参数 loss = criterion(x, y) #调用标准时也有参数 2 损失函数 2-1 L1范数损失 L1Loss torch.nn.L1Loss(size_average=True) 2-2 均方误差损失 MSELoss torch.nn.MSELoss(siz...

mingo_敏 7万+

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

PyTorch 学习笔记(六):PyTorch的十八个损失函数

本文截取自《PyTorch 模型训练实用教程》,获取全文pdf请点击:https://github.com/tensor-yu/PyTorch_Tutorial 文章目录1.L1loss2.MSELoss3.CrossEntropyLoss4.NLLLoss5.PoissonNLLLoss6.KLDivLoss7.BCELoss8.BCEWithLogitsLoss9.MarginRanking...

人工智能技术学习与分享 1万+

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

PyTorch 学习笔记(六):PyTorch的十七个损失函数

文章目录1. L1loss2.MSELoss3.CrossEntropyLoss5.PoissonNLLLoss6.KLDivLoss7.BCELoss8.BCEWithLogitsLoss9.MarginRankingLoss10.HingeEmbeddingLoss11.MultiLabelMarginLoss12.SmoothL1Loss13.SoftMarginLoss14.MultiLa...

公众号/知乎: AI算法札记,欢迎关注交流 4019

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

pytorch教程之损失函数详解——多种定义损失函数的方法

前言:前面的系列文章已经详细介绍了使用torch.nn.Module来实现自己定义的模型、自定义层,本文将继续来说明如何自定义损失函数,需要明确一个观点,不管是定义层还是损失函数,方法有很多,但是通过统一的接口nn.Module是最便于查看的,这也是pytorch的优点之一,模型、层、损失函数的定义具有统一性,都是通过Module类来完成,不像tensorflow那样不规范。具体可以参考前...

MIss-Y的博客 3万+

Pytorch 的损失函数Loss function

0 损失函数 损失函数,又叫目标函数,是编译一个神经网络模型必须的两个参数之一。另一个必不可少的参数是优化器。 损失函数是指用于计算标签值和预测值之间差异的函数,在机器学习过程中,有多种损失函数可供选择,典型的有距离向量,绝对值向量等。 我们先定义两个二维数组,然后用不同的损失函数计算其损失值。 import torch from torch.autograd import Variable im...

rosefun96的博客 2万+

pytorch 损失函数

计算出来的结果已经对mini-batch取了平均。一、损失函数列表创建一个衡量输入x模型预测输出)和目标y之间差的绝对值的平均值的标准。x和y可以是任意形状,每个包含n个元素。对n个元素对应的差值的绝对值求和,得出来的结果除以n。如果在创建L1Loss实例的时候在构造函数中传入,那么求出来的绝对值的和将不会除以n创建一个衡量输入x模型预测输出)和目标y之间均方误差标准。x和y可以是任意形状,每个包含n个元素。对n个元素对应的差值的绝对值求和,得出来的结果除以n。如果在创建MSELoss。

浩瀚之水的专栏 2059

Pytorch学习-损失函数和正则化

损失函数 说明 一般来说,监督学习的目标函数由损失函数和正则化项组成。(Objective = Loss + Regularization) Pytorch中的损失函数一般在训练模型时候指定。 注意Pytorch中内置的损失函数的参数和tensorflow不同,是y_pred在前,y_true在后,而Tensorflow是y_true在前,y_pred在后。 对于回归模型,通常使用的内置损失函数是均方损失函数nn.MSELoss 。 对于二分类模型,通常使用的是二元交叉熵损失函数nn.BCELoss (输入

Zzz_zhongqing的博客 1万+

PyTorch学习笔记 - 损失函数

只需实现 forward() 方法,无需手动编写反向传播(自动求导引擎处理)。自定义损失函数类实例化后直接调用即可计算损失值。在 PyTorch 中,torch.autograd.Function 是一个用于定义自定义自动求导操作的类。它允许用户实现自定义的前向传播forward 和反向传播 backward 逻辑。这对于实现非标准操作、自定义激活函数、或在某些特殊场景中替代现有 PyTorch 操作非常有用。torch.autograd.Function 实现自定义求导,需要实现forward。

2501_90669630的博客 989

Pytorch学习笔记(6):模型的权值初始化与损失函数

Pytorch学习笔记(6):模型的权值初始化与损失函数

路人贾的博客 4365

PyTorch自定义损失函数

PyTorch自定义损失函数 1. 直接使用tensor提供的function接口和python内建的方法 import torch import torch.nn as nn import torch.nn.functional as func class TripletLossFunc(nn.Module): def __init__(self, t1, t2, beta): super(TripletLossFunc, self).__init__() self

weixin_43424482的博客 6857
上一篇: PyTorch学习笔记(三)构建卷积神经网络模型
下一篇: PyTorch学习笔记(四)优化器
longrootchen
博客等级 码龄7年 19粉丝 29原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值