5 手写卷积函数

背景

从现在开始各种手写篇章,先从最经典的卷积开始

介绍

对于卷积层的具体操作,我这里就不在具体说卷积具体是什么东西了。
对于手写卷积操作而言,有两种方式,一种就是最朴素的通过滑动窗口来实现的方式,另一种方式就是使用矩阵乘法来简化操作过程的方式。

滑动窗口的方式

在这里插入图片描述

卷积操作的动图https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md

通过上面的图片和连接就可以很直观地感受到卷积操作的方式,也能很直接想到使用简单的滑动窗口来实现,如果还不能理解,建议去B站搜下视频学习下

代码

"""
-*- coding: utf-8 -*-
使用滑动窗口方式的手动卷积
@Author : Leezed
@Time : 2025/6/27 15:33
"""

import numpy as np


class ManualSlideWindowConv():
    """
    手动实现卷积操作,使用滑动窗口方式
    没有实现反向传播功能
    """

    def __init__(self, kernel_size, in_channel, out_channel, stride=1, padding=0, bias=True):
        self.kernel_size = kernel_size
        self.in_channel = in_channel
        self.out_channel = out_channel
        self.stride = stride
        self.padding = padding
        self.bias = bias

        self.weight = np.random.randn(out_channel, in_channel, kernel_size, kernel_size)

        if bias:
            self.bias = np.random.randn(out_channel)
        else:
            self.bias = None

    def print_weight(self):
        print("Weight shape:", self.weight.shape)
        print("Weight values:\n", self.weight)

    def get_weight(self):
        return self.weight

    def set_weight(self, weight):
        if weight.shape != self.weight.shape:
            raise ValueError(f"Weight shape mismatch: expected {self.weight.shape}, got {weight.shape}")
        self.weight = weight

    def __call__(self, x, *args, **kwargs):
        if self.padding > 0:
            x = np.pad(x, ((0, 0), (0, 0), (self.padding, self.padding), (self.padding, self.padding)), mode='constant')  # 在四周填充0
        batch_size, in_channel, height, width = x.shape
        kernel_size = self.kernel_size
        # 计算输出的高度和宽度
        out_height = (height - kernel_size) // self.stride + 1
        out_width = (width - kernel_size) // self.stride + 1
        output = np.zeros((batch_size, self.out_channel, out_height, out_width))
        for channel in range(self.out_channel):
            # 取出当前输出通道的权重
            kernel = self.weight[channel, :, :, :]
            # 添加bias
            if self.bias is not None:
                output[:, channel, :, :] += self.bias[channel]
            else:
                output[:, channel, :, :] = 0
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

理智点

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值