Python和PyTorch对比实现卷积convolution函数及反向传播

本文对比介绍了如何使用纯Python和PyTorch来实现卷积函数及其对应的反向传播过程,提供了详细的代码实现,并引用了相关资源进行深入理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要

本文使用纯 Python 和 PyTorch 对比实现 convolution 函数及其反向传播.

相关

原理和详细解释, 请参考文章 :

卷积convolution函数详解及反向传播中的梯度求导

系列文章索引 :
https://blog.youkuaiyun.com/oBrightLamp/article/details/85067981

正文

import torch
import numpy as np


class Conv2d:
    def __init__(self, stride=1):
        self.weight = None
        self.bias = None

        self.stride = stride

        self.x = None
        self.dw = None
        self.db = None

        self.input_height = None
        self.input_width = None
        self.weight_height = None
        self.weight_width = None
        self.output_height = None
        self.output_width = None

    def __call__(self, x):
        self.x = x
        self.input_height = np.shape(x)[0]
        self.input_width = np.shape(x)[1]
        self.weight_height = np.shape(self.weight)[0]
        self.weight_width = np.shape(self.weight)[1]

        self.output_height = int((self.input_height - self.weight_height) / self.stride) + 1
        self.output_width = int((self.input_width - self.weight_width) / self.stride) + 1

        out = np.zeros((self.output_height
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值