我如何在纽比为CNN实现反褶积层?

2024-09-21 03:18:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试为卷积网络实现反褶积层。我所说的反褶积是指,假设我有3x227x227输入图像到一个带有大小为3x11x11和步长为4的过滤器的层。因此,生成的特征映射的大小为55x55。我尝试做的是应用反向操作,我将55x55特征映射投影到3x227x227图像。基本上,55x55特征图上的每个值都由3x11x11过滤器加权并投影到图像空间,并对由于步长而产生的重叠区域进行平均。在

我试图用numpy实现它,但没有成功。我找到了一个用强力嵌套for循环的解决方案,但速度太慢了。如何在numpy中有效地实现它?欢迎任何帮助。在


Tags: 图像网络numpy区域过滤器for空间特征
1条回答
网友
1楼 · 发布于 2024-09-21 03:18:47

正如在this question中所讨论的,反褶积只是一个卷积层,但是有特定的填充、步长和滤波器大小的选择。在

例如,如果您当前的图像大小是55x55,那么您可以应用padding=20stride=1和{}的卷积来获得75x75图像,然后95x95依此类推。(我不是说这个数字的选择给出了输出图像的期望质量,只是大小。实际上,我认为从227x227向下采样到55x55然后再向上采样到227x227太激进了,但您可以自由尝试任何架构)。在

以下是任何步幅和填充的向前传球的实现。它使用im2col transformation,但是使用numpy中的stride_tricks。它不像现代GPU实现那样优化,但绝对比4 inner loops更快:

import numpy as np

def conv_forward(x, w, b, stride, pad):
  N, C, H, W = x.shape
  F, _, HH, WW = w.shape

  # Check dimensions
  assert (W + 2 * pad - WW) % stride == 0, 'width does not work'
  assert (H + 2 * pad - HH) % stride == 0, 'height does not work'

  # Pad the input
  p = pad
  x_padded = np.pad(x, ((0, 0), (0, 0), (p, p), (p, p)), mode='constant')

  # Figure out output dimensions
  H += 2 * pad
  W += 2 * pad
  out_h = (H - HH) / stride + 1
  out_w = (W - WW) / stride + 1

  # Perform an im2col operation by picking clever strides
  shape = (C, HH, WW, N, out_h, out_w)
  strides = (H * W, W, 1, C * H * W, stride * W, stride)
  strides = x.itemsize * np.array(strides)
  x_stride = np.lib.stride_tricks.as_strided(x_padded,
                                             shape=shape, strides=strides)
  x_cols = np.ascontiguousarray(x_stride)
  x_cols.shape = (C * HH * WW, N * out_h * out_w)

  # Now all our convolutions are a big matrix multiply
  res = w.reshape(F, -1).dot(x_cols) + b.reshape(-1, 1)

  # Reshape the output
  res.shape = (F, N, out_h, out_w)
  out = res.transpose(1, 0, 2, 3)
  out = np.ascontiguousarray(out)
  return out

相关问题 更多 >

    热门问题