【问题标题】:Tensorflow lite model is giving wrong outputTensorflow lite 模型给出错误的输出
【发布时间】:2018-07-27 12:11:03
【问题描述】:

我正在开发一个带有回归预测的深度学习模型。我创建了一个 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 文件转换为 tflile 格式

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

为什么会出现这个问题?

【问题讨论】:

  • TocoConvert.from_keras_model_file 中存在错误。它已在 8 月 9 日的夜间版本中修复。感谢您报告此问题。

标签: tensorflow keras tensorflow-lite toco


【解决方案1】:

最后我找到了一个解决方案,通过this 代码 sn-p 将 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 模型预测准确率非常高。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2019-05-16
    相关资源
    最近更新 更多