Being new to theano, pls bear with me. I thought the shape of the tensor variable is already well defined out of the Conv2D layer since the input is specified, as follow,

from keras.layers import Input, Convolution2D
import theano
input_img = Input(shape=(1, 28, 28))
x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')   (input_img)
print type(x)
print theano.tensor.shape(x)

But the output is,

<class 'theano.tensor.var.TensorVariable'>

Since I'm taking the default stride of 1, and same border mode here means that padding is added so the output is the same as input. Using this information I could calculate by hand what the output shape should be.

Did I miss something here? The question is how to get the shape of the output of a convolution layer?


1 Answer 1


You can't get the shape of a theano tensor, because it is not fixed. The output of the convolutional layer is just a symbolic variable and its shape depends on whatever you put into the layer as input.

You can get the shape of the output for a specific input by making a theano function for the output of the layer, and feeding a numpy array through the function:

import numpy as np
input = np.ones(28*28).reshape(1, 1, 28, 28).astype('float32')
fn = theano.function([input_img], x)

print fn(input).shape
>>> (1, 16, 28, 28)
  • $\begingroup$ So you're saying that despite the fact the input is already sized in input_img, x still has no information about its output? That's kind of strange. But I got the point that it must come thru a function for it to be a real thing. $\endgroup$
    – horaceT
    Dec 21, 2016 at 0:01
  • $\begingroup$ Oh, something else's wrong. I use the same input as yours above, but get `(1, 1, 28, 16)' ? $\endgroup$
    – horaceT
    Dec 21, 2016 at 0:21
  • $\begingroup$ Defining the shape as (1, 28, 28) for the input layer, and defining the number and size of the filters for the conv layer is just a keras thing, theano still doesn't know about the shape until actual data is passed through. As for your different output, I'm not sure what could be causing that. I've just retried both code snippets and I'm still getting (1, 16, 28, 28) as the output. Can you post your entire code that is giving the wrong output? $\endgroup$ Dec 21, 2016 at 1:00
  • 1
    $\begingroup$ Turns out dim_ordering in Convolution2D is defaulted to tensorflow , while I'm using theano. Once set to th, it comes out right. $\endgroup$
    – horaceT
    Dec 21, 2016 at 2:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.