提示:2021.10.24.
文章目录- 前言
- pytorch,nn包的学习
- 一、两个基本结构:
- **Containers(容器):**
- add_module(name,module)
- 加入super(A, self).__init__()时调用A的父类Root的属性和方法
前言 pytorch,nn包的学习 一、两个基本结构:
1,parameter 参数
2,container 容器
第一个我不是很理解,我讲一下第二个吧
Containers(容器):Module(模型)
Modules也可以包括其他Modules,运行使用树结构来嵌入,可以将子模块给模型赋予属性,从下列看出,self.conv1 , self.conv2 是模型的子模型
import torch.nn as nn
import torch.nn.functional as F
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5)# submodule: Conv2d
self.conv2 = nn.Conv2d(20, 20, 5)
def forward(self, x):
x = F.relu(self.conv1(x))
return F.relu(self.conv2(x))
#super(MLP, self).__init__() 的含义:进行初始化
class MLP(nn.Module):
def __init__(self, num_layers, input_dim, hidden_dim, output_dim):
super(MLP, self).__init__()
#意思很简单:先找到MLP的父类(这里是类nn.Module),然后把类MLP的对象self转换为类nn.Module的对象,然后“被转换”的类nn.Module对象调用自己的_init_函数
add_module(name,module)
将子模块加入当前的模块中,被添加的模块可以name来获取
import torch.nn as nn
class Model(nn.Module): def __init__(self):
super(Model, self).__init__()
self.add_module("conv", nn.Conv2d(10, 20, 4))
#self.conv = nn.Conv2d(10, 20, 4) 和上面这个增加module的方式等价
>> model = Model()
>> print(model.conv)
# Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))
加入super(A, self).init()时调用A的父类Root的属性和方法
class Root(object):
def __init__(self):
self.x = '这是属性'
def fun(self):
print(self.x)
print('这是方法')
class A(Root): #继承上面root的类,所以他可以调用类root
def __init__(self):
super(A,self).__init__()
print('实例化时执行')
#下面这三行代码就是用来执行上面信息的,不要以为是没有用的哦
test = A() # 实例化类
test.fun() # 调用方法
test.x # 调用属性
# 输出结果:
实例化时执行
这是属性
这是方法



