【转】Android - Add some machine learning to your apps, with TensorFlow

【转】

TensorFlow is an open source software library for machine learning, developed by Google and currently used in many of their projects.

Aneasy, fast, and funway to get started with TensorFlow is to build an image classifier: an offline and simplified alternative toGoogle’s Cloud Vision APIwhere our Android device can detect and recognize objects from an image(or directly from the camera input).

In this article, we will create an Android app that can recognize video-game characters.

First, run the Android classifier sample

An official TensorFlow Android image classifier sample is available on the mainGitHub repository.

However, if you want to build it, it will take you some time, as you’ll need to install the NDK, Bazel, and the total build time with Android Studio will take around 40 minutes.

That’s not really compatible with my initial “easy, fast, and fun” description, so instead I’ve created a gradle standalone prebuilt fork of TensorFlow 1.0.1 atgithub.com/Nilhcem/tensorflow-classifier-androidyou can directly clone, import on Android Studio and run within 2 minutes.

OPTIONAL (begin)

If you want to port the TensorFlow official Android Sample to a prebuilt Android Studio project by yourself, you will need to:

Import the original TensorFlow Android sample sources (commit)

Create a new Android Studio project (applicationId:org.tensorflow.demo), to have an already set up gradle configuration (commit)

Move TensorFlow’s Android sample files into the new gradle project (commit)

Remove the DetectorActivity and StylizeActivity (we will only need the ClassifierActivity today) (commit)

Download the CI nightly prebuilt NDK librariesfrom this linkand place those into your gradle project (commit)

Download thepre-trained ImageNet model (inception5h)to your assets folder (commit)

OPTIONAL (end)

Once you have imported the TensorFlow Android sample, run it with Android Studio and start detecting things

Then, create your own image classifier

Right now, the TensorFlow sample uses “Inception”, a model pre-trained to detect 1000 objects fromImageNet2012 Challenge image dataset.

We are going to transfer learning, which means we are starting with a model that has been already trained on another problem. We will then be retraining it on a similar problem. Deep learning from scratch can take days, but transfer learning can be done in short order.

And for that, we’ll need some data….

1. Gather lots of images

Inception works well with a various set of images (at least 30 images, more is better).

We will create a~/tf_files/gamesfolder and place each set of jpeg images in subdirectories (such as~/tf_files/games/mario,~/tf_files/games/bombermanetc)

A quick way to download multiple images at once is to search something on Google Images, and use aChrome extension for batch download.

2. Retrain the model to learn from your images

Now that we have all our images, we will retrain the model.

We can use a docker container to have an already set up TensorFlow environment:

docker run -it -v$HOME/tf_files:/tf_files\gcr.io/tensorflow/tensorflow:latest-develcd/tensorflowgit pullgit checkout v1.0.1python tensorflow/examples/image_retraining/retrain.py\--bottleneck_dir=/tf_files/bottlenecks\--how_many_training_steps 4000\--model_dir=/tf_files/inception\--output_graph=/tf_files/retrained_graph.pb\--output_labels=/tf_files/retrained_labels.txt\--image_dir /tf_files/games

Don’t stop your container yet, you will need it again very soon.

This operation can take several minutes depending on how many images you have and how many training steps you specified.

These commands will make TensorFlow download the inception model and retrain it to detect images from~/tf_files/games.

The script will generate two files: the model in a protobuf file (retrained_graph.pb) and a label list of all the objects it can recognize (retrained_labels.txt).

For more information, the best tutorial you can find on the Internet so far is Google’sTensorFlow for Poetscodelab (I highly recommend you to do it)

3. Optimize the model

We have our model. However, if we try to import it in our Android sample, we will get an error:

Op BatchNormWithGlobalNormalization is not available in GraphDef version 21. It has been removed in version 9. Use tf.nn.batch_normalization().

We first need to optimize it first, using a tool namedoptimize_for_inference:

./configure# you can select all default valuesbazel build tensorflow/python/tools:optimize_for_inference

Building the tool should take around 20 minutes.#BePatient

OPTIONAL (begin)

At this point, a good thing to do, to save time, would be to commit your current docker process to a new image. This way, you won’t have to rebuild theoptimize_for_inferencetool anymore.

exitdocker ps -adocker commit # And then start your new container with:docker run -it -v$HOME/tf_files:/tf_files cd/tensorflow

OPTIONAL (end)

Now the tool is built, you can optimize your model:

bazel-bin/tensorflow/python/tools/optimize_for_inference\--input=/tf_files/retrained_graph.pb\--output=/tf_files/retrained_graph_optimized.pb\--input_names=Mul\--output_names=final_result

You can now exit your docker container.

This script will generate a~/tf_files/retrained_graph_optimized.pbfile you will now be able into import in your Android project.

For more information about mobile optimizations, I suggest you to read theTensorflow for Mobile Poetsarticle

4. Import the new model in your Android application

We have our retrained model.

We can now delete the previous ImageNet model from our Android app’sassetsfolder and place the new model (~/tf_files/retrained_graph_optimized.pband~/tf_files/retrained_labels.txt) instead.

Also, we should update some constants in theClassifierActivity.java, as specified in a comment in this same file:

privatestaticfinalintINPUT_SIZE=299;privatestaticfinalintIMAGE_MEAN=128;privatestaticfinalfloatIMAGE_STD=128;privatestaticfinalStringINPUT_NAME="Mul";privatestaticfinalStringOUTPUT_NAME="final_result";privatestaticfinalStringMODEL_FILE="file:///android_asset/retrained_graph_optimized.pb";privatestaticfinalStringLABEL_FILE="file:///android_asset/retrained_labels.txt";

5. Test the trained AI

We have installed the new AI model. Now, we can deploy the project on an Android device, and have fun detecting objects using our new retrained AI:

How about Android Things?

Using TensorFlow on Android Things is a little bit easier than on Android.

There is already an official gradle sample project that works out-of-the-box with the ImageNet model, and which can be deployed quickly:github.com/androidthings/sample-tensorflow-imageclassifier/.

And if you want to use your own custom model instead, you will simply need to do exactly the same steps explained in this article (Android Things is Android, after all):

Place your custom model (.pband.txtfiles) in the assets directory

Remove the.aarlib and use TensorFlow’s latest libs instead

Modify the constants in theTensorFlowImageClassifier.javafile

(I shamelessly stole this LCD picture idea from@riggaroo’s latest conference. Don’t tell her.)

You can watch the custom classifier in action, on thisYouTube video.

The LCD driver used is the1602 LCD module driver.

Conclusion (a.k.a. why would we need that?)

In this post, you saw something completely useless: using deep learning to classify video game characters, but you could do something funnier, like adab detectorshifumi game, for instance.

Better, you could create a robot that changes its behaviour and its way of talking according to who’s in front of it (a child / an adult).

You can use deep learning algorithm to identify skin cancer, or detect defective pieces and automatically stop a production line as soon as possible.

Why not even create a sign language recognizer?

Have fun!

(Original Link:http://nilhcem.com/android/custom-tensorflow-classifier)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,980评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,178评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,868评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,498评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,492评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,521评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,910评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,569评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,793评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,559评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,639评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,342评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,931评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,904评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,144评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,833评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,350评论 2 342

推荐阅读更多精彩内容

  • (晒韵茶友团拜)芳栈茶香室四溢,齿留余甘口清香。一杯晒韵连友情,团拜宴席会茶友。
    甘朝武阅读 122评论 0 0
  • 好长时间没一口气读完一本书了,《向最高处攀登》是个例外,从大诺老师发到朋友圈的那一刻,我就决定买来拜读。原因在于这...
    补拙莫如勤LV阅读 203评论 0 0
  • 李潇南阅读 193评论 0 0
  • 常说:少来夫妻老来伴。 还常说:夫妻到最后,顶好的变成亲人;次好的变成朋友;最糟糕的是变成互相厌烦的仇人,还没办法...
    婷婷1229阅读 226评论 0 0