[物联网文章之其四] 在物联网中应用机器学习:使用 Android Things 与 TensorFlow

日常前言

  • 四月份花了一大部分时间去深入代码,把我们的双摄虚化流程解析了一遍。然后为了给组内分享,又花了相当一部分时间去做总结,画思维导图、作流程图等等,这其中学到了挺多东西的,尤其是对高通 Camera HAL 层的数据流部分,Camera Post Process 的前后节点都有了一个比较大概的了解,在跟踪数据流的时候没那么头晕了。
  • 还有,总结、分享知识的时候,作图真的非常重要,一份填满大量文字的 PPT,可能讲 3 个小时都讲不完,最后听众也很难有所收获。然而如果有 70% ~ 90% 的篇幅用图片来直观表述,剩下的文字用于精炼、简洁地描述,这样可能 1~2 个小时就能搞定,并且听众至少也能留下一个比较整体的印象。
  • 好吧,扯远了,回归这次的活动,这一期是物联网的主题,又是我不熟悉的领域,只能找一些介绍性的文章来翻译了。以及……上期又送来一个抱枕……这期要是再送公仔,那就把这些东西送给女盆友一宿舍当毕业礼物吧hh
  • 这期采纳了四篇:

版权相关

翻译人:StoneDemo,该成员来自云+社区翻译社
原文链接:Applying ML to IoT With Android Things and TensorFlow
原文作者:Francesco Azzola


Applying ML to IoT With Android Things and TensorFlow

题目:(在物联网中应用机器学习:使用 Android Things 与 TensorFlow)

This project explores how to apply Machine Learning to IoT. As our IoT platform, we will use Android Things, and as our Machine Learning engine, we will use Google TensorFlow. Nowadays, Machine Learning is, with IoT, one of the most interesting technological topics out. To give a simple definition of the Machine Learning, it is possible to the Wikipedia definition:
Machine learning is a field of computer science that gives computer systems the ability to “learn” (i.e. progressively improve performance on a specific task) with data, without being explicitly programmed.

本项目探讨如何将机器学习(Machine learning)应用到物联网(IoT,Internet of Things)中。我们将使用 Android Things 作为我们的物联网平台,并且采用 Google TensorFlow 作为我们的机器学习引擎。如今,机器学习与物联网都是技术话题中的大热门。下面是维基百科上对机器学习的一个简单定义
机器学习是计算机科学中的一个领域,它使计算机系统能够利用数据进行 “学习”(即逐步提高特定任务的性能),而不需要进行显式编程(Explicitly programmed)。

In other words, after a training step, a system can predict outcomes even if it is not specifically programmed for them. On the other hand, we all know IoT and the concept of connected devices. One of the most promising topics is how to apply Machine Learning to IoT in order to build expert systems that are able to “learn”. Moreover, it uses this knowledge to control and manage physical objects.

换句话说,在进行训练步骤以后,系统就可以预测结果(即使这不是专门为这些结果进行编程的)。另一方面,我们都了解物联网以及连接设备的概念。最有前途的话题之一便是如何将机器学习应用于物联网之中,以构建能够 “学习” 的专家系统。此外,该系统会运用这些知识来控制和管理实物。

There are several fields where applying Machine Learning and IoT produce an important value, such as:

  • Industrial IoT (IIoT) in predictive maintenance
  • Consumer IoT where Machine Learning can make the device intelligent so that it can adapt to our habits

下面列举一些应用到机器学习,以及物联网能产生重要价值的领域:

  • 预测维护(Predictive maintenance)中的工业物联网(IIoT,Industrial IoT)。
  • 在消费者物联网(Consumer IoT)中,机器学习可以使设备变得更加智能化,从而适应我们的习惯。

In this tutorial, we want to explore how to apply Machine Learning to IoT using Android Things and TensorFlow. The basic idea that stands behind this Android Things IoT project is exploring how to build a robot car that is able to recognize some basic shapes (like arrows) and be controlled. We have already covered how to build a robot car using Android Things, so I suggest you read the tutorial before starting this project.

在本教程中,我们将探索如何使用 Android Things 和 TensorFlow 将机器学习应用到物联网中。这一 Android Things 物联网项目背后的基本思想就是,探索如何构建一个能够识别一些基本形状(比如箭头)并被控制的机器人小车(Robot car)。我们已经介绍过如何使用 Android Things 构建机器人小车,我建议您在开始此项目之前先阅读那篇教程。

This Machine Learning and IoT project covers these main topics:

  • How to set up the TensorFlow environment using Docker
  • How to train the TensorFlow system
  • How to integrate TensorFlow with Android Things
  • How to control the robot car using TensorFlow results

本次机器学习和物联网项目主要涵盖以下主题:

  • 如何使用 Docker 配置 TensorFlow 环境
  • 如何训练 TensorFlow 系统
  • 如何集成 TensorFlow 与 Android Things
  • 如何使用 TensorFlow 输出结果来控制机器人小车

This project is derived from Android Things TensorFlow image classifier.
Let us start!

本项目衍生自 Android Things TensorFlow 图像分类器

我们开始吧!

How to Create an Image Classifier in Tensorflow

(如何在 Tensorflow 中创建一个图像分类器)

Before starting, it is necessary to install and configure the TensorFlow environment. I’m not a Machine Learning expert, so I need to find something fast and ready to use so that we can build the TensorFlow image classifier. For this reason, we can use Docker to run an image of TensorFlow. Follow these steps:
1. Clone the TensorFlow repository:
—— code ——
2. Create a directory (/tf-data) that will hold all the files that we will use during the project.
3. Run Docker:
—— code ——

在开始之前,我们有必要先安装并配置好 TensorFlow 环境。我并非机器学习专家,所以我需要找一些速成的东西并准备好使用,以便我们可以构建 TensorFlow 图像分类器。因此,我们可以使用 Docker 来运行一个搭载了 TensorFlow 的映像。照着以下步骤进行:

1.克隆 TensorFlow 仓库:

git clone https://github.com/tensorflow/tensorflow.git
cd /tensorflow
git checkout v1.5.0

2.创建一个目录(/tf-data),该目录将保存我们在项目中需要用到的所有文件。
3.运行 Docker:

docker run -it \
--volume /tf-data:/tf-data \
--volume /tensorflow:/tensorflow \
--workdir /tensorflow tensorflow/tensorflow:1.5.0 bash

Using this command, we run an interactive TensorFlow environment and mount some directories that we will use during the project.

使用这些命令,我们就可以运行一个交互式 TensorFlow 环境并增加(Mount)一些我们将在项目中使用到的目录。

How to Train TensorFlow

(如何训练 TensorFlow)

Before the Android Things system is able to recognize images, it is necessary to train the TensorFlow engine so that it can build its model. For this purpose, it is necessary to gather several images. As said before, we want to use arrows to control the Android Things robot car — so we have to collect at least four arrow types:

  • up arrow
  • down arrow
  • left arrow
  • right arrow

在 Android Things 系统能够识别图像之前,我们有必要先训练 TensorFlow 引擎,以构建其模型。以此为由,收集一些图片是有必要的。如前所述,我们希望使用箭头来控制 Android Things 机器人小车 —— 所以我们必须收集至少四种类型的箭头:

  • 向上箭头
  • 向下箭头
  • 左箭头
  • 右箭头

To train the system is necessary to create a “knowledge base” with these four different image categories. Create in /tf-data a directory called images and under it four sub-directories named:

  • up-arrow
  • down-arrow
  • left-arrow
  • right-arrow

为训练该系统,我们有必要对这四种不同的图像类别创建一个“知识库”。在 /tf-data 中一个名为 images 的目录下创建四个目录,命名如下:

  • up-arrow
  • down-arrow
  • left-arrow
  • right-arrow

Now it is time to look for the images. I have used Google Image search, but you can use other approaches, too. To simplify the image download process, you should install a Chrome plugin that downloads all the images with only one click. Do not forget, the more images you download, the better it is for the training process, even if the time to create the model could increase.

现在是时候去搜集图像资源了。我使用的是 Google 图片搜索,您也可以使用其他方法进行搜集。为了简化图片下载过程,您应该安装 Chrome 插件,它能够一键下载所有图片。可别忘了,您下载的图像越多,其训练过程(Training process)越好(即使创建模型的时间可能会有所增加)。

Open your browser and start looking for the four image categories:

打开浏览器,开始查找以下四类图像:

这里写图片描述

I have downloaded 80 images for each category. I do not care about image extensions.

每个类别我分别下载了 80 张图。我并不关心图片的扩展。

Once all the categories have their images, follow these steps (in the Docker interface):

一旦所有类别都有其图像,请按照以下步骤操作(在 Docker 界面中):

python /tensorflow/examples/image_retraining/retrain.py \ 
--bottleneck_dir=tf_files/bottlenecks \
--how_many_training_steps=4000 \
--output_graph=/tf-data/retrained_graph.pb \
--output_labels=/tf-data/retrained_labels.txt \
--image_dir=/tf-data/images

It could take some time, so be patient. At the end, you should have two files in /tf-data folder:

  1. retrained_graph.pb
  2. retrained_labels.txt

这操作可能需要花费一些时间,所以要耐心等待。最后,在你的文件夹 /tf-data 中应有两个文件:

  1. retrained_graph.pb
  2. retrained_labels.txt

The first file contains our model as the result of the TensorFlow training process while the second file contains the labels related to our four image categories.

第一个文件包含我们的模型,这是 TensorFlow 训练过程的结果。而第二个文件则包含了与我们的四个图像类别相关的标签。

How to Test the Tensorflow Model

(如何测试 Tensorflow 模型)

If you want to test the model to check if everything is working, you can use this command:

如果你想测试模型,以检查一切是否正常,你可以使用以下命令:

python scripts.label_image \
--graph=/tf-data/retrained-graph.pb \
--image=/tf-data/images/[category]/[image_name.jpg]

Optimizing the Model

(优化模型)

Before we can use this TensorFlow model in the Android Things project it is necessary to optimize it:

在能够使用这个 TensorFlow 模型到 Android Things 项目中之前,我们有必要优化它:

python /tensorflow/python/tools/optimize_for_inference.py \
--input=/tf-data/retrained_graph.pb \
--output=/tf-data/opt_graph.pb \
--input_names="Mul" \
--output_names="final_result"

That’s all we have for our model. We will use this model to apply Machine Learning to IoT/integrate Android Things with TensorFlow. The goal is giving the Android Things app the intelligence to recognize arrow images and react, controlling the robot car’s directions.

这就是我们的模型。我们将使用此模型将机器学习应用于物联网(即集成 Android Things 与 TensorFlow)。其目标是为 Android Things 应用提供智能识别箭头图像,并作出相应反应,从而控制机器人小车的方向。

If you want to have more details about TensorFlow and how to generate the model, look at the official documentation and this tutorial.

如果您想了解更多关于 TensorFlow 的细节,以及如何生成模型,请查看官方文档和这个教程

How to Apply Machine Learning to IoT Using Android Things and TensorFlow

(如何使用 Android Things 和 TensorFlow 将机器学习应用到物联网中)

Once the TensorFlow data model is ready, we can move to the next step: how to integrate Android Things with TensorFlow. For this purpose, we can split this task into two steps:

  1. The hardware part, where we connect motors and other peripherals to the Android Things board
  2. Implementing the app

一旦 TensorFlow 数据模型准备就绪,我们就可以进入下一步:如何集成 Android Things 与 TensorFlow。为达成这一目的,我们可以将此任务分为两步:

  1. 硬件部分,我们将电机和其他外围设备(Peripheral)连接到 Android Things 板上
  2. 实现应用程序

Android Things Schematics

(Android Things 原理图)

Before digging into the details about how to connect peripherals, this is the list of components used in this Android Things project:

  1. Android Things board (Raspberry Pi 3)
  2. Raspberry Pi Camera
  3. One LED
  4. LN298N Dual H Bridge (to control the motors)
  5. A robot car chassis with two wheels

在深入探讨如何连接外围设备之前,我们先看看下面这个 Android Things 项目中使用的组件列表:

  1. Android Things 板(树莓派 3,Raspberry Pi 3)
  2. 树莓派相机
  3. 一个 LED 灯
  4. LN298N 双H桥(用以控制电机)
  5. 带两个轮子的机器人小车底盘

I do not cover how to control motors using Android Things because we have already covered that in a previous post.

我不在此介绍如何使用 Android Things 控制电机,因为我们已经在之前的文章中介绍过这一点。

Below are the schematics:

以下是原理图:

原理图

In the picture above, the camera is not shown. The final result is:

上图中,相机组件并未表现出来。其最终的结果如下:

结果图

Implementing the Android Things App With TensorFlow

(基于 TensorFlow 实现 Android Things App)

The last step is implementing the Android Things app. For this purpose, we can re-use the example available in GitHub named sample TensorFlow image classifier. Before starting, clone the GitHub repository so that you can modify the source code.

最后一步便是实现 Android Things 应用程序。为此,我们可以重用 GitHub 上名为 TensorFlow 图像分类器示例的示例项目。在开始之前,先克隆 GitHub 仓库,以便您可以修改源代码。

This Android Things app is different from the original app because:

  1. It does not use the button to start the camera to capture the image
  2. It uses a different model
  3. It uses a blinking LED to notify that the camera will take the picture after the LED stops blinking
  4. It controls the motors when TensorFlow detects an image (arrows). Moreover, it turns on the motors for 5 seconds before starting the loop from step 3

该 Android Things 应用与原来的应用有所不同,在于:

  1. 它不使用按钮来启动相机捕捉图像
  2. 它使用不同的模型
  3. 它使用一个闪烁的 LED 进行通知,摄像机在 LED 停止闪烁后拍摄照片
  4. 它在 TensorFlow 检测到图像(箭头)时控制电机。此外,在从步骤 3 开始循环之前,先打开电机 5 秒

To handle a blinking LED, use the following code:

要处理闪烁的 LED,请使用以下代码:

private Handler blinkingHandler = new Handler();
private Runnable blinkingLED = new Runnable() {
  @Override
  public void run() {
    try {
     // If the motor is running the app does not start the cam
     if (mc.getStatus())
       return ;
     Log.d(TAG, "Blinking..");
     mReadyLED.setValue(!mReadyLED.getValue());
     if (currentValue <= NUM_OF_TIMES) {
       currentValue++;
       blinkingHandler.postDelayed(blinkingLED, 
                       BLINKING_INTERVAL_MS);
     }
     else {
      mReadyLED.setValue(false);
      currentValue = 0;
      mBackgroundHandler.post(mBackgroundClickHandler);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
  }
};

When the LED stops blinking, the app captures the image.

当 LED 停止闪烁时,应用程序将捕获图像。

Now it is necessary to focus on how to control the motors according to the image detected. Modify the method:

现在有必要关注如何根据检测到的图像来控制电机。修改方法如下:

@Override
public void onImageAvailable(ImageReader reader) {
  final Bitmap bitmap;
   try (Image image = reader.acquireNextImage()) {
     bitmap = mImagePreprocessor.preprocessImage(image);
   }
   final List<Classifier.Recognition> results = 
      mTensorFlowClassifier.doRecognize(bitmap);
   Log.d(TAG, 
    "Got the following results from Tensorflow: " + results);
   // Check the result
   if (results == null || results.size() == 0) {
     Log.d(TAG, "No command..");
     blinkingHandler.post(blinkingLED);
     return ;
    }
    Classifier.Recognition rec = results.get(0);
    Float confidence = rec.getConfidence();
    Log.d(TAG, "Confidence " + confidence.floatValue());
    if (confidence.floatValue() < 0.55) {
     Log.d(TAG, "Confidence too low..");
     blinkingHandler.post(blinkingLED);
     return ;
    }
    String command = rec.getTitle();
    Log.d(TAG, "Command: " + rec.getTitle());
    if (command.indexOf("down") != -1)
       mc.backward();
    else if (command.indexOf("up") != -1)
       mc.forward();
    else if (command.indexOf("left") != -1)
       mc.turnLeft();
    else if (command.indexOf("right") != -1)
       mc.turnRight();
}

In this method, after the TensorFlow returns the possible labels matching the image captured, the app compares the result with the possible directions and controls the motors consequently.

在这种方法中,当 TensorFlow 返回匹配捕获图像的可能标签后,应用程序会将结果与可能的方向进行比较,从而控制电机。

Finally, it is time to use the model created at the beginning. Copy the opt_graph.pb and the reatrained_labels.txt under the assets folder replacing the existing files.

最后,是时候使用在刚开始时创建的模型了。拷贝 assets 文件夹下的 opt_graph.pbreatrained_labels.txt 文件,并替换现有文件。

Open the Helper.java and modify the following lines:

打开 Helper.java 并修改以下几行:

public static final int IMAGE_SIZE = 299;
private static final int IMAGE_MEAN = 128;
private static final float IMAGE_STD = 128;
private static final String LABELS_FILE = "retrained_labels.txt";
public static final String MODEL_FILE = "file:///android_asset/opt_graph.pb";
public static final String INPUT_NAME = "Mul";
public static final String OUTPUT_OPERATION = "output";
public static final String OUTPUT_NAME = "final_result";

Run the app and have fun showing arrows to the camera and checking the result. The robot car has to move according to the arrow shown.

运行应用程序,试试向相机展示箭头,并检查结果。机器人小车必须按照所示的箭头进行移动。

Summary

(小结)

At the end of this tutorial, we have discovered how to apply Machine Learning to IoT using Android Things and TensorFlow. We can control the robot car using images and make it moving according to the image shown.

在本教程的最后,我们介绍了如何运用 Android Things 与 TensorFlow 将机器学习应用到物联网中。我们可以使用图像控制机器人小车,并根据显示的图像移动机器人小车。

猜你喜欢

转载自blog.csdn.net/qq_16775897/article/details/80304364