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,也就是卷积核。那么接下来就要首先生成一个高斯权重了。这里不直接一步步写了,直接输入就行。


 
 
  1. kernel = [[ 0.03797616, 0.044863533, 0.03797616],
  2. [ 0.044863533, 0.053, 0.044863533],
  3. [ 0.03797616, 0.044863533, 0.03797616]]

四 完整代码


 
 
  1. class GaussianBlur(nn.Module):
  2. def __init__(self):
  3. super(GaussianBlur, self).__init__()
  4. kernel = [[ 0.03797616, 0.044863533, 0.03797616],
  5. [ 0.044863533, 0.053, 0.044863533],
  6. [ 0.03797616, 0.044863533, 0.03797616]]
  7. kernel = torch.FloatTensor(kernel).unsqueeze( 0).unsqueeze( 0)
  8. self.weight = nn.Parameter(data=kernel, requires_grad= False)
  9. def forward(self, x):
  10. x1 = x[:, 0]
  11. x2 = x[:, 1]
  12. x3 = x[:, 2]
  13. x1 = F.conv2d(x1.unsqueeze( 1), self.weight, padding= 2)
  14. x2 = F.conv2d(x2.unsqueeze( 1), self.weight, padding= 2)
  15. x3 = F.conv2d(x3.unsqueeze( 1), self.weight, padding= 2)
  16. x = torch.cat([x1, x2, x3], dim= 1)
  17. return x

 这里为了网络模型需要写成了一个类,这里假设输入的x也就是经过网络提取后的三通道特征图(当然不一定是三通道可以是任意通道)

如果是任意通道的话,使用torch.expand()向输入的维度前面进行扩充。如下:


 
 
  1. def blur(self, tensor_image):
  2. kernel = [[ 0.03797616, 0.044863533, 0.03797616],
  3. [ 0.044863533, 0.053, 0.044863533],
  4. [ 0.03797616, 0.044863533, 0.03797616]]
  5. min_batch=tensor_image.size()[ 0]
  6. channels=tensor_image.size()[ 1]
  7. out_channel=channels
  8. kernel = torch.FloatTensor(kernel).expand(out_channel,channels, 3, 3)
  9. self.weight = nn.Parameter(data=kernel, requires_grad= False)
  10. return F.conv2d(tensor_image,self.weight, 1, 1)

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值