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 math

def im2col(img, kernel_h, kernel_w, stride=1):
    N, C, H, W = img.shape
    out_h = (H - kernel_h)//stride + 1
    out_w = (W - kernel_w)//stride + 1
 
    col = torch.zeros((N, C, kernel_h, kernel_w, out_h, out_w))
 
    for y in range(kernel_h):
        y_max = y + stride*out_h
        for x in range(kernel_w):
            x_max = x + stride*out_w
            col[:, :, 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 col

def 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).T
    output = input_vector @ kernel_vector + bias
    output = 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 output
 
batch_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 math

def 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).T
    output = (input_vector.permute(0,2,1).contiguous() @ kernel_vector ) + bias
    output = 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 output
 
batch_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)

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
nn.Conv2d和nn.functional.conv2d是PyTorch中用于进行二维卷操作的两种方式,它们之间有以下区别: 1. 类与函数:nn.Conv2d是一个类,需要实例化为对象后才能使用,而nn.functional.conv2d是一个函数,可以直接调用。 2. 继承关系:nn.Conv2d是nn.Module类的子类,因此它可以被用作神经网络模型的一部分,并且可以在模型的forward方法中被调用。而nn.functional.conv2d不是nn.Module的子类,它是一个纯函数,只能在模型的forward方法中被调用。 3. 参数传递:nn.Conv2d的参数需要在实例化时进行传递,包括输入通道数、输出通道数、卷核大小等。而nn.functional.conv2d的参数需要在每次调用时传递,包括输入张量、卷核、步长、填充等。 4. 内部实现nn.Conv2d使用了可学习的参数,包括卷核权重和偏置项,这些参数会在训练过程中进行更新。而nn.functional.conv2d没有可学习的参数,它只是对输入张量进行卷操作。 下面是一个示例代码,展示了如何使用nn.Conv2d和nn.functional.conv2d进行二维卷操作: ```python import torch import torch.nn as nn import torch.nn.functional as F # 使用nn.Conv2d进行卷操作 conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1) input1 = torch.randn(1, 3, 32, 32) output1 = conv1(input1) # 使用nn.functional.conv2d进行卷操作 input2 = torch.randn(1, 3, 32, 32) kernel = torch.randn(64, 3, 3, 3) output2 = F.conv2d(input2, kernel, stride=1, padding=1) print(output1.shape) print(output2.shape) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值