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. 禁止Edge升级

    管理员命令行运行: 用法:EdgeChromium_Blocker.cmd [<machine name>] [/B][/U][/H] 1.本机禁用更新: EdgeChromium_Blo ...

  2. ECDSA签名验证

    using System; using System.IO; using System.Text; using Org.BouncyCastle.Crypto; using Org.BouncyCas ...

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

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

  4. B - Yet Another Palindrome Problem

    B - Yet Another Palindrome Problem 思路: 给一个长为n(≤5000≤5000)的数组,问是否存在一个长度至少为3的子序列是回文的.回文的定义是把序列reverse, ...

  5. Spring不同版本的AOP

    1.Spring4.SpringBoot1 1.1 代码实现 public interface Calculator { int div(int a,int b); } @Component publ ...

  6. shell脚本变量加减

    #! /bin/bash test_1=1 test_2=2 test = $(expr $test_1 - $test_2)  #减法 test = $(expr $test_1 + $test_2 ...

  7. this指向问题大全和call,apply,bind详解

    详细笔记链接:https://www.jianshu.com/p/bc541afad6ee 函数内外作用域问题: var a = 1function f1(){ var a = 2 console.l ...

  8. 在QAS里面,建立副本请求

  9. 全国IP段列表

    http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest Linux下执行如下命令可将中国大陆ip格式化并导出 wget -c htt ...

  10. 内容类型框架-ContentType 模型

    参考Django官方文档 ContentTypeManager¶ classContentTypeManager¶ ContentType 还有一个自定义管理器, ContentTypeManager ...