F.conv2d实现代码

import math
import torch
import torch.nn.functional as F

def conv(x, kernel, bais, stride, padding):
    '''
    x: n,cin,h,w
    kernel: cout, cin, kh, kw
    '''
    n,c,h,w = x.size()   		#获得x原始尺度信息
    x = F.pad(x, (padding,)*4) #获得kernel参数,计算输出特征图大小和x上划区域的大小
    cout, cin, kh, kw = kernel.size()
    oh = math.floor((h - kh + 2*padding)/stride + 1)  #输出特征图大小,用x原始尺度计算
    ow =  math.floor((w - kw + 2*padding)/stride + 1) #输出特征图大小,用x原始尺度计算
    out = torch.zeros(n,cout,oh, ow)  #定义输出特征图
    for i in range(0, h-kh+1, stride):
        for j in range(0, w-kw+1, stride):
            region = x[:,:,i:i+kh, j:j+kw] #x上取特征大小为n,cin,kw,kw
            for k in range(cout):  #遍历输出个数个卷积核
                out[:,k,int(i/stride),int(j/stride)] = torch.sum(region * kernel[k]) # n,cin,kh, kw * None, cin, kh,kw
    print(out)
if __name__ == '__main__':
    x = torch.rand(1,3,5,5)
    kernel = torch.rand(4,3,3,3)
    conv(x, kernel, None, 2, 1)
    r = F.conv2d(x, kernel, bias=None, stride=2, padding=1)
    print(r)

你可能感兴趣的:(pytorch,python,深度学习,pytorch,python)