pytorch 学习笔记 part8 卷积神经网络基础

二维互相关运算

用corr2d函数实现二维互相关运算,它接受输入数组X与核数组K,并输出数组Y。

import torch 
import torch.nn as nn

def corr2d(X, K):
    H, W = X.shape# H,W表示输入的高和宽
    h, w = K.shape# h,w表示卷积核的高和宽
    Y = torch.zeros(H - h + 1, W - w + 1)
    for i in range(Y.shape[0]):
        for j in range(Y.shape[1]):
            Y[i, j] = (X[i: i + h, j: j + w] * K).sum()
    return Y

举一个简单的例子

X = torch.tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
K = torch.tensor([[0, 1], [2, 3]])
Y = corr2d(X, K)
print(Y)

输出结果
在这里插入图片描述

二维卷积层

二维卷积层将输入和卷积核做互相关运算,并加上一个标量偏置来得到输出。卷积层的模型参数包括卷积核和标量偏置。

class Conv2D(nn.Module):# nn.Module的一个子类
    def __init__(self, kernel_size):# kernel_size是一个长度为2的元组,表示卷积核的高和宽
        super(Conv2D, self).__init__()
        # nn.Parameter为自动为参数附上梯度;会将参数添加到子类中
        self.weight = nn.Parameter(torch.randn(kernel_size))# 卷积核
        self.bias = nn.Parameter(torch.randn(1))# 标量偏置

    def forward(self, x):# x为卷积层的输入
        return corr2d(x, self.weight) + self.bias# 用输入x和卷积核作互相关运算,再加上标量偏置

构造一张6×8的图像,中间4列为黑(0),其余为白(1),希望检测到颜色边缘。我们的标签是一个6×7的二维数组,第2列是1(从1到0的边缘),第6列是-1(从0到1的边缘)。

X = torch.ones(6, 8)# x为输入
Y = torch.zeros(6, 7)# y为标签
X[:, 2: 6] = 0
Y[:, 1] = 1
Y[:, 5] = -1
print(X)
print(Y)

在这里插入图片描述
我们希望学习一个1×2卷积层,通过卷积层来检测颜色边缘。

conv2d = Conv2D(kernel_size=(1, 2))# 构造一个二维卷积层的实例,形状为1×2
step = 30 # 行走步数
lr = 0.01 # 学习率
for i in range(step):
    Y_hat = conv2d(X)# X通过卷积运算得到Y_hat
    l = ((Y_hat - Y) ** 2).sum() # 定义损失值
    l.backward()
    # 梯度下降:
    conv2d.weight.data -= lr * conv2d.weight.grad# 参数值减去学习率乘上对应的梯度值
    conv2d.bias.data -= lr * conv2d.bias.grad
    
    # 梯度清零
    conv2d.weight.grad.zero_()
    conv2d.bias.grad.zero_()
    if (i + 1) % 5 == 0: # 每隔5个训练步,输出一个loss
        print('Step %d, loss %.3f' % (i + 1, l.item()))
        
print(conv2d.weight.data)
print(conv2d.bias.data)

在这里插入图片描述
在这里插入图片描述
两行tensor分别是卷积核和偏置,卷积核的值接近1和-1,因为从1变成0为1,从0变成1为-1

特征图与感受野

二维卷积层输出的二维数组可以看作是输入在空间维度(宽和高)上某一级的表征,也叫特征图(feature map)。影响元素x的前向计算的所有可能输入区域(可能大于输入的实际尺寸)叫做x的感受野(receptive field)。
在这里插入图片描述

以上图为例,输入中阴影部分的四个元素是输出中阴影部分元素的感受野。我们将图中形状为2×2的输出记为Y,将Y与另一个形状为2×2的核数组做互相关运算,输出单个元素z。那么,z在Y上的感受野包括Y的全部四个元素,在输入上的感受野包括其中全部9个元素。可见,我们可以通过更深的卷积神经网络使特征图中单个元素的感受野变得更加广阔,从而捕捉输入上更大尺寸的特征。

填充和步幅

卷积层的两个超参数,填充和步幅,它们可以对给定形状的输入和卷积核改变输出形状。
在这里插入图片描述
在这里插入图片描述

多输入通道和多输出通道

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

卷积层的实现

主要参数:
1.in_channels (python:int) – Number of channels in the input imag
2.out_channels (python:int) – Number of channels produced by the convolution
3.kernel_size (python:int or tuple) – Size of the convolving kernel
4.stride (python:int or tuple, optional) – Stride of the convolution. Default: 1
5.padding (python:int or tuple, optional) – Zero-padding added to both sides of the input. Default: 0
6.bias (bool, optional) – If True, adds a learnable bias to the output. Default: True
在这里插入图片描述

X = torch.rand(4, 2, 3, 5)# 批量大小为4,通道数为2,高和宽为3和5
print(X.shape)

conv2d = nn.Conv2d(in_channels=2, out_channels=3, kernel_size=(3, 5), stride=1, padding=(1, 2))
Y = conv2d(X)
print('Y.shape: ', Y.shape)
print('weight.shape: ', conv2d.weight.shape)# 卷积核形状
print('bias.shape: ', conv2d.bias.shape)

在这里插入图片描述
每个通道上加一个偏置,所以偏置是3

池化层的实现

在这里插入图片描述
主要参数:

1.kernel_size – the size of the window to take a max over
2.stride – the stride of the window. Default value is kernel_size
3.padding – implicit zero padding to be added on both sides
在这里插入图片描述

X = torch.arange(32, dtype=torch.float32).view(1, 2, 4, 4)
pool2d = nn.MaxPool2d(kernel_size=3, padding=1, stride=(2, 1))
Y = pool2d(X)
print(X)
print(Y)

在这里插入图片描述
平均池化层使用的是nn.AvgPool2d,使用方法与nn.MaxPool2d相同。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值