在手机上使用训练得到的模型文件
模型通常都是在 PC 端训练的,对于大部分使用者,都是用 Python 编写的代码,得到 ckpt 格式的模型文件。在使用模型文件的时候,一种做法就是用代码重新构建出完整的神经网络,然后加载这个 ckpt 格式的模型文件,如果是在 PC 上使用模型文件,用这个方法其实也是可以接受的,复制粘贴一下 Python 代码就可以重新构建整个神经网络。但是,在手机上只能使用 TensorFlow 提供的 C++ 接口,如果还是用同样的思路,就需要用 C++ API 重新构建一遍神经网络,这个工作量就有点大了,而且 C++ API 使用起来比 Python API 复杂的多,所以,在 PC 上训练完网络后,还需要把 ckpt 格式的模型文件转换成 pb 格式的模型文件,这个 pb 格式的模型文件,是用 protobuf 序列化得到的二进制文件,里面包含了神经网络的具体结构以及每个矩阵的数值,使用这个 pb 文件的时候,不需要再用代码构建完整的神经网络结构,只需要反序列化一下就可以了,这样的话,用 C++ API 编写的代码就会简单很多,其实这也是 TensorFlow 推荐的使用方法,在 PC 上使用模型的时候,也应该使用这种 pb 文件(训练过程中使用 ckpt 文件)。
How to convert the tf-model from data/index/meta to single pb file?
Answer from official document:
Exporting a trained model for inference
After your model has been trained, you should export it to a Tensorflow graph proto. A checkpoint will typically consist of three files:
- model.ckpt-${CHECKPOINT_NUMBER}.data-00000-of-00001,
- model.ckpt-${CHECKPOINT_NUMBER}.index
- model.ckpt-${CHECKPOINT_NUMBER}.meta
After you've identified a candidate checkpoint to export, run the following command from tensorflow/models/research/object_detection:
Question: tensorflow also provide a so-called freeze method to convert the models , what is the difference?
Reference:
[1] https://github.com/tensorflow/models/issues/2092
[2] https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/exporting_models.md
[3] https://zhuanlan.zhihu.com/p/27191354