torch 默认的初始化方法

查了下torch里的源码,如下:

conv

主要代码为:
可见,使用的是 kaiming_uniformuniform初始化

def reset_parameters(self) -> None:
    init.kaiming_uniform_(self.weight, a=math.sqrt(5))
    if self.bias is not None:
        fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
        bound = 1 / math.sqrt(fan_in)
        init.uniform_(self.bias, -bound, bound)

batchnorm

主要代码为:
可见是[0, 1]的正态分布。

def reset_running_stats(self) -> None:
    if self.track_running_stats:
        self.running_mean.zero_()
        self.running_var.fill_(1)
        self.num_batches_tracked.zero_()

nn.linear

主要代码为:
可知使用的是 kaiming_uniform_uniform_

def reset_parameters(self) -> None:
    init.kaiming_uniform_(self.weight, a=math.sqrt(5))
    if self.bias is not None:
        fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
        bound = 1 / math.sqrt(fan_in)
        init.uniform_(self.bias, -bound, bound)

kaiming_uniform_可以参考

https://zhuanlan.zhihu.com/p/305055975

conv 源码

class _ConvNd(Module):

    __constants__ = ['stride', 'padding', 'dilation', 'groups',
                     'padding_mode', 'output_padding', 'in_channels',
                     'out_channels', 'kernel_size']
    __annotations__ = {'bias': Optional[torch.Tensor]}

    _in_channels: int
    out_channels: int
    kernel_size: Tuple[int, ...]
    stride: Tuple[int, ...]
    padding: Tuple[int, ...]
    dilation: Tuple[int, ...]
    transposed: bool
    output_padding: Tuple[int, ...]
    groups: int
    padding_mode: str
    weight: Tensor
    bias: Optional[Tensor]

    def __init__(self,
                 in_channels: int,
                 out_channels: int,
                 kernel_size: _size_1_t,
                 stride: _size_1_t,
                 padding: _size_1_t,
                 dilation: _size_1_t,
                 transposed: bool,
                 output_padding: _size_1_t,
                 groups: int,
                 bias: Optional[Tensor],
                 padding_mode: str) -> None:
        super(_ConvNd, self).__init__()
        if in_channels % groups != 0:
            raise ValueError('in_channels must be divisible by groups')
        if out_channels % groups != 0:
            raise ValueError('out_channels must be divisible by groups')
        valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'}
        if padding_mode not in valid_padding_modes:
            raise ValueError("padding_mode must be one of {}, but got padding_mode='{}'".format(
                valid_padding_modes, padding_mode))
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.dilation = dilation
        self.transposed = transposed
        self.output_padding = output_padding
        self.groups = groups
        self.padding_mode = padding_mode
        # `_reversed_padding_repeated_twice` is the padding to be passed to
        # `F.pad` if needed (e.g., for non-zero padding types that are
        # implemented as two ops: padding + conv). `F.pad` accepts paddings in
        # reverse order than the dimension.
        self._reversed_padding_repeated_twice = _reverse_repeat_tuple(self.padding, 2)
        if transposed:
            self.weight = Parameter(torch.Tensor(
                in_channels, out_channels // groups, *kernel_size))
        else:
            self.weight = Parameter(torch.Tensor(
                out_channels, in_channels // groups, *kernel_size))
        if bias:
            self.bias = Parameter(torch.Tensor(out_channels))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

    def reset_parameters(self) -> None:  # 这里
        init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)

batchnorm 源码

class _NormBase(Module):
    """Common base of _InstanceNorm and _BatchNorm"""
    _version = 2
    __constants__ = ['track_running_stats', 'momentum', 'eps',
                     'num_features', 'affine']
    num_features: int
    eps: float
    momentum: float
    affine: bool
    track_running_stats: bool
    # WARNING: weight and bias purposely not defined here.
    # See https://github.com/pytorch/pytorch/issues/39670

    def __init__(
        self,
        num_features: int,
        eps: float = 1e-5,
        momentum: float = 0.1,
        affine: bool = True,
        track_running_stats: bool = True
    ) -> None:
        super(_NormBase, self).__init__()
        self.num_features = num_features
        self.eps = eps
        self.momentum = momentum
        self.affine = affine
        self.track_running_stats = track_running_stats
        if self.affine:
            self.weight = Parameter(torch.Tensor(num_features))
            self.bias = Parameter(torch.Tensor(num_features))
        else:
            self.register_parameter('weight', None)
            self.register_parameter('bias', None)
        if self.track_running_stats:
            self.register_buffer('running_mean', torch.zeros(num_features))
            self.register_buffer('running_var', torch.ones(num_features))
            self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long))
        else:
            self.register_parameter('running_mean', None)
            self.register_parameter('running_var', None)
            self.register_parameter('num_batches_tracked', None)
        self.reset_parameters()

    def reset_running_stats(self) -> None:   # 这里
        if self.track_running_stats:
            self.running_mean.zero_()
            self.running_var.fill_(1)
            self.num_batches_tracked.zero_()

    def reset_parameters(self) -> None:
        self.reset_running_stats()
        if self.affine:
            init.ones_(self.weight)
            init.zeros_(self.bias)

nn.linear 源码

class Linear(Module):
    r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b`

    This module supports :ref:`TensorFloat32<tf32_on_ampere>`.

    Args:
        in_features: size of each input sample
        out_features: size of each output sample
        bias: If set to ``False``, the layer will not learn an additive bias.
            Default: ``True``

    Shape:
        - Input: :math:`(N, *, H_{in})` where :math:`*` means any number of
          additional dimensions and :math:`H_{in} = \text{in\_features}`
        - Output: :math:`(N, *, H_{out})` where all but the last dimension
          are the same shape as the input and :math:`H_{out} = \text{out\_features}`.

    Attributes:
        weight: the learnable weights of the module of shape
            :math:`(\text{out\_features}, \text{in\_features})`. The values are
            initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
            :math:`k = \frac{1}{\text{in\_features}}`
        bias:   the learnable bias of the module of shape :math:`(\text{out\_features})`.
                If :attr:`bias` is ``True``, the values are initialized from
                :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
                :math:`k = \frac{1}{\text{in\_features}}`

    Examples::

        >>> m = nn.Linear(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])
    """
    __constants__ = ['in_features', 'out_features']
    in_features: int
    out_features: int
    weight: Tensor

    def __init__(self, in_features: int, out_features: int, bias: bool = True) -> None:
        super(Linear, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight = Parameter(torch.Tensor(out_features, in_features))
        if bias:
            self.bias = Parameter(torch.Tensor(out_features))
        else:
            self.register_parameter('bias', None)
        self.reset_parameters()

    def reset_parameters(self) -> None:
        init.kaiming_uniform_(self.weight, a=math.sqrt(5))
        if self.bias is not None:
            fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
            bound = 1 / math.sqrt(fan_in)
            init.uniform_(self.bias, -bound, bound)
### 回答1: 在PyTorch中,torch.nn.Module类中的层初始化是一致的,即默认情况下所有的层组件都使用相同的初始化方法默认情况下,PyTorch中的各种层使用均匀分布或正态分布的方法进行初始化。 例如,当创建一个全连接层(torch.nn.Linear)时,默认初始化方法是从均匀分布中随机选择权重值。我们可以通过指定权重初始化方法的输入参数来改变初始化方法,比如使用正态分布来初始化。 对于某些特定类型的层组件,PyTorch提供了特殊的初始化方法。比如,对于卷积层(torch.nn.Conv2d),可以通过设置参数来自定义初始化默认情况下,卷积层的权重参数是从均匀分布中随机选择的。但我们也可以通过设置参数来改变初始化方法,比如使用正态分布初始化。 除了权重参数初始化外,偏置参数(bias)也可以通过设置输入参数来进行初始化。偏置参数的初始化默认也是从均匀分布中随机选择的。 在实际使用中,我们也可以自己定义初始化方法。我们可以通过继承torch.nn.Module类,然后重写层组件的初始化方法来实现自定义的初始化过程。这样我们就可以根据实际需要选择合适的初始化方法了。 总之,PyTorch中的层初始化是一致的,但我们可以通过设置参数来改变初始化方法,或者自定义初始化方法,以满足具体的需求。 ### 回答2: torch的层初始化一致,是指在神经网络的构建过程中,使用相同的初始化方法和参数对所有的层进行初始化。 神经网络模型的层初始化非常重要,它决定了模型的初始状态和性能。如果层初始化不一致,不同的层可能会有不同的初始权重和偏差,这可能导致训练过程中收敛速度慢,性能差,甚至无法收敛。 为了保证层初始化的一致性,Torch提供了一些内置的初始化方法,如常见的xavier初始化、正态分布初始化或均匀分布初始化。这些初始化方法可以保证每个层的初始权重和偏差在一定范围内随机初始化,使得初始值足够接近最优解。当然,用户也可以自定义初始化方法来满足特定需求。 在构建神经网络模型时,通常会使用循环或迭代的方式添加各个层,然后使用统一的初始化方法对它们进行初始化。这样可以确保所有的层使用相同的初始化参数,从而保证了层初始化的一致性。 除了层初始化的一致性外,Torch还提供了一些其他的初始化策略来提高模型的性能和效果,比如Batch Normalization(批归一化)等。这些策略可以有效地减少梯度消失和梯度爆炸等问题,加速网络的收敛速度,提高模型的泛化能力。 总之,torch的层初始化一致是为了确保每个层的初始权重和偏差在一定范围内随机初始化,并提供了一些内置的初始化方法和其他初始化策略来提高模型的性能和效果。 ### 回答3: torch的层初始化一致是指在神经网络模型中,使用torch库提供的初始化方法时,对于每个相同类型的层,初始化的方式是一样的。这种一致性可以帮助我们更好地控制模型的初始化过程,以提高模型的训练性能和泛化能力。 在torch中,我们可以使用nn.Module中提供的方法初始化层,常见的初始化方法包括xavier初始化、正态分布初始化、均匀分布初始化等。这些方法都是基于torch.nn.init模块实现的。 当我们创建一个神经网络模型时,可以通过在模型的初始化方法中调用nn.Module中的初始化方法来对模型的各个层进行初始化。我们可以根据需要选择使用不同的初始化方法,并且对于相同类型的层,可以使用相同的初始化方法。 这种一致的初始化方法带来的好处是可以保持模型的一致性和可复现性。在实验中,我们通常会多次训练模型,并比较不同初始化方法对模型性能的影响。如果每次初始化的方式都是一样的,那么我们可以更准确地比较各种初始化方法的效果,找到最优的初始化方法。 另外,一致的初始化方法还可以帮助我们更方便地调试和验证模型。在模型的训练过程中,如果遇到性能下降或其他问题,我们可以通过检查模型的初始化方法是否一致,来确定是否是初始化方式导致的问题。 总而言之,torch的层初始化一致是指使用相同的初始化方法初始化相同类型的层,这种一致性可以提高模型的训练性能和泛化能力,同时也方便了模型的调试和验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值