iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
⛓

Convolutional Layers in Neural Networks (1)

に公開

Purpose

Convolutional layers in neural networks are often described in books as layers that automatically extract features. Since it seems quite difficult to understand even when looking through the books I have, I want to document my own understanding, even if this is a well-trodden path.

Experiment


Lenna

I will use the usual Lenna image. Here, the number of channels is set to 1 by converting it to grayscale beforehand, and it is further binarized.

Using PyTorch, I will import the modules as follows:

import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torchvision import transforms
import numpy as np
from PIL import Image

In the following, assume im is a variable obtained by something like im = Image.open('Lenna.png').
Against this, we will consider applying a convolutional layer with fixed parameters and observing the results. We set a Laplacian filter and an averaging filter in the kernels of the convolutional layer, outputting 1-channel image data into 2 channels. We set no bias to keep the results straightforward, and the stride is set to 1 because we do not want to change the image size.

conv = nn.Conv2d(1, 2, kernel_size=3, stride=1, padding=1, bias=False)

kernel = np.array([
    # Laplacian filter (edge detection)
    [[
        [1.,  1., 1.],
        [1., -8., 1.],
        [1.,  1., 1.]
    ]],
    # Averaging filter (blurring)
    [[
        [1/9, 1/9, 1/9],
        [1/9, 1/9, 1/9],
        [1/9, 1/9, 1/9]
    ]]
])

conv.weight = Parameter(torch.from_numpy(kernel).float(), requires_grad=False)

By doing this as follows, you can extract the information for each of the two channels separately.

im_tensor = transforms.ToTensor()(im).unsqueeze(0)
convolved_im = conv.forward(im_tensor).cpu().squeeze(0)

im2 = transforms.ToPILImage()(convolved_im[0])
im3 = transforms.ToPILImage()(convolved_im[1])

Displaying each results in the following, and you can see that edge detection and blurring have been applied.


Laplacian filter


Averaging filter

This is how features are extracted by a convolutional layer.
When creating a convolutional layer, setting the stride to > 1 will apply downscaling according to the value.

conv = nn.Conv2d(1, 2, kernel_size=3, stride=2, padding=1, bias=False)


Downscaling by stride 2

Summary

By specifying simple filters used in image processing for the convolutional layer, I was able to visually confirm its behavior.

GitHubで編集を提案

Discussion