本文主要介绍在Retrain a tensorflow model based on Inception v3基础上,将新训练的tensorflow模型移植到Android中。
阅读本文前,请确保已经知晓Retrain a tensorflow model based on Inception v3中内容。
准备工作
$ cd ~
$ git clone https://github.com/googlecodelabs/tensorflow-for-poets-2
$ cd ~/tensorflow-for-poets-2
$ cp -r ~/tf_files .
$ ls -lah tf_files/ # 查看内容应该包含模型文件retrained_graph.pb和retrained_labels.txt
- 下载安装Android Studio
优化模型文件
Optimize for inference
$ cd ~/tensorflow-for-poets-2
$ python -m tensorflow.python.tools.optimize_for_inference \
--input=tf_files/retrained_graph.pb \
--output=tf_files/optimized_graph.pb \
--input_names="Cast" \
--output_names="final_result"
Quantize the network weights
$ cd ~/tensorflow-for-poets-2
$ python -m scripts.quantize_graph \
--input=tf_files/optimized_graph.pb \
--output=tf_files/rounded_graph.pb \
--output_node_names=final_result \
--mode=weights_rounded
评估量化网络前后,模型的整体识别准确率。
$ cd ~/tensorflow-for-poets-2
$ python -m scripts.evaluate tf_files/optimized_graph.pb
$ python -m scripts.evaluate tf_files/rounded_graph.pb
You should see less than a 1% change in the model accuracy. With the reduced dataset you may see no change in accuracy at all.
设置Android App
准备优化后的模型文件
$ cd ~/tensorflow-for-poets-2
$ cp tf_files/rounded_graph.pb tf_files/retrained_labels.txt android/assets/
引入TensorFlow AAR文件
在project的build.gradle文件中添加以下内容:
allprojects {
repositories {
jcenter()
}
}
dependencies {
compile 'org.tensorflow:tensorflow-android:+'
}
This will tell Gradle to use the latest version of the TensorFlow AAR that has been released to https://bintray.com/google/tensorflow/tensorflow-android. You may replace the
+
with an explicit version label if you wish to use a specific release of TensorFlow in your app.
插入手机
- 启动手机的开发者模式;
- 启动 开发者选项,USB调试 和 USB安装;
- 通过数据线链接手机;
运行
- 启动Android Studio
- 点击Open an existing Android Studio project
- 选择
tensorflow-for-poets-2/android
文件夹
等待编译完成后,启动运行,并在手机开机(未锁屏)状态下,点击安装。
在启动手机上的app后,需要点击同意TensorFlowDemo照相和记录视频,同意TensorFlowDemo操作手机上的图片,媒体和文件。