Train ML Model and Build Android Application Using TensorFlow Lite & Keras
In this blog, I will train a very basic Machine Learning model using TensorFlow and Keras then we will develop an android application for that trained model.
We will use Anaconda to train our machine learning model then we will convert this model into a tflite format. After that, we will develop an Android Application using Android studio in java. So at the end of this, you will have your very own machine learning-based Android Application.
Tensorflow lite use in Android is not clear for most of them but in this example, we will explain with a very simple example.
Let us begin….
Step 1: Import required libraries
import tensorflow as tf
import numpy as np
from tensorflow import keras,lite
Tensorflow will be used to train our model and numpy will be used to create a dataset. Keras will be used to generate a neural network model. Using lite, we will convert the model into tflite format for Android.
Step 2: Create a dataset.
The basic dataset will have 2 variables x and y. The relationship pattern with the vars will be y=2x-1. Here y is the label and x is the feature.
x = np.array([-1.0,0.0,1.0,2.0,3.0,4.0],dtype=float)
y = np.array([-3.0,-1.0,1.0,3.0,5.0,7.0],dtype=float)
Step 3: Train a model using Keras
This package has a similar behavior as of neural network package. The hidden layers are created using the Keras. layers.Dense(). This dense() will provide connectivity of current and previous neurons.
model = keras.Sequential([keras.layers.Dense(units=1,input_shape=[1]),keras.layers.Dense(units=1,input_shape=[1])])
model.compile(optimizer=’sgd’,loss=’mean_squared_error’)
units=1 will tell you that it will have 1 neuron and input_shape for the previous layer is 1 because we are using only 1 feature (i.e. x). then, we compile the model. The parameters optimizer and loss values. the loss defines the difference between predicted and actual value. As this is Supervised ML, we have labeled data and we are going to get predicted results which we will be compared with the actual values.
Step 4: Performing training on the model
model.fit(x,y,epochs=500)
print(model.predict([10]))
The x and y values indicate the input and output values to train the model with 500 epochs which means we want to train this dataset 500 times.
Then, predict the value of x=10.
Ideally, the value of y should be 19. The predicted value after executing the code is 18.9999. Hence, the model is quite accurate.
Step 5: Save the model and create h5 and tflite file format
keras_file = “linear.h5”
tf.keras.models.save_model(model,keras_file)
converter = lite.TFLiteConverter.from_keras_model(model)
tfmodel = converter.convert()open(“linear.tflite”,”wb”).write(tfmodel)
Step 6: Create Android Application
Goto Android Studio -> Create New Project.
Initially, you need to add below dependencies in the code:
- Add following package inside dependencies of build.gradle file -
implementation 'org.tensorflow:tensorflow-lite:+'
Then, we need to add the below code just above dependencies
aaptOptions{
noCompress "tflite"
noCompress "lite"
}
This specifies that tflite files should not be compressed like other files.
Sync the project and gradle should compile successfully.
2. Add the tflite file inside the assets folder of the Android project.
3. Add the below function in the Java file
private MappedByteBuffer loadModelFile() throws IOException
{
AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd("linear.tflite");
FileInputStream fileInputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor());
FileChannel fileChannel = fileInputStream.getChannel();
long startOffset = assetFileDescriptor.getStartOffset();
long len = assetFileDescriptor.getLength();
return fileChannel.map(FileChannel.MapMode.READ_ONLY,startOffset,len);
}
This will convert the tflite model file into MappedByteBuffer format. It is an optimized format that will help us to increase efficiency and speed.
4. Add an Interpreter which will interpret the input and output of data using the model.
interpreter = new Interpreter(loadModelFile(),null);
5. Add below doInference() function to evaluate the expression and get the output with the help of the model.
public float doInference(String val)
{
float[] input = new float[1];
input[0] = Float.parseFloat(val);
float[][] output = new float[1][1];
interpreter.run(input,output);
return output[0][0];
}
The parameter val is the input value given by the user.
As the model is developed on float values, we are converting the input string value to float value. Then, we have created a 2D output array (as it has only one row and one column). Later, the interpreter will produce output based on the input value and save it in the output variable of the 0th row and 0th column.
And the output is…..
You can find the entire code snippet on Github.
I hope you enjoyed the blog!!!
Please feel free to post your comments and feedback….
Don’t forget to hit claps if you liked it :)
Also, new ideas are welcomed.
Thank You! :)