0

Problem

I created a workbook in which I classify images on if they are a hotdog or not as a multi-label classification problem. I use the MobileNetv2 architecture trained on ImageNet weights. When testing the model before I converted it into the Tflite format, I was getting 93% accuracy on its predictions. But when I convert the model to the Tflite format to use for mobile and use the Tflite flutter package, I always get a confidence rating of 1.0 for the first label in my labels.txt file. ['hotdog', 'nothotdog']

Model Setup

I am new to converting the model to be used by edge devices so maybe I'm doing something incorrectly but I'm just not seeing it and the issues section on the library repo seems dead so no help there.

conv_base = keras.applications.mobilenet_v2.MobileNetV2(
    weights="imagenet",
    include_top=False
)
conv_base.trainable = False

inputs = keras.Input(shape=(256, 256, 3))
x = data_augmentation(inputs)
x = keras.applications.mobilenet_v2.preprocess_input(x)
x = conv_base(x)
x = layers.Flatten()(x)
x = layers.Dense(512)(x)
x = layers.Dropout(0.5)(x)
outputs = layers.Dense(2, activation=keras.activations.softmax)(x)
model = keras.Model(inputs, outputs)

model.compile(loss=keras.losses.SparseCategoricalCrossentropy(),
              optimizer=keras.optimizers.RMSprop(),
              metrics=["accuracy"])

model.summary()

Model: "model_2"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_6 (InputLayer)        [(None, 256, 256, 3)]     0         
                                                                 
 sequential (Sequential)     (None, 256, 256, 3)       0         
                                                                 
 tf.math.truediv_1 (TFOpLamb  (None, 256, 256, 3)      0         
 da)                                                             
                                                                 
 tf.math.subtract_1 (TFOpLam  (None, 256, 256, 3)      0         
 bda)                                                            
                                                                 
 mobilenetv2_1.00_224 (Funct  (None, None, None, 1280)  2257984  
 ional)                                                          
                                                                 
 flatten_2 (Flatten)         (None, 81920)             0         
                                                                 
 dense_4 (Dense)             (None, 512)               41943552  
                                                                 
 dropout_1 (Dropout)         (None, 512)               0         
                                                                 
 dense_5 (Dense)             (None, 2)                 1026      
                                                                 
=================================================================
Total params: 44,202,562
Trainable params: 41,944,578
Non-trainable params: 2,257,984
_________________________________________________________________
import tensorflow as tf
from tensorflow import keras
import pathlib

test_model = keras.models.load_model(f"{hotDogDir}hotdog_multiclassifier_mobilenet_v1.keras")

converter = tf.lite.TFLiteConverter.from_keras_model(test_model)
tflite_model = converter.convert()

tflite_models_dir = pathlib.Path(f"{hotDogDir}")
tflite_models_dir.mkdir(exist_ok=True, parents=True)

tflite_model_file = tflite_models_dir/"hotdog_multiclassifier_mobilenet.tflite"
tflite_model_file.write_bytes(tflite_model)

converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quant_model = converter.convert()
tflite_model_quant_file = tflite_models_dir/"hotdog_multiclassifier_mobilenet.tflite"
tflite_model_quant_file.write_bytes(tflite_quant_model)

Flutter Setup

I created the flutter application from a base which was supplied and just edited it to work with my custom model which is supplied at this repo for clearer reading: repo.

Questions

  • Why is my predictions now incorrect and always aiming at the first label class on the mobile?
  • What can I do to fix this?

Thank you

SmiffyKmc
  • 801
  • 1
  • 16
  • 34
  • I've build your code and use `Tflite.runModelOnImage(path: image.path, ...` . Then I set `threshold: 0.1` , `imageStd: 20` and your app works well. It can predict the image is hotdog or not. – Miftakhul Arzak Jun 22 '22 at 04:11
  • Your app also works well if you set as default `imageStd: 1` and `threshold: 0.1`. – Miftakhul Arzak Jun 22 '22 at 04:30
  • Why if you set `imageStd:255` and `imageMean:0` your model fail to predict?. I found this information, `if we accidentally set IMAGE_MEAN=0.0f & IMAGE_STD = 255.0f, it will normalize the input to 0 to 1. The model will still "see" the image but everything become brighter. The accuracy may drop a bit`. You can see full here https://stackoverflow.com/a/57979676/11445944 . – Miftakhul Arzak Jun 22 '22 at 04:36
  • Hey Miftakhul, I haven't had time to try this just yet as I'm working. But I really appreciate the fast response. I thought I wouldn't hear from someone for a long period. But I was unsure of the Std and Mean configs but what yoy mentioned as what I had done makes sense now. That link was very valuable! Once I have it tested I'll mention here and you can turn to an answer. – SmiffyKmc Jun 22 '22 at 09:33
  • Hey Miftakhul, I tried making `threshold: 0.1` , `imageStd: 20` but the same thing happens. Every prediction is a hotdog. Bit disappointed, but maybe I did something else wrong? Can you share what changes you made and the example, please? Maybe as a PR on the repo. Have you ran the app against an image with and without a hotdog? – SmiffyKmc Jun 22 '22 at 15:12
  • Update: I changed the model to `hotdog_multiclassifier.tflite` and what you said did work. Did you stay on the `mobilenet` version or did you change? I'd prefer to get the `mobilenet` version to work so if you did it would be amazing to see. – SmiffyKmc Jun 22 '22 at 15:37
  • Yes, I use `hotdog_multiclassifier_mobilenet.tflite`. I just change `threshold` and `imageStd` and your app works. – Miftakhul Arzak Jun 22 '22 at 16:46
  • Thank you for the fast responses! And it does change to nothotdog when I not? I'm not sure why mine isn't working when it's pretty much the same. Are you using an emulator by any chance? I am just to be fast with developing. Also do you have the mean still preset or removed? If you could possibly PR that woukd be so kind – SmiffyKmc Jun 22 '22 at 16:59
  • I use real device and it works nicely. If I pick baguette french bread, it gives right prediction (not hotdog) and yeah, your model gives right prediction for some hotdog image picked from internet. Have you tried using real device? – Miftakhul Arzak Jun 22 '22 at 17:14
  • Not just yet but I'll be doing it first thing once I make it home :). Let me try it again and see! Thanks for your help! – SmiffyKmc Jun 22 '22 at 17:45
  • The real device worked! And it was crazy fast actually . The std change was very helpful thabk you! Want to make it an answer and I'll accept :) – SmiffyKmc Jun 22 '22 at 19:00

0 Answers0