TensorFlow With Keras (Part 2)

This article is in continuation to Part 1, Tensorflow for deep learning. Make sure you go through it for a better understanding of this case study.

Keras is a high-level neural network API written in Python and capable of running on top of Tensorflow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation. In this article, we are going to cover one small case study for fashion mnist.

Fashion-MNIST is a dataset of Zalando’s article images consisting of a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28×28 grayscale image, associated with a label from 10 classes. Zalando intends Fashion-MNIST to serve as a direct drop-in replacement for the original MNIST dataset for benchmarking machine learning algorithms. It shares the same image size and structure of training and testing splits.


Each training and test example is assigned to one of the following labels:

  • 0 T-shirt/top
  • 1 Trouser
  • 2 Pullover
  • 3 Dress
  • 4 Coat
  • 5 Sandal
  • 6 Shirt
  • 7 Sneaker
  • 8 Bag
  • 9 Ankle boot

1)  First load required packages

import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

2) Load the dataset

…which will be downloaded the data set to your system

fashon_mnist = keras.datasets.fashion_mnist
(train_images,train_labeks),(test_images,test_labels) = fashon_mnist.load_data()

3) Visualization for the first few rows

Let’s plot some samples for the images. We add labels to the train set images with the corresponding fashion item category.

for i in range(10): plt.figure() plt.imshow(train_images[i]) plt.colorbar() plt.grid(False) plt.show() train_images = test_images/255.0
test_images = test_images/255.0
plt.figure(figsize=(10,10)) class_name = ['T-shirt/top','Trouser','Pullovers','Dress','Coat','Sandals','Shirt','Sneaker','Bag','Ankle boot'] for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i],cmap=plt.cm.RdBu) plt.xlabel(class_name[train_labeks[i]])

4) Model creation

We start by preparing the model. We will use a Sequential model. The Sequential model is a linear stack of layers. It can be first initialized and then we add layers using add method or we can add all layers at the init stage. The layers added are as follows: Dense. This layer is a regular fully-connected NN layer. It is used without parameters:units:. This is a positive integer, with the meaning: dimensionality of the output space; in this case is 128;activation – activation function : relu;.

Dense. This is the final layer (fully connected). It is used with the parameters:units: the number of classes (in our case 10);activation : softmax; for this final layer it is used softmax activation (standard for multiclass classification) units. This is a positive integer, with the meaning: dimensionality of the output space; in this case is 128;activation – activation function : relu;

model = keras.Sequential( [keras.layers.Flatten(input_shape=(28,28)), keras.layers.Dense(128,activation=tf.nn.relu), keras.layers.Dense(10,activation=tf.nn.softmax) ]

5) Compiling model

Then we compile the model, specifying the following parameters:

  • loss
  • optimizer
  • metrics

6) Fit the model


7) Test prediction accuracy

We calculate the test loss and accuracy.

test_loss , test_acc = model.evaluate(test_images,test_labels)
#Test accuracy is around 0.81

8) Prediction

Now we can use the trained model to make predictions/classifications on the test dataset model.predict(x_test)

prediction = model.predict(test_images)
for i in range(10): print("expected -",class_name[test_labels[i]]) print("predicted-" ,class_name[np.argmax(prediction[i])])


  1. https://www.tensorflow.org/
  2. https://www.kaggle.com

This article was first published on the Knoldus blog.

This UrIoTNews article is syndicated fromDzone

About Post Author