title: How to save and restore a mode's weights with tf.keras.Model - TensorFlow 2.0 - Subclassing API
body: <p>In the examples <a href="https://www.tensorflow.org/api_docs/python/tf/keras/Model" rel="nofollow noreferrer">here</a> it mentions that one can subclass the class tf.keras.Model as follows: </p>
  
  <pre><code>class MyModel(tf.keras.Model):
  
      def __init__(self):
      super(MyModel, self).__init__()
      self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu)
      self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax)
  </code></pre>
  
  <p>However, what happens if I want to have a variable number of layers and also variable type of layers? How do I store my layer objects in my class object?</p>
  
  <p>From what I have understood the name that I give to the attributes (dense1, dense2) in the example above is significant because that will be used to refer to those layers and their variables when saving to a checkpoint, etc.? Is that correct?</p>
  
  <p><strong>My question is basically: How do I store my layers in my tf.keras.Model subclass if I don't know how many of them I have available? And then how do I save and restore the weights of those layers?</strong></p>
  
  <p>My first thought was to have lists of layer objects but then it is not obvious to me how those layer weights will be saved and restored since they will not correspond to distinct attribute names.</p>