温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

torch.nn.Parameter方法如何使用

发布时间:2021-08-05 17:46:50 来源:亿速云 阅读:205 作者:Leah 栏目:大数据

本篇文章给大家分享的是有关torch.nn.Parameter方法如何使用,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

torch.nn.Parameter方法如何使用
解释:

它是Tensor的一个子类,它可以被作为module的参数,把它赋值给module的属性,
那么会自动被添加到module的参数,也就是出现在parameters()迭代器中.
如果不使用Parameter类型,仅仅使用Tensor,
把Tensor类赋值给module的属性,不会有这种效果,
不会出现在parameter()迭代器中.

实验:

import torchimport torch.nn as nnclass Model4CXQ(nn.Module):def __init__(self):super(Model4CXQ, self).__init__()# super().__init__()self.attribute4cxq = nn.Parameter(torch.tensor(20200910.0))self.attribute4lzq = nn.Parameter(torch.tensor(20200.0))# self.attribute4scc = nn.Parameter(torch.Tensor(2.0))  # TypeError: new(): data must be a sequence (got float)# self.attribute4pq = nn.Parameter(torch.tensor(2))  # RuntimeError: Only Tensors of floating point dtype can require gradientsself.attribute4zh = nn.Parameter(torch.Tensor(2))# self.attribute4yzb = nn.Parameter(torch.tensor(912.0))self.attribute4yzb = (torch.tensor(912.0))self.attribute4gcx = (torch.tensor(3))self.attribute4ymw = (torch.Tensor(3))def forward(self, x):passif __name__ == "__main__":model = Model4CXQ()print()print("打印参数".center(50,'-'))for param in model.parameters():print(param)print()print("打印字典".center(50,'-'))for k, v in model.state_dict().items():print(k, v)

控制台输出:

Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。

尝试新的跨平台 PowerShell https://aka.ms/pscore6

加载个人及系统配置文件用了 861 毫秒。(base) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq> conda activate ssd4pytorch2_2_0(ssd4pytorch2_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>  & 'D:\Anaconda3\envs\ssd4pytorch2_2_0\python.exe' 'c:\Users\chenxuqi\.vscode\extensions\ms-python.python-2020.12.424452561\pythonFiles\lib\python\debugpy\launcher' '56980' '--' 'c:\Users\chenxuqi\Desktop\News4cxq\test4cxq\test8.py'-----------------------打印参数-----------------------Parameter containing:
tensor(20200910., requires_grad=True)Parameter containing:
tensor(20200., requires_grad=True)Parameter containing:
tensor([1.1673e-42, 0.0000e+00], requires_grad=True)-----------------------打印字典-----------------------attribute4cxq tensor(20200910.)attribute4lzq tensor(20200.)attribute4zh tensor([1.1673e-42, 0.0000e+00])(ssd4pytorch2_2_0) PS C:\Users\chenxuqi\Desktop\News4cxq\test4cxq>

以上就是torch.nn.Parameter方法如何使用,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI