pytorch 修改卷积核的权重weights、偏置bias

生成卷积核以后如何去自定义修改卷积核的权重呢?

kernel_data = torch.rand(1,1,3,3)
print(kernel_data )
conv = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=(3,3),stride=1, padding=1, padding_mode='zeros', bias=False)
print(conv.weight.data)
conv.weight = nn.Parameter(kernel_data)
print(conv.weight.data)

三个输出分别如下

# kernerl data
tensor([[[[0.6293, 0.9107, 0.7624],
          [0.0922, 0.8235, 0.8948],
          [0.1554, 0.2220, 0.1744]]]])
# 初始化的卷积核权重
tensor([[[[ 0.2976,  0.1347, -0.1313],
          [ 0.2648, -0.1767,  0.2317],
          [-0.1537,  0.1266,  0.0860]]]])
# 修改过后的卷积核权重
tensor([[[[0.6293, 0.9107, 0.7624],
          [0.0922, 0.8235, 0.8948],
          [0.1554, 0.2220, 0.1744]]]])

注意

conv = nn.Conv2d()生成的对象,其属性conv.weight并不是一个tensor类,而是一个torch.nn.parameter.Parameter, conv.weight.data才是一个torch.Tensor

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.


你可能感兴趣的:(pytorch,pytorch,深度学习,python)