iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Pytorch查看tensor是否有梯度(值)以及开启梯度
  • 915
分享到

Pytorch查看tensor是否有梯度(值)以及开启梯度

pytorchpython深度学习 2023-09-21 16:09:20 915人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

文章目录 一. requires_grad 属性:查看是否记录梯度二. requires_grad_ ()函数:调用函数设置记录梯度与否三. requires_grad属性参数,创建tenso

文章目录

一. requires_grad 属性:查看是否记录梯度

x = torch.rand(3, 3)   # 直接创建的tensor变量默认是没有梯度的x.requires_grad

结果如下:

False

二. requires_grad_ ()函数:调用函数设置记录梯度与否

函数:requires_grad_(requires_grad=True)

x = torch.tensor([1., 2., 3.])print('x_base: ', x.requires_grad)   # 正常状态:Falsex.requires_grad_(False) #Falseprint('x.requires_grad_(False): ', x.requires_grad) #Falsex.requires_grad_(True)  # 等价:requires_grad_() #Trueprint('x.requires_grad_(True): ', x.requires_grad) #True

结果如下:

x_base:  Falsex.requires_grad_(False):  Falsex.requires_grad_(True):  True

三. requires_grad属性参数,创建tensor时设置是否记录梯度

x = torch.tensor([1., 2., 3.], requires_grad=True) #Trueprint('x_base: ', x.requires_grad)   # 正常状态

结果如下:

x_base:  True

四. 查看模型的权重名称和参数值

[name for name, param in model.named_parameters()] #查看模型的权重名称[param for name, param in model.named_parameters()] #查看模型的权重值

五. 查看模型权重梯度值

网络结构如下:
在这里插入图片描述

class Simple(nn.Module):    def __init__(self):        super().__init__()        self.conv1 = nn.Conv2d(3, 16, 3, 1, padding=1, bias=False)        self.conv2 = nn.Conv2d(16, 32, 3, 1, padding=1, bias=False)        self.linear = nn.Linear(32*10*10, 20, bias=False)     def forward(self, x):        x = self.conv1(x)        x = self.conv2(x)        x = self.linear(x.view(x.size(0), -1))        return x model = Simple()

查看模型权重梯度值:

print(model.conv1.weight.grad)

来源地址:https://blog.csdn.net/flyingluohaipeng/article/details/129192987

--结束END--

本文标题: Pytorch查看tensor是否有梯度(值)以及开启梯度

本文链接: https://www.lsjlt.com/news/414318.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作