欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

pytorch 自定義卷積核進(jìn)行卷積操作方式

 更新時(shí)間:2019年12月30日 15:23:30   作者:月亮是藍(lán)色  
今天小編就為大家分享一篇pytorch 自定義卷積核進(jìn)行卷積操作方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧

一 卷積操作:在pytorch搭建起網(wǎng)絡(luò)時(shí),大家通常都使用已有的框架進(jìn)行訓(xùn)練,在網(wǎng)絡(luò)中使用最多就是卷積操作,最熟悉不過的就是

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

通過上面的輸入發(fā)現(xiàn)想自定義自己的卷積核,比如高斯核,發(fā)現(xiàn)是行不通的,因?yàn)樯厦娴膮?shù)里面只有卷積核尺寸,而權(quán)值weight是通過梯度一直更新的,是不確定的。

二 需要自己定義卷積核的目的:目前是需要通過一個(gè)VGG網(wǎng)絡(luò)提取特征特后需要對其進(jìn)行高斯卷積,卷積后再繼續(xù)輸入到網(wǎng)絡(luò)中訓(xùn)練。

三 解決方案。使用

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

這里注意下weight的參數(shù)。與nn.Conv2d的參數(shù)不一樣

可以發(fā)現(xiàn)F.conv2d可以直接輸入卷積的權(quán)值weight,也就是卷積核。那么接下來就要首先生成一個(gè)高斯權(quán)重了。這里不直接一步步寫了,直接輸入就行。

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

這里為了網(wǎng)絡(luò)模型需要寫成了一個(gè)類,這里假設(shè)輸入的x也就是經(jīng)過網(wǎng)絡(luò)提取后的三通道特征圖(當(dāng)然不一定是三通道可以是任意通道)

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

  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 自定義卷積核進(jìn)行卷積操作方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論