【问题标题】:Convolutional layer in Python using Numpy - with StridesPython 中使用 Numpy 的卷积层 - 使用 Strides
【发布时间】:2020-12-26 22:49:30
【问题描述】:

我的问题与这个问题高度相关,我从中复制了定义:Convolutional layer in Python using Numpy

我正在尝试使用 Numpy 在 Python 中实现卷积层。输入是一个形状为 [N, H, W, C] 的 4 维数组,其中:

  • N:批量大小
  • H:图像高度
  • W:图片宽度
  • C:编号 频道数

卷积滤波器也是一个形状为 [F, F, Cin, Cout] 的 4 维数组,其中

  • F:方形滤镜的高度和宽度
  • Cin:输入通道数 (Cin = C)
  • Cout:输出通道数

没有填充且步幅为 S,输出应为形状为 [N, (H - F + 1) // S, (W - F + 1) // S, Cout] 的 4 维数组.

对于 S=1 的固定步幅,可以使用以下代码有效地完成此操作:

from numpy.lib.stride_tricks import as_strided

def conv2d(a, b):
    Hout = a.shape[1] - b.shape[0] + 1
    Wout = a.shape[2] - b.shape[1] + 1

    a = as_strided(a, (a.shape[0], Hout, Wout, b.shape[0], b.shape[1], a.shape[3]), a.strides[:3] + a.strides[1:])

    return np.tensordot(a, b, axes=3)

谁能帮助我了解如何实现 S 的可变步幅?如上所述,我了解输出形状,而不是步幅。

【问题讨论】:

  • 可变步幅是什么意思?只是另一个值而不是 1?
  • 是的,完全正确!我想让它适用于任何有效的 S 值
  • 要回答这个问题,我会制作一个较小的 a,并在 as_strided 中尝试一些替代形状和步幅。虽然我在这方面有一些经验,但距离我必须将推理与试错结合起来。
  • 你有机会试一试吗?我正在使形状起作用,但不是值

标签: python arrays numpy conv-neural-network stride


【解决方案1】:

您可以使用以下实现。参数s 表示步幅值。

from numpy.lib.stride_tricks import as_strided

def conv2d(a, b, s=1):
    Hout = (a.shape[1] - b.shape[0]) // s + 1
    Wout = (a.shape[2] - b.shape[1]) // s + 1
    Stride = (a.strides[0], a.strides[1] * s, a.strides[2] * s, a.strides[1], a.strides[2], a.strides[3])

    a = as_strided(a, (a.shape[0], Hout, Wout, b.shape[0], b.shape[1], a.shape[3]), Stride)

    return np.tensordot(a, b, axes=3)

# test
conv2d(x, kernel, 2)

【讨论】:

    猜你喜欢
    • 2019-09-28
    • 2021-02-11
    • 1970-01-01
    • 2011-01-27
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2016-08-02
    相关资源
    最近更新 更多