python 反传播_python实现maxpooling/avgpooling,及其反向传播

maxpooling

import numpy as np

import torch

class MaxPooling2D:

def __init__(self, kernel_size=(2, 2), stride=2):

self.kernel_size = kernel_size

self.w_height = kernel_size[0]

self.w_width = kernel_size[1]

self.stride = stride

self.x = None

self.in_height = None

self.in_width = None

self.out_height = None

self.out_width = None

self.arg_max = None

def __call__(self, x):

self.x = x

self.in_height = np.shape(x)[0]

self.in_width = np.shape(x)[1]

self.out_height = int((self.in_height - self.w_height) / self.stride) + 1

self.out_width = int((self.in_width - self.w_width) / self.stride) + 1

out = np.zeros((self.out_height, self.out_width))

self.arg_max = np.zeros_like(out, dtype=np.int32)

for i in range(self.out_height):

for j in range(self.out_width):

start_i = i * self.stride

start_j = j * self.stride

end_i = start_i + self.w_height

end_j = start_j + self.w_width

out[i, j] = np.max(x[start_i: end_i, start_j: end_j])

self.arg_max[i, j] = np.argmax(x[start_i: end_i, start_j: end_j])

self.arg_max = self.arg_max

return out

def backward(self, d_loss):

dx = np.zeros_like(self.x)

for i in range(self.out_height):

for j in range(self.out_width):

start_i = i * self.stride

start_j = j * self.stride

end_i = start_i + self.w_height

end_j = start_j + self.w_width

index = np.unravel_index(self.arg_max[i, j], self.kernel_size)

dx[start_i:end_i, start_j:en

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值