实现Conv2d-深度学习-python

import numpy as np
import math

class MyConv:
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.weights_scale = math.sqrt(self.kernel_size*self.kernel_size*self.in_channels)
        self.weights = np.random.standard_normal((self.kernel_size, self.kernel_size, self.in_channels, self.out_channels)) // self.weights_scale
        self.bias = np.random.standard_normal(self.out_channels) // self.weights_scale
    
    def forward(self, input): # (B, C, H, W)

        input = np.pad(input, ((0, 0), (0, 0), (self.padding, self.padding), (self.padding, self.padding)), 'constant', constant_values=0)
        B, C, H, W = input.shape
        eta = np.zeros((B, self.out_channels, (H-self.kernel_size)//self.stride+1, (H-self.kernel_size)//self.stride+1))

        col_weights = self.weights.reshape([-1, self.out_channels])
        conv_out = np.zeros(eta.shape)

        for i in range(B):
            img_i = input[i] # (C, H, W)
            col_img_i = self.img2col(img_i, self.kernel_size, self.stride)
            conv_out[i] = np.reshape(np.dot(col_img_i, col_weights)+self.bias, eta[0].shape)
        
        return conv_out
    
    def img2col(self, img, kernel_size, stride):
        image_col = []
        for i in range(0, img.shape[1]-kernel_size+1, stride):
            for j in range(0, img.shape[2]-kernel_size+1, stride):
                col = img[:, i:i+kernel_size, j:j+kernel_size].reshape([-1])
                image_col.append(col)
        return np.array(image_col)

if __name__ == '__main__':
    input = np.random.standard_normal((4, 3, 5, 5))
    myconv = MyConv(3, 32, 3, 1, 2)
    print('input:{}'.format(input.shape))
    output = myconv.forward(input)
    print('output:{}'.format(output.shape))
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值