Keras Models

In this page, we will learn What is keras models?, Keras Sequential Model, Getting started with the Keras Sequential model, Specifying the input shape, Compilation, Training, Stacked LSTM for Sequence Classification, Same Stacked LSTM model, Keras Functional API, First Example: A densely-connected network, Multi-input and multi-output models, and Shared layers.


The Model class

tf.keras.Model()

It is quite useful in integrating the layers into an object that includes aspects such as training and inference.

Arguments

  • inputs: It is defined as an input that is fed into the model. It might be an object of Input or a list of objects, for example, keras.Input. 
  • outputs: It is a reference to the model's output. 
  • name: It could be a string containing the model's name.

The models can be instantiated in the following two ways:

I. The first method will be accomplished with the use of a "Functional API." We will begin with the Input, then connect the layer calls to establish the model's forward pass, and then create the model by employing the inputs and outputs.

import tensorflow as tf

inputs = tf.keras.Input(shape=(3,))

x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs)

outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x)

model = tf.keras.Model(inputs=inputs, outputs=outputs)

II. The second method will be to subclass the Model class. In this case, we'll define layers in _init_first, then run the model's forward pass in the call.

import tensorflow as tf


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)


def call(self, inputs):

x = self.dense1(inputs)

return self.dense2(x)


model = MyModel()

While subclassing the Model, we can optionally include an optional training argument called Boolean in the call for specifying separate behavior in inference and training:

import tensorflow as tf


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)

self.dropout = tf.keras.layers.Dropout(0.5)


def call(self, inputs, training=False):

x = self.dense1(inputs)

if training:

x = self.dropout(x, training=training)

return self.dense2(x)


model = MyModel()

After constructing the model, we may configure it by including losses and metrics by model.compile(). The model can be trained using the model. fit() and model.predict() enable the model to make predictions.

summary method

Model.summary(line_length=None, positions=None, print_fn=None)

It can be used to print a string representation of the network's summary.

Arguments

  • line_length: It is defined as the total length of the printed lines. It can also be configured to display the window widths of different terminals. 
  • positions: It relates to the position of the log items in each line, which can be either relative or absolute. If it is not specified, it is set to [.33,.55,.67, 1.] as the default. 
  • print_fn: It can be used as a print function that defaults to print and is invoked on each line of the summary. It can be set to the custom function to capture the string summary.

Raises

  • ValueError: If we call summary() before constructing the model, we may get a value error.

get_layer method

Model.get_layer(name=None, index=None)

It aids in the retrieval of a layer based on its unique name or index. If both the name and the index are already provided, the index will take precedence, implying that the indices use a bottom-up strategy (horizontal traversal graph).

Arguments

  • name: It can be defined as a string containing the name of the layer. 
  • index: It is an integer that represents the layer's index.

returns

It generates a layer instance.

Raises

  • ValueError: A value error is generated if the layer has an erroneous name or index.