[FIXED] Want to confirm if this is a problem with model or I am doing something wrong tflite

Issue

Someone contacted me because they want fron end of a tflite model! When I actually created a front end it is predicting everything as Positive with an accuracy of 99.9%! Just wanted to know if it’s my fault or the model is not correct!

Here is the code I am using for prediction:

model = tf.lite.Interpreter(model_path='Classifier\\trained_models\\model.tflite')

def predict(imgUrl , model=model):
    interpreter = model
    interpreter.allocate_tensors()
    
    output = interpreter.get_output_details()[0]  # Model has single output.
    input = interpreter.get_input_details()[0] 
    
    img = image.load_img(imgUrl, target_size=(227, 227))
    img = image.img_to_array(img)
    img /= 255
    interpreter.set_tensor(input['index'], [img])
    interpreter.invoke()
    output_data = interpreter.get_tensor(output['index'])
    output_probs = tf.math.softmax(output_data)
    pred_label = tf.math.argmax(output_probs)
    
    print(output_probs)
    # classes = model.predict(images)
    encode_label = np.argmax(output_probs,axis=-1)
    print(encode_label)
    print(pred_label)
    print(output_data)
    
    lb = {0:'Normal', 1:'Head and Neck Cancer'}
    
    chances = str(max(output_data.flatten().tolist())*100)[:4] + '%'
    print(chances)
    encoded = str(lb[encode_label[0]])
    print(output_probs)
    print(encoded)

EDIT[1]

PreProcessing

  train_ds = tf.keras.utils.image_dataset_from_directory(
  "/content/drive/MyDrive/FYP DATA",
  validation_split=0.1,
  subset="training",
  seed=123,
  image_size=(227, 227),
  batch_size=32)

val_ds = tf.keras.utils.image_dataset_from_directory(
  "/content/drive/MyDrive/FYP DATA",
  validation_split=0.1,
  subset="validation",
  seed=1,
  image_size=(227, 227),
  batch_size=32)

Solution

Finally I was able to solve the problem. Actually while training the model the data wasn’t preprocessed but while making prediction I was preprocessing the data!
So I just removed the following line from the predict function:

    img /= 255

Answered By – Huzaifa Azhar

Answer Checked By – Willingham (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published