torch.nn.Conv2d函数调用后会自动初始化weight和bias,本文主要涉及
如何自定义weight和bias为需要的数均分布类型:
torch.nn.Conv2d.weight.data以及torch.nn.Conv2d.bias.data为torch.tensor类型,因此只要对这两个属性进行操作即可。
【sample】
以input_channels = 2, output_channels = 1 为例
In [1]: import torch
In [2]: import torch.nn as nn
In [3]: conv = nn.Conv2d(in_channels=2, out_channels=1, kernel_size=3)
# 此时weight以及bias已由nn.Conv2d初始化
conv.weight, conv.bias
Out[4]:
(Parameter containing:
tensor([[[[-0.0335, 0.0855, -0.0708],
[-0.1672, 0.0902, -0.0077],
[-0.0838, -0.1539, -0.0933]],
[[-0.0496, 0.1807, -0.1477],
[ 0.0397, 0.1963, 0.0932],
[-0.2018, -0.0436, 0.1971]]]], requires_grad=True),
Parameter containing:
tensor([-0.1963], requires_grad=True))
# 手动设定
# conv.weight.data 以及 conv.bias.data属性为torch.tensor
# 因此只要获取conv.weight.data以及conv.bias.data属性,后续调用torch.tensor的不同方法即可进行修改
# 例如:全部修改为0
In [5]: conv.weight.data.zero_(), conv.bias.data.zero_()
In [6]: conv.weight, conv.bias
Out[6]:
(Parameter containing:
tensor([[[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]]], requires_grad=True),
Parameter containing:
tensor([0.], requires_grad=True))