首页 > 解决方案 > 如何将 Tensorflow .pb 模型转换为 Tensforflow Lite

问题描述

我需要使用Google CoLab将tensorflow pb模型转换为tensorflow lite

接下来是转换过程:

1)上传模型:

from google.colab import files
pbfile = files.upload()

2)转换它:

import tensorflow as tf
pb_file = 'data_513.pb'
tflite_file = 'data_513.tlite'

converter = tf.lite.TFLiteConverter.from_frozen_graph(pb_file, ['ImageTensor'], ['SemanticPredictions'], 
                                                      input_shapes={"ImageTensor":[1,513,513,3]})

tflite_model = converter.convert()
open(tflite_file,'wb').write(tflite_model) 

转换失败并出现下一个错误

检查失败:array.data_type == array.final_data_type 数组“ImageTensor”的实际和最终数据类型不匹配(data_type=uint8,final_data_type=float)。

我想我可能需要指定一些额外的命令来克服这个错误,但我找不到任何关于它的信息。

标签: tensorflowmodel

解决方案


终于找到了解决办法。这里的截图供其他人使用:

import tensorflow as tf
pb_file = 'model.pb'
tflite_file = 'model.tflite'

converter = tf.lite.TFLiteConverter.from_frozen_graph(pb_file, ['ImageTensor'], ['SemanticPredictions'], 
                                                      input_shapes={"ImageTensor":[1,513,513,3]})


converter.inference_input_type=tf.uint8
converter.quantized_input_stats = {'ImageTensor': (128, 127)}  # (mean, stddev)

tflite_model = converter.convert()
open(tflite_file,'wb').write(tflite_model) 

interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()

files.download(tflite_file)

推荐阅读