How to Create Custom Model For Android Using TensorFlow?
Tensorflow is an open-source library for machine learning. In android, we have limited computing power as well as resources. So we are using TensorFlow light which is specifically designed to operate on devices with limited power. In this post, we going to see a classification example called the iris dataset. The dataset contains 3 classes of 50 instances each, where each class refers to the type of iris plant.
- sepal length in cm
- sepal width in cm
- petal length in cm
- petal width in cm
Based on the information given in the input, we will predict whether the plant is Iris Setosa, Iris Versicolour, or Iris Virginica. You can refer to this link for more information.
Step by step Implementation
Download the iris data set (file name: iris.data) from this (https://archive.ics.uci.edu/ml/machine-learning-databases/iris/) link.
Create a new python file with a name iris in the Jupyter notebook. Put the iris.data file in the same directory where iris.ipynb resides. Copy the following code in the Jupyter notebook file.
After executing the line open(‘iris.tflite’,’wb’).write(tfmodel) a new file named iris.tflite will get created in the same directory where iris.data resides.
A) Open Android Studio. Create a new kotlin-android project. (You can refer here for creating a project).
B) Right-click on app > New > Other >TensorFlow Lite Model
C) Click on the folder icon.
D) Navigate to iris.tflite file
E) Click on OK
F) Your model will look like this after clicking on the finish. (It may take some time to load).
Copy the code and paste it in the click listener of a button in MainActivity.kt.(It is shown below).
Step 5: Create XML layout for prediction
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 6: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
You can download this project from here.