Pytorch 基于im2col手动实现卷积conv2d(基于nn.Unfold实现卷积)(向量内积实现)

2023-11-07 05:59

本文主要是介绍Pytorch 基于im2col手动实现卷积conv2d(基于nn.Unfold实现卷积)(向量内积实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      如果老老实实地实现卷积运算,估计要重复好几层的for语句。这样的实现有点麻烦,而且, NumPy中存在使用for语句后处理变慢的缺点(NumPy中,访问元素时最好不要用 for语句)

       如上图所示,我们每次取的input,我们可以把它拉直,拉成一个行向量。它跟kernel进行元素相乘再求和,就相当于这个输入行向量,再跟kernel的列向量(将kernel拉成列向量)进行相乘

      在上图中,为了便于观察,将步幅设置得很大,以使滤波器的应用区域不重叠。而在实际的卷积运算中,滤波器的应用区域几乎都是重叠的。在滤波器的应用区域重叠的情况下,使用im2col展开后,展开后的元素个数会多于原方块的元素个数。因此,使用im2col的实现存在比普通的实现消耗更多内存的缺点。但是,汇总成一个大的矩阵进行计算,对计算机的计算颇有益处。比如,在矩阵计算的库(线性代数库)等中,矩阵计算的实现已被高度最优化,可以高速地进行大矩阵的乘法运算。因此,通过归结到矩阵计算上,可以有效地利用线性代数库。

使用 im2col展开输入数据后,之后就只需将卷积层的kernel纵向展开为1列,并计算2个矩阵的乘积即可,如下图。

将矩阵转为列向量

x.reshape(-1,1)

代码

import torch
from torch import nn
import torch.nn.functional as F
import mathdef im2col(img, kernel_h, kernel_w, stride=1):N, C, H, W = img.shapeout_h = (H - kernel_h)//stride + 1out_w = (W - kernel_w)//stride + 1col = torch.zeros((N, C, kernel_h, kernel_w, out_h, out_w))for y in range(kernel_h):y_max = y + stride*out_hfor x in range(kernel_w):x_max = x + stride*out_wcol[:, :, y, x, :, :] = img[:, :, y:y_max:stride, x:x_max:stride]col = col.permute(0, 4, 5, 1, 2, 3).contiguous().reshape(N*out_h*out_w, -1)return coldef my_conv(input, kernel, stride=1, padding=0, bias=0):if padding > 0:input = F.pad(input, (padding,padding,padding,padding))batch_size = input.shape[0]input_h, input_w = input.shape[2:4]kernel_h, kernel_w = kernel.shape[2:4]out_channel, in_channel = kernel.shape[0:2]output_h = math.floor((input_h - kernel_h) / stride + 1)output_w = math.floor((input_w - kernel_w) / stride + 1)input_vector = im2col(input, kernel_h, kernel_w, stride=stride)kernel_vector = kernel.reshape(kernel.shape[0], -1).Toutput = input_vector @ kernel_vector + biasoutput = output.reshape(batch_size, output_h, output_w, out_channel).permute(0,3,1,2).contiguous()    #注意可不能写成下面这样# output = output.reshape(batch_size, out_channel, output_h, output_w)return outputbatch_size = 4
in_channel = 3
out_channel = 16
input = torch.rand(batch_size, in_channel ,5,5)
kernel = torch.rand(out_channel, in_channel, 3,3)
bias = torch.rand(out_channel)my_output = my_conv(input, kernel, padding=1, stride=2, bias=bias)output = F.conv2d(input, kernel, padding=1, stride=2, bias=bias)assert torch.allclose(my_output, output)

用nn.Unfold实现

import torch
from torch import nn
import torch.nn.functional as F
import mathdef my_conv(input, kernel, stride=1, padding=0, bias=0):if padding > 0:input = F.pad(input, (padding,padding,padding,padding))batch_size = input.shape[0]input_h, input_w = input.shape[2:4]kernel_h, kernel_w = kernel.shape[2:4]out_channel, in_channel = kernel.shape[0:2]output_h = math.floor((input_h - kernel_h) / stride + 1)output_w = math.floor((input_w - kernel_w) / stride + 1)unfold = nn.Unfold(kernel_size=(kernel_h, kernel_w), stride=stride)input_vector = unfold(input)kernel_vector = kernel.reshape(kernel.shape[0], -1).Toutput = (input_vector.permute(0,2,1).contiguous() @ kernel_vector ) + biasoutput = output.reshape(batch_size, output_h, output_w, out_channel).permute(0,3,1,2).contiguous()    #注意可不能写成下面这样# output = output.reshape(batch_size, out_channel, output_h, output_w)return outputbatch_size = 4
in_channel = 3
out_channel = 16
input = torch.rand(batch_size, in_channel ,5,5)
kernel = torch.rand(out_channel, in_channel, 3,3)
bias = torch.rand(out_channel)my_output = my_conv(input, kernel, padding=1, stride=2, bias=bias)output = F.conv2d(input, kernel, padding=1, stride=2, bias=bias)assert torch.allclose(my_output, output)

这篇关于Pytorch 基于im2col手动实现卷积conv2d(基于nn.Unfold实现卷积)(向量内积实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/361695

相关文章

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringBatch数据写入实现

《SpringBatch数据写入实现》SpringBatch通过ItemWriter接口及其丰富的实现,提供了强大的数据写入能力,本文主要介绍了SpringBatch数据写入实现,具有一定的参考价值,... 目录python引言一、ItemWriter核心概念二、数据库写入实现三、文件写入实现四、多目标写入

Android Studio 配置国内镜像源的实现步骤

《AndroidStudio配置国内镜像源的实现步骤》本文主要介绍了AndroidStudio配置国内镜像源的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、修改 hosts,解决 SDK 下载失败的问题二、修改 gradle 地址,解决 gradle

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

pytorch之torch.flatten()和torch.nn.Flatten()的用法

《pytorch之torch.flatten()和torch.nn.Flatten()的用法》:本文主要介绍pytorch之torch.flatten()和torch.nn.Flatten()的用... 目录torch.flatten()和torch.nn.Flatten()的用法下面举例说明总结torch

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

MySQL更新某个字段拼接固定字符串的实现

《MySQL更新某个字段拼接固定字符串的实现》在MySQL中,我们经常需要对数据库中的某个字段进行更新操作,本文就来介绍一下MySQL更新某个字段拼接固定字符串的实现,感兴趣的可以了解一下... 目录1. 查看字段当前值2. 更新字段拼接固定字符串3. 验证更新结果mysql更新某个字段拼接固定字符串 -

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio