`Model` groups layers into an object with training and inference features. There are two ways to instantiate a `Model`: 1 - With the "functional API", where you start from `Input`, you chain layer calls to specify the model's forward pass, and finally you create your model from inputs and
| 80 | |
| 81 | @keras_export('keras.models.Model', 'keras.Model') |
| 82 | class Model(network.Network): |
| 83 | """`Model` groups layers into an object with training and inference features. |
| 84 | |
| 85 | There are two ways to instantiate a `Model`: |
| 86 | |
| 87 | 1 - With the "functional API", where you start from `Input`, |
| 88 | you chain layer calls to specify the model's forward pass, |
| 89 | and finally you create your model from inputs and outputs: |
| 90 | |
| 91 | ```python |
| 92 | import tensorflow as tf |
| 93 | |
| 94 | inputs = tf.keras.Input(shape=(3,)) |
| 95 | x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs) |
| 96 | outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x) |
| 97 | model = tf.keras.Model(inputs=inputs, outputs=outputs) |
| 98 | ``` |
| 99 | |
| 100 | 2 - By subclassing the `Model` class: in that case, you should define your |
| 101 | layers in `__init__` and you should implement the model's forward pass |
| 102 | in `call`. |
| 103 | |
| 104 | ```python |
| 105 | import tensorflow as tf |
| 106 | |
| 107 | class MyModel(tf.keras.Model): |
| 108 | |
| 109 | def __init__(self): |
| 110 | super(MyModel, self).__init__() |
| 111 | self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) |
| 112 | self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) |
| 113 | |
| 114 | def call(self, inputs): |
| 115 | x = self.dense1(inputs) |
| 116 | return self.dense2(x) |
| 117 | |
| 118 | model = MyModel() |
| 119 | ``` |
| 120 | |
| 121 | If you subclass `Model`, you can optionally have |
| 122 | a `training` argument (boolean) in `call`, which you can use to specify |
| 123 | a different behavior in training and inference: |
| 124 | |
| 125 | ```python |
| 126 | import tensorflow as tf |
| 127 | |
| 128 | class MyModel(tf.keras.Model): |
| 129 | |
| 130 | def __init__(self): |
| 131 | super(MyModel, self).__init__() |
| 132 | self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) |
| 133 | self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) |
| 134 | self.dropout = tf.keras.layers.Dropout(0.5) |
| 135 | |
| 136 | def call(self, inputs, training=False): |
| 137 | x = self.dense1(inputs) |
| 138 | if training: |
| 139 | x = self.dropout(x, training=training) |
no outgoing calls