pytorch初学笔记(十四):损失函数

 目录

一、损失函数 

1.1 L1损失函数

1.1.1 简介

1.1.2 参数设定

1.1.3 代码实现

1.2 MSE损失函数(平方和)

1.2.1 简介

1.2.2 参数介绍

1.2.3 代码实现

1.3 损失函数的作用

二、在神经网络中使用loss function

2.1 使用交叉熵损失函数 

2.2 反向传播


一、损失函数 

torch.nn — PyTorch 1.13 documentation

每一个样本经过模型后会得到一个预测值,然后得到的预测值和真实值的差值就成为损失(当然损失值越小证明模型越是成功),我们知道有许多不同种类的损失函数,这些函数本质上就是计算预测值和真实值的差距的一类型函数,然后经过库(如pytorch,tensorflow等)的封装形成了有具体名字的函数。

1.1 L1损失函数

1.1.1 简介

L1损失函数: 基于逐像素比较差异,然后取绝对值。

在这里插入图片描述 

1.1.2 参数设定 

L1Loss — PyTorch 1.13 documentation

 CLASS torch.nn.L1Loss(size_average=Nonereduce=Nonereduction='mean')

 

我们一般设定reduction的值来显示平均值或者和。

 参数设定:

reduction可取的值: 'none' | 'mean' | 'sum'

  • 'none': no reduction will be applied
  •  'mean': the sum of the output will be divided by the number of elements in the output,求的是平均值,即各个差求和之后除以总数。

  •  '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'

1.1.3 代码实现

 设置reduction的值为默认值和sum,观察区别。

import torch
from torch.nn import L1Loss

inputs = torch.tensor([1,2,3],dtype=torch.float32)
targets = torch.tensor([1,2,5],dtype=torch.float32)

inputs = torch.reshape(inputs,(1,1,1,3))
targets = torch.reshape(targets,(1,1,1,3))

loss1 = L1Loss()
result1 = loss1(inputs,targets)
print(result1)

loss2 = L1Loss(reduction="sum")
result2 = loss2(inputs,targets)
print(result2)
  • 当取值为默认值mean时,求的是平均值,sum=(1-1+2-2+5-3)=2, n=3, result = sum/n=0.6667 
  • 当取值为sum时,求的是和,即result=2

 

1.2 MSE损失函数(平方和)

1.2.1 简介

均方误差(Mean Square Error,MSE)是回归损失函数中最常用的误差,它是预测值f(x)与目标值y之间差值平方和的均值,其公式如下所示:
在这里插入图片描述 

 

1.2.2 参数介绍

MSELoss — PyTorch 1.13 documentation

 

与上面的L1损失函数一样,我们可以改变reduction的值来进行对应数值的输出。

 

1.2.3 代码实现

import torch
from torch.nn import L1Loss, MSELoss

inputs = torch.tensor([1,2,3],dtype=torch.float32)
targets = torch.tensor([1,2,5],dtype=torch.float32)

inputs = torch.reshape(inputs,(1,1,1,3))
targets = torch.reshape(targets,(1,1,1,3))

loss_mse1 = MSELoss()
result1 = loss_mse1(inputs,targets)
print(result1)

loss_mse2 = MSELoss(reduction="sum")
result2 = loss_mse2(inputs,targets)
print(result2)

 可以看到reduction设置不同的值对应的输出也不同。

 

1.3 损失函数的作用

  1. 计算实际输出和目标之间的差距
  2. 为更新输出(反向传播)提供一定的依据

二、在神经网络中使用loss function

2.1 使用交叉熵损失函数 

使用上次定义的神经网络和CIFAR10数据集进行图像分类,分类问题使用交叉熵损失函数。

import torch.nn
from torch import nn
import torchvision.datasets
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10(root="./CIFAR10",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset,batch_size=1)

class Maweiyi(torch.nn.Module):
    def __init__(self):
        super(Maweiyi, self).__init__()
        self.model1 = Sequential(
            Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
            MaxPool2d(kernel_size=2),
            Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
            MaxPool2d(kernel_size=2),
            Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
            MaxPool2d(kernel_size=2),
            Flatten(),
            Linear(in_features=1024, out_features=64),
            Linear(in_features=64, out_features=10)
        )

    def forward(self, x):
         x = self.model1(x)
         return x

maweiyi = Maweiyi()
# 使用交叉熵损失函数
loss_cross = nn.CrossEntropyLoss()

for data in dataloader:
    imgs,labels = data
    outputs = maweiyi(imgs)
    results = loss_cross(outputs,labels)
    print(results)

可以看到使用loss function计算出了在神经网路中预测的output和真实值labels之间的差距大小。 

 

2.2 反向传播

results_loss.backward() 

  

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch中的MSE(Mean Square Error)是一种衡量预测值与真实值之间差异程度的指标。MSE可以用来评估模型的性能,特别是在回归问题中。MSE的公式为:MSE(x, y) = 1/n * sum((x_i - y_i)^2),其中x和y分别表示预测值和真实值,n表示样本数量。 在PyTorch中,可以使用torch.nn.MSELoss函数来计算MSE。该函数的参数包括size_average、reduce和reduction。其中,size_average决定是否对输出进行平均,reduce决定是否对输出进行求和,reduction决定如何进行归约操作。通常情况下,可以将这些参数设置为默认值。 下面是使用PyTorch计算MSE的示例代码: ```python import torch import torch.nn as nn # 创建预测值和真实值的张量 input = torch.randn(2, 5, requires_grad=True) # 预测值 target = torch.randn(2, 5) # 真实值 # 使用MSELoss计算MSE criterion = nn.MSELoss() loss = criterion(input, target) print('MSE:', loss.item()) ``` 在这个示例中,我们首先创建了一个形状为(2, 5)的预测值张量input和真实值张量target。然后,使用torch.nn.MSELoss()创建了一个MSE损失函数criterion。最后,使用criterion(input, target)计算了预测值和真实值之间的MSE,并将结果打印出来。 总结起来,PyTorch中的MSE是一种用于衡量预测值与真实值之间差异的指标,可以使用torch.nn.MSELoss函数进行计算。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [pytorch中的MSELoss函数](https://blog.csdn.net/weixin_41122036/article/details/103286751)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值