Tensorflow 精简版模型给出了错误的输出

Tensorflow lite model is giving wrong output

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

为什么会出现这个问题?

最后我找到了一个解决方案,使用 this 代码片段将 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模型预测精度非常高了。