《动手学深度学习》-21卷积层里的多输入多输出通道

沐神版《动手学深度学习》学习笔记,记录学习过程,详细的内容请大家购买书籍查阅。

b站视频链接
开源教程链接

卷积层里的多输入多输出通道

大家通常最在意的一个超参数:
在这里插入图片描述
RGB图像不仅仅是单纯的矩阵,是3 x h x w的形状:
在这里插入图片描述
多输入通道计算过程:
在这里插入图片描述
在这里插入图片描述
到这里为止,不管有多少个输入通道,我们都会得到单输出通道,想要输出也有多个通道,我们可以有多个三维卷积核,每个核生成一个输出通道。

多输出通道计算过程:
在这里插入图片描述
每个输出通道可以识别不同模式,输入通道核识别并组合输入中的模式:
在这里插入图片描述
1x1卷积层的唯一计算发生在通道上:
在这里插入图片描述
计算复杂度:
在这里插入图片描述
输出通道数是卷积层的超参数

每个输入通道有独立的二维卷积核,所有通道结果相加得到一个输出通道结果

每个输出通道有独立的三维卷积核
在这里插入图片描述

动手学

多输入通道

import torch
from d2l import torch as d2l

def corr2d_multi_in(X, K):
    # 先遍历“X”和“K”的第0个维度(通道维度),再把它们加在一起
    return sum(d2l.corr2d(x, k) for x, k in zip(X, K))
X = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]],
               [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]])
K = torch.tensor([[[0.0, 1.0], [2.0, 3.0]], [[1.0, 2.0], [3.0, 4.0]]])
print(X.shape, K.shape)
corr2d_multi_in(X, K)
torch.Size([2, 3, 3]) torch.Size([2, 2, 2])
tensor([[ 56.,  72.],
        [104., 120.]])

多输出通道

def corr2d_multi_in_out(X, K):
    # 迭代“K”的第0个维度,每次都对输入“X”执行互相关运算。
    # 最后将所有结果都叠加在一起
    return torch.stack([corr2d_multi_in(X, k) for k in K], 0)

K = torch.stack((K, K + 1, K + 2), 0)
K.shape
torch.Size([3, 2, 2, 2])
corr2d_multi_in_out(X, K)
tensor([[[ 56.,  72.],
         [104., 120.]],

        [[ 76., 100.],
         [148., 172.]],

        [[ 96., 128.],
         [192., 224.]]])

1x1卷积

def corr2d_multi_in_out_1x1(X, K):
    c_i, h, w = X.shape
    c_o = K.shape[0]
    X = X.reshape((c_i, h * w))
    K = K.reshape((c_o, c_i))
    # 全连接层中的矩阵乘法
    Y = torch.matmul(K, X)
    return Y.reshape((c_o, h, w))

X = torch.normal(0, 1, (3, 3, 3))
K = torch.normal(0, 1, (2, 3, 1, 1))

Y1 = corr2d_multi_in_out_1x1(X, K)
Y2 = corr2d_multi_in_out(X, K)
assert float(torch.abs(Y1 - Y2).sum()) < 1e-6
Y1.shape, Y2.shape
(torch.Size([2, 3, 3]), torch.Size([2, 3, 3]))
# 调用pytorch
from torch import nn
conv2d = nn.Conv2d(1, 1, kernel_size=3, padding=1, stride=2) # 输出通道、输入通道、卷积核尺寸、步幅大小

猜你喜欢

转载自blog.csdn.net/cjw838982809/article/details/132456233