从 tensorflow lite 模型预测总是得到 0 [英] Always getting 0 for prediction from tensorflow lite model

查看:59
本文介绍了从 tensorflow lite 模型预测总是得到 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码训练并保存了模型

I have model trained and saved using following code

from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf
from tensorflow.python.keras.optimizer_v2.rmsprop import RMSprop

train_data_gen = ImageDataGenerator(rescale=1 / 255)
validation_data_gen = ImageDataGenerator(rescale=1 / 255)

# Flow training images in batches of 120 using train_data_gen generator
train_generator = train_data_gen.flow_from_directory(
    'datasets/train/',
    classes=['bad', 'good'],
    target_size=(200, 200),
    batch_size=120,
    class_mode='binary')

validation_generator = validation_data_gen.flow_from_directory(
    'datasets/valid/',
    classes=['bad', 'good'],
    target_size=(200, 200),
    batch_size=19,
    class_mode='binary',
    shuffle=False)

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(200, 200, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),

    tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),

    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),

    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),

    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    # Flatten the results to feed into a DNN
    tf.keras.layers.Flatten(),
    # 512 neuron hidden layer
    tf.keras.layers.Dense(512, activation='relu'),
    # Only 1 output neuron. It will contain a value from 0-1
    # where 0 for 1 class ('bad') and 1 for the other ('good')
    tf.keras.layers.Dense(1, activation='sigmoid')])

model.compile(loss='binary_crossentropy',
              optimizer=RMSprop(lr=0.001),
              metrics='accuracy')

model.fit(train_generator,
          steps_per_epoch=10,
          epochs=25,
          verbose=1,
          validation_data=validation_generator,
          validation_steps=8)

print("Evaluating the model :")
model.evaluate(validation_generator)

print("Predicting :")

validation_generator.reset()
predictions = model.predict(validation_generator, verbose=1)
print(predictions)

model.save("models/saved")

然后使用

import tensorflow as tf


def saved_model_to_tflite(model_path, quantize):
    converter = tf.lite.TFLiteConverter.from_saved_model(model_path)
    model_saving_path = "models/converted/model.tflite"
    if quantize:
        converter.optimizations = [tf.lite.Optimize.DEFAULT]
        model_saving_path = "models/converted/model-quantized.tflite"
    tflite_model = converter.convert()
    with open(model_saving_path, 'wb') as f:
        f.write(tflite_model)

然后使用

import tensorflow as tf


def run_tflite_model(tflite_file, test_image):

    interpreter = tf.lite.Interpreter(model_path=str(tflite_file))
    interpreter.allocate_tensors()
    print(interpreter.get_input_details())
    input_details = interpreter.get_input_details()[0]
    output_details = interpreter.get_output_details()[0]

    interpreter.set_tensor(input_details["index"], test_image)
    interpreter.invoke()
    output = interpreter.get_tensor(output_details["index"])[0]

    prediction = output.argmax()

    return prediction

main.py

if __name__ == '__main__':


    converted_model = "models/converted/model.tflite"
    bad_image_path = "datasets/experiment/bad/b.png"
    good_image_path = "datasets/experiment/good/g.png"
    img = io.imread(bad_image_path)
    resized = resize(img, (200, 200)).astype('float32')
    test_image = np.expand_dims(resized, axis=0)
    prediction = run_tflite_model(converted_model, test_image)
    print(prediction)

尽管我将图像输入到模型中,但我总是得到预测为 0.这里有什么问题?

despite what I image I feed into the model I am always getting prediction as 0. What is wrong here?

推荐答案

在将图像传递给 tflite 模型之前,您忘记对其进行标准化.

You forgot to normalize the image before passing it to the tflite model.

resized = resize(img, (200, 200)).astype('float32')
resized = resized / 255.
test_image = np.expand_dims(resized, axis=0)
prediction = run_tflite_model(converted_model, test_image)

您正在执行二元分类任务而不是多类分类任务,因此您不需要max输出数组中的值,因为它只产生0到1范围内的单个值.如果值是 大于或等于 0.5,您可以将结果解释为 positive examplenegative example 如果它是 >小于0.5.

You are performing a binary classification task not a multi-class classification task so you do not need to take the max value in the output array as it only produces a single value in the range of 0 to 1. You can interpret the results as being a positive example if the value is greater than or equal to 0.5 and a negative example if it is less than 0.5.

import tensorflow as tf

def run_tflite_model(tflite_file, test_image):
    interpreter = tf.lite.Interpreter(model_path=str(tflite_file))
    interpreter.allocate_tensors()
    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()
    interpreter.set_tensor(input_details[0]["index"], test_image)
    interpreter.invoke()
    predictions = interpreter.get_tensor(output_details[0]["index"])
    return 1 if predictions >= 0.5 else 0 # 1 = good, 0 = bad

这篇关于从 tensorflow lite 模型预测总是得到 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆