1. 程式人生 > >pytorch 自定義卷積核進行卷積操作

pytorch 自定義卷積核進行卷積操作

一 卷積操作:在pytorch搭建起網路時,大家通常都使用已有的框架進行訓練,在網路中使用最多就是卷積操作,最熟悉不過的就是

torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True)

通過上面的輸入發現想自定義自己的卷積核,比如高斯核,發現是行不通的,因為上面的引數裡面只有卷積核尺寸,而權值weight是通過梯度一直更新的,是不確定的。

二  需要自己定義卷積核的目的:目前是需要通過一個VGG網路提取特徵特後需要對其進行高斯卷積,卷積後再繼續輸入到網路中訓練。

三 解決方案。使用

torch.nn.functional.conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1)

 

這裡注意下weight的引數。與nn.Conv2d的引數不一樣

可以發現F.conv2d可以直接輸入卷積的權值weight,也就是卷積核。那麼接下來就要首先生成一個高斯權重了。這裡不直接一步步寫了,直接輸入就行。

kernel = [[0.03797616, 0.044863533, 0.03797616],
         [0.044863533, 0.053, 0.044863533],
         [0.03797616, 0.044863533, 0.03797616]]

四 完整程式碼

class GaussianBlur(nn.Module):
    def __init__(self):
        super(GaussianBlur, self).__init__()
        kernel = [[0.03797616, 0.044863533, 0.03797616],
                  [0.044863533, 0.053, 0.044863533],
                  [0.03797616, 0.044863533, 0.03797616]]
        kernel = torch.FloatTensor(kernel).unsqueeze(0).unsqueeze(0)
        self.weight = nn.Parameter(data=kernel, requires_grad=False)

    def forward(self, x):
        x1 = x[:, 0]
        x2 = x[:, 1]
        x3 = x[:, 2]
        x1 = F.conv2d(x1.unsqueeze(1), self.weight, padding=2)
        x2 = F.conv2d(x2.unsqueeze(1), self.weight, padding=2)
        x3 = F.conv2d(x3.unsqueeze(1), self.weight, padding=2)
        x = torch.cat([x1, x2, x3], dim=1)
        return x

 這裡為了網路模型需要寫成了一個類,這裡假設輸入的x也就是經過網路提取後的三通道特徵圖(當然不一定是三通道可以是任意通道)

如果是任意通道的話,使用torch.expand()向輸入的維度前面進行擴充。如下:

    def blur(self, tensor_image):
        kernel = [[0.03797616, 0.044863533, 0.03797616],
               [0.044863533, 0.053, 0.044863533],
               [0.03797616, 0.044863533, 0.03797616]]
       
        min_batch=tensor_image.size()[0]
        channels=tensor_image.size()[1]
        out_channel=channels
        kernel = torch.FloatTensor(kernel).expand(out_channel,channels,3,3)
        self.weight = nn.Parameter(data=kernel, requires_grad=False)

        return F.conv2d(tensor_image,self.weight,1,1)