卷积操作框架

神经网络系列之卷积操作


一、前言

都知道什么是卷积,那么怎么用代码来展示呢?如下所示。

一、卷积图例

1、下图是输入图像为5×5的矩阵,卷积核大小为3×3,步长为1,padding=0,对应的代码及详解如代码一所示。

2、下图是输入图像为5×5的矩阵,卷积核大小为3×3,步长为1,padding=1,对应的代码及详解如代码二所示。

二、代码及详解

1.代码一

代码如下(示例):

import torch
import torch.nn.functional as F
input=torch.tensor([[1,2,0,3,1],
                   [0,1,2,3,1],
                   [1,2,1,0,0],
                   [5,2,3,1,1],
                   [2,1,0,1,1]])
kernel=torch.tensor([[1,2,1],
                    [0,1,0],
                    [2,1,0]])
print(input.shape)                      #之前的形状,5×5
print(kernel.shape)                     #3×3
input=torch.reshape(input,(1,1,5,5))    #变换之后,1×1卷积核,1个通道,尺寸5×5
kernel=torch.reshape(kernel,(1,1,3,3))  #变换之后,1×1卷积核,1个通道,尺寸3×3
print(input.shape)                      #打印变换后输入的形状
print(kernel.shape)                     #打印变换后卷积核的形状

output1=F.conv2d(input,kernel,stride=1) #经过卷积后
print(output1)                          #打印经过卷积后的输出

输出结果为:

2.代码2

代码如下(示例):

import torch
import torch.nn.functional as F
input=torch.tensor([[1,2,0,3,1],
                   [0,1,2,3,1],
                   [1,2,1,0,0],
                   [5,2,3,1,1],
                   [2,1,0,1,1]])
kernel=torch.tensor([[1,2,1],
                    [0,1,0],
                    [2,1,0]])
print(input.shape)                      #之前的形状,5×5
print(kernel.shape)                     #3×3
input=torch.reshape(input,(1,1,5,5))    #变换之后,1×1卷积核,1个通道,尺寸5×5
kernel=torch.reshape(kernel,(1,1,3,3))  #变换之后,1×1卷积核,1个通道,尺寸3×3
print(input.shape)                      #打印变换后输入的形状
print(kernel.shape)                     #打印变换后卷积核的形状

output1=F.conv2d(input,kernel,stride=1) #经过卷积后
print(output1)                          #打印经过卷积后的输出

output2=F.conv2d(input,kernel,stride=1,padding=1) #加了个padding=1
print(output2)                                    #打印输出

输出结果为:


三、总结

根据土堆老师视频,进行代码书写及整理。土堆说卷积操作(可选看)_哔哩哔哩_bilibili

猜你喜欢

转载自blog.csdn.net/weixin_69398563/article/details/126348735