pytorch学习经验(三) pytorch自定义卷积核操作

本文的目的是使用自定义的卷积核对图片进行卷积操作。pytorch封装在torch.nn里的Conv2d非常好用,然而其卷积核的权重都是需要学习的参数,如果想要自定义一个卷积核(比如Gabor核)来提取图像特征,conv2d就不适用了。目前有两个解决方案:
方案一 使用opencv
这是我最初采用的方案,使用opencv自带的getGaborKernel()函数来得到gabor kernel,然后在图像上运用filter2D()函数提取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)

这里可以多设几组参数,进行多次滤波。
方案二 使用pytorch自带卷积核
opencv虽然强大,但是有两个问题。第一,它需要输入ndarray,输出也是ndarray,在训练中在线生成gabor feature时需要进行数据格式转换等操作,时间代价很长,而且操作也不方便;第二,如果想要将filter的参数当成可学习参数,opencv就不能使用了,除非你还想自己写一个backward层。所以,我还是使用了pytorch自带的卷积操作:torch.nn.functional.conv2d()
这个卷积核与nn.Conv2d不同,它的weight可以自己设定。好处是,你既可以把各项参数写死在里面,不让它求导,也可以当成可学习参数,反向传播有pytorch来自动实现;并且,由于这是pytorch自带的,在训练中也不需要我们去考虑batch维度,数据格式采用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等参数是可学习的,卷积核权重是用gabor_fn根据可学习参数得到的,其大小为[channel_out, channel_in, ksize, ksize]。调用这个层可以像调用其他普通卷积一样,很容易加到网络中。

你可能感兴趣的:(pytorch学习经验(三) pytorch自定义卷积核操作)