All Articles

TensorFlow 2 and Keras - Quick Start Guide

TL;DR Learn how to use Tensors, build a Linear Regression model and a simple Neural Network

TensorFlow 2.0 (final) was released at the end of September. Oh boy, it looks much cooler than the 1.x series. Why is it so much better for you, the developer?

  • One high-level API for building models (that you know and love) - Keras. The good news is that most of your old Keras code should work automagically after changing a couple of imports.
  • Eager execution - all your code looks much more like normal Python programs. Old-timers might remember the horrible Session experiences. You shouldn’t need any of that, in day-to-day use.

There are tons of other improvements, but the new developer experience is something that will make using TensorFlow 2 sweeter. What about PyTorch? PyTorch is still great and easy to use. But it seems like TensorFlow is catching up, or is it?

You’ll learn:

  • How to install TensorFlow 2
  • What is a Tensor
  • Doing Tensor math
  • Using probability distributions and sampling
  • Build a Simple Linear Regression model
  • Build a Simple Neural Network model
  • Save/restore a model

Run the complete code in your browser


Let’s install the GPU-supported version and set up the environment:

!pip install tensorflow-gpu

Check the installed version:

import tensorflow as tf


And specify a random seed, so our results are reproducible:




TensorFlow allows you to define and run operations on Tensors. Tensors are data-containers that can be of arbitrary dimension - scalars, vectors, matrices, etc. You can put numbers (floats and ints) and strings into Tensors.

Let’s create a simple Tensor:

x = tf.constant(1)
tf.Tensor(1, shape=(), dtype=int32)

It seems like our first Tensor contains the number 1, it is of type int32 and is shapeless. To obtain the value we can do:


Let’s create a simple matrix:

m = tf.constant([[1, 2, 1], [3, 4, 2]])
[[1 2 1]
 [3 4 2]], shape=(2, 3), dtype=int32)

This shape thingy seems to specify rows x columns. In general, the shape array shows how many elements are in every dimension of the Tensor.


TensorFlow offers a variety of helper functions for creating Tensors. Let’s create a matrix full of ones:

ones = tf.ones([3, 3])
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]], shape=(3, 3), dtype=float32)

and zeros:

zeros = tf.zeros([2, 3])
[[0. 0. 0.]
 [0. 0. 0.]], shape=(2, 3), dtype=float32)

We have two rows and three columns. What if we want to turn it into three rows and two columns:

tf.reshape(zeros, [3, 2])
[[0. 0.]
 [0. 0.]
 [0. 0.]], shape=(3, 2), dtype=float32)

You can use another helper function to replace rows and columns (transpose):

[[0. 0.]
 [0. 0.]
 [0. 0.]], shape=(3, 2), dtype=float32)

Tensor Math

Naturally, you would want to do something with your data. Let’s start with adding numbers:

a = tf.constant(1)
b = tf.constant(1)

tf.add(a, b).numpy()

That seems reasonable :) You can do the same thing using something more human friendly:

(a + b).numpy()

You can multiply Tensors like so:

c = a + b
c * c

And compute dot product of matrices:

d1 = tf.constant([[1, 2], [1, 2]]);
d2 = tf.constant([[3, 4], [3, 4]]);

tf.tensordot(d1, d2, axes=1).numpy()
array([[ 9, 12],
       [ 9, 12]], dtype=int32)


You can also generate random numbers according to some famous probability distributions. Let’s start with Normal:

norm = tf.random.normal(shape=(1000, 1), mean=0., stddev=1.)

We can do the same thing from the Uniform:

unif = tf.random.uniform(shape=(1000, 1), minval=0, maxval=100)

Let’s have a look at something a tad more exotic - the Poisson distribution. It is popular for modeling the number of times an event occurs in some time. It is the first one (in our exploration) that contains a hyperparameter - λ\lambda. It controls the number of expected occurrences.

pois = tf.random.poisson(shape=(1000, 1), lam=0.8)

The Gamma distribution is continuous. It has 2 hyperparameters that control the shape and scale. It is used to model always positive continuous variables with skewed distributions.

gam = tf.random.gamma(shape=(1000, 1), alpha=0.8)

Simple Linear Regression Model

Let’s build a Simple Linear Regression model to predict the stopping distance of cars based on their speed. The data comes from here: It is given by this Tensor:

data = tf.constant([

We can extract the two columns using slicing:

speed = data[:, 0]
stopping_distance = data[:, 1]

Let’s have a look at the data:

It seems like a linear model can do a decent job of predicting the stopping distance. Simple Linear Regression finds a straight line that predicts the variable of interest based on a single predictor/feature.

Time to build the model using the Keras API:

lin_reg = keras.Sequential([
  layers.Dense(1, activation='linear', input_shape=[1]),

optimizer = tf.keras.optimizers.RMSprop(0.001)


We’re using the Sequential API with a single layer - 1 parameter with linear activation. We’ll try to minimize the Mean squared error during training.

And for the training itself:

history =

We’re breaking any ordering issues by shuffling the data and reserving 20% for validation. Let’s have a look at the training process:

The model is steadily improving during training. That’s a good sign. What can we do with a more complex model?

Simple Neural Network Model

Keras (and TensorFlow) was designed as a tool to build Neural Networks. Turns out, Neural Networks are good when a linear model isn’t enough. Let’s create one:

def build_neural_net():
  net = keras.Sequential([
    layers.Dense(32, activation='relu', input_shape=[1]),
    layers.Dense(16, activation='relu'),

  optimizer = tf.keras.optimizers.RMSprop(0.001)

                metrics=['mse', 'accuracy'])

  return net

Things look similar, except for the fact that we stack multiple layers on top of each other. We’re also using a different activation function - ReLU.

Training this model looks exactly the same:

net = build_neural_net()

history =

Seems like we ain’t making much progress after epoch 200 or so. Can we not waste our time waiting for the whole training to complete?

Early Stopping

Sure, you can stop the training process manually at say epoch 200. But what if you train another model? What if you obtain more data?

You can use the built-in callback EarlyStopping to halt the training when some metric (e.g. the validation loss) stops improving. Let’s see how we can use it:

early_stop = keras.callbacks.EarlyStopping(

We want to monitor the validation loss. We’ll observe for improvement for 10 epochs before stopping. Let’s see how we can use it:

net = build_neural_net()

history =

Effectively, we’ve cut down the number of training epochs to ~120. Is this going to work every time that well? Not really. Using early stopping introduces yet another hyperparameter that you need to consider when training your model. Use it cautiously.

Now your model is ready for the real world. How can you store it for later use?

Save/Restore Model

You can save the complete model (including weights) like this:'simple_net.h5')

And load it like that:

simple_net = keras.models.load_model('simple_net.h5')

You can use this mechanism to deploy your model and use it in production (for example).


You did it! You now know (a tiny bit) TensorFlow 2! Let’s recap what you’ve learned:

  • How to install TensorFlow 2
  • What is a Tensor
  • Doing Tensor math
  • Using probability distributions and sampling
  • Build a Simple Linear Regression model
  • Build a Simple Neural Network model
  • Save/restore a model

Run the complete code in your browser

Stay tuned for more :)