numpy实现Conv2d卷积

该篇文章详细展示了如何使用numpy库从头实现2D卷积操作,不依赖于其他库函数,通过定义conv2d函数并提供了一个实际应用的代码片段,包括输入数组和卷积核的创建以及输出数组的计算。
摘要由CSDN通过智能技术生成

问题背景

用numpy实现一个2d卷积,不允许调用其他库函数。

代码

import numpy as np

def conv2d(input_array, kernel):
    batch_size, in_channel, height, width = input_array.shape 
    in_channel, out_channel, k_height, k_width = kernel.shape
    output_height = height - k_height + 1
    output_width = width - k_width + 1
    output_array = np.empty((batch_size, out_channel, output_height, output_width))

    for b in range(batch_size):
        for oc in range(out_channel):
            for h in range(output_height):
                for w in range(output_width):
                    output_array[b, oc, h, w] = np.sum(
                        input_array[b, :, h:h+k_height, w:w+k_width] * kernel[:, oc, :, :]
                    )

    return output_array

input_array = np.random.randn(1, 3, 256, 256)
kernel = np.random.randn(3, 3, 3, 3)

print(conv2d(input_array=input_array, kernel=kernel).shape)
print('OK')

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值