Search code examples
tensorflowkeraskeras-layer

How to flat the tensor in keras?


I have a tensor named words_conv_bigram_pool which is in the shape of (?, 1, 1, 64), ? is the batch size. I try to flatten the tensor to be (?, 64) by Flatten()(words_conv_bigram_pool), but it returns the shape of (?,?).

>>> Flatten()(words_conv_bigram_pool)
WARNING:tensorflow:From /home/xuemeng.cyn/anaconda2/lib/python2.7/site-packages/keras/backend/tensorflow_backend.py:1264: calling reduce_prod (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.
Instructions for updating:
keep_dims is deprecated, use keepdims instead
<tf.Tensor 'flatten_1/Reshape:0' shape=(?, ?) dtype=float32>

What happened and how to use the flatten function in keras?


Solution

  • Don't care much about "tensorflow shapes", care about "keras shapes". It's common to see such ? tensorflow dimensions when you're using keras.

    If you add this flatten layer to your model and then do a model.summary(), you will see the desired shape.

    If you're not using a "keras model", but only want to remove the additional dimensions, you can try tf.squeeze.