python .tflite模型(从keras.h5模型转换而来)始终以相同概率预测相同类

mzsu5hc0  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(104)

我已经训练了一个模型(使用keras)来计算举起的手指数。这个模型工作得很好(测试图像的准确率约为99%)。现在,我正在尝试通过将保存的模型(.h5文件)转换为.tflite文件来部署这个模型。
使用tf.lite.TFLiteConverter.from_keras_model_file(),它进行转换并给我一个.tflite文件,其中包含以下错误:

tensorflow/core/grappler/grappler_item_builder.cc:637] Init node conv2d/kernel/Assign doesn't exist in graph

当我加载此tflite文件并尝试对相同的输入图像进行预测时,它始终预测“ZERO”,这是第一个类,概率= 0.003922。其余类始终为0.00。当我从Tensorflow repo的Android图像分类示例应用中加载tflite模型时,得到了相同的结果。
为什么这个tflite模型不能正常工作?我在转换过程中遗漏了什么或者使用了TFlite不支持的操作吗?请帮助!
到目前为止,我已经尝试在不同版本的Tensorflow上进行转换;

这是我用来转换模型的代码:

import tensorflow as tf

converter = tf.lite.TFLiteConverter.from_keras_model_file("fingers_latest.h5")
tflite_model = converter.convert()
open("fingers_latest.tflite", "wb").write(tflite_model)

我的keras模型:

nbatch = 64
IMG_SIZE = 256

def load_data():
    print("Batch size = ", nbatch, "\n")

    train_datagen = ImageDataGenerator(rescale=1. / 255, rotation_range=12., width_shift_range=0.2,
                                       height_shift_range=0.2,
                                       zoom_range=0.15, shear_range=0.2, horizontal_flip=False)

    test_datagen = ImageDataGenerator(rescale=1. / 255)

    train_gen = train_datagen.flow_from_directory('./datasets/fingers_white/train/', target_size=(IMG_SIZE, IMG_SIZE),
                                                  color_mode='rgb',
                                                  batch_size=nbatch, shuffle=True,
                                                  classes=['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE'],
                                                  class_mode='categorical')

    test_gen = test_datagen.flow_from_directory('./datasets/fingers_white/test/', target_size=(IMG_SIZE, IMG_SIZE),
                                                color_mode='rgb',
                                                batch_size=nbatch,
                                                classes=['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE'],
                                                class_mode='categorical')

    return train_gen, test_gen

def train_model(train_gen, test_gen):
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(IMG_SIZE, IMG_SIZE, 3)))
    model.add(Dropout(0.2))
    model.add(MaxPooling2D((3, 3)))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(Dropout(0.4))
    model.add(MaxPooling2D((3, 3)))
    model.add(Conv2D(128, (3, 3), activation='relu'))
    model.add(Dropout(0.6))
    model.add(MaxPooling2D((3, 3)))
    model.add(Conv2D(32, (3, 3), activation='relu'))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(6, activation='softmax'))

    model.summary()

    model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])

    STEP_SIZE_TRAIN = train_gen.n // train_gen.batch_size
    STEP_SIZE_TEST = test_gen.n // test_gen.batch_size
    print(STEP_SIZE_TEST, STEP_SIZE_TRAIN)

    model.fit_generator(train_gen, steps_per_epoch=STEP_SIZE_TRAIN, epochs=5, validation_data=test_gen,
                        validation_steps=STEP_SIZE_TEST, use_multiprocessing=True, workers=6)

用于加载和运行.tflite模型的代码:

import tensorflow as tf
import tkinter as tk
from tkinter import filedialog
import PIL
from PIL import Image
import numpy as np
import time

# DEF. PARAMETERS
img_row, img_column = 224, 224
num_channel = 3
num_batch = 1
input_mean = 127.5
input_std = 127.5
floating_model = False

path_1 = r"./models/mobilenet_v2_1.0_224.tflite"
labels_path = "./models/labels_mobilenet.txt"

def load_labels(filename):
    my_labels = []
    input_file = open(filename, 'r')
    for l in input_file:
        my_labels.append(l.strip())
    return my_labels

interpreter = tf.lite.Interpreter(path_1)
interpreter.allocate_tensors()

# obtaining the input-output shapes and types
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
print(input_details, '\n', output_details)

# file selection window for input selection
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
input_img = Image.open(file_path)
input_img = input_img.resize((img_row, img_column))
input_img = np.expand_dims(input_img, axis=0)

input_img = (np.float32(input_img) - input_mean) / input_std

interpreter.set_tensor(input_details[0]['index'], input_img)

# running inference
interpreter.invoke()

output_data = interpreter.get_tensor(output_details[0]['index'])
results = np.squeeze(output_data)

top_k = results.argsort()[-5:][::-1]
labels = load_labels(labels_path)
for i in top_k:
    print('{0:08.6f}'.format(float(results[i] / 255.0)) + ":", labels[i])
ars1skjm

ars1skjm1#

在训练代码中,将图像归一化到[0..1]范围,该范围由以下行指定:

train_datagen = ImageDataGenerator(rescale=1. / 255, ...)
test_datagen = ImageDataGenerator(rescale=1. / 255)

但是,转换后的tflite模型的输入范围是[-1..1],由以下行指定:

input_mean = 127.5
input_std = 127.5
input_img = (np.float32(input_img) - input_mean) / input_std

因此,您可以尝试将上面的行替换为:

input_mean = 0.
input_std = 255.

相关问题