pytorch學習經(jīng)驗(三) pytorch自定義卷積核操作

本文的目的是使用自定義的卷積核對圖片進行卷積操作。pytorch封裝在torch.nn里的Conv2d非常好用,然而其卷積核的權重都是需要學習的參數(shù),如果想要自定義一個卷積核(比如Gabor核)來提取圖像特征,conv2d就不適用了。目前有兩個解決方案:
方案一 使用opencv
這是我最初采用的方案,使用opencv自帶的getGaborKernel()函數(shù)來得到gabor kernel,然后在圖像上運用filter2D()函數(shù)提取gabor特征:

# 得到卷積核
kernel_size = 7
theta = np.pi / 2
lamda = np.pi / 2
kernel = cv2.getGaborKernel((kernel_size, kernel_size), 1.0,\
 theta, lamda, 0.5, 0, ktype=cv2.CV_32F)
# 進行濾波
ac = np.zeros_like(im)
gabor_feature = cv2.filter2/d(img, cv2.CV_8UC3, kern)
np.maximum(ac, gabor_feature, gabor_feature)

這里可以多設幾組參數(shù),進行多次濾波。
方案二 使用pytorch自帶卷積核
opencv雖然強大,但是有兩個問題。第一,它需要輸入ndarray,輸出也是ndarray,在訓練中在線生成gabor feature時需要進行數(shù)據(jù)格式轉(zhuǎn)換等操作,時間代價很長,而且操作也不方便;第二,如果想要將filter的參數(shù)當成可學習參數(shù),opencv就不能使用了,除非你還想自己寫一個backward層。所以,我還是使用了pytorch自帶的卷積操作:torch.nn.functional.conv2d()
這個卷積核與nn.Conv2d不同,它的weight可以自己設定。好處是,你既可以把各項參數(shù)寫死在里面,不讓它求導,也可以當成可學習參數(shù),反向傳播有pytorch來自動實現(xiàn);并且,由于這是pytorch自帶的,在訓練中也不需要我們?nèi)タ紤]batch維度,數(shù)據(jù)格式采用torch tensor,方便得很。還有一個好處是,它可以像普通cnn的卷積核一樣操作,有4個維度,分別是輸出通道,輸入通道,卷積核高,卷積核寬,這樣可以很方便地把自定義的卷積核寫成一個卷積層。具體操作:

import torch.nn.functional as F
import torch

def gabor_fn(kernel_size, channel_in, channel_out, sigma, theta, Lambda, psi, gamma):
    sigma_x = sigma    # [channel_out]
    sigma_y = sigma.float() / gamma     # element-wize division, [channel_out]

    # Bounding box
    nstds = 3 # Number of standard deviation sigma
    xmax = kernel_size // 2
    ymax = kernel_size // 2
    xmin = -xmax
    ymin = -ymax
    ksize = xmax - xmin + 1
    y_0 = torch.arange(ymin, ymax+1)
    y = y_0.view(1, -1).repeat(channel_out, channel_in, ksize, 1).float()
    x_0 = torch.arange(xmin, xmax+1)
    x = x_0.view(-1, 1).repeat(channel_out, channel_in, 1, ksize).float()   # [channel_out, channelin, kernel, kernel]

    # Rotation
    # don't need to expand, use broadcasting, [64, 1, 1, 1] + [64, 3, 7, 7]
    x_theta = x * torch.cos(theta.view(-1, 1, 1, 1)) + y * torch.sin(theta.view(-1, 1, 1, 1))
    y_theta = -x * torch.sin(theta.view(-1, 1, 1, 1)) + y * torch.cos(theta.view(-1, 1, 1, 1))

    # [channel_out, channel_in, kernel, kernel]
    gb = torch.exp(-.5 * (x_theta ** 2 / sigma_x.view(-1, 1, 1, 1) ** 2 + y_theta ** 2 / sigma_y.view(-1, 1, 1, 1) ** 2)) \
         * torch.cos(2 * math.pi / Lambda.view(-1, 1, 1, 1) * x_theta + psi.view(-1, 1, 1, 1))

    return gb


class GaborConv2d(nn.Module):
    def __init__(self, channel_in, channel_out, kernel_size, stride=1, padding=0):
        super(GaborConv2d, self).__init__()
        self.kernel_size = kernel_size
        self.channel_in = channel_in
        self.channel_out = channel_out
        self.stride = stride
        self.padding = padding

        self.Lambda = nn.Parameter(torch.rand(channel_out), requires_grad=True)
        self.theta = nn.Parameter(torch.randn(channel_out) * 1.0, requires_grad=True)
        self.psi = nn.Parameter(torch.randn(channel_out) * 0.02, requires_grad=True)
        self.sigma = nn.Parameter(torch.randn(channel_out) * 1.0, requires_grad=True)
        self.gamma = nn.Parameter(torch.randn(channel_out) * 0.0, requires_grad=True)

        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        theta = self.sigmoid(self.theta) * math.pi * 2.0
        gamma = 1.0 + (self.gamma * 0.5)
        sigma = 0.1 + (self.sigmoid(self.sigma) * 0.4)
        Lambda = 0.001 + (self.sigmoid(self.Lambda) * 0.999)
        psi = self.psi

        kernel = gabor_fn(self.kernel_size, self.channel_in, self.channel_out, sigma, theta, Lambda, psi, gamma)
        kernel = kernel.float()   # [channel_out, channel_in, kernel, kernel]

        out = F.conv2d(x, kernel, stride=self.stride, padding=self.padding)

        return out

我在這里把gabor操作寫成了一個層,即GaborConv2d,可以輸入卷積核大小,輸入及輸出通道,步長以及padding,跟普通卷積相同。lambda、sigma等參數(shù)是可學習的,卷積核權重是用gabor_fn根據(jù)可學習參數(shù)得到的,其大小為[channel_out, channel_in, ksize, ksize]。調(diào)用這個層可以像調(diào)用其他普通卷積一樣,很容易加到網(wǎng)絡中。

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容