我有一个问题,关于Pythorchnn.模块作品
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.sub_module = nn.Linear(10, 5)
self.value = 3
net = Net()
print(net.__dict__)
输出
^{pr2}$我知道类的每个属性都应该存储在中,为什么值(int值)在其中,但是子模块(ann.模块)相反,子模块不是存储在模块中的
我读了密码nn.模块实施,但我没想到。有人有什么想法吗?在
谢谢你!!在
我会尽量保持简单。在
每次在类
Net
中创建一个新项,例如:self.sub_module = nn.Linear(10, 5)
,它会调用其父类的方法__setattr__
,在本例中是nn.Module
。然后,在__setattr__
方法中,将参数存储到它们所属的dict中。在本例中,由于nn.Linear
是一个模块,因此它被存储到_modules
dict中下面是在
Module
类https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py#L389中执行此操作的代码段相关问题 更多 >
编程相关推荐