Skip to content

Instantly share code, notes, and snippets.

@stes
Last active January 10, 2017 10:14
Show Gist options
  • Save stes/1777c9e5f4c7e6114b2751fda9fd3c39 to your computer and use it in GitHub Desktop.
Save stes/1777c9e5f4c7e6114b2751fda9fd3c39 to your computer and use it in GitHub Desktop.
Bilinear Upsampling in Lasagne
import theano
import lasagne
import numpy as np
def upsample(layer, nb_kernels):
def build_bilinear_kernel(ratio):
half_kern = np.arange(1, ratio + 1)
kern = np.concatenate([half_kern, half_kern[-2::-1]])
kern = kern / ratio
kern = kern[:,np.newaxis] * kern[np.newaxis, :]
return kern
kernel = build_bilinear_kernel(ratio=2)
kernel_shape = (nb_kernels, nb_kernels) + kernel.shape
W_init = np.zeros(kernel_shape)
W_init[range(nb_kernels), range(nb_kernels), :, :] = kernel
W_init = np.float32(W_init)
return lasagne.layers.TransposedConv2DLayer(layer, nb_kernels, 3, stride=(2, 2), W=W_init, b=None, nonlinearity=None)
if __name__ == '__main__':
from scipy.misc import face
from pylab import *
inp = theano.tensor.tensor4()
l = lasagne.layers.InputLayer((1,3,256,342),inp)
l = upsample(l, 3)
print("Output shape:", lasagne.layers.get_output_shape(l))
fn = theano.function([inp], lasagne.layers.get_output(l), allow_input_downcast=True)
X = face()[np.newaxis,::3,::3].transpose((0,3,1,2))
img = fn(X)[0,...].transpose((1,2,0))
imshow(img/255.)
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment