How do I "flatten" a nested model?

1,174 views
Skip to first unread message

Isaac Gerg

unread,
Nov 16, 2016, 3:04:34 PM11/16/16
to Keras-users
I have a model built with the functional API which is composed of other models.  This breaks some tools which analyze keras graphs.  Is there a function in keras which allows me to "flatten" these nested models so that when I do a model.layers, the list does not contain any keras.models?

Isaac

fabia...@googlemail.com

unread,
Jan 27, 2017, 5:23:35 AM1/27/17
to Keras-users
Hi Isaac,

I just had the same problem. Here is my solution for only one level of nesting. For multiple levels of nesting you could use recursion of course.

layers_flat = []
for layer in  model_nested.layers:
    try:
        layers_flat.extend(layer.layers)
    except AttributeError:
        layers_flat.append(layer)

model_flat = Sequential(layers_flat)


Fabian

Isaac Gerg

unread,
Jan 27, 2017, 11:13:20 AM1/27/17
to Keras-users, fabia...@googlemail.com
Thank you.  
Reply all
Reply to author
Forward
0 new messages