Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Tensorflow Layers in Keras

I've been trying to build a sequential model in Keras using the pooling layer tf.nn.fractional_max_pool. I know I could try making my own custom layer in Keras, but I'm trying to see if I can use the layer already in Tensorflow. For the following code snippet:

p_ratio=[1.0, 1.44, 1.44, 1.0]

model = Sequential()
model.add(ZeroPadding2D((2,2), input_shape=(1, 48, 48)))
model.add(Conv2D(320, (3, 3), activation=PReLU()))
model.add(ZeroPadding2D((1,1)))
model.add(Conv2D(320, (3, 3), activation=PReLU()))
model.add(InputLayer(input_tensor=tf.nn.fractional_max_pool(model.layers[3].output, p_ratio)))

I get this error. I've tried some other things with Input instead of InputLayer and also the Keras Functional API but so far no luck.

like image 263
Bart C Avatar asked Jul 08 '17 22:07

Bart C


1 Answers

Got it to work. For future reference, this is how you would need to implement it. Since tf.nn.fractional_max_pool returns 3 tensors, you need to get the first one only:

model.add(InputLayer(input_tensor=tf.nn.fractional_max_pool(model.layers[3].output, p_ratio)[0]))

Or using Lambda layer:

def frac_max_pool(x):
    return tf.nn.fractional_max_pool(x,p_ratio)[0]

With the model implementation being:

model.add(Lambda(frac_max_pool))
like image 144
Bart C Avatar answered Nov 15 '22 02:11

Bart C