pytorch学习笔记(9)--损失函数
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)--损失函数的更多相关文章
- [PyTorch 学习笔记] 4.2 损失函数
本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson4/loss_function_1.py https:// ...
- 【pytorch】pytorch学习笔记(一)
原文地址:https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html 什么是pytorch? pytorch是一个基于p ...
- Pytorch学习笔记(一)——简介
一.Tensor Tensor是Pytorch中重要的数据结构,可以认为是一个高维数组.Tensor可以是一个标量.一维数组(向量).二维数组(矩阵)或者高维数组等.Tensor和numpy的ndar ...
- [PyTorch 学习笔记] 1.3 张量操作与线性回归
本章代码:https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/linear_regression.py 张量的操作 拼 ...
- [PyTorch 学习笔记] 1.1 PyTorch 简介与安装
PyTorch 的诞生 2017 年 1 月,FAIR(Facebook AI Research)发布了 PyTorch.PyTorch 是在 Torch 基础上用 python 语言重新打造的一款深 ...
- [PyTorch 学习笔记] 4.3 优化器
本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson4/optimizer_methods.py https: ...
- Pytorch学习笔记(二)---- 神经网络搭建
记录如何用Pytorch搭建LeNet-5,大体步骤包括:网络的搭建->前向传播->定义Loss和Optimizer->训练 # -*- coding: utf-8 -*- # Al ...
- Pytorch学习笔记(一)---- 基础语法
书上内容太多太杂,看完容易忘记,特此记录方便日后查看,所有基础语法以代码形式呈现,代码和注释均来源与书本和案例的整理. # -*- coding: utf-8 -*- # All codes and ...
- 【深度学习】Pytorch 学习笔记
目录 Pytorch Leture 05: Linear Rregression in the Pytorch Way Logistic Regression 逻辑回归 - 二分类 Lecture07 ...
- [PyTorch 学习笔记] 1.4 计算图与动态图机制
本章代码:https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/computational_graph.py 计算图 深 ...
随机推荐
- elementUI合并单元格
<el-table :data="tableDataFormat" border :header-cell-style="{background:'#FAFAFA' ...
- 通过ESP8266WiFi模块调用“心知天气”接口 获取天气信息
在分析代码之前,首先介绍 ArduinoJson 库的安装及"心知天气"的ID申请 一.安装 ArduinoJson 库 进入 Arduino 开发环境后,选择菜单栏-->工 ...
- win系统airtest+pytest-xdist服务器分布式运行。
1.准备至少两台服务器,集群全部是局域网,(启动脚本的时候可以使用外网ip). 2.输出的报告地址,需要把文件夹设置成共享文件夹,(连接的时候使用内外ip). 启动脚本文件 import os, da ...
- QT-groupBox组件内的组件失去交互功能
属性设置: 首先 然后 可以实现.
- [Swift] 在 OC 工程中,创建和使用 Swift
1.我们创建了一个 Objective-C 的工程,叫做 playGround. 2.首先,我们需要在 工程的 Build Settings,找到 如中所示的项目,并将 Defines Module ...
- BLOG-2
前言 这几次的PTA作业和考试涉及到的知识点有面向对象中对数据的封装,还有继承和多态,还有抽象类和对象容器 也涉及到了一些,同时还有关于正则表达式的一些内容.而关于题量,这应该对于一个初学者来说是一个 ...
- 当前我对Visual Grounding的看法
3D Visual Grounding 在看到相关论文的时候,我有一种非常严重的直觉--我的博士课题大概就是做这个了,虽然还没找老师聊. 简要解释:在这个任务中,研究者的主要目标是探索如何利用图像和自 ...
- android判断是否连接wifi跟网络状态的判断及wifi信号强度的方法
场景:android判断是否连接wifi跟网络状态的判断 android判断是否连接wifi和网络状态的判断 // 是否连接WIFI public static boolean isWifiConne ...
- go开发框架推荐
根据自己了解的情况,从易用性和文档完善程度来说,推荐优先考虑使用如下框架: fiber revel echo iris gin beego 以revel作为入门教程,在go项目的根文件夹里执行下面2条 ...
- Spring不同版本的AOP
1.Spring4.SpringBoot1 1.1 代码实现 public interface Calculator { int div(int a,int b); } @Component publ ...