class MyTFLiteModel(context: Context) {
private val interpreter: Interpreter
init {
val tfliteModel = loadModelFile(context, "compressed_model.tflite")
interpreter = Interpreter(tfliteModel)
}
private fun loadModelFile(context: Context, filename: String): ByteBuffer {
val inputStream = FileInputStream(context.assets.open(filename))
val fileChannel = inputStream.channel
val startOffset = 0
val declaredLength = fileChannel.size()
return fileChannel.map(
FileChannel.MapMode.READ_ONLY,
startOffset.toLong(),
declaredLength
)
}
fun predict(inputData: List<ArrayList<Float>>): Int {
val inputBuffer = prepareInput(inputData)
val outputSize = interpreter.getOutputTensor(0).shape()[1]
val outputBuffer = ByteBuffer.allocateDirect(outputSize * java.lang.Float.SIZE / java.lang.Byte.SIZE)
.order(ByteOrder.nativeOrder())
val floatOutputBuffer = outputBuffer.asFloatBuffer()
interpreter.run(inputBuffer, floatOutputBuffer)
val outputArray = FloatArray(outputSize)
floatOutputBuffer.rewind()
floatOutputBuffer.get(outputArray)
var maxIndex = 0
for (i in 1 until outputArray.size) {
if (outputArray[i] > outputArray[maxIndex]) {
maxIndex = i
}
}
return maxIndex
}
private fun prepareInput(inputData: List<ArrayList<Float>>): ByteBuffer {
val inputSize = interpreter.getInputTensor(0).shape()[1]
val inputBuffer = ByteBuffer.allocateDirect(inputSize * inputData.size * java.lang.Float.SIZE / java.lang.Byte.SIZE)
.order(ByteOrder.nativeOrder())
for (inputList in inputData) {
for (input in inputList) {
inputBuffer.putFloat(input)
}
}
return inputBuffer
}
}
Doubt :-
In this line interpreter.run(inputBuffer, floatOutputBuffer)
I am getting a type error for inputBuffer and floatOutpurBuffer:-
Required:
TypeVariable(T).() → TypeVariable(R)
Found:
ByteBuffer
Can someone help me in this