How to use tensorflow pre-trained model in Android

本文介绍如何将基于Inception v3重新训练的TensorFlow模型优化并移植到Android平台,包括模型优化、量化及在Android应用中的部署过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要介绍在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Digital2Slave

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值