1 结构组件
层(自定义)
class MyLInear(nn.Module):
def __init__(self,in_units,units):
super().__init__()
self.weight=nn.Parameter(torch.randn(in_units,units))
self.bias=nn.Parameter(torch.randn(units,))
sef forward(self,X):
linear=torch.matmul(X,self.weight.data)+self.bias.data
return F.relu(linear)
块
import torch
from torch import nn
from torch.nn import functional as F
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.hidden=nn.Linear(20,256)
self.out=nn.Linear(256,10)
def forward(self,X):
return self.out(F.relu(self.hidden(X)))
层组成块
以上自定义块可以进行更多功能实现
区别nn.Relu()与F.relu(...)
定义__init__()通过super().__init__()调用父类的__init__()
nn.Linear(),nn.ReLu()均为块
块列表
net=nn.Sequential(nn.Linear(),nn.ReLU(),nn.Linear())
2参数
2.1 参数的访问
对于Sequential定义的模型
检查第一个全连接层参数 net[1].state_dict()
访问目标参数 net[2].bias net[2].bias.data net[2].weight.grad
net.state_dict()['2.bias'].data
访问所有参数 *[(name,param) for name,param in net.named_parameters()]
输出: ('0.weight',torch.Size([8,4])) ('0.bias',....)('2.weight',....)
注意嵌套块的访问:net[0][1][0].bias.data
2.2 参数的初始化
内置初始化nn.init()的使用:
def init_normal(m):
if type(m)==nn.Linear:
nn.init.normal_(m.weight,mean=0,std=0.01)
nn.init.zeros_(bias)
#也可尝试以下
nn.init.constant_(m.weight,1)
net.apply(init_normal)
#不同层不同初始化方法
def init_xavier(m):
if type(m)==nn.Linear:
nn.init.xavier_uniform_(m.weight)
net[1].apply(init_xavier)
当输入维数未知时,采取延迟初始化(?)
2.3 参数绑定
shared=nn.Linear(8,8)
net=nn.Sequential(nn.LInear(4,8),nn.ReLU(),
shared,nn.ReLU(),
shared,nn.ReLU())
net[2]与net[4]参数绑定