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

2021-10-03 05:41:40 字數 2594 閱讀 7974

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

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

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

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

三 解決方案。使用

這裡注意下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)

defforward

(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)

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

opencv自定義卷積核

include opencv2 imgproc imgproc.hpp include opencv2 highgui highgui.hpp using namespace cv mat get blur kernel int kernel size 獲得歸一化濾波的卷積核 int main in...

Pytorch自定義引數

如果想要靈活地使用模型,可能需要自定義引數,比如 class net nn.module def init self super net,self init self.a torch.randn 2 3 requires grad true self.b nn.linear 2,2 defforwa...

PyTorch 自定義層

與使用module類構造模型類似。下面的centeredlayer類通過繼承module類自定義了乙個將輸入減掉均值後輸出的層,並將層的計算定義在了forward函式裡。這個層裡不含模型引數。class mydense nn.module def init self super mydense,se...