1、损失函数的作用:

(1)计算实际输出和目标输出之间的差距;

(2)为我们更新输出提供一定的依据(也就是反向传播)

官网链接:https://pytorch.org/docs/1.8.1/nn.html

2、损失函数的使用

2.1、L1Loss

注:reduction = “sum” 表示求和  /    reduction = "mean" 表示求平均值   默认求平均值

代码:

# file     : nn_lose.py
# time : 2022/8/2 上午10:31
# function : L1Loss
import torch
from torch.nn import L1Loss
from torch import nn inputs = torch.tensor([1, 2, 3], dtype=torch.float32)
targets = torch.tensor([1, 2, 5], dtype=torch.float32) # reshape()添加维度,原来tensor是二维
inputs = torch.reshape(inputs, (1, 1, 1, 3))
targets = torch.reshape(targets, (1, 1, 1, 3)) loss = L1Loss()
result = loss(inputs, targets)
print(result)

    上述代码计算了实际输出[1, 2, 3]和目标输出[1, 2, 5]之间的L1Loss,代码输出结果为:

tensor(0.6667)

2.2MSELoss 均方损失函数:可以设置reduction参数来决定具体的计算方法

代码:

# file     : nn_lose.py
# time : 2022/8/2 上午10:31
# function :
import torch
from torch.nn import L1Loss
from torch import nn inputs = torch.tensor([1, 2, 3], dtype=torch.float32)
targets = torch.tensor([1, 2, 5], dtype=torch.float32) # reshape
inputs = torch.reshape(inputs, (1, 1, 1, 3))
targets = torch.reshape(targets, (1, 1, 1, 3)) loss = L1Loss(reduction="sum")
result = loss(inputs, targets)
print(result) # MSELoss 均方损失函数
loss_mse = nn.MSELoss(reduction="sum")
result_mse = loss_mse(inputs, targets)
print(result_mse)
结果:
tensor(2.)
tensor(4.) #均方误差损失函数计算结果

2.3 CrossEntropyLoss交叉熵损失函数----没懂

交叉熵损失函数计算方法的细节可以参照这个博文:交叉熵损失函数。(看上去很牛)

代码:

# file     : nn_lose.py
# time : 2022/8/2 上午10:31
# function :
import torch
from torch.nn import L1Loss
from torch import nn inputs = torch.tensor([1, 2, 3], dtype=torch.float32)
targets = torch.tensor([1, 2, 5], dtype=torch.float32) # reshape
inputs = torch.reshape(inputs, (1, 1, 1, 3))
targets = torch.reshape(targets, (1, 1, 1, 3)) loss = L1Loss(reduction="sum")
result = loss(inputs, targets)
print(result) # MSELoss 均方损失函数
loss_mse = nn.MSELoss(reduction="sum")
result_mse = loss_mse(inputs, targets)
print(result_mse) # CrossEntropyLoss
x = torch.tensor([0.1, 0.2, 0.3])
y = torch.tensor([1])
x = torch.reshape(x, (1, 3))
loss_cross = nn.CrossEntropyLoss()
result_cross = loss_cross(x, y)
print(result_cross)
结果:
tensor(1.1019)

用了之前的一个简单神经网络,测试了损失函数及反向传播

# file     : nn_loss_network.py
# time : 2022/8/2 下午2:39
# function :
import torch
import torchvision.datasets
from torch import nn
from torch.nn import Conv2d, MaxPool2d, Flatten, Linear, Sequential
from torch.utils.data import DataLoader dataset = torchvision.datasets.CIFAR10("../dataset", train=False, transform=torchvision.transforms.ToTensor(), download=False)
dataloader = DataLoader(dataset, batch_size=1) class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.model1 = Sequential(
Conv2d(3, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 32, 5, padding=2),
MaxPool2d(2),
Conv2d(32, 64, 5, padding=2),
MaxPool2d(2),
Flatten(),
Linear(1024, 64),
Linear(64, 64)
) def forward(self, x):
x = self.model1(x)
return x loss = nn.CrossEntropyLoss()
tudui = Tudui()
for data in dataloader:
imgs, targets = data
outputs = tudui(imgs)
result_loss = loss(outputs, targets)
result_loss.backward()
print("ok")

pytorch学习笔记(9)--损失函数的更多相关文章

  1. [PyTorch 学习笔记] 4.2 损失函数

    本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson4/loss_function_1.py https:// ...

  2. 【pytorch】pytorch学习笔记(一)

    原文地址:https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html 什么是pytorch? pytorch是一个基于p ...

  3. Pytorch学习笔记(一)——简介

    一.Tensor Tensor是Pytorch中重要的数据结构,可以认为是一个高维数组.Tensor可以是一个标量.一维数组(向量).二维数组(矩阵)或者高维数组等.Tensor和numpy的ndar ...

  4. [PyTorch 学习笔记] 1.3 张量操作与线性回归

    本章代码:https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/linear_regression.py 张量的操作 拼 ...

  5. [PyTorch 学习笔记] 1.1 PyTorch 简介与安装

    PyTorch 的诞生 2017 年 1 月,FAIR(Facebook AI Research)发布了 PyTorch.PyTorch 是在 Torch 基础上用 python 语言重新打造的一款深 ...

  6. [PyTorch 学习笔记] 4.3 优化器

    本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson4/optimizer_methods.py https: ...

  7. Pytorch学习笔记(二)---- 神经网络搭建

    记录如何用Pytorch搭建LeNet-5,大体步骤包括:网络的搭建->前向传播->定义Loss和Optimizer->训练 # -*- coding: utf-8 -*- # Al ...

  8. Pytorch学习笔记(一)---- 基础语法

    书上内容太多太杂,看完容易忘记,特此记录方便日后查看,所有基础语法以代码形式呈现,代码和注释均来源与书本和案例的整理. # -*- coding: utf-8 -*- # All codes and ...

  9. 【深度学习】Pytorch 学习笔记

    目录 Pytorch Leture 05: Linear Rregression in the Pytorch Way Logistic Regression 逻辑回归 - 二分类 Lecture07 ...

  10. [PyTorch 学习笔记] 1.4 计算图与动态图机制

    本章代码:https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/computational_graph.py 计算图 深 ...

随机推荐

  1. Agilepoint中的JS Method 封装

    /**================================================================================================= ...

  2. springboot文件流下载

    1. 将文件以流的形式一次性读取到内存,通过响应输出流输出到前端 /** * @param path 想要下载的文件的路径 * @param response * @功能描述 下载文件: */ @Re ...

  3. chrome驱动版本与python不一致时

    图片: 解决办法: 1.先去chrome浏览器找到版本号:在chrome找到帮助-关于Google chrome 2.通过网址:https://npm.taobao.org/mirrors/chrom ...

  4. uwsgi部署flask,flask_apscheduler任务遇到各种问题解决

    背景:最近在做的全域事件项目,快要靠近尾声了,需要用到uwsgi部署至生产环境,由于之前是debug模式,运行项目也是通过命令 python manager.py runserver (manage是 ...

  5. C# 设置桌面为父窗口

    #region 设置桌面为父窗口 IntPtr hDesktop; public const int GW_CHILD = 5; public IntPtr GetDesktopHandle(Desk ...

  6. Linux 命令 diff

    比较两个文件不同 $ diff file1 file2 比较两个目录不同 $ diff --brief --recursive dir1/ dir2/ --brief 仅显示有无差异,不显示详细的信息 ...

  7. HIVE- set

    SET hive.execution.engine = tez;SET hive.tez.auto.reducer.parallelism = true;SET hive.auto.convert.j ...

  8. 在前端js worker里使用dom并且加载jquery

    四个工具: nodejs + npm npm安装的jsdom npm安装的jquery npm安装的browserify 网址: browserify: https://browserify.org/ ...

  9. python+ffmpeg,批量转换手机中的m3u8文件

    前段时间,有朋友找我帮忙,自述其手机上使用UC浏览器,缓存的电影有近千个,手机存储不够了,想把这些电影转存到PC机上,并且将其转换为Mp4文件.小事情,安排! 一.分析情况,确定方案. 首先连接手机, ...

  10. pyg安装

    pyg官网:pytorch_geometric documentation (pytorch-geometric.readthedocs.io) win安装pyg各种报错,原因在于pytorch和py ...