Skip to content

Instantly share code, notes, and snippets.

@hvy
Created April 17, 2017 07:33
Show Gist options
  • Save hvy/b1f6bb0c4139d5e55a724b7e33d86bc0 to your computer and use it in GitHub Desktop.
Save hvy/b1f6bb0c4139d5e55a724b7e33d86bc0 to your computer and use it in GitHub Desktop.
Chainer Convolution2D and Deconvolution2D comparison
from chainer import Variable
from chainer import links as L
import numpy as np
# Compare single-channel Convolution2D with Deconvolution2D
h = 128
w = 128
x = np.arange(h * w, dtype=np.float32)
x = x.reshape(1, 1, h, w)
# Weights for both convolution and deconvolution
W = np.arange(3 * 3, dtype=np.float32)
size_preserving_paddings = (1, 1)
size_non_preserving_paddings = (2, 0)
paddings = [size_preserving_paddings, size_non_preserving_paddings]
for c_pad, dc_pad in paddings:
# Convolution
c = L.Convolution2D(1, 1, 3, stride=1, pad=c_pad)
c.W = Variable(W.reshape(1, 1, 3, 3).copy())
y_c = c(Variable(x))
# Deconvolution
dc = L.Deconvolution2D(1, 1, 3, stride=1, pad=dc_pad)
dc.W = Variable(W[::-1].reshape(1, 1, 3, 3).copy())
y_dc = dc(Variable(x))
y_c, y_dc = y_c.data, y_dc.data
assert(y_c.shape == y_dc.shape)
assert(np.array_equal(y_c, y_dc))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment