本文主要内容:
- 单层网络初始化
- 多层网络初始化
- 使用apply和weight_init函数
- 在
__init__
函数使用self.modules()
初始化
1.单层网络
- 在创建model后直接调用
torch.nn.innit
里的初始化函数
layer1 = torch.nn.Linear(10,20)
torch.nn.init.xavier_uniform_(layer1.weight)
torch.nn.init.constant_(layer1.bias, 0)
- 也可以重写
reset_parameters()
方法,并不推荐
2. 使用tf.Squential 或自定义多层网络
tf.Sequential() ,请查看pytorch系列7 -----nn.Sequential讲解
apply(fn)
: 看一下apply
在Module的实现。
将函数fn
递归的运用在每个子模块上,这些子模块由self.children()
返回.
关于self.children()和self.modules()的工作方式,请查看此篇博文pytorch系列8 --self.modules() 和 self.children()的区别
常被用来初始化网络层参数。注意fn需要一个参数。
具体步骤是:
- 定义weight_init函数,并在weight_init中通过判断模块的类型来进行不同的参数初始化定义类型。
- model=Net(…) 创建网络结构
- model.apply(weight_init),将weight_init初始化方式应用到submodels上
在以下的代码中只初始化线性层,至于卷积层,批归一化层后面会讲到的
示例:https://github.com/pytorch/examples/blob/master/dcgan/main.py#L95
# -*- coding: utf-8 -*-
import torch
from torch import nn
# hyper parameters
in_dim=1
n_hidden_1=1
n_hidden_2=1
out_dim=1
class Net(nn.Module):
def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim):
super(</