How to create amazing Tensorflow model in few lines of code

Shivam Agarwal
2 min readNov 14, 2022


Photo by Umberto on Unsplash

Although TensorFlow looks very hare but it is very easy to create a machine learning model using this library in very easy and few steps. In this tutorial I will share how to create a machine learning model in minimum lines of code

  1. What is Tensoflow: It is open source library mainly designed to handle large scale machine learning. It has state of the arts function and capability to handle end to end machine learning tasks.
  2. Why are we using TensorFlow: It is one of the most popular library used for deep learning task at enterprise level. It is very easy to learn and implement
  3. Steps to create model : You need to follow below simple steps to create your first deep learning model in TensorFlow
  • Importing the libraries: We need to import TensorFlow library in python. If TensorFlow is not installed you can use pip install tensorflow
import tensorflow as tf
  • Downloading the data: In this tutorial we are going to use inbuilt data set available in tensorflow. The MNIST database of handwritten digits, has a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a larger set available from NIST. The digits have been size-normalized and centered in a fixed-size image.
mnist = tf.keras.datasets.mnist
  • Transforming the data : To check the accuracy of our model we need to divide the dataset in two parts training set and test set.

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

  • Building the model : In this step we are creating the architecture of deep learning model. We are building a Sequential model with Flat and Dense layer. (You can play with the layers and see the impact on accuracy)

First layer is Flatten layer that will transform the input matrix [28*28] into flat array

Second layer will be Dense layer with ‘relu’ activation function

Third is also a dense layer. This layer also works as output layer

model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
  • Training the model : Lets train the model on the training dataset. You can select less epochs if you want to train your model fast. The accuracy may be impacted with less epochs., y_train, epochs=5)
  • Checking the accuracy of model : Now it is time to evaluate the accuracy of your model.
model.evaluate(x_test,  y_test, verbose=2)

That’s it. Kudos to you. You have created your first deep learning model



Shivam Agarwal

Shivam is an accomplished analytics professional and algo trader, sharing expertise in algo trading, data science, and AI through insightful publications.