MTCNN、FaceNet转tflite模型,迁移至安卓使用(2)

这篇文章介绍将Tensorflow的ckpt模型,"冻结”为pb模型,和一些我经过的“坑”。

上面博客已经介绍了Tensorflow的几种模型的定义和关系。传送门:https://blog.csdn.net/qq_17721239/article/details/89295209

facecnet的模型中已经提供冻结图的程序,之前没有发现,导致耽搁了很长时间。这里介绍两种方法冻结变量,生成pb模型。

Methods A:

使用bazel工具编译tensorflow源码。

1、首先下载bazel编译工具:https://docs.bazel.build/versions/master/install.html 我使用的ubuntu18.04:

step1:install require packages

sudo apt-get install pkg-config zip g++ zlib1g-dev unzip python

step2:download bazel

    下载bazel-<version>-installer-linux-x86_64.sh文件,从github链接。我下载最新的总是失败,我就下载次最新的。

step3:run the installer

chmod +x bazel-<version>-installer-linux-x86_64.sh
./bazel-<version>-installer-linux-x86_64.sh --user

step 4:set up your environment

export PATH="$PATH:$HOME/bin"

注意:如果把bazel-<version>-installer-linux-x86_64.sh放入目录有中文的路径下,会报错(Use the binary installer(recommended)),使用全英文路径

2、下载tensorflow源码

mkdir tf2019
cd tf2019
git clone https://github.com/tensorflow/tensorflow.git

   进入tensorflow目录,编译生成freeze_graph和toco工具。最新版本toco替换成tflite_convert工具

cd tensorflow
bazel build tensorflow/python/tools:freeze_graph
bazel build tensorflow/lite/toco:toco

注意:推介在性能好一点的机器上运行,内存大一点,不然会卡死。编译时ctrl+Alt+T打开终端,输入gnome-system-monitor可以监控CPU,内存和swap内存。会发现,在编译某一项的时候,内存占到99%(我的是4G内存),然后使用交换内存。直至卡死。

解决方法:

cd tensorflow
bazel build -c opt --jobs 1 --local_resources 2048,0.5,1.0 tensorflow/python/tools:freeze_graph
bazel build -c opt --jobs 1 --local_resources 2048,0.5,1.0 tensorflow/lite/toco:toco

这里限制了内存和线程,会使得编译速度非常慢。也可能卡死。我查的资料,swap内存使用后不会自动清理。手动清理的办法是,进入root模式,再输入命令。

sudo su
swapoff -a
swapon -a

知道编译success。

3、在终端中继续输入下面命令。

bazel-bin/tensorflow/python/tools/freeze_graph \
  --input_graph=./model.pb \                       输入模型的图
  --input_checkpoint=./model.ckpt \                输入模型的ckpt文件
  --output_graph=./frozen_model.pb \               输出模型的路径
  --input_binary=true \
  --output_node_names=result                       输出结点的名字 facenet是embeddings

分别带入的模型路径和,输出的文件名。至此得到冻结了变量的模型,frozen.pb文件

Methods B:

使用代码生成。

首先下载fecenet的源码

git clone https://github.com/davidsandberg/facenet.git

 发现facenet/src/ 下面有freeze_graph.py文件。

def parse_arguments(argv):
    parser = argparse.ArgumentParser()
    
    parser.add_argument('model_dir', type=str, 
        help='Directory containing the metagraph (.meta) file and the checkpoint (ckpt) file containing model parameters')
    parser.add_argument('output_file', type=str, 
        help='Filename for the exported graphdef protobuf (.pb)')
    return parser.parse_args(argv)

直接cd 到此目录

python freeze_graph.py 20180402-114759 frozen.pb

至此得到冻结了变量的模型,frozen.pb文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值