Pytorch之parameters net.parameters()

1.预构建网络

import torch
import matplotlib.pyplot as plt
import torch.nn.functional as F

#torch.unsqueeze,torch.squeeze,torch.linspace我的之前文章有讲解
#在torch中,只会处理2维的数据
x=torch.unsqueeze(torch.linspace(-1,1,100),dim=1)
#x.pow(2)的意思是x的平方
y=x.pow(2)+0.2*torch.rand(x.size())

class Net(torch.nn.Module):#继承torch的module
    def __init__(self,n_feature,n_hidden,n_output):
        super(Net,self).__init__() #继承__init__功能
        #定义每一层用什么样的样式
        self.hidden = torch.nn.Linear(n_feature,n_hidden) #隐藏层线性输出
        self.predict = torch.nn.Linear(n_hidden,n_output) #输出层线性输出
    def forward(self,x):
        # 激励函数(隐藏层的线性值)
        x=F.relu(self.hidden(x))
        x=self.predict(x) #输出值
        return x
   
net = Net(1,10,1)
print(net)

网络结构

Net(
  (hidden): Linear(in_features=1, out_features=10, bias=True)
  (predict): Linear(in_features=10, out_features=1, bias=True)
)

2.net.parameters()

print(net.parameters())

结果:

<generator object Module.parameters at 0x7ff10f745bd0>
para = list(net.parameters())
print(para)

结果:

[Parameter containing:
tensor([[-0.5081],
        [-0.2130],
        [-0.0958],
        [ 0.3794],
        [-0.4636],
        [-0.4734],
        [-0.8516],
        [ 0.3321],
        [ 0.3731],
        [ 0.5131]], requires_grad=True), Parameter containing:
tensor([ 0.7409, -0.2740, -0.0841,  0.2299,  0.4780, -0.5051,  0.4487, -0.2391,
         0.7307,  0.0095], requires_grad=True), Parameter containing:
tensor([[-0.1322, -0.0158,  0.2620,  0.0499,  0.3109,  0.1158, -0.1099, -0.0687,
         -0.1557,  0.1864]], requires_grad=True), Parameter containing:
tensor([0.1522], requires_grad=True)]

官方解释

class torch.nn.Parameter()

Variable的一种,常被用于模块参数(module parameter)。

Parameters 是 Variable 的子类。Paramenters和Modules一起使用的时候会有一些特殊的属性,即:当Paramenters赋值给Module的属性的时候,他会自动的被加到 Module的 参数列表中(即:会出现在 parameters() 迭代器中)。将Varibale赋值给Module属性则不会有这样的影响。 这样做的原因是:我们有时候会需要缓存一些临时的状态(state), 比如:模型中RNN的最后一个隐状态。如果没有Parameter这个类的话,那么这些临时变量也会注册成为模型变量。

Variable 与 Parameter的另一个不同之处在于,Parameter不能被 volatile(即:无法设置volatile=True)而且默认requires_grad=True。Variable默认requires_grad=False。

参数说明:

data (Tensor) – parameter tensor.

requires_grad (bool, optional) – 默认为True,在BP的过程中会对其求微分。

  • 13
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值