0Pricing
Machine Learning Academy · レッスン

畳み込みとフィルター:エッジとパターンの検出

手作業で設計したエッジ検出カーネルを画像に適用し、次にnn.Conv2dにフィルターを自動学習させ、学習後の重みを確認します。

「畳み込みとフィルター:エッジとパターンの検出」はCoddyKit上の無料Machine Learning Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMachine Learning Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Machine Learning Academyコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

What Is a Convolution Operation?

Convolution is a mathematical operation that slides a small matrix called a filter (or kernel) across an input (e.g., an image), computing an element-wise dot product at each position. The result is a feature map that highlights where the pattern represented by the filter appears in the input. In image processing, different filters detect different features: edges, corners, textures, or higher-level concepts when stacked in multiple layers.

import torch

# Manual 2D convolution (single filter)
image = torch.tensor([
    [1., 0., 1., 0.],
    [0., 1., 0., 1.],
    [1., 0., 1., 0.],
    [0., 1., 0., 1.]
]).unsqueeze(0).unsqueeze(0)  # shape: (1,1,4,4)

# Vertical edge detector filter
filter_ = torch.tensor([[[-1., 1., -1.],
                          [-1., 1., -1.],
                          [-1., 1., -1.]]]).unsqueeze(0)  # (1,1,3,3)

import torch.nn.functional as F
feature_map = F.conv2d(image, filter_, padding=0)
print(feature_map.shape)   # (1, 1, 2, 2)

Filters and Edge Detection

Classic image processing uses hand-crafted filters: the Sobel filter detects horizontal or vertical edges; the Laplacian filter detects all edges; the Gaussian filter blurs (smooths) images. In deep learning, these filters are learned from data rather than hand-crafted. The key insight of CNNs is that the network automatically discovers which filters are useful for the task by minimising the training loss.

import torch
import torch.nn.functional as F

# Sobel horizontal edge detector
sobel_h = torch.tensor([[
    [-1., -2., -1.],
    [ 0.,  0.,  0.],
    [ 1.,  2.,  1.]
]]).unsqueeze(0)   # shape (1, 1, 3, 3)

# Create a simple gradient image (brightness increases left->right)
image = torch.arange(16.).reshape(1, 1, 4, 4)
feature_map = F.conv2d(image, sobel_h, padding=1)
print('Edge response shape:', feature_map.shape)
print('Edge values:', feature_map.squeeze())

nn.Conv2d: Parameters Explained

nn.Conv2d(in_channels, out_channels, kernel_size) is the core CNN layer. in_channels is the number of input channels (3 for RGB images); out_channels is the number of filters to learn; kernel_size is the spatial size of each filter (3 means 3x3). Each filter produces one output channel, so 64 filters produce a 64-channel feature map. The total parameters in one Conv2d layer is out_channels * in_channels * kernel_h * kernel_w + out_channels (bias).

import torch
import torch.nn as nn

# 3-channel (RGB) input -> 64 feature maps, 3x3 filters
conv = nn.Conv2d(
    in_channels=3,
    out_channels=64,
    kernel_size=3,
    padding=1,     # 'same' padding: output same size as input
    stride=1       # move filter by 1 pixel at a time
)
print('Filter shape:', conv.weight.shape)  # (64, 3, 3, 3)
# 64 filters, each 3x3 applied to 3 channels

params = 64 * 3 * 3 * 3 + 64  # weights + bias
print('Parameters:', params)   # 1792

Padding and Stride

Padding adds zeros around the input border before convolution. padding=1 with a 3x3 filter preserves the spatial dimensions of the input (same padding). Without padding, each convolution reduces width and height by kernel_size - 1. Stride controls how many pixels the filter moves at each step. stride=2 halves the output dimensions, acting like a lightweight pooling operation. Stride-2 convolutions are often used in modern CNNs instead of explicit pooling.

import torch
import torch.nn as nn

# Output size formula: floor((W - K + 2P) / S) + 1
# W=input, K=kernel, P=padding, S=stride

x = torch.randn(1, 3, 32, 32)  # single 32x32 RGB image

conv_same = nn.Conv2d(3, 16, 3, padding=1, stride=1)
print(conv_same(x).shape)  # (1, 16, 32, 32) -- same size

conv_down = nn.Conv2d(3, 16, 3, padding=1, stride=2)
print(conv_down(x).shape)  # (1, 16, 16, 16) -- halved

conv_no_pad = nn.Conv2d(3, 16, 3, padding=0, stride=1)
print(conv_no_pad(x).shape)  # (1, 16, 30, 30) -- reduced

Multiple Channels: Input and Output

A colour image has 3 channels (R, G, B). Each filter in a Conv2d layer has depth equal to in_channels — it operates across all input channels simultaneously, producing a single output value per spatial position. With 64 filters you get 64 output channels. The next convolution layer then takes these 64 channels as input. This channel-stacking allows the network to progressively build more abstract representations from low-level colour edges to high-level object parts.

import torch
import torch.nn as nn

# Layer 1: RGB (3ch) -> 32 feature maps
conv1 = nn.Conv2d(3, 32, 3, padding=1)
# Layer 2: 32 feature maps -> 64 feature maps
conv2 = nn.Conv2d(32, 64, 3, padding=1)

x = torch.randn(4, 3, 28, 28)  # batch of 4 MNIST-like images
out1 = torch.relu(conv1(x))
print('After conv1:', out1.shape)  # (4, 32, 28, 28)
out2 = torch.relu(conv2(out1))
print('After conv2:', out2.shape)  # (4, 64, 28, 28)

Parameter Efficiency: Weight Sharing

A key advantage of convolutions is weight sharing: the same filter is applied at every spatial location. A 3x3 filter over a 256x256 image involves 9 parameters regardless of image size, compared to a fully connected layer that would require millions of parameters. This makes CNNs far more parameter-efficient than MLPs for image data and gives them translation equivariance — a shifted version of a pattern in the input produces a correspondingly shifted feature map.

# Parameter comparison: Conv vs FC for 256x256 images
image_size = 256 * 256

# Convolution: 3x3 filter, 1 input channel, 1 output channel
conv_params = 3 * 3 * 1 + 1   # 10 parameters

# Fully connected: every input pixel connects to every output
fc_params = image_size * image_size  # 4 billion params!

print(f'Conv params:    {conv_params}')
print(f'FC params:      {fc_params:,}')
print(f'Ratio: {fc_params / conv_params:.1e}x fewer parameters for convolution')

What Filters Learn in CNNs

Visualising learned filters reveals a hierarchy of learned features. First layer filters typically detect oriented edges, colour gradients, and textures — similar to hand-crafted Sobel filters. Middle layer filters detect combinations: curves, corners, textures. Deep layer filters respond to object parts (eyes, wheels, feathers). This hierarchical feature learning is why deep CNNs dramatically outperform shallow models on image recognition tasks.

import torch
import torch.nn as nn

# Visualise first-layer filter weight ranges
conv1 = nn.Conv2d(3, 64, 3, padding=1)
print('Filter weights shape:', conv1.weight.shape)
# (64, 3, 3, 3) -- 64 filters, each 3x3 for 3 RGB channels

# One filter: 3-channel 3x3 spatial pattern
filter_0 = conv1.weight[0]   # shape: (3, 3, 3)
print('Filter 0 (R channel):')
print(filter_0[0].detach())  # 3x3 pattern for Red channel
# After training, this would show edge-like patterns

Receptive Field: What Each Neuron Sees

The receptive field of a neuron in a CNN is the region of the original input image that contributes to its activation. A single 3x3 conv layer has a 3x3 receptive field. Two stacked 3x3 layers give a 5x5 receptive field. Three give 7x7. Stacking many small filters is more parameter-efficient than one large filter while achieving the same receptive field. This is why modern CNNs use 3x3 filters almost exclusively — inspired by the VGGNet finding.

# Receptive field grows with depth
# Each 3x3 conv adds 2 to each side of the receptive field

def receptive_field(n_layers, kernel_size=3):
    rf = 1
    for _ in range(n_layers):
        rf += (kernel_size - 1)
    return rf

for n in [1, 2, 3, 5, 10, 20]:
    rf = receptive_field(n)
    print(f'{n} layers of 3x3: receptive field = {rf}x{rf}')
# 1 -> 3, 2 -> 5, 3 -> 7, 5 -> 11, 10 -> 21, 20 -> 41

Building a Simple CNN Block

The standard CNN block follows the pattern: Conv2d -> BatchNorm2d -> ReLU -> (optional Pooling). This trio is repeated multiple times with increasing channel counts, progressively reducing spatial dimensions while increasing the number of feature channels. The spatial reduction compresses location information while the channel expansion captures more abstract features. This pattern is the backbone of ResNet, VGG, EfficientNet, and most other architectures.

import torch
import torch.nn as nn

def conv_block(in_ch, out_ch):
    return nn.Sequential(
        nn.Conv2d(in_ch, out_ch, 3, padding=1),
        nn.BatchNorm2d(out_ch),
        nn.ReLU(inplace=True)
    )

model = nn.Sequential(
    conv_block(3, 32),    # 3 -> 32 channels
    nn.MaxPool2d(2),      # halve spatial size
    conv_block(32, 64),   # 32 -> 64 channels
    nn.MaxPool2d(2),
    conv_block(64, 128),  # 64 -> 128 channels
)

x = torch.randn(4, 3, 32, 32)
print(model(x).shape)   # (4, 128, 8, 8)

Visualising Filter Activations

After training, you can visualise feature maps (filter activations) for a specific input image to see what each filter has detected. Bright regions in a feature map indicate where the corresponding filter pattern was detected. This is useful for debugging (checking that early layers learned edge detectors) and for interpretability (showing which regions of an image activated a 'dog fur' detector or 'wheel' detector in later layers).

import torch
import torch.nn as nn

# Extract feature maps after the first conv layer
conv1 = nn.Conv2d(3, 8, 3, padding=1)
relu = nn.ReLU()

x = torch.randn(1, 3, 16, 16)   # single image
feature_maps = relu(conv1(x))   # shape: (1, 8, 16, 16)

print('Number of feature maps:', feature_maps.shape[1])  # 8
print('Feature map size:', feature_maps.shape[2:])        # 16x16

# Plot with matplotlib:
# import matplotlib.pyplot as plt
# fig, axes = plt.subplots(1, 8)
# for i, ax in enumerate(axes):
#     ax.imshow(feature_maps[0, i].detach(), cmap='gray')

1x1 Convolutions: Channel Mixing

1x1 convolutions apply a linear combination across channels at each spatial position without any spatial mixing. They are used to reduce or expand the number of channels cheaply (as in the Inception and MobileNet bottleneck designs). A 1x1 conv from 256 to 64 channels reduces computation in the subsequent 3x3 conv by 16x. They also introduce non-linearity (via activation) between channel mixing steps, increasing model capacity at minimal parameter cost.

import torch
import torch.nn as nn

# Bottleneck block: expand -> 3x3 conv -> compress
bottleneck = nn.Sequential(
    nn.Conv2d(256, 64, 1),   # 1x1: channel reduction
    nn.ReLU(),
    nn.Conv2d(64, 64, 3, padding=1),  # 3x3: spatial mixing
    nn.ReLU(),
    nn.Conv2d(64, 256, 1),   # 1x1: channel expansion
    nn.ReLU()
)

x = torch.randn(4, 256, 14, 14)
out = bottleneck(x)
print(out.shape)   # (4, 256, 14, 14) -- same shape as input

Quick Check

Test your understanding of Machine Learning with Python concepts from this lesson.

Lesson Recap

In this lesson you learned: convolution slides a filter across the input computing dot products to produce a feature map that highlights where the filter pattern occurs, nn.Conv2d parameters (in_channels, out_channels, kernel_size, padding, stride) control the filter bank, and weight sharing makes convolutions dramatically more parameter-efficient than fully connected layers for spatial data. Next up we explore pooling layers for spatial downsampling and translation invariance.

よくある質問

「畳み込みとフィルター:エッジとパターンの検出」レッスンは無料ですか?

はい。「畳み込みとフィルター:エッジとパターンの検出」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Machine Learning Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Machine Learning Academyコースには全4レッスンが含まれています。

「畳み込みとフィルター:エッジとパターンの検出」で何を学びますか?

手作業で設計したエッジ検出カーネルを画像に適用し、次にnn.Conv2dにフィルターを自動学習させ、学習後の重みを確認します。 ブラウザで直接実行するハンズオンコードでMachine Learning Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Machine Learning Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのMachine Learning Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「畳み込みとフィルター:エッジとパターンの検出」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このMachine Learning Academyレッスンでコードを書いて実行できますか?

はい。すべてのMachine Learning Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. 畳み込みとフィルター:エッジとパターンの検出
  2. プーリング層:空間的ダウンサンプリングと不変性
  3. CIFAR-10でCNNを構築して学習する
  4. データ拡張:頑健性を高める変換
← Machine Learning Academyに戻る