How can Keras be used to create a model where the input shape of model is specified in advance?

PythonServer Side ProgrammingProgrammingKeras

Tensorflow is a machine learning framework that is provided by Google. It is an open-source framework used in conjunction with Python to implement algorithms, deep learning applications and much more. It is used in research and for production purposes.

Keras was developed as a part of the research for the project ONEIROS (Open-ended Neuro-Electronic Intelligent Robot Operating System). Keras is a deep learning API, which is written in Python. It is a high-level API that has a productive interface that helps solve machine learning problems.

It runs on top of the Tensorflow framework. It was built to help experiment in a quick manner. It provides essential abstractions and building blocks that are essential in developing and encapsulating machine learning solutions.

It is highly scalable and comes with cross-platform abilities. This means Keras can be run on TPU orclusters of GPUs. Keras models can also be exported to run in a web browser or a mobile phone as well.

Keras is already present within the Tensorflow package. It can be accessed using the below line of code.

import tensorflow
from tensorflow import keras

We are using Google Colaboratory to run the below code. Google Colab or Colaboratory helps run Python code over the browser and requires zero configuration and free access to GPUs (Graphical Processing Units). Colaboratory has been built on top of Jupyter Notebook. Following is the code snippet −


print("Three dense layers are being created")
layer = layers.Dense(3)
print("The weights associated with the layers are")

print("The created layers is called on test data")
x = tf.ones((2, 3))
y = layer(x)
print("Now, the weights are : ")

Code credit −


Three dense layers are being created
The weights associated with the layers are
The created layers is called on test data
Now, the weights are :
[<tf.Variable 'dense_11/kernel:0' shape=(3, 3) dtype=float32, numpy=
array([[-0.9901273 , -0.70897937, -0.44804883],
   [ 0.6849613 , 0.5198808 , 0.48534775],
   [-0.07876515, -0.73648643, 0.44018626]], dtype=float32)>, <tf.Variable 'dense_11/bias:0'
shape=(3,) dtype=float32, numpy=array([0., 0., 0.], dtype=float32)>]


  • All layers in the Keras model requires to know the shape of the input so that the optimal weights can be created.

  • Initially, when a layer is created, it doesn’t have any weights associated with it.

  • Hence, it creates weights when it is called on input for the first time.

  • This is because the weights depend on the shape of the input.

  • The layers are created sequentially.

  • This is called on test data.

  • The weights associated with this new model is displayed on the console.

Published on 18-Jan-2021 10:53:44