MTCNN、FaceNet轉tflite模型,遷移至安卓使用(3)

上一片介紹將普通模型轉換爲frozen凍結模型。這一篇介紹把“凍結”的pb模型轉換爲tflite模型。

如果直接將上篇文章得到facenet的frozen模型轉換,肯定是會報錯的。因爲tflite的轉換工具不支持模型中的一些結構。

開門見山,從頭開始介紹≈傻瓜教程。

step1:下載facenet源碼和tensorflow源碼,下載facenet模型文件。bazel編譯tensorflow(見上面的博客)。

step2: striping train brach

在這裏,我們去掉了phase_train輸入分支,這將減少ops的總數,並使其僅使用推理圖。在facenet目錄下創建inference_graph.py,把下面的程序粘貼進去。

import tensorflow as tf
from src.models import inception_resnet_v1
import sys

def main():
    
    traning_checkpoint = “models/model-20180402-114759.ckpt-275”
    eval_checkpoint = “model_inference/imagenet_facenet.ckpt”
    
    data_input = tf.placeholder(name=’input’, dtype=tf.float32, shape=[None, 160, 160, 3])
    output, _ = inception_resnet_v1.inference(data_input, keep_probability=0.8, phase_train=False, bottleneck_layer_size=512)
    label_batch= tf.identity(output, name=’label_batch’)
    embeddings = tf.identity(output, name=’embeddings’)
    
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        saver = tf.train.Saver()
        saver.restore(sess, traning_checkpoint)
        save_path = saver.save(sess, eval_checkpoint)
        print(“Model saved in file: %s” % save_path)

if __name__ == “__main__”:
    main()

cd 到該目錄。運行 

python inference_graph.py models/ model_inference/

然後就可以凍結圖了

python src/freeze_graph.py model_inference/ facenet_frozen.pb

Once the frozen model is generated, time to convert it to .tflite

$ tflite_convert --output_file model_mobile/facenet.tflite \
--graph_def_file facenet_frozen.pb \
--input_arrays “input” \
--input_shapes “1,160,160,3” \
--output_arrays "embeddings" \
--output_format TFLITE \
--mean_values 128 \
--std_dev_values 128 \
--default_ranges_min 0 \
--default_ranges_max 6 \
--inference_type QUANTIZED_UINT8 \
--inference_input_type QUANTIZED_UINT8

這裏我們將float32量化爲uint8,所以大小隻是原來的1/4。

如果不想量化。

$ tflite_convert --output_file model_mobile/facenet.tflite \
--graph_def_file facenet_frozen.pb  \
--input_arrays "input" \
--input_shapes "1,160,160,3" \
--output_arrays output \
--output_format TFLITE

至此 facenet_frozen.pb以及facenet.tflite生成結束。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章