tensorflow - Tensorflow lite 模型给出错误的输出
问题描述
我正在开发一个带有回归预测的深度学习模型。我创建了一个 tflite 模型,但它的预测与原始模型不同,而且完全错误。这是我的过程:
我用 keras 训练了我的模型
model = Sequential()
model.add(Dense(100, input_dim=x.shape[1], activation='relu')) # Hidden 1
model.add(Dense(50, activation='relu')) # Hidden 2
model.add(Dense(1)) # Output
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(x,y,verbose=0,epochs=500)
并将我的模型保存为 h5 文件
model.save("keras_model.h5")
然后通过 TocoConverter 将 h5 文件转换为 tfile 格式
converter = tf.contrib.lite.TocoConverter.from_keras_model_file("keras_model.h5")
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
当我用相同的输入测试两个文件时,原始 keras 模型给出了合理的输出,但转换后的模型给出了不合理的输出。
# Load TFLite model and allocate tensors.
interpreter = tf.contrib.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Test model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(input_data)
print(output_data)
//Original model testing
from keras.models import load_model
model2 = load_model("keras_model.h5")
pred = model2.predict(x)
print(pred)
输出是这样的:
[[10. 10. 10. 10. 10. 10.]]//input_data
[[-1.4308803]]// tflite output (meaningless)
[[335.0276]] // keras file output
为什么会出现这个问题?
解决方案
最后,我通过使用此代码片段将 keras 模型转换为冻结图找到了解决方案。我复制了这个 python 文件 tensorflow Scripts 文件夹。并将 keras 模型文件复制到同一文件夹。并创建一个名为“frozen”的文件夹。然后运行这个命令
py cerasconvert.py keras_model.h5 frozen/ freeze_graph
我将新创建的 .pb 文件转换为 tflite 格式
import tensorflow as tf
import numpy as np
graph_def_file = "frozen/frozen.pb"
input_arrays = ["dense_1_input_1"]
output_arrays = ["dense_3_1/BiasAdd"]
converter = tf.contrib.lite.TocoConverter.from_frozen_graph(
graph_def_file, input_arrays, output_arrays)
tflite_model = converter.convert()
open("frozen/converted.tflite", "wb").write(tflite_model)
现在我的 tflite 模型预测准确率非常高。
推荐阅读
- vimeo - 使用 Vimeo API 创建/列出子文件夹
- plot - 如何根据给定的 pi、A 和 B 值绘制 HMM?
- ibm-mq - -bash:/bin/crtmqm:权限被拒绝
- node.js - 转换为有效的 URL NodeJs
- javascript - 如何在下拉列表中添加按钮?
- kubernetes - Kubernetes 创建服务耗时过长
- html - 查询:CSS 覆盖 reg
- python - Numpy 内存错误
- python - python多处理和整洁python的奇怪行为
- angular - Nebular Ngx-admin,如何将 nb-auth-block 的宽度从 35 rem 更改为全宽