How to use tensorflow pre-trained model in Android

本文主要介紹在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

優化模型文件

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.

插入手機

  1. 啓動手機的開發者模式;
  2. 啓動 開發者選項USB調試USB安裝
  3. 通過數據線鏈接手機;

運行

  1. 啓動Android Studio
  2. 點擊Open an existing Android Studio project
  3. 選擇tensorflow-for-poets-2/android文件夾

等待編譯完成後,啓動運行,並在手機開機(未鎖屏)狀態下,點擊安裝。

在啓動手機上的app後,需要點擊同意TensorFlowDemo照相和記錄視頻,同意TensorFlowDemo操作手機上的圖片,媒體和文件。

參考

  1. TensorFlow For Poets 2
  2. Android TensorFlow support
  3. TensorFlow Android Camera Demo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章