{"id":8872,"date":"2021-03-11T17:09:02","date_gmt":"2021-03-11T11:39:02","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=8872"},"modified":"2025-09-30T07:03:59","modified_gmt":"2025-09-30T11:03:59","slug":"creating-deep-learning-model-with-keras","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/creating-deep-learning-model-with-keras\/","title":{"rendered":"Creating Deep Learning Model with Keras Functional API"},"content":{"rendered":"\n<p>In the last tutorial, it was said that there are two ways of creating deep learning models in Keras. The first was by using the sequential class where layers of the network are stacked on each other. Although these models are common amongst learners, they, however, have limitations. For instance, with the sequential model, the <a class=\"rank-math-link\" href=\"https:\/\/en.wikipedia.org\/wiki\/Deep_learning\" rel=\"nofollow noopener\" target=\"_blank\">Deep learning architecture<\/a> cannot be made to share two different layers or have more than one input or output. In real-life applications, this is a bottleneck.<\/p>\n\n\n\n<p>The good news is that the second method; using the functional API, solves this problem. The functional API gives room for more flexibility in the model architecture and is typically ideal for a more complex model. In this tutorial, we shall talk about the <a class=\"rank-math-link\" href=\"https:\/\/www.h2kinfosys.com\/blog\/how-to-install-keras-and-use-to-build-deep-neural-network\/\">Keras functional API<\/a> and go further to implement it using the same example in the last tutorial where the sequential model was used. By the end of this tutorial you will learn the following:<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Artificial Intelligence Introduction Class | Artificial Intelligence Tutorial For Beginners |\" width=\"800\" height=\"450\" src=\"https:\/\/www.youtube.com\/embed\/Vd3CLCyjesg?start=78&#038;feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Sequential Models&nbsp;<\/li>\n\n\n\n<li>Using the Keras Functional Models&nbsp;<\/li>\n\n\n\n<li>Using a Functional Model to Fit a Linear Regression Problem.&nbsp;<\/li>\n\n\n\n<li>Building a Model with Shared Input Layer<\/li>\n<\/ul>\n\n\n\n<p>Let\u2019s begin with an overview of the Sequential model.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Sequential Models&nbsp;<\/h2>\n\n\n\n<p>Keras sequential model API is used to build deep learning models that allow the different layers to be stacked upon each other sequentially.&nbsp; First, the sequential class must be instantiated then the layers are created and added to it. See an example below&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">model = Sequential()\nmodel.add(Dense(64, input_dim=1, activation='relu'))\nmodel.add(Dense(32, input_dim=1, activation='relu'))\nmodel.add(Dense(1, activation='linear'))\n<\/pre>\n\n\n\n<p>As seen in the code example above,&nbsp; the sequential class was instantiated with a variable name model.&nbsp; A fully connected layer with 64 nodes was added after which another fully connected layer with 32 nodes was added on top of the first hidden layer. Finally, the output layer with just one node was added. As explained earlier these kinds of models are not perfect for multiple input sources or output.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using the Keras Functional Models&nbsp;<\/h2>\n\n\n\n<p>The Functional Model is another way of creating a deep learning model in Keras. It allows you to create layers that can be reused and have shared inputs and output data. The functional model is typically used for creating a more sophisticated model. Using the Functional Model method can be done in three steps.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Define the input&nbsp;<\/h2>\n\n\n\n<p>When using the Functional model, you must first define the input layer as a standalone object and pass its shape. This is unlike the case in Sequential models where the shape of the input data is passed alongside the first hidden layer.&nbsp;<\/p>\n\n\n\n<p>The shape of the input data is a tuple of the number of features contained in the data. Note that the tuple must make room for the data splitting (in mini-batch size) that would take place during training. So for data with one feature, the shape is defined as (1, ).&nbsp;<\/p>\n\n\n\n<p>To define the input layer, the Input class must be imported from Keras layers.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from keras.layers import Input\n#define the input layer\ninput_layer = Input(shape=(1, ))\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2: Create and Connect the Layers.&nbsp;<\/h2>\n\n\n\n<p>The next step is to create the layers. When creating the layers, you will need to define the number of nodes the layer would have and importantly where the input data would come from. The input data is placed inside a bracket after defining the type of layer you wish to create. See the example below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&nbsp;from keras.layers import Input\n&nbsp;\n#define the hidden layers and the data to be received.&nbsp;\nhidden_1 = Dense(64)(input_layer)<\/pre>\n\n\n\n<p>Now, this is the interesting part. Because you define where the input data comes from for every created layer, you are at liberty to use shared data inputs\/outputs for different layers. Thus, making the possibilities with the Functional Models largely sophisticated.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Create the model<\/h2>\n\n\n\n<p>The final step is to create the model. The Model class has to be first imported from the models module of Keras. The class must then be instantiated, passing the inputs and outputs parameters as variable. The input parameters are the input layer already defined while the output data is the last hidden layer of the model.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from keras.models import Model\nmodel = Model(inputs=input_layer, outputs=hidden_1)<\/pre>\n\n\n\n<p>The model can then be created and trained on the data. Let\u2019s take an example.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using a Functional Model to Fit a Linear Regression Problem.&nbsp;<\/h2>\n\n\n\n<p>In the last tutorial, we built a Sequential model to be trained on data points and produced the line of best fit. Here, we will do the same with a Function model with Keras. Let\u2019s begin by importing the necessary libraries.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#import the necessary libraries\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Dropout<\/pre>\n\n\n\n<p>Next is to create the dataset.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#define a random seed\nnp.random.seed(42)\n&nbsp;\n#create random points for the x and y axis from 0 to 20\nxs = np.linspace(0, 20, 50)\nys = np.linspace(20, 0, 50)\n&nbsp;\n# add some positive and negative noise on the y axis\nys += np.random.uniform(-2, 2, 50)\n&nbsp;\n#plot the graph\nplt.plot(xs, ys, '.');<\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/yeFJ9VQu0ZMV8Lx1wxAPPz0nOe2jcU8yqKwDMgnOd8hE8MGELOI3mAzZjrDiVnSiJhS4mNN4e1AKcJ2cs5LE4BVvm92mgY3Bxt3uSZqpNbSG3dUkCJrdvfmP-CJ5Zbana5npduI\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>Next is to build the model. Remember that the Input layer has to be instantiated with the shape of the expected data, Then the other hidden layers will be defined and called on the data it is expected to receive. The model architecture is built in the code below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#create the input layer\ninput_layer = Input(shape=(1, ))\n&nbsp;\n#create the other hidden layers and the output layer\nhidden_1 = Dense(64, activation='relu')(input_layer)\nhidden_2 = Dense(32, activation='relu')(hidden_1)\noutput = Dense(1, activation='linear')(hidden_2)<\/pre>\n\n\n\n<p>Finally, the Model class is instantiated receiving the already defined input layer and output layer as arguments.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">model = Model(inputs=input_layer, outputs=output)<\/pre>\n\n\n\n<p>Before going ahead to train the model, we can visualize the model architecture using the plot_model module of keras.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from keras.utils import plot_model\n&nbsp;\nplot_model(model)\n<\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/wCGs-uc0soQfAgH0KCJy0PJ_yNCzQhLRDI39RPidq9B9A6QMC--1HI8sGvb4G4vBNzs_8FI4Aaz0AZNp643uWIp0-i8V8VwaO9q6YxePav4SCRP_GdigLmxWP9FsW6l1Qp5sp1w\" alt=\"\" title=\"\"><\/figure>\n<\/div>\n\n\n<p>As seen, the model has an input layer, two fully connected layers and an output layer. You can get more information about the model architecture by using the summary() method.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">model.summary()<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Output:\nModel: \"model\"\n<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-large\"><img fetchpriority=\"high\" decoding=\"async\" width=\"584\" height=\"214\" src=\"https:\/\/www.h2kinfosys.com\/blog\/wp-content\/uploads\/2021\/03\/image-8.png\" alt=\"\" class=\"wp-image-8876\" title=\"\" srcset=\"https:\/\/www.h2kinfosys.com\/blog\/wp-content\/uploads\/2021\/03\/image-8.png 584w, https:\/\/www.h2kinfosys.com\/blog\/wp-content\/uploads\/2021\/03\/image-8-300x110.png 300w\" sizes=\"(max-width: 584px) 100vw, 584px\" \/><\/figure>\n\n\n\n<p>Total params: 2,241<br>Trainable params: 2,241<br>Non-trainable params: 0<br>The model can finally be compiled and trained.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">model.compile(optimizer='adam', loss='mse')\nhistory = model.fit(xs, ys, epochs=200)<\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Epoch 1\/200\n2\/2 [==============================] - 1s 6ms\/step - loss: 122.2916\nEpoch 2\/200\n2\/2 [==============================] - 0s 15ms\/step - loss: 122.3255\nEpoch 3\/200\n2\/2 [==============================] - 0s 5ms\/step - loss: 109.8412\nEpoch 4\/200\n2\/2 [==============================] - 0s 10ms\/step - loss: 113.5361\nEpoch 5\/200\n...\nEpoch 196\/200\n2\/2 [==============================] - 0s 10ms\/step - loss: 3.6998\nEpoch 197\/200\n2\/2 [==============================] - 0s 10ms\/step - loss: 4.8764\nEpoch 198\/200\n2\/2 [==============================] - 0s 5ms\/step - loss: 4.6869\nEpoch 199\/200\n2\/2 [==============================] - 0s 5ms\/step - loss: 4.5548\nEpoch 200\/200\n2\/2 [==============================] - ETA: 0s - loss: 2.816 - 0s 0s\/step - loss: 3.6678<\/pre>\n\n\n\n<p>The prediction can then be made and the line plotted.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#model makes prediction\ny_pred = model.predict(xs)\n&nbsp;\n#plot the graph\nplt.plot(xs, y_pred, 'k', label='Predicted')\nplt.scatter(xs, ys, label='True')\nplt.legend()\nplt.xlabel('X Axis')\nplt.ylabel('Y Axis')\nplt.title('A plot to show the prediction of the model')\n;\n<\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh4.googleusercontent.com\/qvXeJls4y-cRmeen9vJqNYcS48KqeekGNaQ_D-ogYpVdafv2dBBUaJbGu8nX-nxfHTY6pvdiDAznbpmWHnyXlBeLk0Sgq96QnLc985nyD5jvcC2BQndo96GR2lvOTRILZ56Jr0s\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>This is a pretty decent result.&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Building a Model with Shared Input Layer<\/h2>\n\n\n\n<p>The Functional API model particularly shines when you wish to share the data on different layers or have multiple inputs and outputs. If we wish to build a model that shares its input layer, we just need to call the input layer function to different hidden layers. Then you can concatenate it with the concatenate sub-module in Keras. See an example below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from keras.layers import merge\n#create the input layer\ninput_layer = Input(shape=(1, ))\n&nbsp;\n#create two hidden layers with shared input layer\nhidden_1 = Dense(64, activation='relu')(input_layer)\nhidden_2 = Dense(64, activation='relu')(input_layer)\n&nbsp;\n#merge the two layers&nbsp;\nmerged_layers = merge.concatenate([hidden_1, hidden_2])\n&nbsp;\n#built the rest of the layers\nhidden_3 = Dense(32, activation='relu')(merged_layers)\noutput = Dense(1, activation='linear')(hidden_3)\n&nbsp;\nmodel = Model(inputs=input_layer, outputs=output)\n<\/pre>\n\n\n\n<p>Let\u2019s visualize what the model looks like<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">from keras.utils import plot_model\nplot_model(model)<\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/6CWTY7ZZ2E0p_H-fc_Lw5gtOY-Gt5AeTEqO_0LEAhYA1vxvhuHg96spkzWcxhXxEW8qfwZPYfaOHJ6CVSo4Hf_UlWQJm2V09K0EPVexJqC47-vuGOU-4zU42AA4-RXIatbpjZ7c\" alt=\"\" style=\"width:258px;height:395px\" title=\"\"><\/figure>\n<\/div>\n\n\n<p>We can also check its summary.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">model.summary()<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Model: \"model\"\n__________________________________________________________________________________________________\nLayer (type)                    Output Shape         Param #     Connected to                     \n==================================================================================================\ninput_1 (InputLayer)            &#91;(None, 1)]          0                                            \n__________________________________________________________________________________________________\ndense (Dense)                   (None, 64)           128         input_1&#91;0]&#91;0]                    \n__________________________________________________________________________________________________\ndense_1 (Dense)                 (None, 64)           128         input_1&#91;0]&#91;0]                    \n__________________________________________________________________________________________________\nconcatenate (Concatenate)       (None, 128)          0           dense&#91;0]&#91;0]                      \n                                                                 dense_1&#91;0]&#91;0]                    \n__________________________________________________________________________________________________\ndense_2 (Dense)                 (None, 32)           4128        concatenate&#91;0]&#91;0]                \n__________________________________________________________________________________________________\ndense_3 (Dense)                 (None, 1)            33          dense_2&#91;0]&#91;0]                    \n==================================================================================================\nTotal params: 4,417\nTrainable params: 4,417\nNon-trainable params: 0<\/code><\/pre>\n\n\n\n<p>Running this model also produces good results.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">model.compile(optimizer='adam', loss='mse')\nhistory = model.fit(xs, ys, epochs=200)<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Output:\nEpoch 1\/200\n2\/2 &#91;==============================] - 1s 5ms\/step - loss: 108.9526\nEpoch 2\/200\n2\/2 &#91;==============================] - 0s 5ms\/step - loss: 105.3066\nEpoch 3\/200\n2\/2 &#91;==============================] - 0s 5ms\/step - loss: 99.1887\nEpoch 4\/200\n2\/2 &#91;==============================] - 0s 10ms\/step - loss: 108.9373\nEpoch 5\/200\n2\/2 &#91;==============================] - 0s 5ms\/step - loss: 103.2374\n...\nEpoch 196\/200\n2\/2 &#91;==============================] - 0s 5ms\/step - loss: 4.4243\nEpoch 197\/200\n2\/2 &#91;==============================] - 0s 5ms\/step - loss: 3.9060\nEpoch 198\/200\n2\/2 &#91;==============================] - 0s 5ms\/step - loss: 4.6090\nEpoch 199\/200\n2\/2 &#91;==============================] - 0s 5ms\/step - loss: 3.5898\nEpoch 200\/200\n2\/2 &#91;==============================] - 0s 0s\/step - loss: 3.4363<\/code><\/pre>\n\n\n\n<p>Now, we can plot the predicted values of the model<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">y_pred = model.predict(xs)\nk\nplt.plot(xs, y_pred, 'k', label='Predicted')\nplt.scatter(xs, ys, label='True')\nplt.legend()\nplt.xlabel('X Axis')\nplt.ylabel('Y Axis')\nplt.title('A plot to show the prediction of the model')\n;\n<\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh4.googleusercontent.com\/cS9i17ajDNRRqpZPzyWmbIdsba-DddFwjb4q3uFzDppRFtThJ6zrIPEUv03Qi_8MLOYQ7mDnJo3iNPupTdrZKBh4Lxu53pmOV4v0n7hbzTrcu9m14E5dAzZvlYFoKB2JGuJDf10\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">In summary,&nbsp;<\/h2>\n\n\n\n<p>We have explained how to use this Functional API in Keras. You learned that using this model creates more flexibility in building the architecture of the model and overall its performance. This is why it is mostly used in more complex situations than the sequential model. If you have any questions as to how the model was created, please leave them in the comment section and I\u2019d do my best to answer them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Deep learning is evolving rapidly, and professionals must keep pace. The <strong>Keras Functional API<\/strong> bridges the gap between theory and real-world AI applications by allowing us to build flexible, production-grade models. Whether you are learning independently or pursuing an <strong><a href=\"https:\/\/www.h2kinfosys.com\/courses\/artificial-intelligence-online-training-course-details\/\">Artificial intelligence certification<\/a> online<\/strong>, mastering this API will give you a competitive edge.<\/p>\n\n\n\n<p>If your career goal involves earning an <strong>AI course certification<\/strong>, adding Functional API projects to your portfolio is a strategic move. It not only proves your technical skill but also your readiness to solve real-world business problems with AI.<br><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the last tutorial, it was said that there are two ways of creating deep learning models in Keras. The first was by using the sequential class where layers of the network are stacked on each other. Although these models are common amongst learners, they, however, have limitations. For instance, with the sequential model, the [&hellip;]<\/p>\n","protected":false},"author":10,"featured_media":8879,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[498],"tags":[],"class_list":["post-8872","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-artificial-intelligence-tutorials"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/8872","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/10"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=8872"}],"version-history":[{"count":1,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/8872\/revisions"}],"predecessor-version":[{"id":30168,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/8872\/revisions\/30168"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/8879"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=8872"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=8872"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=8872"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}