神经网络各种初始化方法(normal,uniform,xavier)的numpy实现以及表现对比

Numpy实现

if self.initialization == 'zeros':
    self.W[layer] = np.zeros([out_dim, in_dim])
    self.b[layer] = np.zeros([out_dim])
elif self.initialization == 'ones':
    self.W[layer] = np.ones([out_dim, in_dim])
    self.b[layer] = np.ones([out_dim])
elif self.initialization == 'normal':
    self.W[layer] = np.random.normal(loc=0., scale=1., size=[out_dim, in_dim])
    self.b[layer] = np.random.normal(loc=0., scale=1., size=[out_dim])
elif self.initialization == 'xavier_Glorot_normal':
    self.W[layer] = np.random.normal(loc=0., scale=1., size=[out_dim, in_dim]) / np.sqrt(in_dim)
    self.b[layer] = np.random.normal(loc=0., scale=1., size=[out_dim]) / np.sqrt(in_dim)
elif self.initialization == 'xavier_normal':
    std = np.sqrt(2. / (in_dim + out_dim))
    self.W[layer] = np.random.normal(loc=0., scale=std, size=[out_dim, in_dim])
    self.b[layer] = np.random.normal(loc=0., scale=std, size=[out_dim])
elif self.initialization == 'uniform':
    a = np.sqrt(1. / in_dim)
    self.W[layer] = np.random.uniform(low=-a, high=a, size=[out_dim, in_dim])
    self.b[layer] = np.random.uniform(low=-a, high=a, size=[out_dim])
elif self.initialization == 'xavier_uniform':
    a = np.sqrt(6. / (in_dim + out_dim))
    self.W[layer] = np.random.uniform(low=-a, high=a, size=[out_dim, in_dim])
    self.b[layer] = np.random.uniform(low=-a, high=a, size=[out_dim])
else:
    print("initialization error!")
    exit(1)

表现对比

Mnist数据集 input_feature_dim=784(28*28)

MLP-64-64-softmax网络(自己用numpy搭建的,可能有问题)

SGD优化方法 batch_size=128 max_epoch=100 lr=0.05 

以下数值为test set上的accuracy

需要注意的是:只跑了100个epoch(100*128=12800个shuffled training samples)

 

zeros

ones

normal

xavier_Glorot

xavier_normal

uniform

xavier_uniform

sigmoid

not convergence

not convergence

0.838

0.756

0.623

0.347

0.645

relu

not convergence

not convergence

not convergence

0.895

0.895

0.881

0.896


参考:

神经网络参数初始化 xavier_Glorot

https://blog.youkuaiyun.com/qq_26972735/article/details/81984111

初始化函数 uniform, normal, const, Xavier, He initialization

https://blog.youkuaiyun.com/dss_dssssd/article/details/83959474

常用权重初始化方法Xavier,He initialization的推导

https://xubin.blog.youkuaiyun.com/article/details/107890916

### PyTorch 中的随机权重初始化 在 PyTorch 中,可以通过多种方式实现模型参数的随机初始化。以下是几种常见的方式及其具体实现: #### 1. 利用 `reset_parameters` 方法 PyTorch 的每一层模块通常都提供了一个名为 `reset_parameters` 的方法,用于重置该层的参数到其默认的初始化状态。如果需要对整个网络重新应用这些默认初始化逻辑,则可以遍历所有的子模块并调用此方法。 ```python import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc = nn.Linear(10, 2) def reset_my_model(self): for layer in self.children(): if hasattr(layer, 'reset_parameters'): layer.reset_parameters() ``` 这种方法适用于希望恢复到框架内置的初始化策略的情况[^1]。 #### 2. 手动设置权重和偏置 对于更灵活的需求,可以直接访问各层的 `.weight` 和 `.bias` 属性,并通过 NumPy 或者其他工具生成所需的分布来填充它们。 ```python import torch from torch import nn linear_layer = nn.Linear(in_features=50, out_features=20) nn.init.uniform_(linear_layer.weight, a=-0.1, b=0.1) # 均匀分布 [-0.1, 0.1] if linear_layer.bias is not None: nn.init.constant_(linear_layer.bias, val=0.) # 设置偏差为常数 0. ``` 上述例子展示了如何利用均匀分布来进行初始化以及固定偏差值的操作[^4]。 #### 3. 应用自定义初始化规则至整个网络 为了简化过程,还可以编写一个辅助函数,在其中定义特定类型的张量应该如何被初始化,之后借助于 `Module.apply()` 将这个函数递归应用于所有子模块上。 ```python def custom_init(m): classname = m.__class__.__name__ if isinstance(m, (nn.Conv2d, nn.Linear)): nn.init.xavier_uniform_(m.weight) # Xavier 初始化 if m.bias is not None: nn.init.zeros_(m.bias) # 零初始化偏差 net = SomeCustomNetwork() net.apply(custom_init) ``` 这里采用了Xavier正态分布作为线性和卷积层的主要初始化手段之一[^3]。 另外值得注意的是,“凯明”(Kaiming)初始化特别推荐给ReLU激活后的神经元使用,因为它考虑到了非线性的特性从而调整了方差计算公式[^2]: ```python for name, param in model.named_parameters(): if 'weight' in name and len(param.shape)>1 : nn.init.kaiming_normal_(param, mode='fan_out', nonlinearity='relu') ``` 以上就是关于PyTorch环境下执行随机权重初始化的一些基本指导原则和技术细节说明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值