博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网络的权重初始化示例
阅读量:1873 次
发布时间:2019-04-26

本文共 2135 字,大约阅读时间需要 7 分钟。

1.比较常用的就是对每一个类型的网络层进行初始化,并且作为一个函数定义在网络中。具体的初始化,按照先实例化网络再调用初始化函数来达成初始化操作。

def _load_pretrained_model(self):  # 加载预训练模型参数        pretrain_dict = model_zoo.load_url('https://download.pytorch.org/models/resnet101-5d3b4d8f.pth')        model_dict = {}        state_dict = self.state_dict()        for k, v in pretrain_dict.items():            if k in state_dict:                model_dict[k] = v        state_dict.update(model_dict)        self.load_state_dict(state_dict)    def freeze_bn(self):  # 冻结BN层,不对该层进行参数更新;同理可用于其他层        for m in self.modules():            if isinstance(m, nn.BatchNorm2d):                m.eval()     def __init_weight(self):        for m in self.modules():            if isinstance(m, nn.Conv2d):                # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels                # m.weight.data.normal_(0, math.sqrt(2. / n))                torch.nn.init.kaiming_normal_(m.weight)            elif isinstance(m, nn.BatchNorm2d):                m.weight.data.fill_(1)                m.bias.data.zero_()

2.使用网络的自有的apply函数进行初始化。

def init_weights(net, init_type='normal', gain=0.02):    def init_func(m):        classname = m.__class__.__name__        if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):            if init_type == 'normal':                init.normal_(m.weight.data, 0.0, gain)            elif init_type == 'xavier':                init.xavier_normal_(m.weight.data, gain=gain)            elif init_type == 'kaiming':                init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')            elif init_type == 'orthogonal':                init.orthogonal_(m.weight.data, gain=gain)            else:                raise NotImplementedError('initialization method [%s] is not implemented' % init_type)            if hasattr(m, 'bias') and m.bias is not None:                init.constant_(m.bias.data, 0.0)        elif classname.find('BatchNorm2d') != -1:            init.normal_(m.weight.data, 1.0, gain)            init.constant_(m.bias.data, 0.0)    print('initialize network with %s' % init_type)    net.apply(init_func)  # 使用网络自带的apply函数

 

转载地址:http://elwbf.baihongyu.com/

你可能感兴趣的文章
JAVA笔记(六)面向对象--类和对象
查看>>
JAVA笔记(十一)面向对象--多态
查看>>
webpack打包错误:Invalid configuration object. Webpack has been initialised using a configuration object
查看>>
TypeError: this.getOptions is not a function
查看>>
el-table 二维数组合并行
查看>>
js获取当月的天数
查看>>
多个相邻的盒子外边框合并的问题
查看>>
js实现复制功能
查看>>
git报错sign_and_send_pubkey: signing failed: agent refused operation
查看>>
UR5e机械臂运行一直阻塞在waitForServer
查看>>
ROS把pkg1下的某个头文件和源文件生成动态链接库供pkg2调用
查看>>
使用urdf_tutorial快速可视化urdf文件
查看>>
SQl 数据完整性(随堂博客)
查看>>
左连接、右连接、内连接
查看>>
MySQL DQL语句基础(随堂博客)
查看>>
MySQL基础练习
查看>>
利用MySQL进行数据复杂查询(1)
查看>>
利用MySQL进行数据复杂查询(2)
查看>>
MySQL 表与表之间的关系
查看>>
Python数据处理
查看>>