Unflattening Layer in Keras

Viewed 2270

I would like to create a simple Keras neural network that accepts an input matrix of dimension (rows, columns) = (n, m), flattens the matrix to a dimension (n*m, 1), sends the flattened matrix through a number of arbitrary layers, and in the final layer, once more unflattens the matrix to a dimension of (n, m) before releasing this final matrix as an output.

The issue I'm having is that I haven't found any documentation for an Unflatten layer at the keras.io page, and I'm wondering whether there is a reason that such a seemingly standard common use layer doesn't exist. Is there a much more natural and easy way to do what I'm proposing?

1 Answers

You can use the Reshape layer for this purpose. It accepts the desired output shape as its argument and would reshape the input tensor to that shape. For example:

from keras.layers import Reshape

rsh_inp = Reshape((n*m, 1))(inp)  # if you don't want the last axis with dimension 1, you can also use Flatten layer

# rsh_inp goes through a number of arbitrary layers ...

# reshape back the output
out = Reshape((n,m))(out_rsh_inp)
Related