Running tflite classifier in Android (Kotlin)

Viewed 593

I developed a classifier in python and converted it into a tflite model. afterwards when ever I run the classifier in python:

import tensorflow as tf
import numpy as np
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test the model on random input data.
input_data = np.array([[566, 12, 12, -12, 1, 7, 1, 1, 1, -1]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
[[output_data]] = interpreter.get_tensor(output_details[0]['index'])
print(output_data) # prints 0.99999845

I get a valid output.

In Android (kotlin) I am using the following code:

val model = Model.newInstance(this)
val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, 10), DataType.FLOAT32)
var byteBuffer = ByteBuffer.allocate(4 * 10)
for (value in floatArrayOf(566f, 12f, 12f, -12f, 1f, 7f, 1f, 1f, 1f, -1f)) {
   byteBuffer.putFloat(value)
}
inputFeature0.loadBuffer(byteBuffer)
val outputs = model.process(inputFeature0)
val result = outputs.outputFeature0AsTensorBuffer.floatArray[0]
print(result) // 0.51473397
model.close()

in python whenever I change the input values the output changes accordingly but in Android (kotlin) the output (result) remain the same

please help me understand what am I doing wrong in Kotlin so that the prediction (processing the model) keep giving me the same result (with the input being changed)

1 Answers

I am not sure how to use the bytebuffer, the problem must be there, as the following line yilds the correct result:

inputFeature0.loadArray(floatArrayOf(566F, 12F, 12F, -12F, 1F, 7F, 1F, 1F, 1F, -1F))

so replace your loadbuffer with loadArray

Related