Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of a sequential model to a functional model with Keras 2.2.0

Tags:

python

keras

Up to Keras version 2.1.6 one was able to "convert" a sequential model to a functional model by accessing the underlying model.model. Since version 2.2.0 this is no longer possible.

Can it still be done in some other way?

(In case you wonder why I would like to do something like this, I'm maintaining a library that relies on this conversion. :wink:)

like image 863
Tobias Hermann Avatar asked Jun 13 '18 12:06

Tobias Hermann


2 Answers

I can't test this solution right now since I don't have Keras 2.2.0 installed, but I think it should work. Let's assume your sequential model is stored in seqmodel:

from keras import layers, models

input_layer = layers.Input(batch_shape=seqmodel.layers[0].input_shape)
prev_layer = input_layer
for layer in seqmodel.layers:
    prev_layer = layer(prev_layer)

funcmodel = models.Model([input_layer], [prev_layer])

This should give the equivalent functional model. Let me know if I am mistaken.

like image 174
today Avatar answered Sep 17 '22 10:09

today


There is no need for conversion anymore because Sequential is now a subclass of Model hence it is already a model. Before it used to be a wrapper presumably that is why you are asking. From the source code:

class Sequential(Model):
  # ...
  @property
  def model(self):
    # Historically, `Sequential` was once
    # implemented as a wrapper for `Model` which maintained
    # its underlying `Model` as the `model` property.
    # We keep it for compatibility reasons.
    warnings.warn('`Sequential.model` is deprecated. '
                  '`Sequential` is a subclass of `Model`, you can '
                  'just use your `Sequential` instance directly.')
    return self

Whatever you can do with a model you can also do with Sequential, it only adds extra functionality like .add function for ease of use. You can just ignore those extra functions and use the object as if it's a functional model.

like image 22
nuric Avatar answered Sep 19 '22 10:09

nuric