How to create functional model in TensorFlow

The Keras functional API is a way to create models that are more flexible than the tf.keras.Sequential API. The functional API can handle models with non-linear topology, shared layers, and even multiple inputs or outputs.
Creating functional model using functional API

Create an input node, having image input with a shape of (32, 32, 3)


import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

img_inputs = keras.Input(shape=(32, 32, 3))

Create a new node in the graph of layers by calling a layer on input object from the previous step


dense = layers.Dense(64, activation="relu")
x = dense(inputs)

Add a few more layers to the graph of layers


x = layers.Dense(64, activation="relu")(x)
outputs = layers.Dense(10)(x)

Now create a Model by specifying its inputs and outputs


model = keras.Model(inputs=inputs, outputs=outputs, name="sample_model")

View the model summary


model.summary()

### Output ###
Model: "sample_model"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         [(None, 784)]             0
_________________________________________________________________
dense (Dense)                (None, 64)                50240
_________________________________________________________________
dense_1 (Dense)              (None, 64)                4160
_________________________________________________________________
dense_2 (Dense)              (None, 10)                650
=================================================================
Total params: 55,050
Trainable params: 55,050
Non-trainable params: 0
_________________________________________________________________


Follow US on Twitter: