【发布时间】:2019-11-07 19:20:28
【问题描述】:
我已经训练了一个模型(使用 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 文件并尝试对相同的输入图像进行预测时,它总是预测“零”,这是第一类,概率 = 0.003922。其余类始终为 0.00 在从 Tensorflow 存储库的 Android 图像分类示例应用程序中加载我的 tflite 模型时,我得到了相同的结果。
为什么这个 tflite 模型不能按预期工作?我在转换过程中是否遗漏了某些内容或使用了 TFlite 不支持的操作?请帮忙!
到目前为止,我已经尝试在不同版本的 Tensorflow 上进行转换;
- 1.12
- 1.14
- tf-nightly-gpu 1.14
所有结果都相同。
My .h5 model and a test image, if you would like to try it yourself!
这是我用来转换模型的代码:
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])
【问题讨论】:
-
展示你如何使用它,因为那是它出错的地方。
-
@YoloSwaggins 我已经添加了用于加载和测试我的 .tflite 模型的代码,请看一下!我也尝试在 Android 上运行该模型(使用来自 Tensorflow 存储库的示例应用程序),它做同样的事情..
-
可能是输入的比例不对,尽量不要用
input_mean和input_std进行归一化,而是把图片保留在[0,256)。我相信tflite应该在输入节点中自动执行此操作。要确定,请添加转换器的graphviz输出。 -
@YoloSwaggins 好的,我试过这样做,结果是一样的!
-
@YoloSwaggins 将 .h5 模型转换为 tflite 时出现此错误 - tensorflow/core/grappler/grappler_item_builder.cc:637] 图中不存在初始化节点 conv2d/kernel/Assign I'已更新问题
标签: python tensorflow keras deep-learning tensorflow-lite