E2E tf.Keras to TFLite to Android

Margaret Maynard-Reid
5 min readSep 7, 2019

This tutorial covers how to train a model from scratch with TensorFlow 2.0 — train an image classifier with tf.Keras Sequential API, convert the trained model to tflite format, and run the model on Android. I will walk through an example with the MNIST data for image classification, and share some of the common issues you may face. This tutorial focuses on the end to end experience, and I will not go in-depth with deep learning, the various tf.Keras APIs or Android development. [Note: this is a simple classification model with MNIST. If you are interested in other TFLite samples, check out the awesome-tflite repo.]

Download my sample code and follow along:

  • Run in Colab - Training model with tf.Keras and convert Keras model to TFLite (link to Colab notebook) .
  • Run in Android Studio - DigitRecognizer (link to Android app).

1. Train an custom classifier

Load the data

We will use the MNST data which is available as part of the tf.Keras framework.

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

Preprocess data

Next we will reshape the input image from 28x28 to 28x28x1, normalize it and one-hot encode the labels.

--

--

Margaret Maynard-Reid
Margaret Maynard-Reid

Written by Margaret Maynard-Reid

AI, Art & Design: ML GDE (Google Developer Expert) | Google Cloud Champion Innovator | 3D Fashion Designer