本文主要介紹在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操作手機上的圖片,媒體和文件。