Geek Culture
Published in

Geek Culture

Train ML Model and Build Android Application Using TensorFlow Lite & Keras

ML + Android

import tensorflow as tf
import numpy as np
from tensorflow import keras,lite

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)

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’)

model.fit(x,y,epochs=500)
print(model.predict([10]))

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)

implementation 'org.tensorflow:tensorflow-lite:+'

aaptOptions{
noCompress "tflite"
noCompress "lite"
}

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);
}

interpreter = new Interpreter(loadModelFile(),null);

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];
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store