Java-机器学习实践指南-全-

Java 机器学习实践指南(全)

原文:Practical Java Machine Learning

协议:CC BY-NC-SA 4.0

一、简介

第一章为这本书奠定了基础。

它描述了这本书将实现什么,这本书的目标读者是谁,为什么机器学习(ML)很重要,为什么 Java 有意义,以及如何部署 Java ML 解决方案。

The chapter includes the following:

  • 回顾人工智能及其子领域的所有术语,包括机器学习

  • 为什么 ML 很重要,为什么 Java 是实现的好选择

  • 最流行的开发环境的设置说明

  • ML-Gates 介绍,一种 ML 开发方法

  • ML 和货币化策略的商业案例

  • 为什么这本书没有涵盖深度学习,为什么这是一件好事

  • 何时以及为什么你可能需要深度学习

  • 探索 ML 解决方案时如何创造性地思考

  • 重要的洗钱调查结果概述

1.1 术语

随着人工智能和机器学习越来越受欢迎,相关术语也出现了很多混乱。似乎每个人使用这些术语的方式都不同且不一致。

Some quick definitions for some of the abbreviations used in the book:

  • 人工智能(AI):任何假装聪明的东西。

  • 机器学习(ML):一个通用术语,包括深度学习(DL)和经典机器学习(CML)的子领域。

  • 深度学习(DL):一类利用神经网络的机器学习算法。

  • 强化学习(RL):一种接受反馈的监督学习方式,但不一定针对每个输入。

  • 神经网络(NN):模仿人脑和神经系统的计算机系统。

  • 经典机器学习(CML):一个更狭义地定义 ML 算法集的术语,不包括深度学习算法。

  • 数据挖掘(DM):寻找数据中隐藏的模式,这是一项通常由人来完成的任务。

  • 机器学习门(MLG):这本书将介绍一种叫做 ML-Gates 的开发方法。门号从 ML-Gate 5 开始,到 ML-Gate 0 结束。例如,MLG3 是该方法的 ML-Gate 3 的缩写。

  • 随机森林(RF)算法:一种用于分类、回归和其他任务的学习方法,通过在训练时构建决策树来运行。

  • 朴素贝叶斯(NB)算法:一个“概率分类器”家族,基于应用贝叶斯定理,在特征之间具有强(朴素)独立性假设。

  • k-最近邻(KNN)算法:一种用于分类和回归的非参数方法,其中输入由特征空间中 k 个最近的训练示例组成。

  • 支持向量机(SVM)算法:一种带有相关学习算法的监督学习模型,用于分析用于分类和回归的数据。

大部分混乱源自使用这些术语的不同派别或“领域”。在许多情况下,他们创造了这些术语,并在其领域内使用了几十年。

Table 1-1 shows the domains that have historically claimed ownership to each of the terms. The terms are not new. Artificial intelligence is a general term. AI first appeared back in the 1970s.Table 1-1

人工智能定义和领域

|

学期

|

定义

|

领域

|
| --- | --- | --- |
| 统计数字 | 量化数据。DM,ML,DL 都是用统计学来做决策的。 | 数学系 |
| 人工智能 | 关于如何创造智能代理的研究。任何假装聪明的事情。我们给计算机编了一个程序,让它像智能代理一样工作。它不需要学习或归纳。 | 历史、营销、趋势。 |
| 数据挖掘 | 解释和识别有意义的模式。无人监管的方法。发现你的数据中隐藏的模式,这些模式可以被的人用来做决策。一个完整的商业流程,通常在大型数据集(大数据)上。 | 商业世界,商业智能 |
| 机器学习 | 人工智能的一个大分支,我们在其中建立模型来预测结果。使用算法并有明确的目标。我们把现有的知识归纳成新的数据。而是学习一个模型来对物体进行分类。 | 学术部门 |
| 深度学习 | 将神经网络应用于 ML。模式识别是一项重要的任务。 | 趋势 |

表 1-1 中的定义代表了我在阅读大量研究并与行业专家交谈后的综合理解。你可以在网上找到大量支持或反驳这些定义的哲学辩论。

Do not get hung up on the terminology. Usage of the terms often comes down to domain perspective of the entity involved. A mathematics major who is doing research on DL algorithms will describe things differently than a developer who is trying to solve a problem by writing application software. The following is a key distinction from the definitions:

数据挖掘 都是关于 人类 发现数据中隐藏的模式,而 机器学习 自动化这个过程,并允许 计算机 通过使用算法来执行这项工作。

It is helpful to think about each of these terms in context of “infrastructure” and “algorithms.” Figure 1-1 shows a graphical representation of these relationships. Notice that statistics are the underlying foundation, while “artificial intelligence” on the right-hand side includes everything within each of the additional subfields of DM, ML, and DL.

机器学习就是对 选择 将算法 应用于我们的数据的实践。

I will discuss algorithms in detail in Chapter 3. The algorithms are the secret sauce that enables the machine to find the hidden patterns in our data. img/468661_1_En_1_Fig1_HTML.jpg Figure 1-1

人工智能子领域关系

1.2 历史

The term “artificial intelligence” is hardly new. It has actually been in use since the 1970s. A quick scan of reference books will provide a variety of definitions that have in fact changed over the decades. Figure 1-2 shows a representation of 1970s AI, a robot named Shakey, alongside a representation of what it might look like today.img/468661_1_En_1_Fig2_HTML.png Figure 1-2

艾,过去和现在

Most historians agree that there have been a couple of “AI winters.” They represent periods of time when AI fell out of favor for various reasons, something akin to a technological “ice age.” They are characterized by a trend that begins with pessimism in the research community, followed by pessimisms in the media, and finally followed by severe cutbacks in funding. These periods, along with some historical context, are summarized in Table 1-2.Table 1-2

艾的历史与“冬天”时期

|

时期

|

语境

|
| --- | --- |
| One thousand nine hundred and seventy-four | 英国议会发表研究称,人工智能算法将在“现实世界”问题上陷入停滞。这一挫折引发了包括 DARPA 在内的全球资金削减。这场危机被归咎于“不切实际的预测”和对技术的“日益夸大”。 |
| One thousand nine hundred and seventy-seven | AI WINTER 1 |
| 1984-1987 | 对人工智能的热情在 20 世纪 80 年代失去了控制,导致了价值数十亿美元的人工智能产业的又一次崩溃。 |
| One thousand nine hundred and ninety | 人工智能冬天 2 当人工智能再次到达一个低水位标志。 |
| Two thousand and two | 人工智能研究员罗德尼·布鲁克斯抱怨说,“有一个愚蠢的神话,人工智能已经失败了。” |
| Two thousand and five | 雷·库兹韦尔宣称,“许多观察家仍然认为人工智能冬天是故事的结尾...然而今天,成千上万的应用程序已经深深嵌入到每个行业的基础设施中。” |
| Two thousand and ten | 人工智能再次得到广泛应用和资金支持。机器学习越来越重要。 |

理解为什么会发生这些 AI 冬天是很重要的。如果我们打算投资学习和部署人工智能解决方案,我们希望确定另一个人工智能冬天不会迫在眉睫。

Is another AI winter on the horizon? Some people believe so, and they raise three possibilities:

  • 归咎于统计数据:人工智能正走向错误的方向,因为它严重依赖统计技术。回想一下图 1-1 中,统计是人工智能和人工智能的基础。

  • 机器疯狂运转:顶级研究人员认为另一个人工智能冬天可能会发生,因为滥用这项技术将导致它的灭亡。2015 年,埃隆·马斯克(Elon Musk)、史蒂文·霍金(Steven Hawking)、史蒂夫·沃兹尼亚克(Steve Wozniak)和 3000 名人工智能和机器人研究人员签署了一封禁止开发和使用自主武器的公开信。

  • 假数据:数据是机器学习的燃料(在第二章中有更多关于这方面的内容)。这一论点的支持者认为,不断增加的熵将继续降低全球数据完整性,直到 ML 算法变得无效和无价值。这是 2018 年的一个相关论点。我将在第二章中讨论多种类型的数据。

看起来,另一个人工智能冬天不太可能在不久的将来到来,因为 ML 是如此有前途,因为我们可以利用高质量的数据来推动它。

今天,我们现有的大部分数据质量不高,但我们可以通过保持对模型所依赖的源数据的控制来降低这种风险。

政府资金的削减导致了之前的 AI 寒冬。今天,私营部门的资金是巨大的。只要看看人工智能初创公司正在筹集的一些风投资金就知道了。未来政府支持的类似削减将不再产生重大影响。对曼梯·里来说,这一次这匹马似乎永远离开了马厩。

1.3 机器学习商业案例

无论您是自由开发人员,还是为拥有大量可用资源的大型组织工作,在开始将有价值的资源应用于 ML 部署之前,您都必须考虑业务案例。

机器学习炒作

ML 当然也不能幸免于炒作。这本书的序言列举了媒体最近的一些炒作。这本书的目标是帮助你克服宣传和实现真正的问题解决方案。

ML and DL are not the only recent technology developments that suffer from excessive hype. Each of the following technologies has seen some recent degree of hype:

  • 虚拟现实

  • 增强现实

  • 比特币

  • 区块链

  • 互联家庭

  • 虚拟助手

  • 物联网

  • 3D 电影

  • 4K 电视台

  • 机器学习

  • 深度学习

一些技术变得广泛和普遍使用,而另一些技术则逐渐消失。回想一下,就在短短几年前,3D 电影有望在影院上映时完全取代传统电影。这并没有发生。

对我们来说,继续密切关注 ML 和 DL 技术非常重要。事情将如何发展还有待观察,但最终,我们可以通过实验、构建和部署我们自己的应用程序来说服自己相信这些技术的可行性。

挑战和关切

表 1-3 列出了 IT 主管在考虑 ML 和 DL 计划时最担心什么时强调的一些主要挑战和顾虑。与任何 it 计划一样,实现 IT 计划都有机会成本,并且从计划中获得的收益必须大于机会成本,即通过进行 AI/ML 而放弃另一个潜在机会的成本。

Fortunately, there are mitigation strategies available for each of the concerns. These strategies, summarized below, are even available to small organization and individual freelance developers.Table 1-3

机器学习问题和缓解策略

|

ML 关注

|

缓解策略

|
| --- | --- |
| IT 基础设施的成本 | 利用云服务提供商,如谷歌 GCP、亚马逊 AWS、微软 Azure |
| 没有足够的有经验的员工 | 即使我们不能雇佣数据科学家,ML 也要求开发人员开始像数据科学家一样思考。这并不意味着我们突然需要数学博士。组织可以从采用数据优先的方法开始,如本章后面介绍的 ML-Gates。 |
| 数据或分析平台的成本 | 有很多非常昂贵的数据科学平台;然而,我们可以从使用免费开源软件的经典 ML 开始,并取得令人印象深刻的结果。 |
| 数据质量不足 | 存在大量低质量的数据。我们可以通过减少对“社会”数据的依赖,转而关注我们自己创造的数据来减轻这种影响。我们还可以利用来自传感器的数据,这些数据应该没有这种偏差。 |
| 数据量不足 | 通过控制采样间隔,可以以更高的规模产生自生数据或传感器数据。在早期阶段将数据集成到项目中应该是 ML 方法的一部分。 |

使用上述缓解策略,开发人员可以用最小的学习曲线投资产生一些潜在的突破性 ML 软件解决方案。这是一个软件开发人员的大好时机。

接下来,我将进一步了解 ML 数据科学平台。这种平台可以帮助我们实现将我们的机器学习投资货币化的目标。货币化战略可以进一步缓解这些挑战和担忧。

数据科学平台

If you ask business leaders about their top ML objectives, you will hear variations of the following:

  • 提高组织效率

  • 对未来情景或结果做出预测

  • 利用人工智能/人工智能获得竞争优势

  • 将 AI/ML 货币化

Regardless of whether you are an individual or freelance developer, monetization is one of the most important objectives.

无论组织规模如何,货币化 ML 解决方案都需要两个构建模块:部署一个 数据科学平台 ,并遵循一个 ML 开发方法论

When it comes to the data science platforms, there are myriad options. It is helpful to think about them by considering a “build vs. buy” decision process. Table 1-4 shows some of the typical questions you should ask when making the decision. The decisions shown are merely guidelines.Table 1-4

数据科学平台:构建还是购买决策

|

构建与购买问题

|

决定

|
| --- | --- |
| 有没有一个软件包可以完全解决你的问题? | 是:购买 |
| 有没有解决你很多需求的包?这是常见的情况,没有简单的答案。 | 未确定的 |
| 有没有可以考虑的开源包? | 是:构建 |
| 是不是套餐太难实现了? | 是:购买 |
| 你定义好的问题需要深度学习吗? | 不:也许建造 |
| 分析是您业务的关键优势吗? | 是:也许建造 |
| 你的分析场景独特吗? | 是:构建 |
| 有新的数据吗? | 是:构建 |
| 你的领域需要你敏捷吗? | 是:构建 |
| 您是否能够获得您的问题所需的数据科学人才?不要低估你自己或你的员工;许多开发人员很快掌握了数据科学技能。 | 否:购买 |

那么“购买”一个数据科学平台实际上意味着什么呢?让我们考虑一个例子。

You wish to create a recommendation engine for visitors to your website. You would like to use machine learning to build and train a model using historical product description data and customer purchase activity on your website. You would then like to use the model to make real-time recommendations for your site visitors. This is a common ML use case. You can find offerings from all of the major vendors to help you implement this solution. Even though you will be “building” your own model using the chosen vendor’s product, you are actually “buying” the solution from the provider. Table 1-5 shows how the pricing might break down for this project for several of the cloud ML providers.Table 1-5

示例 ML 云提供商定价cloud.google.com/ml-engine/docs/pricingaws.amazon.com/aml/pricing/azure . Microsoft . com/en-us/Pricing/details/machine-learning-studio/

|

供应者

|

功能

|

定价

|
| --- | --- | --- |
| 谷歌云 ML 引擎 | 建模费用批量预测实时预测 | 每小时 0.27 美元(标准机器)每节点小时 0.09 美元每节点小时 0.30 美元 |
| 亚马逊机器学习(AML) | 建模费用批量预测实时预测 | 每小时 0.42 美元,每 1000 次预测 0.10 美元,每次预测 0.0001 美元 |
| Microsoft Azure ML Studio | 建模费用批量预测实时预测 | 每月 10 美元,每小时 1 美元(标准)每月 100 美元包括 100,000 次交易(API) |

在本例中,由于构建模型需要计算时间,因此您应计成本。随着非常大的数据集和深度学习模型的构建,这些成本变得很大。

另一个“购买”ML 解决方案的常见例子是使用发布的 API 访问预先构建的模型。您可以将这种方法用于图像检测或自然语言处理,其中存在庞大的模型,您可以简单地通过使用您的输入细节调用 API(通常使用 JSON)来利用这些模型。在本书的后面,您将看到如何实现这个简单的例子。在这种情况下,大多数服务提供商按照给定时间段内的 API 调用次数收费。

那么“建立”一个数据科学平台意味着什么呢?在这种情况下,构建是指获得一个软件包,该软件包将提供实现您自己的 AI 或 ML 解决方案所需的构建块。

The following list shows some of the popular data science platforms:

  • MathWorks :传奇的 MATLAB 软件包的创造者,MathWorks 是业界的老玩家。

  • SAP :大型数据库玩家拥有完整的大数据服务和咨询业务。

  • IBM : IBM 提供 Watson Studio 和 IBM 数据科学平台产品。

  • 微软:微软 Azure 提供全方位的数据和分析服务及资源。

  • KNIME analytics 是一个基于 Java 的、开放的、直观的、综合的数据科学平台。

  • RapidMiner:一个基于 Java 的商业解决方案。

  • H2O.ai :流行的开源数据科学和 ML 平台。

  • Dataku:一个协作数据科学平台,允许用户进行原型设计、部署和大规模运行。

  • Weka :基于 Java 的解决方案,您将在本书中深入探讨。

该列表包括许多流行的数据科学平台,其中大多数是商业数据科学平台。关键词是商业。由于 Rapidminer 是基于 Java 的,所以在本书的后面,您将会更仔细地了解它。其他商业解决方案功能齐全,有从基于许可到基于订阅的一系列定价选项。

好消息是,您不必为了构建数据科学平台而进行资本支出,因为有一些开源替代方案可用。你将在第三章仔细查看 Weka 包。无论您决定构建还是购买,像 Weka 这样的开源替代方案都是非常有用的入门方式,因为它们允许您在学习的同时构建自己的解决方案,而不会将您束缚在昂贵的技术解决方案中。

ML 货币化

One of the best reasons to add ML into your projects is increased potential to monetize. You can monetize ML in two ways: directly and indirectly.

  • 间接货币化:让 ML 成为你产品或服务的一部分。

  • 直接货币化:向客户销售人工智能能力,客户反过来应用这些能力来解决特定问题或创造自己的产品或服务。

Table 1-6 highlights some of the ways you can monetize ML.Table 1-6

ML 货币化方法

|

战略

|

类型

|

描述

|
| --- | --- | --- |
| 架构 | 直接的 | AI 即服务,比如 Salesforce Einstein 或者 IBM Watson。 |
| MLaaS | 直接的 | ML 即服务,如表 1-5 中的 Google、Amazon 或 Microsoft 示例。 |
| 模型 API | 间接的 | 例如,您可以创建模型,然后发布一个 API,允许其他人使用您的模型进行自己的预测。 |
| 纳普拉斯 | 直接的 | NLP 即服务。苹果 Siri、微软 Cortana 或亚马逊 Echo/Alexa 等聊天机器人。Nuance Communications、Speechamatics 和 Vocapia 等公司。 |
| 集成 ML | 间接的 | 您可以创建一个模型来帮助解决您的问题,并将该模型集成到您的项目或应用程序中。 |

许多直接策略采用了 DL 方法。在本书中,重点主要放在间接 ML 策略上。在本书的后面,您将实现几个集成的 ML 应用程序。这种策略是间接的,因为 ML 功能对最终用户是不可见的。

客户不会因为你在申请中加入 ML 就多付钱。然而,如果你能解决一个新问题,或者为他们提供以前没有的能力,你就大大增加了赚钱的机会。

There is not much debate about the rapid growth of AI and ML. Table 1-7 shows estimates from Bank of America Merrill Lynch and Transparency Market Research. Both firms show a double-digit cumulative annual growth rate, or CAGR. This impressive CAGR is consistent with all the hype previously discussed.Table 1-7

AI 和 ML 爆发式增长

|

公司

|

领域

|

增长

|

CAGR

|
| --- | --- | --- | --- |
| 美银美林 | 人工智能 | 2015 年 580 亿美元,2020 年 1530 亿美元 | 27% |
| 透明度市场研究 | 机器语言(Machine Language) | 2106 年 10.7 亿美元,2025 年 198.6 亿美元 | 38% |

这些复合年增长率代表了令人印象深刻的增长。一些增长归因于 DL;但是,您不应该忽视 CML 为您提供的可能机会,尤其是在移动设备方面。

手机上的经典机器学习案例

经典机器学习不是一个很常用的术语。我将使用该术语来表示我们正在排除深度学习。图 1-3 显示了这种关系。这两种方法使用不同的算法,我将在第四章中讨论它们。

This book is about implementing CML for widely available computing devices using Java. In a sense, we are going after the “low-hanging fruit.” CML is much easier to implement than DL, but many of the functions we can achieve are no less astounding.img/468661_1_En_1_Fig3_HTML.jpg Figure 1-3

经典机器学习关系图

There is a case for mastering the tools of CML before attempting to create DL solutions. Table 1-8 highlights some of the key differences between development and deployment of CML and DL solutions.Table 1-8

经典机器学习和深度学习的比较

|

经典机器学习

|

深度学习

|
| --- | --- |
| 算法 |
| 算法大都商品化了。你不需要花很多时间去选择最好的算法或者调整算法。算法更容易解读和理解。 | 神经网络算法背后有很多新的研究。这涉及到大量的理论,并且需要大量的调整来为您的应用找到最佳的算法。 |
| 数据要求 |
| 需要适量的数据。您可以在某些应用程序中生成自己的数据。 | 训练 DL 模型需要大量的数据。大多数实体缺乏足够的数据来创建自己的 DL 模型。 |
| 性能 |
| 为许多移动、web 应用或嵌入式设备环境提供足够的性能。 | 深度学习神经网络算法最近的增长很大程度上是因为它们的性能优于 CML 算法。 |
| 语言 |
| 许多 Java 工具都是可用的,既有开源的也有商业的。 | 大多数 DL 库和工具都是基于 Python 或 C++的,只有基于 Java 的 DL4J 例外。一些流行的 C++ DL 引擎通常有 Java 包装器。 |
| 模型创建 |
| 模型大小可以适中。可以在桌面环境下创建模型。易于嵌入移动设备或嵌入式设备。 | 模型尺寸可能很大。难以将模型嵌入到移动应用中。创建模型需要大量 CPU/GPU 资源。 |
| 典型用例 |
| 回归聚类分类数据的特定用例 | 图像分类语音计算机视觉玩游戏自动驾驶汽车模式识别声音合成艺术创作照片分类异常(欺诈)检测行为分析推荐引擎翻译自然语言处理面部识别 |
| 货币化 |
| 间接 ML | 模型 APIsMLaaS |

对于移动设备和嵌入式设备,CML 很有意义。对于较小的数据集,CML 优于 DL,如图 1-7 中图表的左侧所示。

用一个现代的 CPU 在合理的时间内创建 CML 模型是可能的。CML 在桌面上启动。它不需要大量的计算资源,例如多个 CPU/GPU,而这在构建 DL 解决方案时是常见的。

The interesting opportunity arises when you build your models on the desktop and then deploy them to the mobile device either directly or through API interface. Figure 1-4 shows a breakdown of funding by AI category according to Venture Scanning.img/468661_1_En_1_Fig4_HTML.jpg Figure 1-4

按人工智能类别拨款

数据显示,移动应用的 ML 的资金大约是第二大领域 NLP 的三倍。所包含的类别表明,许多常见的 DL 领域,如计算机视觉、NLP、语音和视频识别,已经作为一个特定的类别包含在内。这让我们可以假设 ML 应用类别的很大一部分是经典的机器学习。

1.4 深度学习

I will not cover deep learning in this book because we can accomplish so much more easily with CML. However, in this short section I will cover a few key points of DL to help identify when CML might not be sufficient to solve an ML problem.img/468661_1_En_1_Fig5_HTML.jpg Figure 1-5

机器学习红色药丸/蓝色药丸隐喻

Morpheus described the dilemma we face when pursuing ML in the motion picture “The Matrix” (see also Figure 1-5):

“你服下蓝色药丸,故事结束;你在床上醒来,相信你想相信的一切。你吃了红色药丸,你就呆在仙境里,我让你看看兔子洞有多深。”

深度学习是一种仙境。这是我们今天在这个领域大肆宣传的原因。然而,它有一个很好的理由来达到炒作的目的。

You will often hear it stated the DL operates at scale. What does this mean exactly? It is a performance argument, and performance is obviously very important. Figure 1-6 shows a relationship between performance and data set size for CML and DL.img/468661_1_En_1_Fig6_HTML.jpg Figure 1-6

深度学习规模化运营

图表显示,对于较小的数据集,CML 的性能略优于 DL。问题是,多小才算小?当我们设计 ML 应用程序时,我们需要考虑数据集大小位于拐点的哪一边。没有简单的答案。如果有,我们会将实际数字放在 x 轴刻度上。这取决于您的具体情况,您需要在设计解决方案时决定使用哪种方法。

幸运的是,我们有工具来定义 CML 模型的性能。在第 4 和 5 章中,您将了解如何使用 Weka workbench 向您展示增加数据集大小是否真的会提高模型的性能。

识别 DL 应用程序

深度学习已经在许多特定领域展示了优于 CML 的结果,包括语音、自然语言处理、计算机视觉、玩游戏、自动驾驶汽车、模式识别、声音合成、艺术创作、照片分类、不规则(欺诈)检测、推荐引擎、行为分析、翻译等等。

随着你获得 ML 的经验,你开始对一个项目什么时候适合 DL 有一种感觉。

Deep networks work well when

  • 更简单的 CML 模型达不到你想要的精度。

  • 你有复杂的模式匹配需求。

  • 你的数据(序列)中有时间维度。

If you do decide to pursue a DL solution, you can consider the following deep network architectures:

  • 无监督预训练网络(UPN ),包括深度信念网络(DBN)和生成对抗网络(GAN)

  • 卷积神经网络(CNN)

  • 包括长短期记忆(LSTM)的循环神经网络(RNN)

  • 循环神经网络

我会在第四章多讲算法。在设计 CML 解决方案的时候,可以从确定你所追求的 CML 的算法类开始,比如分类或者聚类。然后,您可以很容易地在类中试验算法,以找到最佳解决方案。在 DL 中,就没有这么简单了。您需要将您的数据与特定的网络架构相匹配,这个主题超出了本书的范围。

While building deep networks is more complicated and resource intensive, as described in Table 1-8, tuning deep networks is equally challenging. This is because, regardless of the DL architecture you choose, you define deep learning networks using neural networks that are comprised of a large number of parameters, layers, and weights. There are many methods used to tune these networks including the methods in Table 1-9.Table 1-9

DL 网络的调谐方法

|

DL 神经网络的调谐方法

|
| --- |
| 反向传播 | 随机梯度下降 |
| 学习率衰减 | 拒绝传统社会的人 |
| 最大池化 | 批量标准化 |
| 长短期记忆 | Skipgram |
| 连续的单词袋 | 迁移学习 |

如表所示,DL 很复杂。可用于 DL 的 AI 引擎试图简化这个过程。表 1-10 显示了许多包含 DL 库的流行 AI 引擎。在本书中,您将关注面向 Java 开发人员的 CML 解决方案。

When you create DL solutions there are not as many Java tools and libraries available. DL4J and Spark ML are the two most common Java-based packages that can handle DL. DL4J is built from the ground up with DL in mind, whereas the popular Spark open source project has recently added some basic DL capabilities. Some of the excellent C++ libraries do provide Java wrappers, such as Apache MXNet and OpenCV.Table 1-10

具有深度学习库的人工智能引擎

|

包裹

|

描述

|

语言

|
| --- | --- | --- |
| 提亚诺 | 数学编程的强大通用工具。旨在促进深度学习。用于 GPU 的高级语言和编译器。 | 计算机编程语言 |
| 张量流 | 与深度学习相关的所有类型的数值计算的库。深受 Theano 的启发。数据流图表示多维数组(张量)的通信方式。(谷歌) | C++和 Python |
| CNT(消歧义) | 计算网络工具包。由微软研究院在许可许可下发布。 | C++ |
| 框架 | 简洁和可扩展的设计。基于赢得 2012 年 ImageNet 挑战赛的 AlexNet。(脸书支持) | C++和 Python |
| DL4J 系列 | 基于 Java 的开源深度学习库(Apache 2.0 许可证)。使用带有线性代数和矩阵操作的多维数组类。(Skymind) | 爪哇 |
| 火炬 | 开源的科学计算框架,优化用于 GPU。 | C |
| Spark MLlib(消歧义) | 大规模分布式数据处理的快速通用引擎。MLlib 是机器学习库。庞大的用户群。DL 支持正在增长。 | 爪哇 |
| Apache MXNet | 开源 Apache 项目。由 AWS 使用。美国有线电视新闻网和 LSTM。可扩展。由华盛顿大学和卡内基梅隆大学创办。 | C++Java 包装器 |
| 硬 | 用于开发和评估 DL 模型的功能强大、易于使用的库。最棒的张量流。 | 计算机编程语言 |
| 开放计算机视觉 | 可以为 Android 集成的开源计算机视觉库。 | C++Java 包装器 |

While it is entirely possibly that DL can solve your unique problem, this book wants to encourage you to think about solving your problem, at least initially, by using CML. The bottom line before we move onto ML methodology and some of the technical setup topics is the following:

深度学习令人惊叹,但在本书中,我们抵制诱惑,青睐经典的机器学习,只是因为它可以以少得多的麻烦完成如此多同样令人惊叹的事情。

在本书的其余部分,我们将选择蓝色药丸,并留在舒适的模拟现实的矩阵与 CML。

1.5 毫升-盖茨方法

Perhaps the biggest challenge of producing ML applications is training yourself to think differently about the design and architecture of the project. You need a new data-driven methodology. Figure 1-7 introduces the ML-Gates. The methodology uses these six gates to help organize CML and DL development projects. Each project begins with ML-Gate 6 and proceeds to completion at ML-Gate 0. The ML-Gates proceed in a decreasing order. Think of them as leading to the eventual launch or deployment of the ML project.img/468661_1_En_1_Fig7_HTML.jpg Figure 1-7

ML-Gates,一种机器学习开发方法

作为开发人员,我们编写大量代码。当我们接受新项目时,我们通常只是开始编码,直到我们得到可交付的产品。使用这种方法,我们通常会得到大量编码的应用程序。

对于 ML,我们想彻底改变这种方法。相反,我们试图用最少的代码实现数据密集型应用。最小编码的应用程序更容易支持。

ML-Gate 6:识别明确定义的问题

这一切都始于一个定义明确的问题。在这个阶段,你需要比从事传统的非 ML 项目时考虑得更狭隘一些。这可能导致创建集成到更大系统中的 ML 模块。

为了说明这一点,让我们考虑一个具有客户需求的示例项目。

For the project, you map the client requirements to well-defined ML solutions. Table 1-11 shows the original client requirements mapped to the ML models.Table 1-11

将需求映射到 ML 解决方案

|

初始客户要求

|

定义明确的 ML 解决方案

|
| --- | --- |
| R1:创建一个购物应用程序,这样实体店的顾客将会有更好的用户体验。 | 您发现需要一个基于位置的店内解决方案来让这款应用变得有用。您可以使用一种巧妙的 CML 方法来实现这一点。第六章的最后有更多关于实现的内容。 |
| R2:对使用该应用程序帮助增加销售额的购物者实现忠诚度计划。 | 忠诚度计划都是关于保存和召回客户数据。您可以使用产品库存数据和客户购买历史数据来构建 ML 模型,以便向客户推荐产品,从而增强用户体验。 |

在这个例子中,客户想要一个店内购物应用程序。这些是完全有效的需求,但是这些高层次的需求并不代表定义良好的 ML 问题。您的客户“表达了”提供“增强用户体验”的需求这到底意味着什么?要创建一个 ML 解决方案,你需要考虑客户未表达或潜在的需求。

右栏显示了如何将表达的需求映射到定义良好的 ML 解决方案。在这种情况下,您将构建两个独立的 ML 模型。您将需要这些模型的数据,这将引导您进入 ML-Gate 5。

ML-Gate 5:获取足够的数据

Data is the key to any successful ML app. In MLG5, you need to acquire the data. Notice this is happening well before you write any code. There are several approaches for acquiring data. You have several options and I will discuss the following in detail in Chapter 2:

  • 从第三方购买数据。

  • 使用公开可用的数据集。

  • 使用你自己的数据集。

  • 自己生成新的静态数据。

  • 来自实时源的流数据。

ML-Gate 4:处理/清理/可视化数据

一旦有了明确的问题和足够的数据,就该设计解决方案了。接下来的三个门涵盖此活动。在 MLG4 中,您需要处理、清理并可视化您的数据。

MLG4 就是为模型构建准备数据。您需要考虑缺失值、规范化、相关性、格式、数据类型和数据量等技术。

可视化是一个重要的方面,因为你努力对你的数据负责。对数据应用 CML 或 DL 算法时,未正确预处理的数据可能会导致错误。正因如此,MLG4 非常重要。俗话说垃圾进,垃圾出,这是你必须避免的。

ML-Gate 3:生成模型

准备好数据后,MLG3 就是您实际创建模型的地方。在 MLG3,您将初步决定使用哪种算法。

在第四章中,我将介绍可以生成模型的基于 Java 的 CML 环境。我将介绍如何创建模型以及如何测量模型的性能。

这是一种强大的设计模式,您将使用它来离线构建模型,以供以后在 Java 项目中使用。第五章将涵盖“预制”模型的进口和出口。

在 MLG3,您还必须考虑您的模型的版本控制和更新方法。管理模型的这一方面与管理非 ML 软件开发中的代码更新一样重要。

ML-Gate 2:测试/改进模型

创建初始模型后,MLG2 允许您测试和优化模型。正是在这里,您要检查模型的性能,以确认它将满足您的预测要求。

推理是使用模型进行预测的过程。在此过程中,您可能会发现需要调整或优化所选的算法。你可能会发现你需要改变你最初选择的算法。您甚至可能发现 CML 没有提供想要的结果,您需要考虑 DL 方法。

通过 ML-Gate 2 表示模型已经准备好了,是时候进入 MLG1 来集成模型了。

ML-Gate 1:整合模型

在 MLG1,是时候编写实际的生产代码了。请注意,在方法论中,您已经将实际的代码编写向前推进了多远。好消息是,您不必像平时那样编写大量代码,因为您创建的训练有素的模型将完成大部分繁重的工作。

您需要在 MLG1 编写的大部分代码处理模型的“打包”。在这一章的后面,我将讨论潜在的目标环境,这些环境也会影响模型需要如何被打包。

通常,使用训练数据在 MLG3/4 上创建 CML 模型,然后利用该模型进行预测。在 MLG1 中,您可能需要编写额外的代码来获取新的实时数据,并将其输入到模型中以输出预测。在第六章中,您将看到如何从设备中收集传感器数据并输入到模型中。

MLG1 是您认识到编码时间节省的地方。通常只需要几行代码就可以打开一个预构建模型并进行新的预测。

方法的这一阶段还包括解决方案的系统测试。

ML-Gate 0:部署

At MLG0, it is time for deployment of the completed ML solution. You have several options to deploy your solution because of the cross-platform nature of Java, including

  • 通过 Google Play 等应用商店发布移动应用。

  • 向您的客户端发送独立软件包。

  • 通过网络浏览器访问在线提供软件。

  • 提供对您的解决方案的 API 访问。

无论您如何部署您的 ML 解决方案,在 MLG0 要记住的重要一点是,“发货后就忘了”是错误的。

当我们创建模型时,我们必须认识到它们不应该成为永远不变的静态实体。我们需要一种机制来更新它们并保持它们的相关性。ML 模型帮助我们避免代码繁重的应用程序的缺点,但是我们必须有效地管理我们创建的模型,这样它们才不会过时。

方法总结

现在,您已经了解了 CML 的必要背景,并且有了可以用来创建 CML 应用程序的方法。

你可能听说过这样一句话:“当你是一把锤子时,一切看起来都像钉子。”在精通 CML 并采用数据驱动的方法后,您很快就会发现大多数问题至少在某个方面有一个优雅的 ML 解决方案。

接下来,您将看到书中 Java 项目所需的设置,以及 ML 成功的最后一个关键因素:创造性思维。

1.6 Java 的案例

关于哪种编程语言是最好的,你应该学习哪种语言,什么语言最适合孩子们开始编写代码,哪些语言正在消亡,哪些新语言代表了编程的未来,等等,总是有激烈的争论。

Java 无疑是这些争论的一个重要部分。有许多人质疑 Java 满足现代开发人员需求的能力。每种编程语言都有自己的优点和缺点。

Christina Videira Lopes 的 编程风格的练习 很有趣,因为作者解决了大量不同语言中的一个常见编程问题,同时强调了每种风格的优点和缺点。这本书阐明了我们可以使用任何语言来解决给定的问题。作为程序员,我们需要找到给定所选语言约束的最佳方法。Java 当然有它的优点和缺点,接下来我将回顾一下 Java 适合 CML 解决方案的一些原因。

Java 市场

Java has been around since 1995 when it was first released by Sun Microsystems, which was later acquired by Oracle. One of the benefits of this longevity is the market penetration it has achieved. The Java market share (Figure 1-8) is the single biggest reason to target the Java language for CML applications.img/468661_1_En_1_Fig8_HTML.jpg Figure 1-8

Java 市场

Java 应用程序编译成字节码,可以在任何 Java 虚拟机(JVM)上运行,而不管计算机架构如何。它是拥有数百万开发人员的最受欢迎的语言之一,尤其是对于客户机-服务器 web 应用程序。

When you install Java, Oracle is quick to point out that three billion devices run Java. It is an impressive claim. If we drill down deeper into the numbers, they do seem to be justified. Table 1-12 shows some more granular detail of the device breakdown.Table 1-12

运行 Java 的设备

|

设备

|

数数

|
| --- | --- |
| 运行 Java 的台式机 | 11 亿 |
| JRE 每年的下载量 | 9.3 亿 |
| 运行 Java 的手机 | 30 亿 |
| 蓝光播放器 | 100%运行 Java |
| Java 卡 | 每年生产 14 亿个 |
| 专有盒子 | 未知数量的设备,包括机顶盒、打印机、网络摄像头、游戏控制台、汽车导航系统、彩票终端、停车计时器、VOIP 电话、电表、工业控制等。 |

The explosion of Android development and the release of Java 8 helped Java to gain some of its market dominance.

Java 的巨大规模是我选择它作为 CML 解决方案语言的主要原因。开发人员只需要掌握一种语言,就可以产生有效的 CML 解决方案,并将其部署到大量的目标受众中。

For your target environments, the focus will be on the following three areas that make up the majority of installed Java devices:

  • 运行 Java 的台式机:这一类别包括可以运行独立 Java 程序的个人电脑,或者可以运行 Java 小程序的电脑上的浏览器。

  • 运行 Java 的手机 : Android 移动设备在这一类中占了很大一部分,其中也包括低价功能手机。ML 的一个关键发现是数据的重要性,手机可以说是有史以来最伟大的数据收集设备。

  • Java 卡:这个类别代表最小的 Java 平台。Java 卡允许 Java 小程序在嵌入式设备上运行。设备制造商负责集成嵌入式 Java,消费者不能下载或安装。

Java 版本

Oracle supplies the Java programming language for end users and for developers:

  • JRE (Java 运行时环境)是为希望安装 Java 以便运行 Java 应用程序的最终用户准备的。

  • JDK (Java SE Developer Kit)包括 JRE 以及用于开发、调试和监控 Java 应用程序的附加工具。

There are four platforms of the Java programming language:

  • Java 平台,标准版(Java SE)

  • Java Platform,Enterprise Edition (Java EE)构建在 Java SE 之上,包括用于构建网络应用程序的工具,如 JSON、Java Servlet、JavaMail 和 WebSocket。Java EE 是在 Java 社区过程下开发和发布的。

  • Java Platform,Micro Edition (Java ME)是一个小型虚拟机,用于在小型设备上运行应用程序。

  • Java FX 用于使用轻量级 API 创建富互联网应用程序。

所有的 Java 平台都由一个 Java 虚拟机(JVM)和一个应用编程接口(API)组成。

Table 1-13 summarizes the current Java releases.Table 1-13

最新支持的 Java 版本

|

释放;排放;发布

|

描述

|
| --- | --- |
| Java 8 SE 内部版本号 171 | 目前支持的长期支持(LTS)版本。引入 lambda 表达式 |
| Java 10 SE 10.0.1 | 当前支持的快速发布版本。2018 年 3 月 20 日发布。包括 12 项新的主要功能。最新更新是 171。 |
| Android SDK | 用于开发 Android 应用程序的替代 Java 软件平台。包括自己的 GUI 扩展系统和移动设备库。Android 不提供完整的 Java SE 标准库。Android SDK 支持 Java 6 和部分 Java 7 特性。 |

Java 的最新版本解决了该语言落后于一些更新、更流行的语言的一些领域。值得注意的是,Java 8 包括了一个意义深远的特性,称为λ表达式 ,以及一个新的运算符(- >)和一个新的语法元素。Lambda 表达式增加了函数式编程特性,有助于简化和减少创建某些结构所需的代码量。

在本书中,你不会用到 lambda 表达式,也不会用到 Java 10 语言中的任何新特性。尽管如此,最好运行 Java 8 长期支持版本或当前支持的 Java 10 快速版本的最新更新。

如果你正在寻找一本全面的 Java 书籍, Java,甲骨文 第十版完整参考,超过 1300 页,是一个极好的选择。它涵盖了 Java 的所有内容。谈到 Java 性能调优,Charlie Hunt 和 John Binu 的《Java 性能是一本 720 页的权威指南,旨在最大限度地提高 Java 性能。

安装 Java

在安装 Java 之前,您应该首先从系统中卸载所有旧版本的 Java。在您的系统上保留旧版本的 Java 存在安全风险。卸载旧版本可确保 Java 应用程序在最新的安全和性能环境下运行。

所有平台下载的主 Java 页面和链接可从以下 URL 获得:

java.com/en/

Java . com/en/download/manual . JSP

Java 可用于您需要的任何平台。一旦你决定了你需要哪一个加载,继续下载和安装。对于本书中的项目,建议安装 Java 8 SE 的最新稳定版。对于 Android 项目,允许 Android Studio 管理您的 Java 版本。Android Studio 通常会使用 Java 7 的最新稳定版本,直到 Android 团队添加了对 Java 8 的支持。

图 1-9 显示了主 Java 下载页面。

图 1-10 显示了 Java 的安装。

Figure 1-11 shows the completion of the installation. img/468661_1_En_1_Fig9_HTML.jpg Figure 1-9

下载 Java

img/468661_1_En_1_Fig10_HTML.jpg Figure 1-10

安装 Java

img/468661_1_En_1_Fig11_HTML.jpg Figure 1-11

成功安装 Java SE

Java 性能

史蒂夫·乔布斯曾经说过一句关于 Java 的名言:“它是一个巨大的、重量级的球和链条。”当然,苹果从来都不喜欢这种语言。Java 经久不衰的原因之一是多年来对该语言的支持和改进。Java 的最新版本比早期版本提供了更多的功能和性能。

开发人员犹豫选择 Java 作为 ML 解决方案的原因之一是担心性能。

询问哪种语言“更快”或提供更好的性能并不是一个真正有用的问题。当然,这要视情况而定。语言的性能取决于它的运行时、操作系统和实际代码。当开发人员问,“哪种语言为机器学习提供了最好的性能?”我们真的应该问,“我应该使用哪个平台来最快速、最轻松地完成机器学习模型的训练和构建?”

使用算法创建 ML 模型是 CPU 密集型的,尤其是对于 DL 应用程序。这本书是关于 Java 的,但是如果你研究 ML,你会知道 Python 和 C++也是非常流行的 ML 语言。为 ML 创建三种语言的公平比较并不容易,但是许多研究人员已经尝试这样做了,你可以从他们的发现中学习。由于 ML 是基于算法的,所以他们经常试图选择一个标准算法,然后在其他变量相同的情况下进行比较,例如 CPU 和操作系统。

Java 性能是语言中最难衡量的,因为有几个因素,包括未优化的代码、Java 的 JIT 编译方法和著名的 Java 垃圾收集。此外,请记住,Java 和 Python 可能依赖 C++库的包装器来完成实际的繁重工作。

Table 1-14 shows a high-level summary of the performance for a mathematical algorithm implemented in three different languages on the same CPU and operating system. To learn more about the underlying research used in the summary, refer to these sources:

Table 1-14

语言表现比较-数学算法

|

语言

|

比 C++慢%

|

注意

|
| --- | --- | --- |
| C++ | - | C++编译成 native,所以是第一。 |
| Java 8 | 15% | Java 为平台独立性产生字节码。Java 的“软肋”是它的垃圾收集(GC)开销。这些年来,对 Java GC 算法进行了许多改进。 |
| 我的锅 | 15+% | Kotlin 还生产 Java 虚拟机(JVM)字节码。通常,Kotlin 和 Java 一样快。 |
| 计算机编程语言 | 55% | Python 有高级数据类型和动态类型,所以运行时要比 Java 辛苦。 |

表 1-14 当然不是详尽的性能指标评测,但确实提供了一些关于相对性能的见解,以及对差异的可能解释。

当您为 ML 解决方案创建预构建模型时,关注数据质量和算法选择比编程语言更重要。你应该使用最容易、最准确的编程语言来表达你试图解决的问题。

Java 怀疑论者经常问:“Java 是实现深度学习的合适编程语言吗?”简短的回答是:当然!它有足够的性能,所有需要的数学和统计库都可用。在本章的前面,我将 DL4J 列为完全用 Java 编写的主要 Java 包。DL4J 是一个神奇的软件包,它的能力可以与 DL 中的所有大型玩家相媲美。一句话:借助云中的多节点计算,我们可以轻松地为计算密集型操作添加更多资源。可伸缩性是基于云的平台提供的巨大优势之一,我将在第二章中讨论。

1.7 开发环境

There are many IDEs available to Java developers. Table 1-15 shows the most popular choices for running Java on the desktop or device. There are also some online browser-based cloud Java IDEs such as Codenvy, Eclipse Che, and Koding, which I will not cover.Table 1-15

Java IDE 摘要

|

IDE 名称

|

特征

|
| --- | --- |
| Android Studio | 来自 Google 的 Android 专用开发环境。它已经成为 Android 事实上的 IDE。提供了大量有用的开发和调试工具。 |
| 智能理念 | 功能齐全的专业 IDE。年费。许多开发人员喜欢 IntelliJ。Android Studio 是基于 IntelliJ 的。 |
| 黯然失色 | 免费开源 IDE。Eclipse 公共许可证。支持 Git。大量可用的插件。 |
| BlueJ | 轻量级开发环境。附带树莓派。 |
| 开发工具 | 免费的开源 IDE,Eclipse 的替代品。开源项目正在转移到 Apache,这应该会增加它的受欢迎程度。 |

The book uses two development environments for the projects depending on the target platform:

  • 谷歌的 Android Studio 帮助开发者为运行 Android 的移动设备创建应用。

  • 不针对 Android 移动设备的 Java 项目的 Eclipse IDE。这包括面向桌面、浏览器或非 Android 设备(如 Raspberry Pi)的 Java 程序。

Android Studio

谷歌让 Android Studio 轻松入门。最新的稳定发布版本是 2018 年 4 月发布的版本 3.1.2。下载页面是developer.android.com/studio/

Figure 1-12 shows the available platforms. Note that the files and disk requirements are large. The download for 64-bit Windows is over 700MB.img/468661_1_En_1_Fig12_HTML.jpg Figure 1-12

Android Studio 下载

Android Studio has really been improving the last couple of years. The full featured development environment for Android includes

  • Kotlin 版本 1.2.30

  • 绩效工具

  • 实时网络分析器

  • 可视化 GUI 布局编辑器

  • 瞬间奔跑

  • 快速仿真器

  • 灵活的分级构建系统

  • 智能代码编辑器

Figure 1-13 shows the show the Android Studio installation setup.img/468661_1_En_1_Fig13_HTML.jpg Figure 1-13

Android Studio 安装

Figure 1-14 shows the shows the Android Studio opening banner including the current version 3.1.2.img/468661_1_En_1_Fig14_HTML.jpg Figure 1-14

Android Studio 版本 3.1.2

Android Studio uses the SDK Manager to manage SDK packages. SDK packages are available for download. The SDK packages are required to compile and release your app for a specific Android version. The most recent SDK release is Android 8.1 (API level 27), also known as Oreo. Figure 1-15 shows the Android SDK Manager.img/468661_1_En_1_Fig15_HTML.jpg Figure 1-15

Android Studio SDK 管理器

始终关注您使用的 Android Studio 和 SDK 平台的更新。Google 经常发布更新,您希望您的开发环境保持最新。

当终端用户不断购买最新设备时,这对于移动开发尤为重要。

黯然失色

Android 移动应用是我们 CML 战略的重要组成部分,但不是我们唯一的目标受众。对于非 Android 项目,我们需要一个更合适的开发环境。

Eclipse 是 Eclipse foundation 提供的多功能 IDE。下载页面是eclipse.org/downloads。Eclipse 适用于所有平台。最新的版本是 Oxygen.3a,版本是 4.7.3a。与 Android 类似,Eclipse 通过字母表使用收益,并且与 Android 一样,目前也处于“o”

Similar to the options available for the Java distributions, developers can choose either

  • 面向 Java EE 开发人员的 Eclipse IDE(包括用于 web 应用程序的额外工具),或者

  • 面向 Java 开发人员的 Eclipse IDE

The latter is sufficient for the projects in this book. Figure 1-16 shows the Eclipse IDE for Java Developers installation banner.img/468661_1_En_1_Fig16_HTML.jpg Figure 1-16

Eclipse 安装

Eclipse makes it easy to get started with your Java projects. Once installed, you will have the option to

  • 创建新项目。

  • 从现有源代码导入项目。

  • 从 Git 源代码控制系统中签出或克隆项目。

The Git checkout feature is very useful, and you can use that option to get started quickly with the book projects. Figure 1-17 shows the Eclipse IDE for Java Developers startup page with the various options.img/468661_1_En_1_Fig17_HTML.jpg Figure 1-17

面向 Java 开发人员的 Eclipse IDE

One of the big advantages of Eclipse is the huge number of plugins available. There are plugins for almost every imaginable integration. Machine learning is no exception. Once you get a feel for the types of ML projects you are producing, you may find the Eclipse plugins in Table 1-16 to be useful. For the book projects, you will use a basic Eclipse installation without plugins.Table 1-16

Eclipse IDE 机器学习相关插件

|

Eclipse ML 插件

|

描述

|
| --- | --- |
| AWS 工具包 | 帮助 Java 开发人员将 AWS 服务集成到他们的 Java 项目中。 |
| 谷歌云工具 | 谷歌赞助的开源插件,支持谷歌云平台。Cloud Tools for Eclipse 使您能够在 Google cloud 中创建、导入、编辑、构建、运行和调试。 |
| 微软 Azure 工具包 | Azure Toolkit for Eclipse 允许您创建、开发、配置、测试和部署轻量级、高可用性和可伸缩的 Java web 应用程序。 |
| r 代表数据科学 | Eclipse 有几个插件支持 R 统计语言。 |
| 物联网日食 | 80 个插件可用。 |
| Eclipse 智能家居 | 47 个插件可用。 |
| 定量组件 | 金融时间序列和算法交易的开源框架。 |

It is important to keep your Eclipse environment up to date. Figure 1-18 shows the Eclipse startup banner with the current version. Just as with your Java installation, Android Studio, and Android SDK platforms, always keep your Eclipse IDE up to date.img/468661_1_En_1_Fig18_HTML.jpg Figure 1-18

面向 Java 开发人员的 Eclipse IDE

成开发环境

对于不想使用 Eclipse 的 Java 开发人员来说, Net Beans IDE 是一个替代选择。下载页面是 https://netbeans.org.downloads 的。

这些年来,Eclipse 获得了更多的用户,但是 NetBeans 仍然有它的支持者。最近,Oracle 宣布将 NetBeans 移交给 Apache 基金会以获得未来的支持。NetBeans 的粉丝认为这是一个积极的发展,因为现在 NetBeans 的长期支持者将能够继续其发展。

I will not be using NetBeans in the book, but you are free to do so. The projects should import easily. It is an IDE worth keeping an eye on in the future. Figure 1-19 shows the NetBeans main page.img/468661_1_En_1_Fig19_HTML.png Figure 1-19

netbeans ide(netbeans ide)

1.8 竞争优势

在本章的前面,您开发了一个为基于 Java 的设备部署 CML 应用程序的策略。你还建立了一个方法论,数据驱动开发的 ML-Gates。目标是创造竞争优势,将您的 ML 解决方案货币化。实现这一目标需要的不仅仅是使用每个人都容易获得的开发工具。

This section will discuss two additional ingredients needed to help create a competitive advantage when designing ML solutions:

  • 创造性思维

  • 桥接域

尝试创建 ML 解决方案的关键成功因素之一是创造力。你需要跳出框框思考。这是老生常谈,但往往需要稍微不同的视角才能发现独特的 ML 解决方案。

站在巨人的肩膀上

如果你参观当地学院或大学的数学系、计算机系或物理系,你会发现走廊的墙上贴满了学术研究论文。细看之下,你会发现这些作品很多都是专注于机器学习的。如果你在网上搜索,你也会找到很多这样的论文。

PhD students in mathematics or statistics usually author these papers. They typically spend months or even years on the particular topic they are exploring. These papers are often difficult for developers to understand. Sometimes we may only grasp a fraction of the content. However, these papers are a very useful resource in our search for creative ideas.

学术研究论文可以为我们可以在机器学习应用中利用的内容和方法提供有价值的想法。

利用这些研究人员的发现可能会帮助您找到解决方案,或者为您节省大量时间。如果你找到一篇相关的研究论文,不要害怕联系作者。在大多数情况下,他们不是软件开发人员,你们可以建立有趣的合作关系。

桥接域

Everybody has access to the technologies in this book. How can we differentiate ourselves? Recall from Table 1-1 in the beginning of this chapter, ML terminology originates from different domains. Figure 1-20 shows a graphical view of the domains. As developers, we approach the problem from the technology domain. With our toolkits, we occupy a unique position, allowing us to produce Java ML solutions that lie at the intersection of the domains.img/468661_1_En_1_Fig20_HTML.jpg Figure 1-20

域关系

企业有数据、要部署的资金(美元)和许多需要解决的问题。科学家有算法。作为 Java 开发人员,我们可以把自己定位在交叉点上,产生 ML 解决方案。最能理解业务问题,将问题与可用数据联系起来,并应用最合适的算法的开发人员将处于最有利的位置。

1.9 章节总结

在这一章中,我已经涉及了相当多的主题领域。以下是对主要发现的快速回顾。当你继续阅读这本书的其余部分时,请记住它们。

主要发现

    采用数据驱动的方法。

    “定了就算了”是不对的。您需要经常更新模型以反映基础数据的变化。

    采用数据驱动的方法,如 ML-Gates。

    总是从一个明确的问题开始。

    不要求 DL 产生惊人的解决方案。您可以使用 CML 技术,对于许多现实场景来说,这种技术更容易构建和实现。

    DL 可以规模化经营。您提供给模型的数据越多,它就变得越准确。

    CML 对于较小的数据集表现更好。

    创造性地思考以获得竞争优势。

    科学研究论文可以提供极好的思想来源。

跨领域思考。弥合技术、商业和科学领域之间的差距。

二、数据:机器学习的燃料

  • 回顾一下数据爆炸和使这场机器学习革命成为可能的三大趋势。

  • 介绍数据的重要性,重新编程自己,像数据科学家一样思考。

  • 查看不同类别的数据。

  • 回顾各种格式的非结构化数据,包括 CSV、ARFF 和 JSON。

  • 使用 OpenOffice Calc 程序准备 CSV 数据。

  • 查找和使用公开可用的数据。

  • 介绍创建您自己的数据的技术。

  • 引入预处理技术以提高数据质量。

  • 用 JavaScript 可视化数据(项目)。

  • 为 Android 实现数据可视化(项目)。

2.1 大趋势

Why is the ML revolution happening now? It is not the first time. In Chapter 1, I reviewed the previous AI booms and subsequent winter periods. How do we know if this time it is for real? Three transformational megatrends are responsible for the movement.

三个 大趋势 为我们现在正在经历的机器学习革命铺平了道路:

1)数据爆炸

2)访问高度可扩展的计算资源

3)算法的进步

值得对这些大趋势进行更深入的探究。

数据爆炸

您可能已经看到过那些关于每天创建的数据量的疯狂统计。IBM 有一个被广泛引用的统计数据,表明今天互联网上 90%的数据是自 2016 年以来创建的。在 2016 年之前,大量数据肯定已经存在,所以这项研究证实了我们已经知道的事情:今天的人和设备正在以前所未有的速度产生大量数据。IBM 表示,每天产生超过 2.5 艾字节(25 亿吉字节)的数据。

How much data is actually out there, and what are the sources of the data? It is hard to know with any degree of certainty. The data can be broken down into the following categories :

  • 互联网社交媒体

  • 互联网非社交媒体

  • 移动设备数据

  • 传感器数据

  • 公开日期

  • 政府数据

  • 私人数据

  • 综合数据

Table 2-1 attempts to provide some insight into each category.Table 2-1

数据类别

|

数据类别

|

观察

|
| --- | --- |
| 互联网数据 | 全球有 38 亿桌面互联网用户。 |
| 2017 年,用户每分钟观看 400 万个 YouTube 视频。 |
| 2017 年每天有 50 亿次谷歌搜索。 |
| 社交媒体数据 | 每天有 6.55 亿条推文。 |
| 每天有 100 万个新的社交媒体账户。 |
| 有 20 亿活跃的脸书用户。 |
| Instagram 帖子每天增加 6700 万条 |
| 移动设备数据 | 2017 年每天发送 220 亿条短信。 |
| 有 35 亿移动设备互联网用户。 |
| 2017 年售出 4000 万台可穿戴设备。 |
| 91%的人拥有移动设备。 |
| 传感器数据 | 56%的人拥有智能设备。 |
| 到 2020 年,将有 250 亿个物联网。 |
| 到 2020 年,单个传感器的数量可能超过 1 万亿。 |
| 物联网(IoT)市场完全是关于传感器的。物联网市场预计将从 2014 年的 3 万亿美元增长到 2020 年的 9 万亿美元,CAGR 为 20%。 |
| 公开日期 | 研究机构提供大型数据集。比如加州大学尔湾分校(UCI)就有很多有用的数据集: |
| GitHub 上牛逼的公开数据集:【https://github.com/awesomedata/awesome-public-datasets】?? |
| CIA World Factbook 提供了 267 个国家的历史、人口、经济、政府、基础设施、军事等信息:【www.cia.gov/library/publications/the-world-factbook/】?? |
| AWS 公共数据集是一个庞大的公共数据资源,包括 1000 基因组计划和 NASA 的地球卫星图像数据库:【https://aws.amazon.com/datasets】 |
| 政府数据 | 人口普查数据。 |
| 债务和融资数据。 |
| 选举委员会数据。 |
| 美国政府承诺在网上免费提供所有政府公共数据:【https://data.gov】 |
| 私人数据 | 由于具有加速度计和 GPS 功能的低成本传感器设备和智能手机的可用性,个人越来越多地收集自己的数据。 |
| 综合数据 | 模拟真实数据的计算机生成的数据。 |

As Table 2-1 suggests, there are many types of data. If you require a specific type of data for your ML project, a quick Google search will probably identify a dataset that can at least get you started on a proof of concept.

今天,我们几乎可以数字化任何东西。一旦数字化,数据就有资格进行机器学习。

You have heard the term “big data.” Similar to the terminology used in ML, the usage of this term is also inconsistent. Table 2-2 shows some guidelines for relative data sizes and the related architectures.Table 2-2

相对数据大小

|

名字

|

大小

|

数据库ˌ资料库

|

体系结构

|
| --- | --- | --- | --- |
| 正常数据 | < 1GB | 平面/SQL | 当地的 |
| 小数据 | 1GB - 100GB | NoSQL | 当地的 |
| 中等数据 | 100GB - 1TB | NoSQL | 分布式的 |
| 大数据 | 超过 1TB | hadoop spark | 分布式多集群 |

通常,大数据是指大于 1tb 的数据集。

您可能没有在项目中处理大数据规模的数据,但是在设计 ML 项目时考虑数据可伸缩性是很重要的。当今存在的大部分数据是非结构化的。这意味着它没有被标记或分类。它通常基于文本,并不真正遵循预定义的结构。我将在第三章讨论非结构化数据。

两章 2 和 3 都展示了帮助驯服数据爆炸的工具。

高度可扩展的计算资源

如果没有存储和处理数据的能力,数据爆炸是不可能的。第二个大趋势是我们今天拥有的高度可扩展的计算资源。

Cloud service providers have changed the game for practitioners of ML. They give us on-demand highly scalable access to storage and computing resources. These resources are useful for many ML functions, such as the following:

  • 存储:我们可以使用云服务作为 ML 数据的存储库。

  • CPU 资源:通过配置具有大 CPU 容量的高可用性分布式计算集群,我们可以更快地创建 ML 模型。

  • 托管:我们可以使用 API 或其他接口方法提供对数据或 ML 模型的托管访问。

  • 工具:所有的云提供商都有一整套工具,我们可以用来创建 ML 解决方案。

第三章将详细介绍云提供商的潜在 ML 用例。

算法的进步

第三个大趋势是 ML 算法的进步。最大似然算法已经存在很长时间了。然而,一旦数据和 IaaS 提供商开始出现爆炸式增长,优化其性能的新努力就开始了。

DL 神经网络算法的进步是最重要的。然而,CML 算法也取得了进步。第四章将详细讲解算法。

2.2 像数据科学家一样思考

对于一个成功的 ML 项目来说,数据是唯一最重要的因素。你需要高质量的数据,而且你需要大量的数据。

数据挖掘就是处理你的数据,找出隐藏的模式。ML 采取了应用算法来处理数据的额外步骤。数据是每个学科的基本要素。在 DM 和 ML 中,您经常处理大型的、结构松散的数据集。

在构建能够有效处理数据的 ML 模型之前,您需要很好地理解您的数据。在 Nate Silver 的《信号与噪音》 中,作者鼓励我们对自己的数据拥有所有权。这真的是像数据科学家一样思考的本质。

作为软件工程师,我们习惯于思考代码。对我们来说,代码一直是最重要的。回想一下第一章,我颠倒了开发方法,将数据放在 ML-Gates 的前面,并将编码阶段保持到最后。

Mr. Silver summed it up perfectly:

数字本身无法说明问题。我们为他们说话。数据驱动的预测可以成功,也可以失败。当我们否认自己在这个过程中的角色时,失败的几率就会增加。在我们对数据提出更多要求之前,我们需要对自己提出更多要求。”

在今天的 ML 世界中,你必须从考虑数据如何影响你的解决方案开始,决定你有什么数据,你如何组织它,然后让数据驱动你的软件架构。

数据命名

A first step in taking ownership for your data is classifying the type of data itself. Before you can understand which algorithm is best suited for your well-defined ML problem, you need to understand the nature and type of the data you possess. Table 2-3 shows the two broad types of data.Table 2-3

常规数据类型摘要

|

数据类型

|

描述

|

例子

|
| --- | --- | --- |
| 质量数据 | 观察结果分为不同的类别。数据是离散的,因为每个观察值可能属于有限数量的类别。 | 最喜欢的颜色:蓝色、绿色、棕色 |
| 数据 | 当观察值是计数或测量值时,就会产生定量或数值数据。 | 人的身高 |

Qualitative data , classified as

  • 如果类别之间没有自然顺序,则为名义上的(如眼睛颜色)。

  • 如果存在排序,则为序数(如考试分数或班级排名)。

Quantitative data , classified as

  • 离散,如果测量值是整数(如城市或国家的人口)。

  • 连续的,如果测量值可以取任何值,通常在某个范围内(如一个人的身高或体重)。

定义数据

回想一下第一章,MLG5 要求您识别和定义您的数据。接下来,您将对一个数据集执行此任务,该数据集将用于本书后面的项目,即 Android Activity Tracker 应用程序。

表 2-4 中显示的数据来自 PAMAP2_Dataset,可从第一章中提到的加州大学欧文分校(UCI)机器学习库中获得。这是免费提供的数据,在用于研究目的时没有任何限制。您可以通过下面的链接下载数据集。由于数据集的大小,它不包括在图书资源中。这些文件很大,所以下载需要一些时间。

http://archive . ics . UCI . edu/ml/datasets/pamap 2+身体+活动+监控

To collect this data, the researchers asked subjects to wear sensors while performing various activities. The table shows each of the fields together with a data type assigned.Table 2-4

定义您的数据

|

字段(列)

|

单位

|

例子

|

数据类型

|
| --- | --- | --- | --- |
| 时间戳 | 秒 | Three point three eight | 定量连续 |
| 活动 ID | 1 躺 2 坐 3 站 4 走 5 跑 6 骑自行车 7 北欧 | Two | 定性名义 |
| 心率 | 每分钟的节拍数 | One hundred and four | 定量离散 |
| 传感器 1:温度 | 摄氏度 | Thirty | 定量离散 |
| 传感器 1: 3D 加速度 | ms -2 | 2.37223 | 定量连续 |
| 传感器 1: 3D 加速度 | ms -2 | 8.60074 | 定量连续 |
| 传感器 1: 3D 陀螺仪 | 我喜欢 | 3.51058 | 定量连续 |
| 传感器 1: 3D 磁力计 | 超声试验 | 2.43954 | 定量连续 |
| 传感器 1:方向 | 拉德 | 8.76165 | 定量连续 |

当涉及到您的数据时,识别您拥有的数据类型是对自己要求更高的第一步。当您为数据构建分类器时,您将仔细查看第 7 章中的 PAMAP2_Dataset。

2.3 数据格式

Data format is a key consideration when building ML models. Table 2-5 shows the important file formats and their common file extensions.Table 2-5

常见数据文件类型

|

文件格式

|

文件扩展名

|
| --- | --- |
| 文本文件 | . txt.dat |
| 包括 MS Excel 和 OpenOffice Calc 在内的所有电子表格包都支持逗号分隔值(CSV) | 。战斗支援车 |
| Weka 支持的属性关系文件格式 | 。飞机救援消防 |
| 互联网上广泛使用的 JavaScript 对象符号(JSON)标准交换格式 | . json .txt 文件 |

当您为 ML 项目定位数据时,它可能是任何格式的。纯文本文件很常见。数据文件通常是。txt 或者。dat 文件,两者都是文本文件。表 2-1 中引用的加州大学欧文分校存储库中的许多数据文件是。dat 文本文件。

The first step in using text data files for ML is to open them and understand how they are structured. You can use any text editor. Figure 2-1 shows the subject101.dat file from the PAMAP2_Dataset.img/468661_1_En_2_Fig1_HTML.jpg Figure 2-1

在文本编辑器中打开的 PAMAP2_Dataset 中的文件 subject101.dat

You can see that spaces separate the data fields. Each row contains 54 values or columns separated by a single space character. Note that Figure 2-1 does not show all of the columns. The easiest way to work with datasets for ML is to convert them to CSV. The first step is to make a copy of the .dat file and then rename it as .csv. Figure 2-2 shows the list of all files in the PAMAP2_Dataset, with the newly created .csv copy file.img/468661_1_En_2_Fig2_HTML.jpg Figure 2-2

PAMAP2_Dataset。dat 文件到。战斗支援车

仅仅因为您将文件重命名为. csv 并不意味着它就是这样。你必须转换它。通过执行全局搜索并将空格替换为逗号,可以用您的文本编辑器执行转换,但是还有更好的方法。你将使用一个电子表格程序。

CSV 文件和 Apache OpenOffice

电子表格程序的优点是允许你对我们的数据做一些基本的编辑。它们还允许您轻松导入或导出 CSV 文件。

Microsoft Excel 可以完成这项工作,但 Apache 开源程序 OpenOffice 是更好的选择。OpenOffice 包含一个电子表格、文字处理器、演示包、数据库、矢量图形编辑器和数学公式编辑器。你对电子表格程序 Calc 感兴趣。您需要下载整个套件。

Calc has several advantages over Excel, including

  • Calc 是免费的开源软件,在 Apache 2.0 软件许可下获得许可。它是 OpenOffice 套件的一部分。

  • Calc 更擅长导入导出 CSV 文件。还有更多的选项可用,比如对引号(" ")中的文本字段进行转义。

  • Calc 支持数据字段的 UTF-8 编码。这一点很重要,尤其是当您的项目使用国际字符集或多字节字符集时。

  • Calc 支持 BOM 处理。BOM 代表字节顺序标记。Windows 系统使用 BOM 作为每个文件的第一个字符来通知应用程序字节顺序。在 Windows 中创建的包含 BOM 的文件在其他平台(如 Unix)上可能会有问题。当你在 Calc 中保存文件时,Calc 让你指定你想要如何处理 BOM(非常周到;谢谢阿帕奇)。

Figure 2-3 shows the installation screen for Apache OpenOffice. The OpenOffice download link is www.openoffice.org/download/ .img/468661_1_En_2_Fig3_HTML.jpg Figure 2-3

安装 Apache OpenOffice

Once you have installed OpenOffice, launch Calc. If you are familiar with the Microsoft Office suite, you will notice that Calc looks similar. Open the subject101.csv file you copied earlier. Figure 2-4 shows that Calc recognizes it as a text file and give you some import options on the text import window.img/468661_1_En_2_Fig4_HTML.jpg Figure 2-4

OpenOffice Calc 导入 CSV 文件

Calc 允许您为每个检测到的字段选择字符集、字段分隔符,甚至是列类型。该数据最重要的设置是选择空格作为分隔符。检查完空格后,您将看到文本导入窗口底部显示的字段中正确填充了数据。

After you click OK, Calc will import the data.

您将使用的 PAMAP2_Dataset 很大。仅单个文件subject 101 . dat就包含 54 列和 376417 行。这是一个很大的电子表格,所以给 Calc 一些时间来导入或导出文件。

Figure 2-5 shows the file after importing into Calc.img/468661_1_En_2_Fig5_HTML.png Figure 2-5

导入 OpenOffice Calc 的 subject101.dat 文件

The advantage of using Calc over a text editor is that once Calc completes the import, it is easy to view and manipulate the data. Some common operations for manipulating ML data in Calc are as follows:

  • 您可以搜索缺少的值。这个文件中的数据相对干净。缩写“NaN”代表“不是数字”,代表缺失值。列 C 主要包含 NaN 值。

  • 添加或删除列很容易。如果您希望删除某列,只需突出显示该列,右键单击并删除即可。移除不需要的列减小了大小,因此减少了导入、导出和训练 ML 模型所需的时间和存储空间。

  • 宏可以根据条件(如单元格的值)删除行或列。例如,如果您想要删除数据中所有缺少的值行,这将非常有用。Calc 可以使用 Excel 宏。它还允许你记录击键。

  • 您可以使用“,”作为分隔符,以真正的 CSV 格式导出文件。

Figure 2-6 shows the save dialog box for the CSV file export. Click the “Keep Current Format” box to save a CSV file.img/468661_1_En_2_Fig6_HTML.png Figure 2-6

保存 CSV 文件

大多数 ML 环境都允许直接导入 CSV 文件,Apache OpenOffice Calc 是准备此类文件的最佳方式。CSV 是您可以用于 ML 的最简单的数据格式。接下来,您将看到更复杂的其他方法。

ARFF 档案

ARFF is an abbreviation for Attribute-Relation File Format. It is an extension of the CSV file format. The Weka machine learning environment uses ARFF files to load data. Weka comes with many sample datasets. The iris flower dataset is one of the most famous in machine learning. The following code block shows a partial view of the iris.arff dataset included with the environment:001   @relation iris-weka.filters.unsupervised.attribute.Remove-R1-2 002   % Iris.arff file available with the Weka distribution (partial file) 003 004   @attribute petallength numeric 005   @attribute petalwidth numeric 006   @attribute class {Iris-setosa,Iris-versicolor,Iris-virginica} 007 008   @data 009   1.4,0.2,Iris-setosa 010   1.4,0.2,Iris-setosa 011   1.3,0.2,Iris-setosa 012   1.7,0.2,Iris-setosa 013   1.5,0.4,Iris-setosa 014   1,0.2,Iris-setosa 015   1.7,0.5,Iris-setosa 016   1.9,0.2,Iris-setosa 017   1.5,0.2,Iris-setosa 018   1.4,0.2,Iris-setosa 019   4.7,1.4,Iris-versicolor 020   4.5,1.5,Iris-versicolor 021   4.9,1.5,Iris-versicolor 022   4,1.3,Iris-versicolor 023   3.3,1,Iris-versicolor 024   4.2,1.3,Iris-versicolor 025   6.6,2.1,Iris-virginica 026   5.4,2.3,Iris-virginica 027   5.1,1.8,Iris-virginica Note that the familiar CSV data follows the @data directive at the bottom of the file. In ARFF files, an additional header at the top provides metadata about the data and labels. The following describes the differences between CSV and ARFF file formats:

  • 注释从注释行前面的百分号%开始。

  • @relation 指令启动文件并允许您指定数据集的名称。

  • @attribute 指令定义了数据集中每个属性的名称和数据类型。

  • ARFF 文件的头段(在 @data 指令上面)可以包含空行。

  • 名义数据,比如@属性类 ,后面是它们可以采用的一组值,用花括号括起来。

  • CSV 数据遵循 @data 指令。

  • 数据集中未知或缺失的值用问号“?”表示。。

Weka 包括将 CSV 数据转换为 ARFF 格式的转换工具。一旦生成了初始的 ARFF 文件,就没有必要再进行转换了。

数据

CSV 和 ARFF 文件非常有用。然而,CSV 数据的平面结构没有提供太多的灵活性。您的工具箱中需要一个额外的工具来帮助您表示更复杂的数据结构。

作为 Java 或 Android 开发人员,您可能对 JSON 很熟悉。JSON 代表 JavaScript 对象符号。它是一种非常轻量级的、基于文本的、灵活的交换格式。JSON 是一种广泛用于服务器和客户端设备之间的数据交换格式。

你可以在json.org了解更多关于 JSON 如何工作的信息,并找到所有平台的下载。

JSON has several important properties that have helped to make it hugely popular across the Internet and especially for mobile app development:

  • JSON 对于我们来说很容易读写,对于机器来说也很容易解析和生成。

  • 几乎每个平台和语言都有一个 JSON 库。

  • JSON 基于 JavaScript 编程语言的子集,因此得名。

  • JSON 是一种文本格式,与语言无关。

  • JSON 使用 C 语言系列的程序员熟悉的约定。

JSON 使用简单但功能强大的 数组对象 集合来表示数据。名称/值对通常表示对象中的数据。这使得 JSON 在整个互联网上非常流行。JSON 的灵活结构使它能够表示非常复杂的数据关系。

In JSON, the placement of parenthesis and brackets to represent arrays and objects is very important. Figure 2-7 shows valid construction rules for JSON structures.img/468661_1_En_2_Fig7_HTML.jpg Figure 2-7

JSON 结构定义

注意(左括号)和和{(左括号)和}(右括号)在 JSON 中作为标识符的用法。

JSON 由两个原语组成,对象和数组,以及可以是字符串、数字、对象、数组或布尔值的值。JSON 出奇的简单,如图 2-7 所示。

Using only the following two primitives, you can construct complex structures to represent almost any type of data relationship:

  • JSONObject:名称/值对的无序集合或集合

  • JSONArray:值的有序列表

Both JSON objects and JSON arrays contain values. A value can be any of the following:

  • 双引号中的字符串

  • 一个数字

  • 真实的

  • 错误的

  • 另一个 JSON 对象

  • 另一个 JSON 数组

Notice that values can also be JSON objects or JSON arrays. This feature of JSON provides the secret that makes it so powerful:

JSON 是一种强大的表示结构的方式,因为它允许 JSON 对象和 JSON 数组结构的嵌套。

Recall the iris.arff file discussed in the last section. You can also represent this data using JSON, as shown in part in Listing 2-1. Note that just like the ARFF file, the JSON representation also contains a header and a data section.001   { 002       "header" : { 003           "relation" : "iris", 004           "attributes" : [ 005               { 006                   "name" : "sepallength", 007                   "type" : "numeric", 008                   "class" : false, 009                   "weight" : 1.0 010               }, 011               { 012                   "name" : "sepalwidth", 013                   "type" : "numeric", 014                   "class" : false, 015                   "weight" : 1.0 016               }, 017               { 018                   "name" : "petallength", 019                   "type" : "numeric", 020                   "class" : false, 021                   "weight" : 1.0 022               }, 023               { 024                   "name" : "petalwidth", 025                   "type" : "numeric", 026                   "class" : false, 027                   "weight" : 1.0 028               }, 029               { 030                   "name" : "class", 031                   "type" : "nominal", 032                   "class" : true, 033                   "weight" : 1.0, 034                   "labels" : [ 035                       "Iris-setosa", 036                       "Iris-versicolor", 037                       "Iris-virginica" 038                   ] 039               } 040           ] 041       }, 042       "data" : [ 043           { 044               "sparse" : false, 045               "weight" : 1.0, 046               "values" : [ 047                   "5.1", 048                   "3.5", 049                   "1.4", 050                   "0.2", 051                   "Iris-setosa" 052               ] 053           }, 054           { 055               "sparse" : false, 056               "weight" : 1.0, 057               "values" : [ 058                   "4.9", 059                   "3", 060                   "1.4", 061                   "0.2", 062                   "Iris-setosa" 063               ] 064           }, 065           { 066               "sparse" : false, 067               "weight" : 1.0, 068               "values" : [ 069                   "5.9", 070                   "3", 071                   "5.1", 072                   "1.8", 073                   "Iris-virginica" 074               ] 075           } 076       ] 077   } Listing 2-1

iris.json,iris.arff 数据集的 json 表示

如果您想尝试 json 格式的 iris 数据集,可以在参考资料一书中找到文件 iris.json

You might be asking why we need JSON for data files when we already have CSV and ARFF that are perfectly capable of representing data for ML. There are two reasons you may want to consider using JSON:

  • JSON 是网络数据交换的理想选择。如果您需要将数据发送到联网设备,使用 JSON 和 HTTP 是一项简单的任务,但是使用 CSV 和 ARFF 就不那么简单了。

  • 许多 NoSQL 数据库使用 JSON 文件作为数据的对象存储。我将在第三章进一步讨论这些数据库。这种数据库架构解决了大量数据带来的可伸缩性问题。

JSON 文件总是比 CSV 或 ARFF 版本大,因为它们包含缩进的结构和空间。文件大小的增加是对 JSON 提供的额外灵活性的公平权衡。

Weka 桌面环境使得 ARFF 和 JSON 之间的转换变得很容易。你将在第四章中探索 Weka。

2.4 JSON 集成

JSON 是 ML 解决方案的重要组成部分。JSON 的优势之一是几乎每个开发平台都有库。它是真正的跨平台。因为您关注的是 Java,所以接下来您将研究如何集成 JSON for Android 和 Java JDK。

带有 Android SDK 的 JSON

JSON has been included in Android since the earliest release of the SDK. Table 2-6 shows a list of the Android JSON classes including the exception handler.Table 2-6

Android SDK 中包含的 JSON 类

|

班级

|

描述

|
| --- | --- |
| JSONArray | 密集的索引值序列 |
| 【jsonobject】 | 一组可修改的名称/值映射 |
| 【jsconstraint inger】 | 实现了JSON object . tostring()JSON array . tostring() |
| 【jsontokener】 | 将 JSON 编码的字符串解析为相应的对象 |
| JSONException | 抛出表示 JSON API 有问题 |

The JSONArray and JSONObject objects are all you need to manage your JSON encoding and decoding. The following code shows how to define JSON objects and JSON arrays in Android:001   // Define a new JSON Object 002   // Remember that JSON Objects start with { (left brace) and end with } (right brace) 003 004   JSONObject jsonObject = new JSONObject(myJsonDataString); 005 006   // Define a new JSON Array 007   // Remember that JSON Arrays start with [ (left bracket) and end with ] (right bracket) 008 009   JSONArray jsonArray = new JSONArray(myJsonDataString);

有效使用 JSON 的诀窍在于使用 JSON 对象和 JSON 数组原语定义 JSON 数据结构来表示您的数据。你将在本章的后面探索如何实现这一点。

带有 Java JDK 的 JSON

虽然 JSON 类从一开始就包含在 Android SDK 中,但 Java JDK 却不是这样。要在 Java 中使用 JSON,必须包含 JSON 库。

There are many JSON libraries available for Java. Table 2-7 shows two common sources for Java JDK JSON libraries.Table 2-7

Java JDK 的 JSON 库

|

JSON 源代码

|

|
| --- | --- |
| 谷歌 JSON 简单 | 【https://code.google.com/archive/p/json-simple/】 |
| Maven JSON 存储库 | 【https://mvnrepository.com/artifact/org.json/json】 |

Maven 存储库很有用,因为它允许您下载 Eclipse 的 jar 文件。Maven 资源库中有许多版本的 JSON。20171018 版本运行良好,可从以下链接获得:

【https://mvnrepository.com/artifact/org.json/json/20171018】

Figure 2-8 shows the download page for this version of Java JSON. The page contains instructions for many different types of build environments, including Maven, Gradle, SBT, Ivy, and others. The Java build environment you use will determine how you include the JSON library.img/468661_1_En_2_Fig8_HTML.jpg Figure 2-8

Java JSON 的 Maven 仓库

如果您希望下载 Eclipse 的 jar 文件,请选择“JSON Libraries”并下载 jar zip 文件。然后,您可以直接将 jar 文件库添加到 Eclipse Java 构建路径中。

Figure 2-9 shows the json-20171018.jar file added to the Eclipse Java build path.img/468661_1_En_2_Fig9_HTML.jpg Figure 2-9

JSON jar 库的 Eclipse IDE Java 构建路径

将 JSON 添加到 Java JDK 之后,您现在可以利用 JSON 的强大功能来满足您所有的 ML 数据结构需求。无论您是使用 Eclipse 的外部 Java JSON 库还是 Android Studio 中的内置 Android JSON 库,您编写的用于 JSON 对象和数组的 Java 应用程序代码都是相同的。

2.5 数据预处理

One of the key activities for ML-Gate 5 is data preprocessing . There are many potential actions you can take in this area to improve the quality of your data. This section does not include an exhaustive list. Nor does it provide a deep dive into the mathematical or statistical principles behind each technique.

了解您的数据是无可替代的。这是一项耗时的手工练习。提前投入时间分析数据以提高数据的质量和完整性,在 ML 项目的后期总是有回报的。

请将以下部分视为一个清单。在选择 ML 算法、构建 ML 模型或编写任何代码之前,您可以使用清单来探索数据的各个方面。随着时间的推移,数据清理会有回报。

实例、属性、标签和特征

At the top of the checklist is the identification of instances, attributes, labels, and features. ML-Gate 6 requires you to have a well-defined problem. This directly relates to understanding the structure of your data. Some important definitions:

  • 实例:一行数据。实例是机器学习方案的输入。CSV 文件可以将实例表示为独立的列表,而 JSON 可以表示数据中的关系。

  • 属性:一列数据。属性可以有不同的数据类型,如实数、整数、名义值或字符串。对于监督学习,存在属性、要素和标注的类型。

  • 特性:描述性属性。

  • 标签:你试图预测或预报的东西。

例如,如果您回顾表 2-3 中的数据,该表显示了 PAMAP2 数据集的属性(或列)。回想一下,在这个数据集中有 54 个属性(或列)。在这个数据集中, 活动 Id 是标签,其余属性是特征。

Checklist questions to ask:

    所有实例的结构是否一致?

    有多少实例?

    有多少属性?

    数据集的格式和原始文件大小是什么?

    属性包含标签还是所有属性都是特征?

    是否所有标签都包含合规值?

    以后可以添加新属性吗?

    如果添加一个新属性,如何更新新属性的现有实例?

最后两个问题特别重要,因为数据集会随着时间的推移而增长和发展。当您添加新的属性时,实际上在更改之前的每个实例中都缺少该属性的值。在下一节关于缺失值和重复值的内容中,我将讨论一些处理这种情况的技术。

数据类型识别

Table 2-2 summarized the data types for ML datasets. Define the data type of each attribute in your dataset. The data types can be either

  • 定性数据(名义数据或序数数据)

  • 定量数据(离散或连续)

一些公司为他们所有的软件项目维护一个数据字典。数据字典表示所有数据资产的正式记录,包括每个属性的数据类型。这是最佳实践。维护数据字典会产生开销,但是正如数据清理随着时间的推移会有回报一样,数据组织知识也会有回报。

Checklist questions to ask:

    数据集中的每个属性都有定义的数据类型吗?

    在项目生命周期中,当做出影响数据设计的更改时,数据类型是否会更新?

缺失值和重复值

缺失值和重复值是数据预处理的一个重要方面。

缺失值可以采用空白、破折号或 NaN 的形式,如您在 PAMAP2_Dataset 中所见。

Missing values are not hard to find. The difficulty lies with what action you should take when you find them. Missing values tend to fall into two categories:

  • MCAR(完全随机失踪)

  • 系统性缺失:价值缺失是有原因的。

值丢失并不能说明值丢失的原因。当您发现缺少值时,您必须仔细考虑解决方案。大多数最大似然算法不重视缺失值。用生成的值替换丢失的值有时可以提高整体数据的完整性。这完全取决于数据的上下文。

There are multiple approaches you can consider when handling missing values. When you have familiarity with the data and the collection methodology, you can make an informed judgement and select one of the following approaches:

  • 不要采取行动。保留丢失的值。

  • 将该值替换为“未测试”或“不适用”指示器。在这种情况下,您添加了细节并提高了数据完整性,因为您主动知道某个值不应该出现。

  • 如果标签包含缺少的值,您应该考虑删除整个实例,因为它不会为您定型的模型增加值。

  • 如果数据类型为定量和范围限制,则为缺失值分配范围下限或范围上限。有时,您有一个范围内的规范化值,分配一个最小值或最大值可以使算法更有效。

  • 为缺失值估算一个值。估算是指在研究其他属性的基础上用新值替换该值。

重复并不总是容易找到的。一旦找到,它们就相对容易处理。它们可以被删除,或者如果可行的话,如果不是所有属性都重复,它们可以与其他实例组合。

Checklist questions to ask:

    数据集有重复的值吗?如何找到重复的值?存在重复项时,如果数据集完整性增强,请删除该实例。

    数据集是否有缺失值?如何解决缺失值以最大化数据集完整性?

错误值和异常值

发现数据中的错误和异常值比识别缺失值和重复值更困难。

Let’s start with an example. The dataset shown in Figure 2-10 is a time series containing 24 data points. The graph shows data released by the Belgium Ministry of Economy. It represents international phone calls made during a 23-year period.img/468661_1_En_2_Fig10_HTML.jpg Figure 2-10

24 个点的时间序列数据集

很明显,在七年的时间里,这些数据包含了几个异常值。知道了这些数据的来龙去脉,有些事情就说不通了。我们可以想象这样一个场景,这样一个数据集是有意义的。例如,如果我们查看一家钢铁厂的生产量,并且我们知道有一个多年的时期,战争导致需求激增,会怎么样?这样的图表可能有意义。

然而,在这种情况下,数据没有意义。我们应该忽略异常值吗?

事实证明这个数据是错误的。在 1963 年至 1970 年期间,该部使用了不同的记录方法。受影响期间,数据代表的总分钟数,而不是 的总通话数 。哎呀。

**即使我们不知道是什么导致了错误,我们仍然应该删除异常值,因为它们在数据的上下文中没有意义。我们可能不会注意到 1963 年和 1970 年的轻微影响,但保留它们不会产生剧烈的影响。

图表包括两条回归线。回归是一种简单的预测方法。在这种情况下,最小二乘法不是很准确,因为它很容易受到异常值的影响。最小中值平方回归方法在忽略异常值方面做得更好。

在这种情况下得到的教训是,我们需要评估异常值,然后选择一种 ML 方法,尽可能减少异常值的影响。

讽刺的是,机器学习可以检测异常值。一类学习是 ML 用于这个任务的特殊类。

Checklist questions to ask:

    数据的可视化会显示异常值吗?

    异常值在数据环境中有意义吗?如果是这样,考虑删除离群值。

    如果异常值持续存在,考虑一种可以合理容忍噪声数据的方法。

用 OpenOffice Calc 进行宏处理

在第三章,我会介绍 Weka ML 环境。Weka 使用其基于 Java 的工具具有许多预处理数据的能力。但是,您也可以使用 OpenOffice Calc 的宏处理功能来预处理您的数据。

学习使用 Calc 电子表格宏是一个非常强大的 ML 工具。宏允许您根据特定条件对数据文件进行批量更改。它们允许你自动化重复的任务。对于大型数据集,这可以节省您大量的时间和精力。Calc 就像 Microsoft Excel 一样,使用 Visual Basic 来处理宏。

与 Microsoft Excel 一样,Calc 对宏使用 Visual Basic 编程语言。不难掌握。Calc 宏可以自动执行您可以手动执行的任何电子表格操作。Calc 允许你记录击键来构建宏。Calc 还允许您手动输入宏代码。

OpenOffice 文档的第 12 章包含对 Calc 宏的精彩介绍:

www . open office . org/documentation/manuals/user guide 3/0312 cg3-calc macros . pdf

OpenOffice wiki 页面上提供了 Calc 宏的其他文档:

https://wiki . open office . org/wiki/Documentation/ooo authors _ User _ Manual/Getting _ Started/Creating _ a _ simple _ macro

The following code shows a useful macro for iterating through all rows in a Calc spreadsheet and displaying non-empty cells. Calc and the Visual Basic language contain a huge library of functions and the possibilities are endless.001   Sub TraverseRows 002      Dim oRange 'The primary range 003      Dim oSheet 'Sheet object 004      Dim oRows 'Rows object 005      Dim oRow 'A single row 006      Dim oRowEnum 'Enumerator for the rows 007      Dim s As String 'General String Variable 008 009      oSheet = ThisComponent.Sheets(3) 010      oRange = oSheet.getCellRangeByName("B6:C9") 011 012      oRows = oRange.getRows() 013 014      oRowEnum = oRows.createEnumeration() 015      Do While oRowEnum.hasMoreElements() 016         oRow = oRowEnum.nextElement() 017         s = s & NonEmptyCellsInRange(oRow, " ") & CHR$(10) 018      Loop 019      MsgBox s, 0, "Non-Empty Cells In Rows" 020   End Sub

如果您正在努力寻找对数据进行必要清理的方法,Calc 宏是一个很好的解决方案,尤其是对于 CSV 数据。

If you have huge spreadsheets, Calc macros might not offer the best performance for data cleaning and manipulation. The limitations of Apache OpenOffice Calc are

  • 最大行数:1,048,576

  • 最大列数:1,024

  • 最大张数:256

JSON 验证

如果使用 JSON 作为数据格式,需要在创建后验证 JSON。有许多在线工具可以执行 JSON 验证。它们中的许多都是开源的或者是用脚本语言创建的,所以如果您愿意,您可以在本地运行验证。

Figure 2-11 shows the JSON validation of the file you created earlier in the chapter by the online tool available at https://jsonlint.com .img/468661_1_En_2_Fig11_HTML.jpg Figure 2-11

JSON 验证

运行您创建的任何 JSON 总是一个好主意,特别是如果您通过 JSON 验证手动创建它。

Checklist question to ask:

    用 JSON 表示数据吗?在建模之前验证所有 JSON 文件。

2.6 创建您自己的数据

在本章的前面,我将私有数据和合成数据列为潜在的数据源。我们生成这两类数据。合成数据代表由计算机创建的数据。我们都携带着有史以来最伟大的数据收集设备:智能手机。您可以利用其数据创建能力来解决第一章中提出的问题,即表 1-11 中所示的室内位置跟踪要求(R1)。接下来,您将探索这一需求的潜在解决方案。

Wifi 聚集

我们的移动设备能够扫描 Wifi 和蓝牙网络。当你使用这些 Wifi 扫描应用程序时,你会注意到有许多 Wifi 信号分布在可用的频道上。当你在空间中移动时,这些信号代表数据。

Figure 2-12 shows a typical room that has three different Wifi access points (AP) visible to a device. The signal strength received by the device depends on many factors, such as proximity to the AP and obstructions within the space. The combined strength of these signals throughout the space can allow you to locate the device.img/468661_1_En_2_Fig12_HTML.jpg Figure 2-12

使用 Wifi 信号强度进行室内定位

两种度量单位 dBm 和 RSSI 代表信号强度。RSSI 是一个相对指数,而 dBm 是一个绝对数字。对于 dBm,越接近 0 dBm,信号越好。Android 设备返回的相关 RSSI 在-100(最弱)到-55(最强)之间。

您将使用 AndroidWifi manager从所有可见的 Wifi 接入点(AP)收集信号强度信息。移动电话用户熟悉设备状态栏中显示的四栏 Wifi 信号强度图标。Android 提供了一个名为wifi manager . calculate signal level的静态方法,在 0-4 的范围内计算信号电平。Android 使用这个值来生成信号强度图标。该方法还可以提供图 2-12 所示的 归一化 值。

As an example, let’s consider the simple code required to gather the Wifi signal strength data and save it in JSON format as the Android device moves around a room. Listing 2-2 shows the key Android code. This code is not a complete Android project, but the code excerpt file, WifiCollect.java is available in the book resources if you wish to leverage it when building your own project.001   private WifiManager wifi; 002   private JSONObject wifiResults = new JSONObject(); 003 004   @Override 005   public void onCreate() { 006       wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 007 008       // register wifi intent filter 009       IntentFilter intentFilter = new IntentFilter(); 010       intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 011       registerReceiver(mWifiScanReceiver, intentFilter); 012 013       wifiResults = new JSONObject(); 014   } 015 016   private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() { 017       @Override 018       public void onReceive(Context c, Intent intent) { 019           if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { 020               List wifiScanList = wifi.getScanResults(); 021               for (int i = 0; i < wifiScanList.size(); i++) { 022                   String name = wifiScanList.get(i).BSSID.toLowerCase(); 023                   int rssi = wifiScanList.get(i).level; 024                   Log.v(TAG, "wifi-ssid: " + name + " => " + rssi + "dBm"); 025                   try { 026                       wifiResults.put(name, rssi); 027                   } catch (Exception e) { 028                       Log.e(TAG, e.toString()); 029                   } 030               } 031               saveData(); 032           } 033       } 034   }; Listing 2-2

WifiCollect.java-用于 Wifi 数据采集的示例 Android 代码

To summarize the key code in Listing 2-2:

  • 您在 002 行定义了一个 JSONObject 。该对象将保存设备在扫描过程中识别的所有 Wifi 网络的名称(SSID)和信号强度。

  • onCreate() 方法中,使用 Androidwifi manager创建一个 intent 并注册一个broadcast receiver

  • 因为你用的是 Wifi,记得在清单文件中包含SCAN _ Wifi _ NETWORKSACCESS _ Wifi _ STATE的权限。

  • 你在 016 行定义了。Android 在检测到新的 Wifi 网络时会通知 广播接收器

*** 第 022 行和第 023 行显示了从 Wifi 扫描中检索到的网络名称和信号水平。这些值存储在 JSON 对象的第 026 行。JSON 对象随着 广播接收器 接收新网络而增长。

*   第 031 行显示了对 ***saveData()*** 函数的调用。这个函数将保存 JSON 对象以供处理。您可能希望通过网络将它发送到服务器,添加到 NoSQL 数据库,或者在内部使用它在设备上建立模型。** 

**This approach to determining indoor location is very accurate and can operate with very low latency. To achieve the result requires a two-step process:

    使用清单 2-2 中所示的代码绘制出您的空间并收集 Wifi 数据样本。对于您采集的每个样本,将其分配到一个标签上,以标识设备在空间中的位置。例如,您可能希望将目标空间划分为一个正方形网格,并为网格位置指定编号。

    一旦您收集了该空间的所有数据,就可以使用它来构建 ML 模型。然后,您可以使用该模型来预测您在房间中的位置。

使用 ML 进行室内定位是创建您自己的数据来解决 ML 问题的一个强大示例。为了使解决方案更加健壮,您可以对蓝牙信号实现相同的方法。

虽然这个例子说明了在设备附近收集和使用射频数据,但智能手机还擅长产生另一种类型的数据:传感器数据。我会在最后一章详细讨论传感器数据,包括 Java 设备和 Android 智能手机的 ML 传感器数据实现。

2.7 可视化

能够可视化您的数据非常重要。可视化使您能够轻松洞察数据。数据可视化是最好的工具之一,您可以将它添加到您的工具包中,以便对自己的数据提出更高的要求。

实现数据可视化的最佳方法之一是将第三方开源图形库与 web 浏览器或 Android WebView 结合使用。应用这种方法,你可以用最少的代码生成惊人的可视化效果。

JavaScript 可视化库

Table 2-8 shows a partial list of visualization libraries available. JavaScript is the language of choice for most of these libraries because it provides the following benefits:

  • 所有现代浏览器都支持 JavaScript,包括 Android 的 WebView 控件。这意味着您创建的任何可视化都可以跨平台广泛使用。

  • JavaScript 擅长交互式功能。这使得你的可视化比静态图像更引人注目。

Table 2-8

JavaScript 可视化库

|

库/链接

|

描述

|
| --- | --- |
| D3 加 d3plus.org | D3 加 2.0 版本。惊人的例子和可视化设置。 |
| 传单 leafletjs.com | 一个面向移动友好的交互式地图的开源 JavaScript 库。 |
| 时间线 JS timeline.knightlab.com | 开源工具,使任何人都能构建视觉丰富的交互式时间线。 |
| highcharts.com 排行榜 | 广泛使用的库。简单而强大的制图 API。需要许可证。 |
| fusioncharts.com 融合 | 网络和移动 JavaScript 图表。包括 90 多张图表和 1000 多张地图。免费。 |
| dygraphs.com dygraphs | 快速、灵活、开源的 JavaScript 图表库。允许用户探索和解释密集的数据集。 |
| Plotly plot.ly | 通过 Web 撰写、编辑和共享交互式数据可视化。 |
| Raw rawgraphs.io | 电子表格和数据可视化之间缺失的环节。 |
| chartjs.org 图表 | 简单、灵活的 JavaScript 图表。开源。不错的过渡和动画。 |
| Datawrapper datawrapper.de | 从数据到漂亮的图表。被很多记者使用。包月模式。 |
| chartblocks chartblocks . com . cn 上的信息 | 在线图表制作工具。包月模式。 |
| 谷歌图表 developers.google.com/chart | 简单易用,丰富的交互式图表库。免费。 |
| tableau . com 表格 | 拥有许多大客户的大型商业解决方案。纽交所上市。 |
| Infogram infogr.am | 提供完整产品的大型企业供应商。 |

表 2-8 中的库都非常有能力帮助你可视化你的数据。当您探索它们时,您可能会发现其中一个最符合您的要求。Highcharts 和 D3 Plus 是两个最流行的库。

D3 加

D3 代表数据驱动文档。D3 是一个 JavaScript 可视化包。它很轻。D3 Plus 是 D3 的扩展。D3 Plus 目前支持的版本是 2.0 版。

You will explore D3 Plus in more detail for the following reasons:

  • D3 是一个基于 JavaScript 的,提供流畅的交互用户体验。

  • 所有的现代浏览器都可以呈现 JavaScript,所以这对于 Java 和 Android 应用程序来说都是一个很好的解决方案。

  • D3 Plus 使得创建和显示 CSV 和 JSON 可视化变得非常简单。

  • 免费开源。

D3 库、D3 Plus 和综合图表库的下载链接位于

【https://d3js.org】

【https://D3 plus . org

github . com/D3/D3/wiki/gallery

接下来,您将在 D3 可视化项目中使用树状图表类。树形图是一种显示层次结构的树形图。D3 图库页面链接到位于bl.ocks.org/mbostock/4063570的树突图示例。

2.8 项目:D3 可视化

你在本章前面已经看到 CSV 和 JSON 是 ML 的有用数据格式。在这个项目中,您将为桌面浏览器实现 D3 可视化。

树形图对显示层次结构很有用。该项目将探索各种树状结构来可视化 CSV 和 JSON 数据。

Table 2-9 shows the project file summary. The book resources contain the zip file, d3_visualization.zip, which includes all the project files.Table 2-9

D3 可视化项目文件摘要

|

项目名称:D3 可视化 来源:D3 _ Visualization . zip类型:桌面浏览器

|
| --- |
|

文件

|

描述

|
| --- | --- |
| d3.min.js | D3 库 |
| flare . CSV | CSV 数据文件 |
| flare . JSON | JSON 数据文件 |
| dendo-CSV . html??] | 使用 csv 数据的树状图示例 |
| 树-dendo-CSV . html??] | 使用 csv 数据的树形图示例 |
| 径向 dendo-CSV . html??] | 使用 csv 数据的径向树树状图示例 |
| collapse-tree-json.html | 使用 JSON 数据的可折叠树形图示例 |
| 丛集 dendo-json.html | 使用 json 数据的聚类树状图示例 |

可视化就是选择最好的图形样式来表示数据。树形图非常适合 JSON 可视化,因为它们显示了层次结构。

在这个项目中,你有两个数据文件源, flare.csvflare.json 。它们代表相同数据的不同文件格式。D3 能够将每个版本渲染成几个有趣的树状结构。如果您希望呈现另一种图表类型,代码可能与示例非常相似;只需查看 D3 图库中您想要的图表的代码示例。

要在浏览器中查看可视化,您必须设置一个 web 服务器来托管表 2-9 中所示的文件。如果您希望在您的桌面上本地查看它们,您可以安装本地 web 服务器,这取决于您的桌面平台。

If you need to install a web server, refer to the following platform-specific instructions:

一旦你设置好你的网络服务器,只需将你的浏览器指向五个 HTML 文件中的一个。对于所选的数据格式类型,每个文件呈现的树形图略有不同。

D3 可视化需要最少的 JavaScript 代码。JavaScript 代码包含在 HTML 文件中。清单 2-3 展示了一个从 CSV 数据中呈现树状结构的【dendo-csv.html】文件的例子。

There are two key parts in the structure of any D3 based visualizations:

  • 需要包含对 D3 库文件的引用。您可以使用库的本地副本或在线存储库。将库引用包含在 <脚本> 标签内(第 014 行)。

  • 使用 d3.csv 赋值语句(第 025 行)指定要为可视化加载的 CSV 文件。

Note that Listing 2-3 includes the JavaScript code (lines 016-053) and the CSS style code (lines 004-010) used to format the visualization.001    002    003 004    011 012    013 014    015 016    Listing 2-3

dendo-csv.html

A dendogram aligns each of the lower-level leaf nodes, so the visualization appears right justified. Figure 2-13 shows the dendogram visualization of the CSV file that D3 generates when you open the dendo-csv.html file in your browser.img/468661_1_En_2_Fig13_HTML.jpg Figure 2-13

由 dendo-csv.html 生成的树突图可视化

树突可视化显然比原始 CSV 文件更容易阅读。

如果你想改变树形图的样式,你可以在 HTML 文件的 004-010 行修改 CSS 元素。CSS 代表级联样式表。它是网页布局设计和样式的通用语言。它可以控制布局的所有方面,如字体、字体大小、边距、填充、间距、对齐等。

如果您希望更改呈现的树状结构的布局结构,可以修改构造树状结构的 JavaScript 代码。例如,线 045-046 控制所画的代表每个节点的圆的半径。

还有许多其他相关的可视化工具可用于描述 ML 数据。树形可视化是树形图的一种变体。可以把它想象成一个左对齐的树形图,其中节点随着树深度的增加而向右延伸。

Figure 2-14 shows the f lare.csv data file visualized as a tree. The tree display differs from the dendogram because of the way the JavaScript code renders the nodes. The tree-dendo-csv.html file actually gives you the choice to select whether you want the CSV data rendered as a dendogram or a tree.img/468661_1_En_2_Fig14_HTML.jpg Figure 2-14

树木可视化渲染,tree-dendo-csv.html

您将使用 D3 生成的最终 CSV 可视化是放射树突图。一张图片胜过千言万语,放射树图可能是最艺术和最有用的可视化。对于大型数据集,树状图和树可能会变得很长,需要滚动才能查看整个可视化。放射状的树突充满了一个圆,所以它往往更紧凑,更容易看到。

Figure 2-15 shows a radial dendogram produced by radial-dendo-csv.html. Even though the font may be small and there are many labels in the dataset, the radial dendogram gives you a good feel for the structure of your data. With practice, you can take a quick glance at a radial dendogram of your data and identify problems or irregularities.img/468661_1_En_2_Fig15_HTML.png Figure 2-15

放射树状可视化,radial-dendo-csv.html

项目中最后两个可视化将使用 JSON 数据作为它们的来源。文件 f lare.json 是前三个可视化中使用的 f lare.csv 文件的 json 版本。

The cluster-dendo-json.html file structure is similar to the approach used with CSV data. The following code block assigns the JSON file in D3 at line 008:001    002    003    004    Note that when loading JSON into D3, there are some requirements for the JSON structure. The JSON needs to be compatible with D3’s hierarchy rules. If you examine the f lare.json file, you will see that it is comprised of “name” and “children” nodes.001   { 002    "name": "flare", 003    "children": [ 004     { 005      "name": "analytics", 006      "children": [ 007       { 008        "name": "cluster", 009        "children": [ 010 011         ...

如果您的 JSON 数据不符合这种结构,您可能需要转换它,以便 D3 可以正确地解析和显示它。有一些工具可以处理这种转换。D3 包括一个名为 d3.nest() 的函数,还有一个名为 下划线. nest() 的外部函数。这些函数的文档和下载链接可以在

https://github . com/D3/D3 集合】【https://github . com/iros/undercore . nest】

一旦 JSON 数据格式正确,D3 就可以呈现它了。

Figure 2-16 shows the cluster dendogram visualization of the JSON file as rendered by cluster-dendo-json.html.img/468661_1_En_2_Fig16_HTML.jpg Figure 2-16

cluster-dendo-json.html 聚类树状可视化

Flare.json is a large file with many nodes. D3 uses this file for many of its visualization examples. If you look inside the HTML file, you will see the following line of code:

这会将渲染窗口的高度设置为 2200 像素。这可能比你的显示器大,这意味着你必须滚动才能看到整个可视化。如果您降低高度以匹配您的显示大小,例如 1200 像素,您将看到可视化变得如此压缩以至于不再可读。

A solution to this problem is the collapsible tree. Remember, JavaScript is interactive. The collapsible tree visualization allows you to click on nodes to expand or contract them. Figure 2-17 shows the much cleaner collapsible tree visualization as rendered by collapse-tree-json.html.img/468661_1_En_2_Fig17_HTML.png Figure 2-17

collapse-tree-json.html 可折叠树

The collapsible tree is useful because it allows you to click on individual node to expand them. It does not leave your entire screen cluttered with the whole visualization. It is a much easier way to explore the data interactively. The collapse-tree-json.html file is larger than the other versions because it contains JavaScript code, such as the following function, to manage the interactive node navigation:001   // Toggle children on click. 002   function click(d) { 003     if (d.children) { 004       d._children = d.children; 005       d.children = null; 006     } else { 007       d.children = d._children; 008       d._children = null; 009     } 010     update(d); 011   } In this project, you covered five different data visualizations from the dendogram family: three with CSV source data and two with JSON source data.

JavaScript 能产生出色的可视化效果。如果您浏览 D3 图库,您会发现适合您的数据的可视化,以及帮助实现可视化的示例 JavaScript 代码。

拥有一个可视化数据的 JavaScript 解决方案可以让您看到数据的样子。这些可视化可以很美,可视化的力量显而易见。与原始数据文件相比,可视化可以让您更好地感受数据的结构。这是理解数据并能够识别数据中隐藏模式的第一步。

随着 CSV 和 JSON 可视化在您的工具箱中,您已经开始 对自己的 数据提出更多要求。

2.9 项目:Android 数据可视化

这个项目将把你在桌面上用 D3 可视化所做的工作扩展到 Android 移动设备上。显示可视化可能不是你的 Android 应用的核心功能,但有时它可能对你的用户很有帮助。

Table 2-10 shows the project file summary.Table 2-10

项目文件摘要- Android 数据可视化

|

项目名称:Android Data visualization source:Android _ Data _ vis . zip类型:Android

|
| --- |
|

文件

|

描述

|
| --- | --- |
| 【app】>【src】>【mainandorsanifest . XML】 | 配置文件。 |
| 【app】>【src】>【main】>【RES】>【layout activity _ main . XML】 | 用于显示 WebView 的布局文件。 |
| 【应用】>【src】>【main】>【asset SD 3min . jsflare . csvradial-dendo-CSV . html | 资产,如果您决定使用资产的本地副本构建应用程序。如果从 web 服务器加载资产,则不需要。 |
| app->src->main->javaMainActivity.java | 加载和显示 D3 可视化的主 Java 源代码。 |

您已经看到 D3 可视化在桌面浏览器上工作,所以为 Android 设置它很简单。

你不用把一个可视化或者图表库导入到你的应用程序中,你可以走捷径,使用 Android 的 WebView 类来显示 D3 可视化。 WebView 是一个由 Chrome 驱动的系统组件,允许 Android 应用程序直接在应用程序中显示来自网络的内容。该类为您的应用程序提供了干净、集成的用户体验。和任何好的网络浏览器一样, WebView 支持 JavaScript,所以对于 D3 内容很好用。

Figure 2-18 shows the Android Data Visualization project in Android Studio.img/468661_1_En_2_Fig18_HTML.jpg Figure 2-18

Android Studio 中的项目 Android 数据可视化

There are two methods to handle the D3 integration with WebView , depending on how you decide to manage access to the required files:

  • 内部:将所需文件放在 app assets 文件夹中。

  • 外部:从远程 web 服务器加载资产。

The following code from MainActivity.java shows how to set up a full screen WebView layout. A progressDialog provides an indication to the user that network content is loading, which is especially useful if the resources are loaded from external server. Lines 067-068 show the radial-dendo-csv.html file reference, depending on whether you choose the internal or external approach.001   package android.wickham.com.datavis; 002 003   import android.annotation.SuppressLint; 004   import android.app.Activity; 005   import android.app.ProgressDialog; 006   import android.content.DialogInterface; 007   import android.graphics.Color; 008   import android.os.Bundle; 009   import android.webkit.WebChromeClient; 010   import android.webkit.WebView; 011 012   public class MainActivity extends Activity { 013 014       private WebView webView; 015 016       @SuppressLint("SetJavaScriptEnabled") 017       @Override 018       protected void onCreate(Bundle savedInstanceState) { 019           super.onCreate(savedInstanceState); 020           setContentView(R.layout.activity_main); 021 022           webView = (WebView) findViewById(R.id.wb_webview); 023 024           //Scroll bars should not be hidden 025           webView.setScrollbarFadingEnabled(false); 026           webView.setHorizontalScrollBarEnabled(true); 027           webView.setVerticalScrollBarEnabled(true); 028           webView.setFitsSystemWindows(true); 029 030           //Enable JavaScript 031           webView.getSettings().setJavaScriptEnabled(true); 032 033           //Set the user agent 034           webView.getSettings().setUserAgentString("AndroidWebView"); 035 036           //Clear the cache 037           webView.clearCache(true); 038           webView.setBackgroundColor(Color.parseColor("#FFFFFF")); 039           webView.setFadingEdgeLength(10); 040           webView.getSettings().setBuiltInZoomControls(true); 041           webView.getSettings().setDisplayZoomControls(false); 042 043           final Activity activity = this; 044           final ProgressDialog progressDialog = new ProgressDialog(activity); 045           progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 046           progressDialog.setProgressStyle(ProgressDialog.THEME_HOLO_LIGHT); 047           progressDialog.setCancelable(true); 048 049           webView.setWebChromeClient(new WebChromeClient() { 050               public void onProgressChanged(WebView view, int progress) { 051                   progressDialog.setCanceledOnTouchOutside(true); 052                   progressDialog.setTitle("Loading visualization ..."); 053                   progressDialog.setButton("Cancel", new DialogInterface.OnClickListener() { 054                       public void onClick(DialogInterface dialog, int which) { 055                           webView.destroy(); 056                           finish(); 057                       } }); 058                   progressDialog.show(); 059                   progressDialog.setProgress(0); 060                   activity.setProgress(progress * 1000); 061                   progressDialog.incrementProgressBy(progress); 062                   if(progress == 100 && progressDialog.isShowing()) 063                       progressDialog.dismiss(); 064               } 065           }); 066           // Uncomment one of the following two lines based on Internal or External loading 067           //webView.loadUrl("file:///android_asset/radial-dendo-csv.html"); 068           webView.loadUrl("https://www.yourwebserver.com/radial-dendo-csv.html"); 069       } 070   } The following code shows the layout file, fullscreen.xml. It includes the Android WebView control that is contained within a FrameLayout .001   <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 002       xmlns:tools="http://schemas.android.com/tools" 001       android:layout_width="match_parent" 002       android:layout_height="match_parent" 003       tools:context="android.wickham.com.datavis.MainActivity"> 004 005       <WebView 006           android:id="@+id/wb_webview" 007           android:layout_width="fill_parent" 008           android:layout_height="fill_parent" /> 009 010    This Android app, when executed, downloads the HTML/JavaScript file and then displays the visualization on your device, as shown in Figure 2-19.img/468661_1_En_2_Fig19_HTML.jpg Figure 2-19

安卓数据可视化 app 截图

WebView 包含许多控制可视化如何出现的配置参数,例如缩放、滚动等。请记住,这种方法可以显示任何 D3 可视化,而不仅仅是您关注的树状结构,因为它们对 ML 数据文件(如 CSV 和 JSON 文件)很有用。

2.10 摘要

This chapter was all about data. It certainly is the fuel for machine learning. In the subsequent chapters, you will be selecting algorithms, building models, and finally integrating those models. Without careful attention to the data in this early phase, you will not be able to achieve the desired results. Figure 2-20 shows how the data topics you learned in this chapter fit into the overall ML-Gates methodology introduced in Chapter 1.img/468661_1_En_2_Fig20_HTML.jpg Figure 2-20

ML-Gates 方法的前三个门是数据驱动的

你的方法论的最初三个关口都以数据为中心,这并不奇怪。

如果没有在 ML-Gates 6/5/4 投入足够的时间来处理数据,通常会导致 ML-Gates 3 和 2 的结果不佳。到那时,回头去解决数据问题将变得非常昂贵。

下一节在转到基于云的 ML 实现之前,快速回顾关键章节的发现。

关键数据结果

You are on the path to becoming data scientist when you follow these best practices:

  • 要开发 ML 应用程序,您必须采用数据驱动的方法。

  • 要开发成功的 ML 应用程序,您必须对自己的数据有更高的要求。

  • 你的大部分代码都是关于数据的争论。80/20 法则适用于:对于你承担的任何给定项目,你 80%的时间将用于处理数据。

  • 对于一个明确定义的问题,高质量的相关数据是起点。

  • 了解你有什么类型的数据。当您对第四章中的数据应用算法时,这将是必要的。

  • 定义您的数据类型,并考虑将它们保存在数据字典中。

  • 有许多来源可以用于您的 ML 应用程序数据:公共的、私有的、政府的、合成的等等。

  • 您可以生成自己的数据。在本章中,您看到了一个使用 Android 的 Wifi 功能实现室内位置跟踪的示例。

  • 您可以使用许多工具来操作数据,包括 Open Office Calc 电子表格程序。在第四章中,您将探索 ML 环境中可用的其他数据过滤工具。

  • JSON、CSV 和 ARFF 格式是 ML 的流行数据格式。对它们都感到舒适。

  • 大多数实体没有足够的高质量数据用于 DL,而 CML 应用只需要合理的数据量就能成功。

  • 智能手机是有史以来发明的最好的数据收集设备。

  • 可视化是 ML 和理解数据的一个关键方面。

  • 为了帮助您可视化您的数据,您可以利用第三方包,使在浏览器和 Android 设备上可视化数据变得容易。****

三、利用云平台

  • 提供 IaaS 解决方案的云提供商回顾

  • 谷歌云平台(GCP)和亚马逊网络服务(AWS)云产品概述,包括数据存储、数据预处理、模型创建和模型部署功能

  • 如何在云中实现 Weka

  • ML 云提供商 API 产品概述

  • 项目:使用 Android 的云语音 API 实现 GCP ML

  • ML 云数据工具概述

  • 对 ML 的云数据策略的回顾,包括 NoSQL 数据库的使用

3.1 导言

高度可扩展的计算资源的可用性是推动人工智能爆炸的三大趋势之一。在本章中,您将分析云服务提供商。您正在专门寻找他们可以帮助您交付 ML 解决方案的方法。

The big four cloud providers that offer Infrastructure as a Service (IaaS) solutions are the drivers behind this megatrend. Table 3-1 shows a summary of the big four service providers.Table 3-1

美国四大云服务提供商

|

IaaS 提供商

|

网站(全球资讯网的主机站)

|

注意

|
| --- | --- | --- |
| 谷歌云平台 | cloud.google.com | 轻松集成所有有用的谷歌工具,包括 Android 手机。 |
| 亚马逊网络服务 | aws.amazon.com | 最大的云提供商。为 ML 提供全套服务。 |
| 微软 Azure | azure.microsoft.com | 增长最快的 IaaS 提供商。 |
| IBM 云 | ibm.com/cloud | 沃森是云 ML 的先驱。 |

IaaS 解决方案允许您扩展计算环境,以满足您在 CPU、内存和存储方面的需求。您只需要为所需的资源付费。还使您能够轻松地跨地理区域分配资源。

这种方法比构建您自己的服务器并在它们变得太慢时升级它们要容易得多,也便宜得多。

在这一章中,您将研究主要厂商的云产品,看看它们如何帮助您创建和部署 ML 解决方案。

商业云提供商

One of the advantages of creating CML solutions compared to DL is that they require for less data and CPU resources. This generally enables you to create solutions entirely on the desktop. However, you should not overlook the cloud. The cloud providers continuously improve their ML offerings. Today they provide an amazing array of services and APIs that make it easier than ever for developers who do not have prior ML experience to create and deploy ML solutions.

云 ML 服务不是免费的。无论他们使用何种类型的容器或虚拟化技术,在某些时候都需要专用或共享的硬件(CPU、内存、存储)。每个提供商通常都有一个免费的试用版,所以你可以在购买前试用这项服务。

定价与您消耗的计算和存储资源成正比。

With your focus on Java, you will next investigate the ML cloud potential of the four large US-based cloud providers. In the next sections, you will review the following ML-related services for each of the providers:

  • 数据存储:IaaS 提供商为 ML 解决方案提供出色的数据存储产品。它们包括平面文件存储、传统的关系数据库、NoSQL 数据库等等。

  • 数据预处理:平台提供了哪些工具来帮助你准备数据(ML-Gate 4)?

  • 模型创建:云平台提供了哪些工具和 ML 框架来帮助你创建你的模型(ML-Gate 3)?

  • 模型部署:有哪些方法可以部署你的 ML 模型进行预测,比如 API 创建或者直接托管访问?

The key considerations outlined in Table 3-2 can help you decide if cloud services are a good fit for your ML project.Table 3-2

云提供商考虑事项

|

种类

|

考虑

|
| --- | --- |
| 本地资源可用性 | 您是否有可以处理大型数据集并构建 ML 模型的本地台式机或服务器?本地处理允许您保持对数据的控制,并避免云使用费。 |
| 深度学习? | 深度学习项目往往倾向于基于云的架构,因为它们依赖于更大的数据集和对模型创建的高计算要求。 |
| 地理多样性 | 云提供商可以让你在全球多个国家和地区增加资源。将资源放在离用户尽可能近的地方是有利的。 |
| 数据量 | 您是否有一个可以在桌面上管理的数据集大小,就像 CML 项目中经常出现的情况一样? |
| 可量测性 | 您预计未来您的数据或存储需求会增长吗?云提供商提供了更好的可扩展性。添加云资源比升级或购买更强大的台式机/服务器要容易得多。 |
| 时间限制 | 模型创建时间重要吗?即使对于具有中等规模到大型数据集的 CML 项目,在台式机或服务器单 CPU 上创建模型也可能需要几分钟到几小时。将这些计算密集型操作转移到云上可以大大减少模型创建时间。如果您需要实时或接近实时的创建时间,云是您唯一的选择。 |
| 有效 | 您需要高可用性吗?您的项目可以从所有云提供商提供的分布式多节点架构中受益。 |
| 安全考虑 | 如果你有自己的联网服务器,你就会知道安全是一个多么大的挑战。云提供商简化了安全性,因为您可以利用他们的大规模基础架构。 |
| 隐私考虑 | 您的客户可能不希望他们的数据放在由四大提供商之一管理的公共云网络上。在这种情况下,您可以实现私有云解决方案并收取额外费用。 |

即使您决定不为您的项目使用云提供商,关注他们的产品也很重要。服务会不断更新,您的决定可能会根据这些更新而改变。

竞争定位

每个人都想知道哪个云提供商最适合机器学习。当然,没有简单的答案。

在任优势在任何决策中都起着重要作用。如果您已经与非 ML 服务的云提供商建立了关系,您更有可能选择相同的提供商来提供 ML 服务。不利的一面是,你可能会发现自己被某个提供商所束缚。ML 的前景变化很快,ML 的产品也有一些显著的不同。密切关注所有服务的发展。

选择一个框架无关的云提供商是有优势的。在接下来的部分你会看到,Google 云平台的框架选择有限,主要依靠强大的 TensorFlow 框架。GCP 确实有优势,可以很好地契合你对移动设备和安卓系统的关注。

The various cloud providers all have their strengths and weaknesses. Figure 3-1 shows a cloud provider summary for some of the largest cloud providers. The chart plots market share along the X-axis with growth rate along the Y-axis. Publicly available corporate earnings reports provided the data. Growth rates represent quarter-by-quarter revenue comparisons. Market share represents reported active users for each of the providers. The cloud providers shown offer pay-as-you-go services that help you deploy ML solutions. The big four US-based players have a combined market share near 70%. Most observers would agree that Amazon Web Services is the market share leader. However, there is fierce competition amongst all the providers. Outside North America, particularly in Asia, Alibaba cloud, also known as Aliyun, is a very strong player.img/468661_1_En_3_Fig1_HTML.jpg Figure 3-1

云提供商的竞争地位

定价

如果您决定部署云服务,定价很重要。它代表一项直接费用,与第一章中讨论的货币化相反。

Fierce market competition between the big four players in recent years has driven down the price of cloud services. Today, there is essentially no pricing arbitrage opportunity available.

由于最大的云提供商之间的激烈竞争,如今不同平台的云资源成本基本相同。四大银行敏锐地意识到他们竞争对手的产品,定价套利机会不再存在。

The cloud providers make it easy to estimate your potential costs. Each provider gives you access to pricing calculators that can give you an accurate idea of your potential costs. Figure 3-2 shows GCP pricing calculator. These interactive tools allow you to specify many parameters including cloud service type, CPU(s), storage, operating system, availability, region, etc. Once you complete the required fields, the tool shows you a calculated monthly and hourly cost.img/468661_1_En_3_Fig2_HTML.jpg Figure 3-2

GCP 定价计算器

图 3-2 显示了谷歌计算引擎服务的指定最低配置。结果显示每月成本为 30 美元或每小时 0.04 美元。如果你在 AWS、Azure 或 Watson 上运行类似的计算,你会发现定价是可比的。

请记住,在使用定价工具时,服务通常提供的免费试用期不包括在定价估算中。在许多情况下,您可以获得为期一年的免费试用,以测试提供商的服务。

3.2 谷歌云平台(GCP)

GCP gives you access to a large and growing set of hardware and software resources, known as services. The GCP services offered are vast. Google distributes the GCP services into the higher-level categories shown in Table 3-3. There are many services in each category. Only the specific services you need for ML and DL are highlighted.Table 3-3

GCP 服务(突出显示与洗钱相关的服务)

|

GCP 服务类别

|
| --- |
| 计算计算引擎 |
| 存储和数据库 |
| 大数据 |
| 云艾云 ML 引擎云 ML API |
| API 平台和生态系统 |
| 数据传输 |
| 身份和安全性 |
| 管理工具 |
| 开发者工具云 SDKEclipse 的云工具 |
| 物联网 |
| 专业性劳务 |
| 生产力工具****安卓 |
| 建立关系网 |

接下来,您将探索突出显示的 ML 相关服务。第一步是注册 GCP 或登录您现有的帐户。图 3-3 显示了 GCP 仪表板。https://console.cloud.google.com/的 GCP 仪表盘地址是

**The GCP dashboard shows Compute Engine midway down the left panel. Compute Engine lets you use virtual machines that run on Google’s infrastructure. When you click Compute Engine, you will be able to create your first virtual machine instance.img/468661_1_En_3_Fig3_HTML.jpg Figure 3-3

GCP 仪表板

谷歌计算引擎(GCE)虚拟机(VM)

尽管 GCP ML 服务集中于 DL,GCE VM 给了你部署任何开源包的灵活性。您可以部署虚拟机来运行 Java、开源的 Weka ML 环境和基于 Java 的数据存储库,比如卡珊德拉·NoSQL 数据库。在 GCE 虚拟机上运行这些包通常比在本地桌面环境中配置它们更容易,因为 Google 为许多流行的包提供了现成的映像,如果您的项目需要在以后进行扩展,您将拥有云平台可伸缩性的所有优势。

Figure 3-4 shows the options available when you create a GCE VM.img/468661_1_En_3_Fig4_HTML.jpg Figure 3-4

GCE 虚拟机实例创建选项

When creating a VM you can choose an instance name and a region for the VM. Of particular interest are the machine type and the boot disk. The machine type specifies the CPU/memory capacity. The pricing information show in the right panel directly relates to the machine capacity you select. For initial testing, you can choose the micro instance. Figure 3-5 shows the boot disk options available. Many Unix configurations are available.img/468661_1_En_3_Fig5_HTML.jpg Figure 3-5

GCE 虚拟机实例操作系统选项

创建实例后,CGE 将处理请求。需要几秒钟时间,实例才会启动并变得可用。图 3-6 显示了新的微型虚拟机实例。如果点击 SSH 下拉对话框,将可以立即连接到实例,也如图 3-6 所示。

您创建的每个虚拟机实例都有一个内部和外部 IP 地址。如果您希望通过互联网访问虚拟机,您应该使用外部 IP 地址。您可以使用支持 SSH 的 FTP 客户端(如 FileZilla)向/从您的虚拟机传输文件。您还可以在 Windows 上使用第三方 SSH shell 程序,如 Putty。有关 VM 实例连接的更多信息,请参考以下 Google 页面:

https://cloud.google.com/compute/docs/instances/connecting-advanced img/468661_1_En_3_Fig6_HTML.jpg Figure 3-6

从 GCP 仪表板到 GCE 虚拟机的 SSH 连接

如果您喜欢使用命令行界面来管理您的 CGE 虚拟机,Google 提供了 Google Cloud SDK。

谷歌云 SDK

Google Cloud SDK is a command-line interface for Google Cloud Platform products and services. Cloud SDK is a set of tools:

  • gcloud tool:管理认证、本地配置、开发者工作流以及与云平台 API 的交互。

  • gsutil 工具:gsutil 提供命令行访问来管理云存储桶和对象。

  • bq 工具:允许您通过命令行在 BigQuery 中运行查询、操作数据集、表和实体。

  • kubectl 工具:协调 gcloud 上 Kubernetes 容器集群的部署和管理。

You can run each of these tools interactively or in your automated scripts. Figure 3-7 shows the Cloud SDK download page.img/468661_1_En_3_Fig7_HTML.jpg Figure 3-7

谷歌云 SDK 下载页面

Cloud SDK is available for all platforms. Figure 3-8 shows the Cloud SDK after successful installation.img/468661_1_En_3_Fig8_HTML.jpg Figure 3-8

云 SDK 安装

一旦安装了 Cloud SDK,您就可以从命令行管理任何 GCP 服务。这包括谷歌计算引擎(GCE)和机器学习引擎(MLE)。

The gcloud compute command-line tool lets you manage your Google Compute Engine resources in a friendlier format than using the Compute Engine API. The gcloud init command shown in Figure 3-9 allows you to update the parameters of the VM if you decide to change them later.img/468661_1_En_3_Fig9_HTML.jpg Figure 3-9

使用 gcloud init 配置 GCE 虚拟机

For installing packages such as Java, Weka, or Casssandra, SSH access is the best method. You launched this earlier from the dashboard (Figure 3-6). If you wish to do this from the command line, you can use the following:001   gcloud compute --project "subtle-bus-204821" ssh --zone "us-east1-b" "instance-1"

Cloud SDK 提供了无限的命令行可能性。查看下面所示的 GCP gcloud 参考页面,了解所有可用的 gcloud 命令:

https://cloud . Google。com/sdk/gcloud/reference/

谷歌云客户端库

谷歌让你很容易将 Java 与所有的 GCP 服务结合使用。GitHub 上提供了 GCP Java 客户端库:

【https://github.com/GoogleCloudPlatform/google-cloud-java】

Google 推荐调用 Google Cloud APIs 的客户端库。据 Google 称,它们通过使用每种受支持语言的自然约定和风格,提供了优化的开发人员体验。

Java 客户端库对于希望集成 GCP 服务的 Android 开发人员也很有用。

Eclipse 的云工具(CT4E)

第一章讲述了为 Java 建立 Eclipse 开发环境。即使 Android 开发人员不再使用 Eclipse 来支持 Android Studio,Google 也一直支持 Eclipse IDE。毫不奇怪,他们为 Eclipse 提供了一个云工具插件(CT4E)。

图 3-10 显示了 CT4E 文档页面。该插件可从以下网址获得

【https://github.com/GoogleCloudPlatform/google-cloud-eclipse】

CT4E wiki 页面还包含许多有用的信息:

https://github.com/GoogleCloudPlatform/google-cloud-eclipse/wiki/Cloud-Tools-for-Eclipse-Technical-Design img/468661_1_En_3_Fig10_HTML.jpg Figure 3-10

Eclipse 快速入门和文档的云工具

CT4E 支持在 Eclipse IDE 版本 4.5 和更高版本中的 GCP 上开发 Java 应用程序。使用 CT4E,您可以构建运行在 GCE 之上的 web 应用程序。

GCP 云机器学习引擎(ML 引擎)

你一直在探索谷歌云平台和云 SDK。现在你会看云 ML 引擎,谷歌机器学习引擎 API。

Figure 3-11 shows the GCP Cloud ML Engine setup page. The first step is to enable the API. It can take up to 10 minutes to enable.img/468661_1_En_3_Fig11_HTML.jpg Figure 3-11

云机器学习引擎 API

Cloud ML Engine API 允许您创建和使用机器学习模型。在上一节中,您看到了如何创建一个可以托管任何软件包的 VM 实例,比如 Weka ML 环境。Cloud ML 引擎通过 API 让你直接与特定的 Google ML 工具接口,从而简化了这个过程。

The downside is that you are restricted to the ML frameworks that Google MLE supports. Google Cloud MLE currently supports the following frameworks:

  • 面向 TensorFlow 的云 ML 引擎

  • scikit-learn 和 XGBoost 的云 ML 引擎

  • Keras 的云 ML 引擎

Note that none of the Google ML Engine options are Java-based.

GCP ML 服务非常适合希望基于 TensorFlow 框架创建和部署 DL 模型的开发人员。最近,Google 增加了对其他框架的支持,包括 scikit-learn、XGBoost 和 Keras。Google 声明基于 Python 的 scikit-learn 是为希望部署经典 ML 模型的开发人员准备的。

如果您确实希望在 GCE 上试验 Tensorflow,Google 提供了一个很好的教程:

https://cloud . Google . com/solutions/running-distributed-tensor flow-on-compute-engine

本教程展示了如何在多个 GCE 实例上设置 TensorFlow 的分布式配置。本教程介绍了 MNIST 数据集。MNIST 在机器学习中被广泛用作图像识别的训练集。我会在第四章详细讨论。

如果您希望探索 TensorFlow,但不想使用 Google MLE 创建自己的模型,还有另一个选项。您可以使用预构建的 DL 模型,并通过 GCP ML API 访问它们。在本章的后面,你将为 Android 实现这个项目。

GCP 自由层定价详细信息

如果你决定使用 GCP 为你的 ML 项目,你可以利用一年的免费试用期开始。通过免费试用,您将可以使用所有谷歌云平台(GCP)产品。该试用版包括构建和运行您的应用、网站和服务所需的一切。

The free trial has some limitations:

  • 服务水平协议(SLA)不适用。这对于免费层产品来说是合理的。如果服务因任何原因变得不可用,您没有追索权。

  • 计算引擎限于八个内核。

  • 并非所有服务都可用。

  • 不允许加密货币挖掘。

  • 免费试用期为 12 个月或 300 美元的使用费。

  • 不自动续订。免费试用结束后不会自动收费。

GCP 免费试用是一个非常好的交易,当然可以帮助您确定服务是否适合您的项目。

While you use your GCP free trial, keep in mind that if you go over the trial usage limits shown below, charges will apply:

  • 每月 1 个 f1-微型虚拟机实例(美国地区,不包括北弗吉尼亚)

  • 每月 30GB 的标准永久磁盘存储

  • 每月 5GB 的快照存储

  • 每月从北美到其他目的地的 1GB 出口(不包括澳大利亚和中国)

3.3 亚马逊 AWS

AWS 有令人眼花缭乱的云服务。似乎每周他们都会推出一项新服务。在本节中,您将探索 AWS 的机器学习方面。

AWS 有一个为期一年的免费试用,允许您探索许多服务,包括 ML。

Earlier you saw that Synergy Research Group placed AWS in a league of its own. Consistent with their research, AWS does seem to have some advantages:

  • AWS 提供更强大的服务、区域、配置等。很难跟踪所有的 AWS 产品。

  • AWS 有一个发达的市场。第三方供应商打包免费和商业解决方案。这些市场产品简化了设置,因为您不必担心所有的设置步骤。

  • 对于 ML,AWS 是框架不可知的。AWS ML 支持自带算法和自带框架,提供了最大的灵活性。

Table 3-4 shows a list of the AWS ML and EC2 compute services.Table 3-4

AWS ML 服务

|

服务

|

描述

|
| --- | --- |
| 亚马逊理解 | 亚马逊的 NLP 解决方案。Amazon understand 可以提取关于文档内容的见解。 |
| 亚马逊深化 | AWS DeepLens 是一个无线摄像机和 API,允许您开发计算机视觉应用程序。 |
| 亚马逊 Lex | 一种使用语音和文本在任何应用程序中构建对话界面的服务。 |
| 机器学习 | AWS 核心 ML 服务,用于创建和部署 ML 模型。 |
| 亚马逊波利 | 将文本转换成逼真语音的云服务。你可以使用 Amazon Polly 来开发增加参与度和可访问性的应用程序。 |
| 亚马逊萨格玛克 | 完全托管的机器学习服务。根据数据和预测的类型,可以使用许多算法。SageMaker 允许用户在 AWS 上部署 TensorFlow 或在 AWS 上部署 Apache MXNet。 |
| 亚马逊索赔案 | 图像和视频分析的 ML API。该服务可以识别物体、人、文本、场景和活动。 |
| 亚马逊转录 | 使用 ML 识别音频文件中的语音,并将其转录为文本。 |
| 亚马逊翻译 | 使用 ML 在英语和其他六种语言之间翻译文档。 |
| EC2 计算引擎 | EC2 是主要的 AWS 计算引擎,可以用来管理 ML 的 VM 实例,包括 AWS 深度学习 ami。 |

这些服务中有许多类似于 GCP 提供的 DL 产品。您将重点关注两个突出显示的 ML 核心服务:AWS 机器学习和 SageMaker。

AWS 机器学习

At the heart of AWS ML is the ML service. Similar to GCP, its main interface is the dashboard. Figure 3-12 shows the AWs ML dashboard. The AWS ML dashboard shows all of your AWS ML work items in a single integrated interface.img/468661_1_En_3_Fig12_HTML.jpg Figure 3-12

AWS ML 仪表板

Figure 3-12 shows several types of items the AWS dashboard can manage, including

  • 数据源

  • 模型

  • 批量预测

  • 评价

仪表板和直观的 AWS ML 工作流使导入数据、构建模型和评估模型结果变得容易。

AWS ML 构建和部署模型

为了演示 AWS ML 有多简单,让我们回到第二章介绍的 PAMAP2_Dataset 。在这个简短的示例中,您将加载数据集,构建 ML 模型,评估模型,甚至进行一些批量预测。

S3 is the AWS storage service. With AWS ML, the first step is to upload the data to S3. Recall that the dataset contained several large files. Each of the files had 54 attributes (columns) and over 300,000 instances (rows). You will use the subject101.dat file to build your first model on AWS ML. In Chapter 2, you converted the file to CSV format. Figure 3-13 shows the CSV file after uploading to AWS S3. You specify the unique name of the S3 storage bucket when uploading. In this example, the S3 bucket is named pamap2.img/468661_1_En_3_Fig13_HTML.jpg Figure 3-13

上传 ML 数据到 AWS S3

由于文件的大小,上传需要几分钟才能完成。AWS S3 显示数据文件的大小为 135MB。即使对于 CML 应用程序,数据大小也可能很大,这就是 AWS 等云平台的优势所在。

With the data uploaded to S3, the next step is to specify the input data for AWS ML. The easiest way to accomplish this is to use S3 data access. Figure 3-14 shows the AWS ML Create Datasource - Input data screen. Specify the name of the S3 storage bucket you wish to use in the S3 location field.img/468661_1_En_3_Fig14_HTML.jpg Figure 3-14

使用 S3 输入数据的 AWS ML 输入数据

AWS ML will validate the data and let you know if the validation was successful. If unsuccessful, you will need to record the specific issue and then return to OpenOffice where you can correct the data. The three most common issues with data validation are as follows:

  • 不正确的字段分隔符是最常见的验证问题。确保在 CSV 文件中使用逗号分隔符。

  • 在文本字段周围使用引号。文本中的逗号字符(,)会导致问题。OpenOffice 可以用引号将所有文本字段括起来。

  • 保存不带 BOM(字节顺序标记)字符的文件。

Once the data validation is successful, the next step is setting up the schema. Figure 3-15 shows the AWS ML Create Datasource - Schema screen.img/468661_1_En_3_Fig15_HTML.jpg Figure 3-15

AWS 检测数据模式

当 AWS ML 验证您的数据时,它会为每个属性(列)分配一个名称和数据类型。在这一步中,您需要浏览每个属性,并确认这些赋值是正确的。这也是检查属性数量是否正确的好时机;在这种情况下,有 54 个属性。这证实了您的 CSV 值解析是正确的。

AWS ML 创建数据源序列中的步骤 3 是指定 目标 。在第二章中,你将这个重要的属性定义为 标签 。在分类中, 标签 是你试图预测的值。

PAMAP2_Dataset 中,标签位于第 2 列,由赋值名 Var02 标识。该标签代表 活动 ID ,如表 2-4 中所述。指定标签后,按 Continue,并继续 AWS ML 模型设置。现在是创建模型的时候了。

Figure 3-16 shows the AWS ML model settings screen. This is where the magic happens.img/468661_1_En_3_Fig16_HTML.jpg Figure 3-16

AWS ML 模型设置

在 AWS ML 模型设置中,您有两个选项。您可以选择默认或自定义模型训练方法。

剧透警告:无论你选择哪种方法,你都不会从这个模型中得到一个好的结果。

自定义选项允许您指定几个项目,如训练数据的划分、评估数据的随机或顺序分割,以及其他一些训练参数。

问题是,即使您有一个大型数据集,AWS ML 也会为您选择一个回归算法,不管您是选择自定义还是使用默认算法。AWS ML 强制执行此模型选择,因为您为标签输入了单个数值。

PAMAP2_Dataset 执行回归不会产生很好的结果。然而,现在不要担心结果。你将在第四章中详细探讨学习类别的匹配算法。

点击继续按钮,模型创建完成。因为数据集很大,所以可能需要几分钟时间。请注意,您甚至不必使用 VM(虚拟机)创建计算资源来创建模型。

After AWS ML creates the model, you can evaluate the model and make batch predictions. Figure 3-17 show the evaluation summary of the model.img/468661_1_En_3_Fig17_HTML.jpg Figure 3-17

AWS ML 模型评估

评估摘要提供了有用的信息。如您所见,模型创建时间为 4 分钟,包括 2 分钟的计算时间,考虑到数据集如此之大,这还算不错。

模型性能显示了令人失望的结果:回归算法产生了比基线更差的质量分数。对于回归任务,AWS 使用标准的 RMSE(均方根误差)度量作为基线。对于 RMSE 基线,该值越接近零越好。本书的目标之一是避免数学方程,但是如果你想了解更多关于 RMSE 基线的知识,AWS 有一个关于测量回归模型准确性的极好的页面:

https://docs . AWS . Amazon . com/machine-learning/latest/DG/regression-model-insights . html

建立模型的目的是利用它进行预测。AWS ML 允许实时、单次或批量预测。批预测特别有用,它允许您加载许多实例来分类为一个批。AWS ML 通过让您将批量预测加载到 S3 存储桶中来实现这一点,就像您加载原始数据集一样。然后,您只需指定批量预测的 S3 位置,然后模型将生成结果。进行批量预测确实会增加成本,我将在本节的最后讨论这一点。

AWS ML is a really well-designed service. All of the assets created during the process of loading data through to making predictions are available at the dashboard. It is easy to make changes at any phase of the process and experiment with the results.

在短短几分钟内,AWS ML 服务允许您加载和验证数据、定义模式、构建模型、评估模型以及进行批量预测,所有这些都由集中的 AWS ML 仪表板控制。这简单得可笑。

对于那些需要对 ML 算法的选择进行更多控制的情况,例如复杂的 PAMAP2_Dataset ,接下来让我们探索如何使用 AWS 计算资源来构建您自己的 ML 环境。

AWS EC2 朋友

EC2 是 AWS 计算引擎服务。缩写代表弹性计算云。EC2 使用 AMI (Amazon Machine Interface)来定义它的虚拟实例。

EC2 支持许多类型的 ami。在 AWS EC2 上构建您自己的 ML 环境的第一步是选择一个 AMI 类型来支持您打算部署的应用程序软件。

图 3-18 显示了几种可用的 AMI 类型。AMI 类型跨越整个操作系统范围,包括 Amazon Linux、Ubuntu、Red Hat、CentOS、Windows 等。

If you look closely at Figure 3-18, you will see several AMIs that are deep learning-based. This is just another example of how easy AWS makes it to deploy ML solutions. In this example, you will select the Deep Learning AMI (Amazon Linux) version 13.0.img/468661_1_En_3_Fig18_HTML.jpg Figure 3-18

AWS AMI 选择

AWS ML 是框架不可知的。你看到谷歌 GCP 对 TensorFlow 的关注度很高;相比之下,AWS ML 提供了许多框架选项。当您基于深度学习基础 AMIs 创建新实例时,AWS 会将流行的 ML 框架与该实例打包在一起。这些特殊的 ami 包含了 Apache MXNet、TensorFlow、Caffe、Caffe2、PyTech、Keras、Theano、CNTK、Nvidia、CUDA 等各种组合。如果你回头看第一章的表 1-10 ,你会发现 AWS 深度学习基础 AMIs 几乎包括了所有显示的 ML 框架。这消除了下载和安装所有 ML 框架包的需要,节省了时间。

After you select your AMI, the next step allows you to choose an instance type. Figure 3-19 shows the AWS instance type selection.img/468661_1_En_3_Fig19_HTML.jpg Figure 3-19

AWS 实例类型配置

对于这个例子,您将选择 ??.micro 实例类型。这是一年免费层试用中唯一可用的实例类型。它能够处理许多应用程序,包括您在云中托管 Weka ML 环境的目标。有时,AWS 会警告您,您选择的实例不可用于空闲层。这通常是由存储设置造成的。如果您收到此警告,请在启动实例之前仔细检查您的存储是否超过 30GB。您可以在阶段的 存储 部分编辑存储。

**??.micro 实例对于了解 AWS ML 来说很好,但是 Amazon 推荐 ML 训练和预测的更高级配置。Amazon 推荐使用 ml.m4、ml.c4 和 ml.c5 实例族进行训练,使用 ml.c5.xl 实例类型进行预测。

在访问实例之前,必须配置其安全性。继续完成各个步骤,包括为安全 shell 访问分配密钥。

Figure 3-20 shows the instance once it is up and running.img/468661_1_En_3_Fig20_HTML.jpg Figure 3-20

AWS 实例摘要

请注意图 3-20 中的实例有一个公共 IP 和 DNS 名称。这是您从外部世界访问实例的方式。您将使用安全 shell (SSH)和您在实例安全配置期间设置的密钥。

实例运行后,您就可以在 AWS 云中安装和运行 Weka 了。

在 AWS 云中运行 Weka ML

Connect to the public IP of the instance using a secure SSH client, or Putty if you are on Windows. When connecting, note that the user name is ec2-user and the credentials are the key that you created at the completion of the setup process. Figure 3-21 shows the initial connection.img/468661_1_En_3_Fig21_HTML.jpg Figure 3-21

与 AWS EC2 实例的连接

When you first connect to the instance, you can change into the /usr/local directory and see the preinstalled deep learning packages included with the AMI:001   [ec2-user@ip-172-31-3-37 local]$ pwd 002   /usr/local 003   [ec2-user@ip-172-31-3-37 local]$ ls -lsart 004   total 50096 005       4 drwxr-xr-x  2 root root     4096 Jan  6  2012 src 006       4 drwxr-xr-x  2 root root     4096 Jan  6  2012 sbin 007       4 drwxr-xr-x  2 root root     4096 Jan  6  2012 libexec 008       4 drwxr-xr-x  2 root root     4096 Jan  6  2012 games 009       4 drwxr-xr-x  2 root root     4096 Jan  6  2012 etc 010       4 drwxr-xr-x 13 root root     4096 Jan 15 18:42 .. 011       4 drwxr-xr-x  8 root root     4096 May  8 21:12 share 012       4 drwxr-xr-x 18 root root     4096 May  8 21:13 cuda-8.0 013       4 drwxr-xr-x 19 root root     4096 May  8 21:15 cuda-9.0 014       4 drwxr-xr-x 19 root root     4096 May 10 21:17 cuda-9.1 015       4 drwxr-xr-x 19 root root     4096 May 10 21:19 cuda-9.2 016       4 drwxr-xr-x  7 root root     4096 May 10 08:18 mpi 017       4 drwxr-xr-x  7 root root     4096 May 10 09:39 lib64 018       4 drwxr-xr-x  9 root root     4096 May 10 09:39 include 019       4 drwxr-xr-x  7 root root     4096 May 10 09:39 lib 020       4 drwxr-xr-x  2 root root     4096 May 10 09:39 test 021       4 drwxr-xr-x 22 root root     4096 May 10 09:39 caffe2 022       4 drwxr-xr-x  3 root root     4096 May 10 09:39 caffe 023       4 drwxr-xr-x  2 root root     4096 May 10 09:39 bin 024       0 lrwxrwxrwx  1 root root       20 May 10 09:51 cuda -> /usr/local/cuda-9.0/ 025       4 drwxr-xr-x 18 root root     4096 May 30 02:35 .

注意上面的代码显示了深度学习 AMI (Amazon Linux)版本 13.0 可用的包。AWS 会不断更新这些包,所以在启动 AMI 后,您可能会看到稍微不同的内容。

Weka 不包括在内,所以你需要自己添加。

注意:您将把 sudo 添加到以下每个 Unix 命令的前面,以避免权限问题。

Weka requires Java, so you first need to check if Java was included, and if so, which version:001   [ec2-user@ip-172-31-3-37 local]$ java -version 002   openjdk version "1.8.0_121" 003   OpenJDK Runtime Environment (Zulu 8.20.0.5-linux64) (build 1.8.0_121-b15) 004   OpenJDK 64-Bit Server VM (Zulu 8.20.0.5-linux64) (build 25.121-b15, mixed mode) As is often the case with VM instances from the cloud providers, they come preinstalled with the OpenJDK Java distribution. OpenJDK is fine for most applications. However, for Weka installations, using the Oracle Java JDK is required because Weka requires some of the Swing GUI libraries not packaged in OpenJDK. If you try to run Weka with OpenJDK, you will see the following exception, indicating a Sun launcher class was not able to load:001   [ec2-user@ip-172-31-3-37 local]$ sudo java -cp weka.jar weka.classifiers.trees.J48 -t /usr/local/weka-3-8-2/data/iris.arff 002   Exception in thread "main" java.lang.UnsupportedClassVersionError: weka/classifiers/trees/J48 : Unsupported major.minor version 52.0 003           at java.lang.ClassLoader.defineClass1(Native Method) 004           at java.lang.ClassLoader.defineClass(ClassLoader.java:803) 005           at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) 006           at sun.misc.Launcher\(AppClassLoader.loadClass(Launcher.java:312) 007           at java.lang.ClassLoader.loadClass(ClassLoader.java:358) 008           at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482) The solution is to download the Oracle JDK with the following ***wget*** command. Lines 001-006 set up the environment variables. Line 008 executes the ***wget***. Line 010 installs the Oracle JDK package you downloaded.001   [ec2-user@ip-172-31-3-37 local]\) java_base_version="8" 002   [ec2-user@ip-172-31-3-37 local]$ java_sub_version="141" 003   [ec2-user@ip-172-31-3-37 local]$ java_base_build="15" 004   [ec2-user@ip-172-31-3-37 local]$ java_version="\({java_base_version}u\){java_sub_version}" 005   [ec2-user@ip-172-31-3-37 local]$ java_build="b\({java_base_build}" 006   [ec2-user@ip-172-31-3-37 local]\) java_version_with_build="\({java_version}-\){java_build}" 007 008   [ec2-user@ip-172-31-3-37 local]$ sudo wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/\({java_version_with_build}/336fa29ff2bb4ef291e347e091f7f4a7/jdk-\){java_version}-linux-x64.rpm 009 010   [ec2-user@ip-172-31-3-37 local]$ sudo yum install -y jdk-8u141-linux-x64.rpm After the install of Oracle JDK completes, you now have multiple version of Java installed on the VM instance. The following command shows that you actually have three versions: two versions of OpenJDK and the new Oracle JDK. It also allows you to select the Oracle JDK as the current selection.001   [ec2-user@ip-172-31-3-37 local]$ sudo alternatives --config java 002 003   There are 3 programs which provide 'java'. 004 005     Selection    Command 006   ----------------------------------------------- 007      1           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java 008      2           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java 009   + 3           /usr/java/jdk1.8.0_141/jre/bin/java 010 011   Enter to keep the current selection[+], or type selection number: 3 012   [ec2-user@ip-172-31-3-37 local]$ Now that Java is ready to go, it is time to download and install the latest stable version of Weka:001   [ec2-user@ip-172-31-3-37 local]$ sudo wget http://svwh.dl.sourceforge.net/project/weka/weka-3-8/3.8.2/weka-3-8-2.zip 002   --2018-05-30 02:35:43--  http://svwh.dl.sourceforge.net/project/weka/weka-3-8/3.8.2/weka-3-8-2.zip 003   Resolving svwh.dl.sourceforge.net (svwh.dl.sourceforge.net)... 72.5.72.15, 2606:c680:0🅱️3830:34ff:fe66:6663 004   Connecting to svwh.dl.sourceforge.net (svwh.dl.sourceforge.net)|72.5.72.15|:80... connected. 005   HTTP request sent, awaiting response... 200 OK 006   Length: 51223056 (49M) [application/octet-stream] 007   Saving to: ‘weka-3-8-2.zip’ 008 009   weka-3-8-2.zip             100%[======================================>]  48.85M  39.8MB/s    in 1.2s 010 011   2018-05-30 02:35:45 (39.8 MB/s) - ‘weka-3-8-2.zip’ saved [51223056/51223056] When the download completes, confirm the weka-3-8-2.zip file exists in the /usr/local directory:001   [ec2-user@ip-172-31-3-37 local]$ pwd 002   /usr/local 003   [ec2-user@ip-172-31-3-37 local]$ ls -lsart weka 004   total 50096 005   50024 -rw-r--r--  1 root root 51223056 Dec 21 21:16 weka-3-8-2.zip 006   [ec2-user@ip-172-31-3-37 local]$ Next, unzip Weka as shown and when complete, change into the new weka-3-8-2 directory, and you will see the following contents in the new directory:007   [ec2-user@ip-172-31-3-37]$ pwd 008   /usr/local/ 009 010   [ec2-user@ip-172-31-3-37]$ sudo unzip weka-3-8-2.zip 011 012   [ec2-user@ip-172.31.3.37]$ cd weka-3-8-2 013 014   [ec2-user@ip-172-31-3-37 weka-3-8-2]$ ls -l 015   total 42908 016   drwxr-xr-x 2 root root     4096 Dec 22 09:30 changelogs 017   -rw-r--r-- 1 root root    35147 Dec 22 09:30 COPYING 018   drwxr-xr-x 2 root root     4096 Dec 22 09:30 data 019   drwxr-xr-x 3 root root     4096 Dec 22 09:30 doc 020   -rw-r--r-- 1 root root      510 Dec 22 09:30 documentation.css 021   -rw-r--r-- 1 root root     1863 Dec 22 09:30 documentation.html 022   -rw-r--r-- 1 root root    16170 Dec 22 09:30 README 023   -rw-r--r-- 1 root root    43377 Dec 22 09:30 remoteExperimentServer.jar 024   -rw-r--r-- 1 root root 14763219 Dec 22 09:30 wekaexamples.zip 025   -rw-r--r-- 1 root root    30414 Dec 22 09:30 weka.gif 026   -rw-r--r-- 1 root root   359270 Dec 22 09:30 weka.ico 027   -rw-r--r-- 1 root root 11111002 Dec 22 09:30 weka.jar 028   -rw-r--r-- 1 root root  6621767 Dec 22 09:30 WekaManual.pdf 029   -rw-r--r-- 1 root root 10923433 Dec 22 09:30 weka-src.jar You are now ready to run Weka in the cloud. To run Weka from the command line, you instruct Java to run a classifier class on one of the datasets included with Weka. In this example, you will run the random forest classifier on the iris.arff dataset. To run a specified class instead of the main class, provide the –cp option. The following shows the successful Weka classification:001   [ec2-user@ip-172-31-3-37 weka-3-8-2]$ sudo java -cp weka.jar weka.classifiers.trees.J48 -t/usr/local/weka-3-8-2/data/iris.arff 002 003   === Classifier model (full training set) === 004 005   J48 pruned tree 006   ------------------ 007   ... 008   Number of Leaves  :     5 009   Size of the tree :      9 010   Time taken to build model: 0.48 seconds 011   Time taken to test model on training data: 0.01 seconds 012 013   === Error on training data === 014 015   Correctly Classified Instances         147               98      % 016   Incorrectly Classified Instances         3                2      % 017   Kappa statistic                          0.97 018   Mean absolute error                      0.0233 019   Root mean squared error                  0.108 020   Relative absolute error                  5.2482 % 021   Root relative squared error             22.9089 % 022   Total Number of Instances              150 023 024   ... 025 026   === Confusion Matrix === 027 028     a  b  c   <-- classified as 029    50  0  0 |  a = Iris-setosa 030     0 49  1 |  b = Iris-versicolor 031     0  2 48 |  c = Iris-virginica 032 033   Time taken to perform cross-validation: 0.08 seconds 034    035   === Stratified cross-validation === 036 037   ... 038 039   === Detailed Accuracy By Class === 040 041   ... 042 043   === Confusion Matrix === 044 045     a  b  c   <-- classified as 046    49  1  0 |  a = Iris-setosa 047     0 47  3 |  b = Iris-versicolor 048     0  2 48 |  c = Iris-virginica

我将在第四章中详细介绍 Weka。这个例子表明,在 AWS 云上实现 Weka 非常简单。

pagemaker

您已经看到了在 AWS 上构建 ML 的几种方法,首先是通过仪表板使用 AWS ML 服务,其次是在 AWS EC2 计算实例上实现自己的 Weka 环境。

AWS SageMaker is a fully managed platform to help you build DL models. It is one of the recently added AWS services. The main idea behind SageMaker is that ML has been difficult for developers for the following reasons:

  • 收集数据、处理数据、构建模型、测试模型和部署模型的过程给开发人员带来了过多的手动工作。

  • 由于重复的手动工作,创建 ML 解决方案非常耗时。

  • 创建 ML 解决方案太复杂了,因为所需的数据和分析技能已经取代了传统的软件开发。

SageMaker tries to address these issues. It promises to remove complexity and overcome the barriers that slow down developers. Figure 3-22 shows the main AWS SageMaker page.img/468661_1_En_3_Fig22_HTML.jpg Figure 3-22

pagemaker

像所有的 AWS 服务一样,有大量的在线文档帮助您理解服务。SageMaker 开发人员指南的链接是

【https://docs.aws.amazon.com/sagemaker/latest/dg】

SageMaker 很有潜力。两个特别重要的特性使它成为在 AWS- notebook 实例上实现 ML 的一种强大方式,以及它对算法的灵活支持。

SageMaker notebook 实例是一个运行 Jupyter Notebook 应用程序的计算实例。Jupyter 是一个开源的 web 应用程序,运行在 Python(因此它的拼写)上,允许你创建和共享包含实时代码和可视化的文档。它在 Python 和 DL 领域非常流行。

托管 Jupyter 笔记本可以轻松浏览和可视化亚马逊 S3 存储中的训练数据,类似于第二章中介绍的 JavaScript 选项。Jupyter 有几个内核,包括对 Python、Apache MXNet、TensorFlow 和 PySpark 的支持。Jupyter 不支持 Java 内核。笔记本实例是用 SageMaker 实现 ML 的重要部分。

AWS 实验室在 GitHub 上保留了一些优秀的例子供您探索 SageMaker:

【https://github . com/awslabs/Amazon-sag emaker-examples】

SageMaker 的另一个有趣的特性是它的算法灵活性。SageMaker 支持两类算法:内置算法和自带算法。内置算法列表可从以下网址获得

【https://docs.aws.amazon.com/sagemaker/latest/dg/algos.html】

算法列表非常完整。AWS 声称,由于优化,预装算法的性能是其他提供商的 10 倍。这是一个令人印象深刻的说法。然而,AWS 没有提供他们如何做到这一点的细节,或者它适用于哪些算法。

用户可以自带算法或框架。GitHub 上的 SageMaker 示例展示了如何为各种模型和算法实现这一点,包括 XGBoost、k-means、R、scikit、MXNet 和 TensorFlow。

AWS SageMaker 提供了令人印象深刻的 ML 功能,但不幸的是,由于它依赖于 Jupyter,所以不能很好地与 Java 集成。接下来,您将探索 AWS SDK for Java。

用于 Java 的 AWS SDK

Amazon supports Java developers. To show their love for us, they release the SDK for Java to help us accelerate our development. Figure 3-23 shows the main Explore Java on the AWS page available at https://aws.amazon.com/java/ . The page includes links for Java, Eclipse, and Android.img/468661_1_En_3_Fig23_HTML.jpg Figure 3-23

AWS Java 开发人员中心

The Java SDK is available in several formats. Table 3-5 provides a summary of the formats.Table 3-5

AWS Java SDK 包摘要

|

格式

|

笔记

|
| --- | --- |
| 面向 Java 1.11 版的 SDK | 当前支持的 SDK。允许您从 Java 访问所有 AWS 服务。 |
| Eclipse 的 Java 工具包 | AWS Toolkit for Eclipse 方便地包含了 AWS SDK for Java,因此您可以开始在 Eclipse 中的 AWS 基础设施服务上构建 Java 应用程序,包括 Amazon S3、Amazon EC2、Amazon DynamoDB 和 Amazon ML。 |
| Android 版 SDK | 一整套文档、库和示例,帮助您将 AWS 服务集成到 Android 应用中。 |
| 面向 Java 的机器学习 SDK | 这是一个专门为 AWS ML 开发的 SDK。它只能从 Maven 资源库下载。如果您只需要 AWS ML 访问,这个较小的库通过排除所有其他 AWS 服务来保持您的项目规模精简。 |
| 面向 Java 版的 SDK | AWS SDK for Java 2.0 Developer Preview 构建状态。2.0 版本目前是预览版,不建议用于生产。 |

表格中显示的前三种格式可以通过直接点击 AWS Java 开发中心提供的链接来下载。

Android 下载的 SDK 包括许多用于所有 AWS 服务的库文件、示例和文档。图 3-24 显示了 ML 库 jar 文件。注意只有 48Kb。您可以查看。jar 库使用 7-Zip 实用程序打开归档文件。Maven 资源库的链接是

http://central.maven.org/maven2/com/amazonaws/aws-android-sdk-machinelearning .img/468661_1_En_3_Fig24_HTML.jpg Figure 3-24

Android 机器学习库的 AWS SDK

There are two versions of the SDK for Java. Version Java 1 is the currently available version, and Java 2 is a developer preview rewrite of Java 1 with some new features. Both versions enable you to easily interface your Java projects with AWS. Java 2 includes two key new features:

  • 非阻塞 IO

  • 可插拔 HTTP 协议栈

If you develop for Android, you probably know that Google discontinued use of the Apache HTTPClient stack in Android recently. The pluggable HTTP feature in Java 2 follows this trend as Java 1 only supported HTTPClient. With Java 2.0 you can use other stacks such as HTTPurlConnection or OkHTTP.

有了 Java SDK,您可以在几分钟内开始使用 Maven 或任何支持 Maven Central 作为工件源的构建系统。《开发人员指南》包括详细的设置和安装说明,可从以下网址获得

https://docs . AWS . Amazon . com/SDK-for-Java/v1/developer-guide/welcome . html??

如果您对 Java SDK 的代码感兴趣,可以从以下站点获得:

【https://github.com/aws/aws-sdk-java】

【https://github.com/aws/aws-sdk-java-v2】

如果您不需要 SDK 支持的所有 AWS 服务,您可以从以下网址下载用于机器学习的 SDK

https://mvn repository . com/artifact/com . Amazon AWS/AWS-Java-SDK-machine learning

Figure 3-25 shows the Maven repository for the Java machine learning library. You can download the .jar file or see the instructions for Maven or Gradle depending on your build environment.img/468661_1_En_3_Fig25_HTML.jpg Figure 3-25

用于 Java 的 AWS ML SDK 的 Maven 仓库

在 AWS Java 机器学习 SDK 的帮助下,任何通过 AWS ML 仪表板可用的 ML 任务都可以从您的 Java 代码中以编程方式重现。

AWS 自由层定价详细信息

与 GCP 类似,AWS 提供 12 个月的介绍期。免费层包括一些永不过期的免费服务。其他免费服务在 12 个月内有效。亚马逊提供免费服务覆盖范围的全部细节,网址为

【https://aws.amazon.com/free/】

The AWS free tier is quite generous. The main highlights of the free tier include

  • 750 小时的 EC2 ??.micro 实例。您可以根据需要配置实例。您之前使用 ??.micro 实例在云中配置 Weka。

  • AWS 在空闲层提供 5GB 的 S3 存储。这对于探索 AWS ML 来说已经足够了。

  • AWS 每月允许 100 万次 API 调用。开发人员可以使用这些 API 调用来探索 AWS ML APIs。

You can use the ??.micro instance for almost anything you wish, including machine learning. There are some additional considerations for developers considering the AWS free tier to explore ML:

  • AWS 支持北美和全球许多地区的 EC2 实例。并非所有服务在每个地区都可用。如果您决定使用 AWS ML 服务,您需要在创建实例之前选择一个支持该服务的地区。

  • 使用 AWS ML 的批量预测不包括在自由层定价中,并且不免费。批量预测的成本为每 1,000 次预测 0.10 美元。参见表 1-5 。

  • AWS EC2 实例有公共 IP 地址。如果您停止并重新启动实例,IP 地址将会改变。如果您希望为 EC2 实例分配一个永久的 IP 地址,那么您需要创建 AWS 所说的弹性 IP。弹性 IP 不是免费的,不包括在 AWS 免费层中。使用新的 IP 地址停止并重新启动 EC2 实例不会导致与实例相关的任何配置或数据丢失。

如果你追求的是 AWS SageMaker for ML,除了总的免费等级之外,AWS 还提供额外的每月 250 小时的免费等级,用于构建模型,外加 50 小时的 SageMaker 培训。

3.4 机器学习 API

有时候,您可能不需要构建和部署自己的 ML 模型。在这些情况下,您可以利用四大云提供商提供的云 API。

In the preceding section, I covered the AWS ML services. Figure 3-26 summarizes the high-level APIs provided by the big four cloud providers: Amazon, Google, IBM, and Microsoft. All of their APIs fall into five distinct categories: language, vision, data insights, speech, and search.img/468661_1_En_3_Fig26_HTML.jpg Figure 3-26

高级 ML API 比较

Google 和 AWS 在提供我们实现 ML 解决方案所需的底层工具和构件方面做得很好,而 IBM 和微软在提供我们可以通过 API 访问的高层模型方面做得同样出色。图 3-26 显示他们有许多 API 来解决五个类别中的各种各样的问题。

这些 API 中的大多数都采用了从云提供商拥有的大量数据中创建的 DL 方法。这些 API 大部分是免费试用的。如果您决定在商业上使用这些 API,您通常只需要为每次 API 调用支付云提供商的推断费。回想一下,推断费是做预测的费用。您可以进行实时预测或批量预测。价格近似值见表 1-5 。

使用 ML REST APIs

如果您决定使用图 3-26 中的某个服务,他们很可能会允许通过 REST API 调用来访问该服务。使用 REST 调用用 ML 模型 API 进行预测(推断)很容易。API 通常使用 REST 协议,JSON 数据格式将在第二章中介绍。

当对 API 进行 REST 调用时,请求和响应都是 JSON 格式的。例如,清单 3-1 显示了一个 GCP 云视觉 API JSON 请求。该清单只展示了最重要的字段:您的 API 键、对图像源的引用以及所请求的特性。如果您希望实现这个 API 调用,请参考下面的链接,了解有关特定 JSON 要求的完整细节:

https://cloud.google.com/vision/docs/request 001   POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY 002   { 003     "requests": [ 004       { 005         "images": { 006           "content": "your_image.jpg" 007         }, 008         "features": [ 009           { 010             "type": "LABEL_DETECTION" 011           } 012         ] 013       } 014     ] 015   } Listing 3-1

GCP 云愿景 API JSON 请求示例

After you post the request, you will receive a JSON response. Listing 3-2 shows a successful JSON response; in this case, you are getting back the top two image label predictions for the image file submitted in the request.001   { 002     "responses": [ 003       { 004         "labelAnnotations": [ 005           { 006             "mid": "/m/01yrx", 007             "description": "cat", 008             "score": 0.92562944 009           }, 010           { 011             "mid": "/m/0307l", 012             "description": "cat like mammal", 013             "score": 0.65950978 014           } 015         ] 016       } 017     ] 018   } Listing 3-2

GCP 云愿景 API JSON 响应示例

为了帮助您提交 JSON 请求和解析 JSON 响应,Java SDK 提供了示例代码。此外,Java 客户端库可用于各种 API。对于这个例子,参考云视觉 API 客户端库,选择 Java 标签,在

**在下一节中,您将使用这种方法构建一个完整的 Android 应用程序,使用 JSON 来访问强大的 GCP 云语音 API。谷歌云语音 API 将允许你转录设备录制的音频文件。

替代 ML API 提供者

有时候,您可能需要考虑替代的云 API 模型提供商。如果你有一个利基应用程序没有被大的云玩家覆盖,专门从事某些应用程序的替代提供商可以提供一个解决方案。

有时,您只是希望将您的产品与所有使用大型云提供商 API 的竞争对手区分开来。在这些情况下,使用替代的小型云 API 提供商可能是一个可行的策略。

Table 3-6 shows some alternative cloud ML API providers.Table 3-6

备选云 ML API 提供商

|

供应者

|

描述

|
| --- | --- |
| 【www.diffbot.com/products/automatic/】 | 数据析取 |
| 【www.beyondverbal.com/api/】 | 一家以色列公司的情感和声音分析 |
| 【www.kairos.com/face-recognition-api】 | 人脸识别 |
| 【https://wit.ai/getting-started】 | 猫机器人 |
| 【www.openalpr.com/cloud-api.html】 | 实时车牌识别 |

无论您使用替代的 ML API 还是来自四大云提供商的 ML API,都有大量的产品可供您选择。如果你回想 M 门,在 MLG6,你必须从一个明确定义的问题开始。此时,最佳实践是扫描可用的 API,看看它们是否与问题完全匹配。没有必要重新发明轮子。大型云提供商拥有如此多的数据,很难创造出比他们提供给我们的模型更好的解决方案。虽然四大云提供商有许多 API,但探索外部替代方案是否可用可能会有所收获。

3.5 项目:Android 版 GCP 云语音 API

在这个项目中,您将实现 GCP 云语音 API Android 应用程序。您将使用 Android Studio IDE。该项目由 Google (Apache license 2.0)版权所有并发布,可从以下链接下载:

https://github . com/Google cloud platform/Android-docs-samples/tree/master/Speech/Speech

云语音 API 应用概述

Download the project from GitHub and import it into Android Studio. Table 3-7 shows the summary of the key project files.Table 3-7

GCP 云语音 API 项目文件摘要

|

项目名称:GCP 云语音 API

来源:GitHub 谷歌云语音平台

类型:Android 应用程序

|
| --- |
|

文件

|

描述

|
| --- | --- |
| app->src->main->JavaMainActivity.java | 检查设备权限、启动录音机和语音服务以及设置主视图的主要活动。 |
| app->src->main->JavaSpeechService.java | 用于处理 API 访问的服务。这个 Android 服务实现了 GCP 云语音 API 的接口,包括认证和实时口语流。 |
| app->src->main->JavaMessageDialogFragment.java | 一个简单的 Android 对话框 类,应用程序使用它向用户显示消息。 |
| app->src->main->JavaVoiceRecorder.java | 这个类实现了 Androidaudio record类用于语音录制。 |
| 【应用】>【src】>【main】>【RES】>【layout】main.xml | 主 XML 布局。 |
| 【应用】>【src】>【main】>【RES】>【raw】credential . JSON | 在 GCP 云 API 中心创建的 JSON 凭证文件。将文件放入 res/raw 文件夹。 |
| app->src->main->RES->raw**audio.raw | 存储在 /res/raw 文件夹中的样本音频文件,可以发送给 API 进行分类。音频文件是“布鲁克林大桥有多老了?” |
| app- > src- > main**AndroidManifest.xml | 应用程序清单文件。定义活动和服务。 |

Figure 3-27 shows a screenshot of the Android app. The app’s concept is straightforward. The app accepts audio input from the user and uses the Google Cloud Speech API to translate the audio and display a text translation. The app supports two methods for audio input:

  • 该应用程序可以从设备麦克风录制音频。音频以原始 PCM 格式录制。在第二章中,您看到了数字化语音是一种数据形式。稍后我将讨论更多关于音频文件格式的内容。录制的音频被实时发送到云语音 API 进行翻译。

  • 用户也可以按下 加载文件 按钮来加载预先录制的音频文件,该文件将被发送到 API 进行翻译。

The Cloud Speech API uses DL to translate the recorded audio to text. The app receives the translated text and displays the translation in real time as the user is speaking. Because the API uses deep learning, it does a really impressive job at translating voice input.img/468661_1_En_3_Fig27_HTML.jpg Figure 3-27

GCP ML 云语音 API 安卓应用

在设备上运行应用程序允许您使用麦克风录制音频。该应用程序实时批处理口语单词,并将它们传递给 API。如果您正在使用仿真器运行应用程序,您将被限制为按下 加载文件 按钮来为 API 提供音频以进行翻译。

GCP 机器学习 API

Before you can get the app running on your Android device, you need to perform the following two actions on the Google Cloud Platform dashboard:

  • 启用云语音 API。

  • 创建 Android 应用程序所需的认证密钥。

要启用 API,请访问以下链接:

【https://console.cloud.google.com/apis/library?】?? 过滤器=类别:机器学习

Figure 3-28 shows the currently available GCP Cloud ML APIs, including the Cloud Speech API you wish to implement. Click the Cloud Speech API and enable it.img/468661_1_En_3_Fig28_HTML.jpg Figure 3-28

GCP 云 ml apis

接下来,您需要创建 Android 应用程序所需的认证密钥。

云语音 API 认证

云语音 API Android 应用需要你提供一个 JSON 文件认证密钥。该文件将被命名为 credential.json ,并被放置在 app 的 raw 文件夹中。按照以下步骤创建文件。

The first step is to create a service account key. The service account is required for authentication. Figure 3-29 shows the Credentials tab within the API dashboard. Choose Create credentials, and then select Service account key from the drop down list.img/468661_1_En_3_Fig29_HTML.jpg Figure 3-29

GCP 创建服务帐户密钥

The Create service account key dialog box will be displayed, as shown in Figure 3-30.img/468661_1_En_3_Fig30_HTML.jpg Figure 3-30

选择 JSON 服务帐户密钥类型

The service account should appear as speech2text, and you should select the JSON type. Press the Create button and the private key will be saved to your computer, as shown in Figure 3-31.img/468661_1_En_3_Fig31_HTML.jpg Figure 3-31

保存 JSON 私钥文件

私钥将以基于项目名称的文件名保存到您的计算机上。如果将项目名称保留为默认值,它将如下所示:

我的第一个项目——d 817 DCF 314 . JSON

将此文件重命名为

credential . JSON

The JSON configuration file contents will look similar to the following and is required to access the API from Android:001   { 002     "type": "service_account", 003     "project_id": "subtle-bus-204821", 004     "private_key_id": "xxxxxxxxxxxxxxxxxxxxx", 005     "private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxxx\n-----END PRIVATE KEY-----\n", 006     "client_email": "speech2text@subtle-bus-204821.iam.gserviceaccount.com", 007     "client_id": "xxxxxxxxxxxxxxxxxxxxx", 008     "auth_uri": "https://accounts.google.com/o/oauth2/auth", 009     "token_uri": "https://accounts.google.com/o/oauth2/token", 010     "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", 011     "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/speech2text%40subtle-bus-204821.iam.gserviceaccount.com" 012   }

最后将 credential.json 文件复制到 Android app 的 res/raw 目录下。复制完文件后,就可以在 Android Studio 中成功构建 Android 应用了。

值得注意的是,在应用程序中放置私钥来处理身份验证是测试 API 的一种有用而简单的方法,但这种方法对于生产应用程序来说是不可接受的。对于生产应用程序,您应该实现自己的应用程序服务器来处理应用程序用户的身份验证。因为您只是在测试 API,所以您可以复制。

You can always review and manage your service account keys in the dashboard, as shown in Figure 3-32.img/468661_1_En_3_Fig32_HTML.jpg Figure 3-32

显示活动凭据

Android 音频

With the backend setup complete, you can focus on the client Android app. In this section, you will cover the following key events:

  • 录制原始音频

  • 向 API 发送音频

  • 处理 API JSON 响应

Audio is a form of data. ML often uses audio data as input. Android devices are excellent for working with audio because the hardware supports many codecs for encoding and decoding.

Android 设备是处理音频数据的优秀工具。Android 支持许多编解码器。audio recordaudio track 支持原始未压缩音频的录制和处理。虽然 Android audio 的延迟不是很大,但大多数 ML Audio APIs 支持高吞吐量,并且不需要低延迟。

Table 3-8 shows a list of Android’s supported audio formats. Note that Y indicates encoding or decoding is available in all SDK versions for a particular codec. N indicates encoding is not available for a codec.Table 3-8

Android 支持的音频格式

|

多媒体数字信号编解码器

|

编码

|

|

细节

|

文件类型

|
| --- | --- | --- | --- | --- |
| 加气混凝土 | 4.1+ | Y | 单声道/立体声/5.0/5.1 最高 48khz 采样 | 3GPP、MP4、ADTS AAC |
| 自主移动机器人(Adaptive Multi-Rate 的缩写) | Y | Y | 5-12 千位/秒 12-24 千位/秒 | 第三代合作伙伴项目(the3rdGenerationPartnershipProject) |
| 无损音频编解码器 | Y | Y (3.1+) | 单声道/立体声/最高 44.1/48khz | 无损音频编解码器 |
| MP3 文件 | 普通 | Y | 单色/立体声/8-320kbps | MP3 文件 |
| 迷迪 | 普通 | Y | 支持铃声 | 中间的 |
| Vorbis 先生 | 普通 | Y |   | OGG,水手 |
| 脉冲编码调制 | Y (4.1+) | Y | 8 位/16 位线性 PCM 速率达到硬件极限 | 波浪 |
| 作品 | 普通 | Y (5.0+) |   | -水手 |

GCP 云语音 API 可以接受几种类型的音频数据。flac)、PCM(。wav)文件、AMR 和 Linear-16。FLAC 和 PCM 格式表示原始的未压缩音频数据。虽然压缩的音频数据(如 MP3 文件)传输到云端会更小、更快,但压缩会引入噪声,并可能影响准确性。

Androidaudio record类是一个非常强大的低级音频 API。任何处理音频的严肃 app,最有可能使用的是 AudioRecord 。在云语音 API app 中, AudioRecord 类用于记录未压缩的原始音频,传递给 API 进行翻译。

Listing 3-3 shows the key audio recording loop in the app. The ProcessVoice class shown resides inside the VoiceRecorder.java file. The code runs on a thread and is responsible for continuously reading uncompressed voice data from the AudioRecord object into the mBuffer byte array (line 013).001   private AudioRecord mAudioRecord; 002   private Thread mThread; 003   private byte[] mBuffer; 004 005   private class ProcessVoice implements Runnable { 006       @Override 007       public void run() { 008           while (true) { 009               synchronized (mLock) { 010                   if (Thread.currentThread().isInterrupted()) { 011                       break; 012                   } 013                   final int size = mAudioRecord.read(mBuffer, 0, mBuffer.length); 014                   final long now = System.currentTimeMillis(); 015                   if (isHearingVoice(mBuffer, size)) { 016                       if (mLastVoiceHeardMillis == Long.MAX_VALUE) { 017                           mVoiceStartedMillis = now; 018                           mCallback.onVoiceStart(); 019                       } 020                       mCallback.onVoice(mBuffer, size); 021                       mLastVoiceHeardMillis = now; 022                       if (now - mVoiceStartedMillis > MAX_SPEECH_LENGTH_MILLIS) { 023                           end(); 024                       } 025                   } else if (mLastVoiceHeardMillis != Long.MAX_VALUE) { 026                       mCallback.onVoice(mBuffer, size); 027                       if (now - mLastVoiceHeardMillis > SPEECH_TIMEOUT_MILLIS) { 028                           end(); 029                       } 030                   } 031               } 032           } 033       } 034   } Listing 3-3

VoiceRecorder.java 境内的 ProcessVoice 类

The code in Listing 3-3 is a typical audio recording implementation. One of the features that makes the app so powerful is the use of the following callbacks:

  • onVoiceStart :当录音机开始听到声音时调用。

  • onVoice :录音器听到声音时调用。

  • onVoiceEnd :当录音器听不到声音时调用。

这些方法的使用是应用程序能够在用户说话时提供实时翻译的原因。

通过将数据传递给【SpeechService.java】中的 识别输入流 方法,来自麦克风的原始音频被发送到云语音 API。

**SpeechService.java runs as an Android Service within the app. It is responsible for interfacing with the cloud API. The code in Listing 3-4 shows how the service builds the JSON request message for the API.001   public void recognizeInputStream(InputStream stream) { 002       try { 003           mApi.recognize( 004                   RecognizeRequest.newBuilder() 005                           .setConfig(RecognitionConfig.newBuilder() 006                                   .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16) 007                                   .setLanguageCode("en-US") 008                                   .setSampleRateHertz(16000) 009                                   .build()) 010                           .setAudio(RecognitionAudio.newBuilder() 011                           .setContent(ByteString.readFrom(stream)) 012                           .build()) 013                           .build(), 014                   mFileResponseObserver); 015       } catch (IOException e) { 016           Log.e(TAG, "Error loading the input", e); 017       } 018   } Listing 3-4

在 SpeechService.java 建立 API 请求

After processing each audio data stream through its DL model, the Cloud Speech API sends the text results back to the service. The service handles everything for you. The code in Listing 3-5 shows an excerpt from MainActivity.java . This code sets up a SpeechService listener and populates the UI with the text results as they are received.001   private final SpeechService.Listener mSpeechServiceListener = 002           new SpeechService.Listener() { 003               @Override 004               public void onSpeechRecognized(final String text, final boolean isFinal) { 005                   if (isFinal) { 006                       mVoiceRecorder.dismiss(); 007                   } 008                   if (mText != null && !TextUtils.isEmpty(text)) { 009                       runOnUiThread(new Runnable() { 010                           @Override 011                           public void run() { 012                               if (isFinal) { 013                                   mText.setText(null); 014                                   mAdapter.addResult(text); 015                                   mRecyclerView.smoothScrollToPosition(0); 016                               } else { 017                                   mText.setText(text); 018                               } 019                           } 020                       }); 021                   } 022               } 023           }; Listing 3-5

在 MainActivity.java 听文本结果

云语音 API 应用摘要

Google Cloud Speech API 应用程序是在云中利用 DL 模型的有力例子。这是一个高级实现,因为它提供了一个基于服务的架构来处理所有的 API 接口。回调与服务架构的结合使用提供了实时翻译并创建了无缝的用户体验。

这是一个可以为其他 GCP ML API 复制的架构。请记住,这也会产生大量的网络流量和 API 访问量。

Once you successfully deploy a solution such as the Cloud Speech API, you should revisit the dashboard periodically to check on traffic and errors. Figure 3-33 shows the Cloud Speech API Dashboard with traffic recorded. Be careful to watch the API traffic volume, especially if working within the constraints of the free trial.img/468661_1_En_3_Fig33_HTML.jpg Figure 3-33

GCP 监控 API 访问量

3.6 用于机器学习的云数据

云服务提供商擅长存储数据。虽然他们的许多 ML 服务相对较新,但他们提供的数据存储服务从一开始就已经存在。

The data storage services they offer can take a variety of formats, including

  • 容器图像

  • 传统数据库

  • NoSQL 数据库

  • API 和服务

  • 虚拟计算机

在本章的前面,您看到了其中的两种方法。在使用 PAMAP2_Dataset 演示 AWS ML 控制台时,您使用了 AWS S3 存储桶对象存储。然后,在云中设置 Weka 时,您使用虚拟机进行存储。接下来,您将研究非结构化数据的爆炸如何导致 NoSQL 数据库作为存储解决方案的使用增加。

非结构化数据

第二章讨论了一个大趋势:数据爆炸。我们将非结构化数据定义为很少或没有元数据以及很少或没有分类的数据。ML 经常使用非结构化数据。非结构化数据包括许多类别,如视频、电子邮件、图像、物联网设备数据、文件共享、安全数据、监控数据、日志文件、web 数据、用户和会话数据、聊天、消息、twitter 流传感器数据、时间序列数据、物联网设备数据和零售客户数据。

Unstructured data can be characterized by the three Vs: volume, velocity, and variety.

  • 卷:数据的大小。参见表 2-2 。

  • 速度:数据生成的速度。例如,喷气发动机传感器每秒可以产生数千个样本。

  • 多样性:有许多不同种类的数据。

Figure 3-34 shows the exponential growth of unstructured data relative to structured data.img/468661_1_En_3_Fig34_HTML.jpg Figure 3-34

非结构化数据的增长

传统数据库的问题在于它们难以扩展,并且不太适合非结构化数据。在云中存储非结构化数据的最佳方式之一是使用 NoSQL 数据库,因为他们在处理这种类型的数据方面做得更好。

NoSQL 数据库

NoSQL 代表“不是 SQL”这种方法不同于传统的关系数据库管理系统(RDBMS)。SQL 是关系数据库使用的查询语言。这些数据库依靠表、列、行或模式来组织和检索数据。NoSQL 数据库不依赖于这些结构,使用更灵活的数据模型。许多主流企业都采用了 NoSQL。

The benefits of NoSQL databases include

  • 可扩展性:水平扩展架构使得添加商品化节点以增加容量变得容易。

  • 性能:您可以根据需要通过添加商品化资源来轻松提高性能。

  • 高可用性:NoSQL 数据库通常使用无主架构,这使得它们不太容易停机。

  • 全球可用性:分布式数据库可以跨机器和地理区域复制。

  • 灵活的建模:处理 JSON 表示的文档或非结构化数据意味着没有严格的数据类型、表或索引。

To understand how NoSQL databases differ from traditional RDBMS databases, it is useful to review the CAP theorem, originally described by Eric Brewer. The CAP theorem states that for distributed database architectures, it is impossible to simultaneously provide more than two out of the following three guarantees:

  • 一致性:每次读取都会收到最近的写入或错误。

  • 可用性:始终可以读取或写入系统,但不保证它包含最新的值。

  • 分区容差:尽管节点之间的网络丢弃或延迟了任意数量的消息,系统仍能继续运行。

图 3-35 显示了 CAP 定理的图形表示,包括许多流行的 SQL (RDBMS)和 NoSQL 数据库的分类。

The traditional SQL databases are on the left side of the triangle. They support consistency and availability. However, they do not partition easily in a distributed fashion. Partitioning is the key ingredient behind the massive scalability of NoSQL architectures. The triangle shows popular NoSQL databases at the bottom and right side of the triangle.img/468661_1_En_3_Fig35_HTML.jpg Figure 3-35

根据 CAP 定理的数据库分类

Database theorists used two interesting terms to describe these database philosophies:

  • 酸:原子性、一致性、隔离性、持久性

  • 基本:基本可用,柔软状态,最终一致性

RDBMS databases choose ACID for consistency and availability. Distributed NoSQL databases choose BASE for either partitioning/consistency or partitioning/availability. Many popular NoSQL databases use the BASE philosophy. Table 3-9 shows a summary of the most popular NoSQL databases.Table 3-9

流行的 NoSQL 数据库

|

数据库ˌ资料库

|

描述

|
| --- | --- |
| 中文版 | 谷歌的 NoSQL 大数据数据库服务。谷歌表示,它可以以低延迟和高吞吐量处理大量工作负载。它支持许多谷歌服务,如地图、Gmail 和搜索。 |
| AWS DynamoDB | 从亚马逊完全管理的专有 NoSQL 数据库。DynamoDB 支持键值和文档数据结构。高耐用性和可用性。 |
| 阿帕契巴塞 | 分布式、可扩展的大数据存储。HBASE 是 HADOOP 数据库。Apache 项目的目标是托管包含数十亿行和数百万列的非常大的表。用 Java 编写,模仿 Google 的 Bigtable。 |
| 里亚克 | 来自 Basho 的分布式 NoSQL 数据库。允许您存储大量的非结构化键值数据。物联网的流行解决方案。 |
| 阿帕奇卡桑德拉 | 高度可伸缩的 NoSQL 数据库。由于体系结构的选择,声称优于其他 NoSQL 数据库。被网飞、苹果、易趣等使用。 |
| MongoDB | 跨平台、基于文档、基于 JSON 类文档的 NoSQL 数据库。 |
| 数据库 | 分布式面向 NoSQL 文档的数据库,为交互式应用程序而优化。 |

NoSQL 数据存储方法

The NoSQL databases shown in Table 3-8 have differences. When choosing a NoSQL database, the key consideration is how they store the data. There are four types of NoSQL data stores:

  • 键值数据存储

  • 文档存储

  • 宽列存储

  • 图形存储

Table 3-10 shows how the poplar NoSQL products fall into these categories.Table 3-10

NoSQL 数据存储方法

|

数据存储类型

|

特征

|

例子

|
| --- | --- | --- |
| 键/值 | 按关键字索引的哈希表。完全在内存中或内存和磁盘的组合中。不支持辅助索引。 | 快取记忆体 |
| 文件 | 原则存储对象是一个文档,通常是 JSON 格式。支持辅助索引。提供小到中等的可扩展性。在内部,对象以二进制形式存储为 BSON 或 BLOBs。 | mongodbcouchdbcouchbaseddynamodbredis |
| 图表 | 用于存储连接的数据集。 | 新的 |
| 宽栏 | 提供宽大的桌子。支持数百万列。提供巨大的可扩展性。支持大数据。 | 巴什 BigtableCassandra |

在选择 NoSQL 数据库时,数据大小和性能也是需要考虑的重要因素。MongoDB 和 CouchDB 是中小型数据集的绝佳选择,而 Cassandra 则是大型数据集的绝佳选择。

性能是一个复杂的话题,超出了本章的范围。对于 CML 项目,您不需要顶级性能。如果您对 NoSQL 性能指标评测感兴趣,Datastax 网站上有一个很好的总结

www . datastax . com/no SQL-databases/benchmarks-Cassandra-vs-MongoDB-vs-h base

The cloud providers include support for many NoSQL databases. Figure 3-36 show the AWS Database Quickstart page.img/468661_1_En_3_Fig36_HTML.jpg Figure 3-36

AWS 数据库快速启动选项

你可以看到 AWS 为 Couchbase、MongoDB、两种版本的 Cassandra 以及它自己的 DynamoDB NoSQL 产品提供了 NoSQL 快速入门包。

Apache Cassandra Java 接口

使用 Quickstart 软件包可以轻松地在 AWS 或 GCP 等云提供商上部署 NoSQL 数据库。在这最后一部分,您将在很高的层次上探索如何从 Java 程序连接到 Apache Cassandra NoSQL 数据库。

DataStax 是 Apache Cassandra 的主要分销商之一。它适用于 AWS 和 Google 计算引擎,可通过以下链接获得:

https://AWS . Amazon . com/quick start/architecture/datastax-enterprise/

https://console . cloud . Google . com/market place/details/datas tax-public/datas tax-enterprise

请注意,data tax 不收取 Datastax Enterprise 的费用,但云提供商将收取计算资源费用。云提供商和 DataStax 联手,使得在云中构建高度可伸缩的 Cassandra 集群变得非常容易。

DataStax 发行版的一个重要特性是可以为所有流行的编程语言提供驱动程序,包括 Java。Datastax Java 驱动程序可从以下网址获得

【https://github.com/datastax/java-driver】

The DataStax Java driver GitHub site has an excellent Readme.md file with very helpful information for getting started with Java and Cassandra. Some highlights of the DataStax Cassandra distribution and Java driver:

  • 开源驱动程序(Apache 2.0)适用于所有主要语言,包括 Java。

  • DataStax Java 驱动程序包含连接到 Cassandra 和执行查询的逻辑。

  • DataStax Java 驱动程序支持同步和异步查询。

  • 该驱动程序是一个功能丰富且高度可调的 Java 客户端库。

  • 驱动支持 Apache Cassandra (2.1+)。

  • 驱动程序支持 Cassandra 的二进制协议。

  • 驱动程序支持 Cassandra 查询语言 v3。

The following code shows how to connect to a Cassandra database and execute a Cassandra query from Java using the DataStax driver:001   Cluster cluster = null; 002   try { 003       // Connect to the cloud Cassandra cluster 004       cluster = Cluster.builder() 005               .addContactPoint("ip_address") 006               .build(); 007       Session session = cluster.connect(); 008 009       // Provide a Query String for the execute method 010       ResultSet rs = session.execute("select release_version from system.local"); 011 012       // Get the first row 013       Row row = rs.one(); 014       System.out.println(row.getString(0)); // The first column; 015   } finally { 016       if (cluster != null) cluster.close(); 017   } Cassandra uses the Cassandra Query Language (CQL). CQL is very similar to SQL. There are several ways to access CQL, including

  • 在 Cassandra 节点的命令行上启动命令行客户端 cqlsh

  • 使用 DataStaxdev center,一个图形用户界面。

  • 对于开发应用程序,您可以使用官方的 DataStax Java 驱动程序之一。

最有用的 CQL 命令之一是 复制 命令。CQL 的 复制 命令允许你导入和导出 CSV 文件。回想一下第二章,这些文件是 ML 管道不可分割的一部分。只需一个命令,您就可以填充整个卡珊德拉数据库或将卡珊德拉 NoSQL 数据库备份到一个 CSV 文件,以便离线处理。有关 CQL 复制 命令的完整详细信息,请访问

https://docs . datastax . com/en/cql/3.1/cql/cql _ reference/copy _ r . html

有关其他有用的 CQL 命令(包括其他 Java 代码示例)的更多详细信息,请参考位于

https://docs . datastax . com/en/developer/Java-driver/3.4/manual/

使用像 Cassandra 这样基于云的 NoSQL 数据库的优势之一是可伸缩性。如果您正在收集大量的 ML 数据,并且需要存储这些数据,这将非常有用。几年前,谷歌在谷歌计算引擎上使用 Cassandra 实现了每秒 100 万次写入。您可以在这篇博客文章中了解部署细节:

https://cloud platform . Google blog . com/2014/03/Cassandra-hits-million-writes-per-second-on-Google-compute-engine . html

根据作者的说法,2014 年实现这一结果的成本仅为每百万次写入 0.07 美元。这说明了云平台强大的价值主张。

3.7 云平台概述

This chapter had the lofty goal of covering cloud platforms for ML. Cloud ML is a very fast moving space characterized by rapid developments. Keep in mind the following findings as you proceed to the next chapters to cover algorithms and ML environments:

  • 当构建 ML 解决方案时,总是首先扫描可用的云服务,看看是否存在一个可以用最少的模型构建或编码来解决问题的云服务。

  • 在过去几年中,每个云提供商都投入了大量资源来部署计算资源、存储解决方案、模型构建平台和 DL APIs,您可以在应用程序中利用这些资源。

  • 利用云平台提供的免费层来查看特定服务是否适用于您的特定应用。

  • 谷歌通过发布的 JSON APIs 使 Android 应用程序很容易利用谷歌 ML 引擎服务。

  • 像 Cassandra 这样的 NoSQL 数据库允许你实现大规模,并且相对容易配置。

  • 许多服务,尤其是那些由云提供商提供的开源包提供的服务是免费的,但最终用户将为消耗的任何计算资源付费。幸运的是,激烈的行业竞争压低了这些成本。********

四、算法:机器学习的大脑

  • 解释创造 ML 算法的科学家使用的术语。

  • 向您展示如何通过考虑多种因素来选择最佳算法。

  • 总结算法的三种高级风格。

  • 提供一个完整的 CML 算法索引列表,这样你就可以很容易地识别出一个特定的算法使用哪种风格的 ML。

  • 给出一个决策流程图和一个功能流程图,帮助你为你的问题选择最佳算法。

  • 概述七种最重要的最大似然算法。

  • 比较 CML 算法的性能,包括 CML 和 DL 算法在 MNIST 数据集上的总结。

  • 回顾流行算法的 Java 源代码。

4.1 导言

When asked why they fail to deploy ML solutions, developers often express two main reasons:

  • 这需要太多的体力劳动。

  • 算法和模型创建太复杂。

手动工作通常指的是数据争论。在第二章中,我介绍了一些有助于简化这一过程的工具。第五章将介绍作为 Java ML 环境的一部分集成的附加工具。使用 ML,很难避免手工处理数据。我再次引用 Silver 先生的一句有趣的话,即在我们对数据有更多期望之前,先对自己有更多期望。

在图 1-20 中,你看到算法植根于科学领域。开发人员回避部署 ML 的主要原因之一是算法选择和模型创建过于复杂。幸运的是,通过学习一些基本原理并理解与 ML 算法相关的科学语言,您可以克服算法复杂性问题。

这本书和这一章将主要涵盖 CML 算法。在第三章中,您通过 Google Cloud Speech API 访问了 DL 算法,因为云提供商倾向于将他们的 ML APIs 集中在 DL 解决方案上。

ML-门 3

MLG3 是生成 ML 模型的阶段。这个阶段最重要的行动是选择和验证最大似然算法。本章将帮助你选择最佳算法,并确定它的执行情况。

When you first embark on ML solutions, choosing the best algorithm seems somewhat arbitrary. In Chapter 5, you will see that it is actually quite easy to randomly select and apply any algorithm to a dataset. This is not a particularly good use of time. In Chapter 3, you saw disappointing results when the AWS Machine Learning wizard chose the wrong algorithm after misunderstanding the label data type. There is a conventional wisdom for algorithm selection. Answers to the following questions help to determine which algorithm is best suited for your model:

  • 你有多少数据?

  • 你想预测什么?

  • 数据是有标签的还是无标签的?

  • 您需要增量培训还是批量培训?

随着经验的积累,您可以快速确定哪种算法最适合您的问题和数据。

4.2 算法风格

ML 算法的世界分为两个同等重要和有用的类别。在介绍科学家用来描述每个类别的花哨术语之前,让我们先看看定义每个类别的数据类型。

标记数据与未标记数据

你会记得在第二章中,我将术语 标签 定义为你试图预测或预报的东西。在第二章中,标记了 PAMAP2_Dataset。第 1 列包含标签值。在收集数据时,佩戴传感器的参与者被要求记录他们的活动。该标签值随后与来自传感器的所有其他数据一起被存储。

ML 中使用的许多数据集由带标签的数据组成。加州大学欧文分校存储库中的大多数数据集都有标签。大部分由 ML 网站主办的 ML 比赛都使用标签化数据。在现实世界中,情况并非总是如此。

**一些组织认为有标签的数据比无标签的数据更有价值。组织有时甚至认为未标记的数据毫无价值。这大概是短视的。您将看到 ML 可以使用有标签和无标签的数据。

Whether or not the data contains labels is the key factor in determining the ML algorithm style. ML algorithms fall into three general ML styles:

  • 监督学习

  • 无监督学习

  • 半监督学习

Figure 4-1 summarizes these three ML algorithm styles.img/468661_1_En_4_Fig1_HTML.jpg Figure 4-1

ML 算法样式

我将讨论的所有算法都属于这些类别之一。监督算法使用带有标签的数据。无监督算法使用没有标签的数据。半监督算法使用带标签和不带标签的数据。

4.3 监督学习

Supervised learning is the easiest ML learning style to understand. Supervised learning algorithms operate on data with labels. Because each sample includes a label, a function (which we will call a critic) is able to calculate an error value for each sample. Figure 4-2 shows a graphical representation of the supervised learning process.img/468661_1_En_4_Fig2_HTML.jpg Figure 4-2

监督学习逻辑

The term “supervision” refers to the critic-error operation. This operation enables the algorithm to compare actual vs. desired and learn from this. There are many algorithms under the supervised learning umbrella. Later in this chapter, you will explore some of the most useful supervised algorithms:

  • 支持向量机(SVM)

  • 朴素贝叶斯网络

  • 随机森林决策树

当您将监督学习与标记数据相结合时,您就能够对样本进行分类。术语“监督学习”和“分类”因此是高度相关的。

监督学习分类通常发生在两个阶段。您将数据分为两部分:训练数据和测试数据。两组数据都包含完全标记的样本。在第一阶段,使用训练数据训练映射函数,直到它满足某种性能水平(实际输出与期望输出)。在第二阶段,您使用测试数据作为映射函数的输入。第二阶段提供了一个很好的方法来衡量模型在处理不可见数据时的表现。

4.4 无监督学习

Unsupervised learning algorithms operate on data without labels. The key difference is that unsupervised learning lacks a critic and has no way to measure its performance. Figure 4-3 shows the representation of an unsupervised learning system.img/468661_1_En_4_Fig3_HTML.jpg Figure 4-3

无监督学习逻辑

在该系统中,您没有必要的标签来对单个样本进行分类。相反,您接受没有标签的数据作为输入,并执行输出类的任务。无监督学习就是寻找数据的结构,这项任务通常被称为聚类或知识发现。

一个经常被引用来帮助解释集群的常见例子是未知的 Excel 电子表格。考虑一个包含数据列但没有标识数据的标题的电子表格。你能确定什么?您需要分析每一列中包含的数据,并试图发现其含义。您实际上是在试图揭示电子表格中数据的结构。如果一个新的样本到达,您想决定如何将它连接到电子表格中的其他数据。这就是聚类。

聚类算法涉及确定映射函数,该函数根据隐藏在数据中的特征将数据分类。对于无监督学习,因为没有标签,所以你缺乏知识来知道你希望从模型中得到什么。相反,您在数据中寻找关系或相关性。

Unsupervised learning algorithms work their magic by dividing the data into clusters. In Figure 2-10, you saw an interesting dataset that contained erroneous value. If you pass this dataset into a clustering algorithm, you might possibly obtain a result like that shown in Figure 4-4.img/468661_1_En_4_Fig4_HTML.jpg Figure 4-4

数据集的聚类

Visualization is very helpful in understanding clusters. Obviously, Cluster 2 represents the erroneous data in the dataset. Algorithms have many different techniques to determine what constitutes a cluster. Later in this chapter, you will explore the pros and cons of the following clustering algorithms:

  • DBSCAN

  • 期望最大化

  • k 均值聚类

在第五章,你将用 Java 和 Weka 实现集群。

4.5 半监督学习

Semi-supervised learning algorithms operate on mixed data where only some of the data contains labels. This is often the case for real-world data. Semi-supervised learning is becoming increasingly popular for two reasons:

  • 数据爆炸的大趋势导致了越来越多的非结构化数据的收集,这些数据没有一致的标签应用。

  • 一种可能的选择是标记混合数据集中所有未标记的数据,然后使用监督学习算法。然而,由于标记过程是手动且繁琐的,因此用缺失的标签标记样品的成本太高。

Figure 4-5 shows the process diagram for semi-supervised learning. The input and outputs are the same as with the supervised learning style, with the exception of a switch placed before the critic. The switch allows the critic function to be disabled when a data sample is unlabeled.img/468661_1_En_4_Fig5_HTML.jpg Figure 4-5

半监督学习逻辑

与监督和非监督学习风格一样,半监督学习有许多算法。在第五章,你将使用一组集体分类算法实现半监督学习。越来越多的学术研究表明,半监督算法可以优于监督算法。然而,使用半监督算法的主要优势仍然是节省时间,因为不需要标记未标记的数据。

4.6 另类学习风格

回归、深度学习和强化学习是具有独特算法的学习风格,我不会在本章中介绍,但有一个例外:支持向量机算法,它可以很好地进行监督学习分类。

线性回归算法

Regression is useful for predicting outputs that are continuous, rather than outputs confined to a set of labels. Linear regression is the most popular regression algorithm. All of the cloud and desktop ML environments support the linear regression algorithm. It is one of the more simple algorithms. If you recall back to the statistics class you suffered through, linear regression is the process of finding the best fit line through a series of data points. Figure 4-6 shows a linear regression example.img/468661_1_En_4_Fig6_HTML.jpg Figure 4-6

线性回归

回归线使与每个数据点相关的误差值最小化。生成的最佳拟合线可以成功地生成或“预测”沿线的任何独立变量值。

回想一下在第二章中,您将 AWS ML 回归算法应用于 PAMAP2_Dataset。结果很差,因为该数据集与回归算法不匹配。在这个例子中,AWS ML 向导错误地认为您的目标标签是一个连续值,而不是一个整数标签。稍后,您将看到如何为该数据集选择更好的算法。

在本文的其余部分,您将主要关注用于监督和非监督学习的 CML 算法,但如果您有一个需要连续值预测而不是离散标签的简单问题,请记住线性回归算法。

深度学习算法

DL 风格依赖于具有隐藏层的神经网络。在 DL 中有几个流行的算法家族,包括卷积神经网络(CNN)和循环神经网络(RNN)。DL 算法最好的总结资源之一是“深度学习算法最完整指南”,可从【https://asimovinstitute.org】获得。

Figure 4-7 displays a simplified summary of the cells and hidden layers that comprise some of the most popular neural networks.img/468661_1_En_4_Fig7_HTML.jpg Figure 4-7

DL 算法总结

神经网络有许多类型的隐藏层。请参考链接来区分不同的隐藏图层类型,因为很难在灰度图像中可视化图层类型。

图的左下角 4-7 是支持向量机 DL 算法。SVM DL 算法是一个监督的 ML 算法,你也可以应用于 CML。你将在本章的后半部分以及第五章中仔细观察这个算法的性能。

强化学习

半监督学习有时会与强化学习(RL)风格相混淆。他们不一样。RL 是一种有区别的监督学习。对于 RL,每个输入并不总是产生反馈。半监督学习使用带有混合标签的数据,而 RL 则没有标签。

在 RL 中,监督来自一个奖励信号,它告诉批评家它做得有多好,但没有说正确的行动应该是什么。强化学习处理批评家与其环境(状态)的相互作用。批评家所采取的行动影响着它在未来将观察到的状态的分布。在监督学习中,每个决定都是独立的。在 RL 中,标签与序列相关联,这与监督学习中的单个样本相反。

回想一下第一章,扑克问题很难解决,因为扑克是一种不确定或不完整信息的游戏。RL 适用于导航不确定的环境,因此经常用于扑克、象棋、二十一点或围棋等游戏。

前面我提到了 Skymind,它是基于 Java 的 DL 库的创建者。Skymind 在 RL 上也有一些很棒的内容。它将 RL 描述为面向目标的 ML 方法。您可以通过以下链接了解更多关于 RL 的信息:

【https://skymind.ai/wiki/deep-reinforcement-learning】

在本章和本书的其余部分,您将把重点限制在有标签或无标签的监督和无监督算法上,因为它们与您对 CML 问题的关注有很好的重叠。

4.7 CML 算法概述

With an understanding of the major algorithm styles, supervised, unsupervised, and semi-supervised, and their relation to labeled vs. unlabeled data, it is now time to look at the specific algorithms within these styles. Table 4-1 provides an index of most of the popular supervised CML algorithms. The shaded cells indicate the key algorithms you will explore.Table 4-1

监督最大似然算法

|

监督最大似然算法

|

家庭/阶级

|
| --- | --- |
| 平均一元估计量(AODE) | 优于贝叶斯 |
| 方差分析(ANOVA) | 统计的 |
| 人工神经网络 | 神经网络 |
| Apriori 算法 | 关联学习(数据库) |
| 朴素贝叶斯 | 贝叶斯(概率) |
| 贝叶斯统计 | 贝叶斯(概率) |
| 助推 | 集成学习 |
| 条件随机场 | 统计的 |
| C45 | 决策图表 |
| 手推车 | 决策图表 |
| 随机森林 | 决策图表 |
| 雪橇亲卫队 | 决策图表 |
| 冲刺 | 决策图表 |
| Eclat 算法 | 联想学习 |
| 分类器集成 | 集成学习 |
| 信息模糊网络 | 决策树,但带有有向图 |
| 隐马尔可夫模型 | 统计,马尔可夫过程 |
| k-最近邻(KNN) | 基于实例(懒惰学习) |
| 学习自动机 | 加强 |
| 学习矢量量化(LVQ) | 神经网络 |
| 逻辑模型树 | 结合回归和决策树 |
| 最小消息长度 | 基于实例的 |
| 可能近似正确的学习 | 统计的 |
| 二次分类 | 线性分类器 |
| 支持向量机 | 非概率线性分类器 |

Table 4-2 provides an index of most of the popular unsupervised ML algorithms.Table 4-2

无监督 ML 算法

|

无监督 ML 算法

|

家庭/阶级

|
| --- | --- |
| 蜘蛛网 | 概念聚类 |
| 概念聚类 | 数据分组 |
| DBSCAN | 基于密度的聚类 |
| 期望最大化 | 迭代法 |
| FP-growth 算法(频繁模式) | 递归树 |
| 模糊聚类 | 类似于 k-means |
| 生成地形图 | 盖然论的 |
| 工具软件 | 基于密度的聚类 |
| 信息瓶颈 | 深度学习 |
| k-均值算法 | 矢量量化,类似于 KNN |
| 局部异常因素 | 异常检测 |
| 光学算法 | 基于密度的聚类 |
| 自组织映射(ANN) | 神经网络 |
| 单连锁聚类 | 分层聚类 |
| 支持向量聚类 | 矢量量化,类似于 SVM |
| 矢量量化 | 矢量量化 |

Lastly, Table 4-3 shows a list of the semi-supervised algorithms.Table 4-3

半监督 CML 算法

|

半监督最大似然算法

|

家庭/阶级

|
| --- | --- |
| 合作培训 | 大量未标记的数据 |
| 集体分类 | 新西兰黑秧鸡 |
| 生成模型 | 基于图形的 |
| 基于图形的方法 | 基于图形的 |
| 撒尔沙(状态-行动-奖励-状态-行动) | 加强 |
| 暂时的 | 加强 |

These tables are a nearly complete list of CML algorithms. It is not necessary to understand all of these algorithms to write successful ML applications. If you see a particular algorithm referenced in an ML solution, you can use the tables to identify the class or family of algorithms and the learning style. Wikipedia has decent reference pages for all of the algorithms if you wish to learn more about one of them.

CML 算法是一种商品。广泛实现了算法创新和性能提升。然而,CML 算法更喜欢特定类型的问题,所以在选择算法时要考虑算法偏好偏差。

While knowing the details of all the CML algorithms is not necessary, it is necessary to understand the following:

  • 你有什么类型的数据?

  • 哪种学习方式最适合你的数据?

  • 每个 ML 算法的偏好偏差是多少?

接下来,您将探索选择最佳算法的过程。

4.8 选择正确的算法

There is a popular saying among data scientists...

算法容易;难的是数据。

The part about data being hard was a theme of Chapter 2. At first glance, CML algorithms do not appear to be easy. Unlike DL algorithms, which are still undergoing significant development, CML algorithms are widely deployed and relatively stable. This allows us to define a decision flowchart for choosing the right CML algorithm. Figure 4-8 shows the algorithm decision process.img/468661_1_En_4_Fig8_HTML.jpg Figure 4-8

ML 算法决策流程图

该决策图是 Scikit-learn 资源页面上一个更复杂图表的修改版。如果你仔细观察图 4-8 ,你会注意到简单的决策引导你进入三个主要学习风格的盒子之一:分类、聚类和回归。每个方框都突出了你需要知道的关键算法。

在浏览流程图时,决策节点取决于数据量和数据类型。在某些情况下,你会发现你可以使用不止一种算法。一般的经验法则是从简单的开始,首先运行基本的算法。

即使表 4-1 ,表 4-2 ,表 4-3 包含了很多算法,你真的只需要考虑图 4-8 所示的算法。在这一章的后面,你将会更仔细地研究这些特定的算法。

功能算法决策过程

有时候,ML 从业者采取一种更加功能化的方法来选择算法。当云平台希望将用户从与选择算法所需的数据类型决策相关的复杂性中移除时,它们使用这种方法。微软 Azure ML 在使用这种方法帮助用户选择正确的算法方面做得特别好。

The idea is to ask yourself the simple question, “What do I want to find out?” The answer to the question will lead you to the correct learning style and then to specific algorithms. Figure 4-9 show a summary of this approach for each of five distinct answers to the question, including

  • 预测值

  • 发现结构

  • 在几个类别之间预测

  • 查找不寻常的事件

  • 在两个类别之间预测

Figure 4-9 shows examples and algorithms for each of the five categories. Some users appreciate this approach to algorithm selection, because it is simpler. “Discover structure” is an easier concept to understand than “clustering.”img/468661_1_En_4_Fig9_HTML.jpg Figure 4-9

功能算法决策流程图

以这种方式组织 ML 算法表明,相同的算法可以回答几个不同的问题。区别在于输出类的数量。例如,请注意决策树或随机森林算法的情况。您可以将这些算法作为多类算法应用于几个类别之间的预测,作为 2 类算法应用于两个类别之间的预测,或者作为回归算法应用于值的预测。

图 4-8 中的数据驱动决策流程图和图 4-9 中的功能方法都将引导您针对您的问题选择相同的正确学习方式和算法。

接下来,您将进一步了解解决 CML 问题所需的关键算法。

4.9 七种最有用的 CML 算法

图 4-8 和图 4-9 中的算法决策图指导您选择最佳的 ML 算法。有了经验,你会发现屈指可数的算法就能解决你的大部分问题。本节将涵盖你工具箱中需要的七种最有用的 CML 算法。

The following seven algorithms are the “go-to” algorithms for CML problems. The list includes four classifiers and three clustering algorithms.

  • 朴素贝叶斯(分类)

  • 随机森林(分类)

  • k-最近邻(分类)

  • 支持向量机(分类器)

  • 数据库扫描(集群)

  • 期望值最大化(聚类)

  • k 均值(聚类)

当然,当你需要一个模糊的算法时,特殊的情况就会出现,但是 95%的情况下,这七个算法都会产生很好的结果。最棒的是,所有算法都有开源的 Java 产品代码。

朴素贝叶斯算法

NB 是一种基于贝叶斯定理的概率建模算法。这本书的目标之一是避免数学方程式。因为它的根源是概率,NB 算法代表了一种保证使用数学方程的情况,但是我们将避免这种诱惑。

Bayes’ theorem simply states the following:

  • 事件的概率是基于可能与事件相关的条件的先验知识。贝叶斯定理讨论条件概率。条件概率是假设条件 B 为真,事件 A 发生的可能性。

例如,考虑人的视力及其与人的年龄的关系。根据贝叶斯定理,与在不知道一个人年龄的情况下做出的评估相比,年龄可以帮助更准确地评估一个人戴眼镜的概率。在这个例子中,人的年龄是条件。

名称中“幼稚”部分的原因是算法对属性的独立性做了一个非常“幼稚”的假设。NB 算法假设给定类,所有属性都是条件独立的。即使有这种假设,NB 算法也经常胜过使用更复杂技术的分类器。

Some advantages of NB algorithms include

  • NB 适用于垃圾邮件检测,其中分类返回一个类别,如垃圾邮件或非垃圾邮件。

  • NB 可以接受分类和连续数据类型。

  • NB 可以通过在估计概率时忽略数据集中的缺失值来处理它们。

  • NB 对于有噪声的数据也是有效的,因为噪声通过使用概率来平均。

  • NB 是高度可伸缩的,它特别适合大型数据库。

  • NB 可以适应大多数分类。NB 是文档分类、垃圾邮件过滤和欺诈检测的优秀算法选择。

  • NB 有利于增量更新。

  • NB 提供了有效的内存使用和快速的训练速度。该算法适合并行处理。

Disadvantages of NB include

  • 当数据属性具有某种程度的相关性时,NB 算法不能很好地工作。这违背了算法的“幼稚”假设。

您将在第五章中使用朴素贝叶斯实现文档分类。

随机森林算法

如果我只能为我的 ML 工具箱选择一种算法,我会选择随机森林算法。

要理解 RF,首先要理解决策树。决策树是一种用于分类的监督学习方法。决策树算法使用训练数据集来生成树。决策树可以对测试数据集中的实例进行分类。决策树是一种分而治之的学习方法。

决策树是一种结构,其中“内部节点”代表数据集中的每个属性。树的每个“分支”代表一个测试的结果,树底部的“叶节点”代表所做的分类。

The test can take on a variety of forms, including

  • 将属性值与常数进行比较。

  • 如果属性是名义属性,那么子属性的数量通常代表匹配的类别。

  • 如果属性是数字,子属性可以表示“>”或“

CART(分类和回归树)算法是最基本的决策树算法之一。CART 使用有两个输出的二叉树。C45 是一种改进的算法,可以处理缺失值,并具有修剪功能来帮助解决过度拟合问题。通过决策树,您可以对离散值目标使用分类树,对连续值目标使用回归树。

The RF algorithm is an improvement over the basic decision tree algorithms such as CART and C45. RF is an ensemble model because it uses multiple decision trees and bases each decision tree on a random subset of attributes (columns) and observations (rows) from the original data. Figure 4-10 shows a graphical representation of how the RF algorithm classifies an instance.img/468661_1_En_4_Fig10_HTML.jpg Figure 4-10

随机森林算法

许多树组成随机森林,多数投票决定最终分类。

The RF algorithm has several advantages:

  • RF 易于可视化,因此您可以了解导致分类结果的因素。如果您必须向业务领域专家或用户解释您的算法是如何工作的,这将非常有用。

  • 随机森林中的每棵树都在随机特征上生长结构,从而最小化偏差。

  • 与朴素贝叶斯算法不同,基于决策树的算法在属性具有某种相关性时工作良好。

  • RF 是最简单、最稳定、最容易理解的算法之一。

  • RF bagging 功能非常有用。它提供了牢固的贴合性,通常不会过度贴合。

  • RF 高度可扩展,并提供合理的性能。

RF has some disadvantages:

  • 当决策树很复杂时,由于训练时间很长,可能会很慢。

  • 缺失值会给基于决策树的算法带来问题。

  • 属性排序很重要,这样那些“信息增益”最大的属性会首先出现。

RF 算法是对朴素贝叶斯算法的很好补充。射频变得流行的一个主要原因是因为它非常容易得到好的结果。你将在本章的后面看到,RF 算法通常优于所有其他 CML 分类器算法。

k 近邻算法(KNN)

k-最近邻算法是一种产生良好结果的简单算法。KNN 对于分类和回归是有用的。回想一下表 4-1 ,KNN 算法是一种基于实例的算法,一种学习,也称为懒惰学习。原因是这项工作是在您准备对新实例进行分类时完成的,而不是在处理定型集时完成的。基于实例的学习因此变得“懒惰”。KNN 算法不会对底层数据做出任何假设,也不会从训练数据中构建模型。

因为 KNN 算法依赖于距离计算,所以它可以很好地处理数值属性,但是 KNN 也可以通过转换为数值或二进制值来支持分类属性。

KNN algorithms classify each new instance based on the classification of its nearby neighbor(s). Figure 4-11 shows a graphical representation of a KNN algorithm with K=5.img/468661_1_En_4_Fig11_HTML.jpg Figure 4-11

KNN 算法(k=5)

图 4-11 显示了三个不同类别的二维数据。该算法从它试图分类的实例向外扫描。该算法维护一个距离数组,该数组包含从未分类实例到每个已分类邻居的距离。因为 K=5,所以只有五个最近的邻居被考虑用于确定类别的多数投票。在本例中,计数为 3 的情况对未知实例进行了分类,如下所示。

The trick with KNN is determining the best value for K. If you pick a K that is too large, perhaps even equal to the total number of observations, then your classification result will simply be the most populous class. If K is too small, the result will simply be the class of the closest neighbor. There are many approaches to choosing K:

  • 进行猜测,并通过反复试验来完善。

  • 选择与类别数相关的 K 值,例如,类别数+ 1。

  • 用另一种算法选 k。

KNN advantages:

  • KNN 对基础数据不做任何假设。

  • KNN 是一个简单的分类器,可以很好地处理基本的识别问题。

  • KNN 很容易想象和理解分类是如何确定的。

  • 与朴素贝叶斯不同,KNN 对相关属性没有问题,如果数据集不大,它也能很好地处理有噪声的数据。

KNN disadvantages:

  • 选择 K 可能会有问题,您可能需要花时间调整 K 值。

  • 由于依赖于基于距离的测量,KNN 受到维数灾难的影响。为了帮助解决这个问题,您可以尝试在建模之前减少尺寸或执行特征选择。

  • KNN 是基于实例的,处理整个数据集进行分类,这是资源密集型的。对于大型数据集,KNN 不是一个很好的算法选择。

  • 将分类值转换为数值并不总能产生好的结果。

  • 作为一个懒惰的分类器,KNN 不是实时分类的好算法选择。

KNN 是一个简单而有用的分类器。在最初的分类尝试中考虑它,特别是如果上面列出的缺点对您的问题来说不是问题的话。

支持向量机算法(SVM)

支持向量机算法在你的七种算法工具箱中占据了一个有用的位置。SVM 在技术上是一个线性分类器,但有一种方法也允许它处理复杂的非线性数据。

对于其输入,SVM 仅对数字要素有效,但该算法的大多数实现都允许您将分类要素转换为数值。SVM 输出是一个类别预测。

The SVM works its magic similar to the linear regression algorithm discussed earlier. Figure 4-12 shows the SVM concept.img/468661_1_En_4_Fig12_HTML.jpg Figure 4-12

支持向量机

图 4-12 中虚线上的点是支持向量。该算法试图通过最大化支持向量之间的间隔来创建类之间的最优超平面决策边界。

The SVM algorithm has several advantages:

  • 在构建模型时,支持向量机需要设置的参数较少。

  • SVM 算法有很好的理论基础。

  • 支持向量机在支持的数据类型上非常灵活。

  • 与决策树相比,支持向量机需要更少的计算资源来获得精确的模型。

  • 支持向量机对噪声数据不敏感。

  • 对于二进制两类输出,SVM 是一个很好的算法。

  • 通过使用核变换,可以用支持向量机完成非线性分类。

  • 支持向量机可以很好地处理大量的特征和较少的训练数据。

Disadvantages of SVM algorithms:

  • 支持向量机是黑盒。与决策树不同,很难解释或说明幕后发生了什么。

  • 支持向量机会消耗大量内存。它们被认为是 O( n 2 )和 O( n 3 ),这意味着它们随着实例的数量呈指数级增长,因此会产生可伸缩性问题。

  • 支持向量机通常适用于二元分类(两类),但不适用于多类分类。

你并不总是有如图 4-12 所示的线性数据。幸运的是,您可以通过使用核变换(也称为“核技巧”)用 SVM 对非线性数据进行分类使用核技巧,支持向量机可以通过将输入映射到高维特征空间来有效地分类非线性数据。

为了理解二维到三维的转换,考虑下面的例子。一套由便士和一角硬币组成的硬币随机散落在桌子上。它们肯定会以非线性模式着陆,这样就没有线可以把它们分成两个不同的类别。想象一下,如果你把所有的一角硬币举起(变换)到桌子上方几英寸的地方。你可以这样做,因为这是监督学习,你已经标记了数据。经过这种转换后,您现在可以轻松地用一个平面来分隔这些类。这是本质上的核心技巧,也是支持向量机如此流行的原因。

Spoiler alert: In the next section, you will discover that SVMs can perform almost as well as neural networks on the MNIST image classification problem. Because of such excellent performance, SVMs are becoming increasingly popular and many people are starting to ask if they are an alternative to neural networks. SVMs cannot match the performance of deep networks, but they do have some advantages worth mentioning:

  • 支持向量机比神经网络更不容易过度拟合。

  • 支持向量机比神经网络需要更少的内存来存储预测模型。

  • 支持向量机产生一个更可读的结果,因为他们有一个几何解释。

你将在第五章中进一步探索 SVM。

k-均值算法

Clustering is the main task of explorative ML, and when seeking a clustering algorithm , k-means is the usual starting point. It works well for many datasets. Figure 4-13 shows a simplified view of how the algorithm works.img/468661_1_En_4_Fig13_HTML.jpg Figure 4-13

k-均值聚类算法

如图所示,k-means 算法是迭代的。该算法试图将 N 个观察值划分成 K 个聚类。您必须从集群的数量开始。k-means 算法的主要缺点是需要预先知道有多少个聚类。在所示的例子中,K=3。然后,该算法随机选择三个初始“平均值”,并通过将每个观察值分配到最近的平均值来创建初始聚类。每个聚类的质心成为新的平均值,并且重复该过程,直到实现收敛。

K-means 自 1967 年以来一直存在,它是用于聚类问题的最简单的无监督算法之一。K-means 表现也比较好。

除了必须事先知道星团的数量,k-means 还面临另一个缺点:它对非球状星团不太适用。k-means 算法倾向于找到具有相同可比形状的聚类。幸运的是,额外的聚类算法可以处理 k-means 的弱点。

DBSCAN 算法

DBSCAN stands for density-based spatial clustering of applications with noise. The easiest way to understand density-based clustering is to look at Figure 4-14, a reproduction of the original clusters shown from Ester et al. Ester introduced the DBSCAN algorithm in 1996. The graphic shows three database examples. Each of the examples contains four easily visible clusters. The clusters are non-globular, inconsistent shapes. If you were to run a k-means clustering algorithm on the datasets shown in Figure 4-14, the k-means algorithm would fail miserably. A density-based algorithm like DBSCAN is required to cluster such datasets.img/468661_1_En_4_Fig14_HTML.jpg Figure 4-14

DBSCAN 集群示例

显示的三幅图像突出了基于密度的算法的优势。在数据库 1 中,与三个周围聚类相比,较大的中心聚类的相对聚类大小对于 k-means 来说是有问题的。在数据库 2 中,围绕两个较小聚类的 S 形聚类会给 k-means 带来麻烦。在数据库 3 中,散布在整个区域的随机噪声点对于 k-means 算法来说是有问题的。

The DBSCAN algorithm employs an approach not unlike human intuition to identify clusters and noise. To accomplish this, DBSCAN requires two important parameters:

  • MinPts:数据集中的维数。该值必须至少为 3。

  • e:ε是欧氏距离。较小的值更好。如果 e 太小,很大一部分数据就不会聚类。如果 e 太大,集群将会合并。选择一个好的 e 值是 DBSCAN 成功的关键。

DBSCAN is one of the most common clustering algorithms and its advantages include

  • DBSCAN 不需要预先知道簇的数量。

  • DBSCAN 可以找到任何形状的集群。

  • DBSCAN 可以发现异常值。

  • DBSCAN 可以识别噪声。

  • DBSCAN 只需要两个参数。

  • 数据集的顺序无关紧要。

The key disadvantages of DBSCAN include

  • DBSCAN 的质量取决于 e 值。对于高维数据,可能很难为 e 找到一个好的值。这就是所谓的“维数灾难”。如果数据和规模不太了解,很难选择 e。

  • DBSCAN 不能很好地聚类密度差异较大的数据集。

请注意,光学算法是 DBSCAN 的分层版本。HDBSCAN 算法是 optics 算法的更快版本。

期望最大化算法

当 k-means 不能达到理想的结果时,考虑 EM 算法。EM 通常能为真实世界的数据集提供出色的结果,尤其是当您感兴趣的区域很小时。

EM 是一种迭代算法,在模型依赖于未观察到的潜在变量时效果很好。该算法在两个步骤之间迭代:期望(E)和最大化(M)。在期望步骤(E)中,为可能性的期望创建一个函数。在最大化步骤(M)中,创建参数以最大化 E 步骤中的预期可能性。

EM 算法背后的理论很难理解。使用 EM 聚类,您是在概率上将候选项分配给聚类。EM 算法往往运行相对较慢,因为它需要计算大量的协方差和均值。

你将在下一章探索如何在真实世界的数据上实现 EM 算法。

4.10 算法性能

无论是分类还是聚类,算法预测准确性都是衡量所选算法性能的关键。你所要求的准确度是相对于你要解决的问题而言的。如果您正在构建一个 ML 模型来确定打高尔夫球的最佳日期,90%的置信度是可以接受的。如果你试图确定一张皮肤斑点的照片是否是癌性的,或者一块土地是否埋有地雷,90%是不可接受的。

深度学习的兴起在某种程度上是不断增加的对算法准确性的搜索的结果。CML 算法的用户寻求更高程度的准确性,这导致他们使用 DL 算法。

MNIST 数据库是 ML 中最流行的“Hello World”应用程序之一。MNIST 是一个大型手写数字数据库,用于训练图像识别中的神经网络和 CML 算法。因为图像识别非常适合 DL 算法,所以不需要实现 MNIST。然而,由于 MNIST 已经存在了很长时间,你可以深入了解算法的性能。

MNIST 算法评估

MNIST is the abbreviation for Mixed National Institute of Standards and Technology. The MNIST database consists of 60,000 handwritten digits. Figure 4-15 shows what these images look like.img/468661_1_En_4_Fig15_HTML.jpg Figure 4-15

MNIST 示例图像

Characteristics of the MNIST image database:

  • 60,000 次训练

  • 10,000 个测试实例

  • 每个图像尺寸为 28x28 像素

  • 所有图像都是灰度的

除了图像文件,MNIST 数据库还包括每个图像的标签。因为 MNIST 数据集包含标签,MNIST 是一个分类 ML 问题。

Figure 4-16 shows a visualization of the MNIST dataset. You can distinguish the 10 unique digits. Digits that have similar appearance appear in close proximity. For example, x and y appear together at the top left. Digits 1 and 2 are also similar and appear in close proximity to each other at the center of the visualization.img/468661_1_En_4_Fig16_HTML.jpg Figure 4-16

MNIST 可视化

有大量关于 MNIST 数据库的学术研究。您可以利用结果来帮助您理解算法。因为您已经标记了数据,所以您可以了解监督学习分类器如何相互堆叠。

为了在 MNIST 数据库上评估 ML 模型,有必要用 60,000 个训练实例来训练该模型。评估使用额外的 10,000 个测试实例。因为 MNIST 是如此受欢迎的数据集,许多模型和算法已经解决了 MNIST。您可以使用这项工作的结果来获得一些关于相对算法性能的见解。

Table 4-4 shows a summary of the results for many of the popular classifiers on MNIST. The table summarizes MNIST results from the following references:

  • https://en . Wikipedia . org/wiki/mnst _ database

  • MNIST 评估绩效总结,数据挖掘,Witten 等人,第 421 页

  • 网站,

*** 作者 MNIST 评价**

**The second column in the table displays the algorithm category as either CML or DL. Most of the recent results with error rates < 1% use DL algorithms.Table 4-4

MNIST 分类算法性能总结

|

分类者

|

类型

|

误差(%)

|

参考

|
| --- | --- | --- | --- |
| 线性分类器(1 层神经网络) | currentmodelogic 电流型逻辑的 | Twelve | LeCun 等人(1998 年) |
| 线性分类器(成对) | currentmodelogic 电流型逻辑的 | Seven point six | 维基百科(一个基于 wiki 技术的多语言的百科全书协作计划ˌ也是一部用不同语言写成的网络百科全书ˌ 其目标及宗旨是为全人类提供自由的百科全书)ˌ开放性的百科全书 |
| k-最近邻,欧几里德(L2) | currentmodelogic 电流型逻辑的 | Five | LeCun 等人(1998 年) |
| 2 层神经网络,300 个隐藏单元 | currentmodelogic 电流型逻辑的 | Four point seven | LeCun 等人(1998 年) |
| 随机森林 | currentmodelogic 电流型逻辑的 | Two point eight | 韦翰 |
| 高斯支持向量机 | currentmodelogic 电流型逻辑的 | One point four | MNIST 网站 |
| 卷积网,LeNet-5 | 分升 | Zero point nine five | LeCun 等人(1998 年) |
| 虚拟支持向量机 | 分升 | Zero point five six | 德科斯特(2002 年) |
| KNN(可移动边缘预处理) | currentmodelogic 电流型逻辑的 | Zero point five six | 维基百科(一个基于 wiki 技术的多语言的百科全书协作计划ˌ也是一部用不同语言写成的网络百科全书ˌ 其目标及宗旨是为全人类提供自由的百科全书)ˌ开放性的百科全书 |
| 卷积神经网络 | 分升 | Zero point four | Simard (2003 年) |
| 6 层前馈神经网络 GPU | 分升 | Zero point three five | Ciresan (2010 年) |
| 大型深度卷积神经网络 | 分升 | Zero point three five | Ciresan (2011 年) |
| 35 个卷积神经网络委员会 | 分升 | Zero point two three | Ciresan (2012 年) |

回想一下图 4-8 ,k 近邻和支持向量机是分类问题的两种推荐算法。KNN 的 MNIST 性能是 95%的分类准确度,而 SVM 达到 98.6%的准确度。这些都是令人印象深刻的结果,尤其是对 SVM 而言。SVM 的结果与几个 DL 算法的结果相当。向下扫描表格的下半部分,可以看到上面的结果是用 DL 算法得到的,> 99.5%的准确率。

MNIST 是一个图像识别问题。虽然给出的准确性结果很有用,但是在得出任何结论之前,您还需要考虑不同的问题类型。

Earlier in the book, I discussed leveraging academic research papers as a means to gain a competitive advantage. One of the common metrics published by researchers is algorithm classification accuracy. Figure 4-17 shows the my summary of CML algorithm performance across a wide variety of ML classification problems published in academic research.img/468661_1_En_4_Fig17_HTML.jpg Figure 4-17

CML 分类算法比较

You saw earlier in the chapter that different algorithms are useful for different types of problems. The data in Figure 4-17 represents a very wide snapshot, and it is not very scientific to aggregate the results, but you can use it to make some general insights:

  • 由于图表中使用了以零为基的 Y 轴,很明显算法之间的差异并不大。所有这些 CML 算法都实现了 90% - 95%范围内的准确性。

  • 随机森林通常做得很好,通常优于其他分类器。这使得随机森林成为大多数 CML 分类的首选算法。

You saw with MNIST results that the SVM algorithm outperformed all of the non-DL algorithms, including random forest. This is likely because decision trees do not work as well for high-dimensional problems like MNIST. Depending on the problem, random forest and SVM are two very important, yet different, algorithms for your toolbox.

如果您正在寻求对多类标记数据进行分类,只需选择随机森林,节省您宝贵的时间和精力。十有八九,随机森林将优于其他 CML 分类算法。对于高维数据,如模式识别,选择 SVM 算法作为首选算法。

分类准确性不是唯一重要的衡量标准。接下来,您将看到用于算法度量的其他重要工具。

4.11 算法分析

Because of their close affiliation to the field of statistics, ML environments are loaded with statistical analysis features, some of which are useful, and others not so much. Next, you will explore the three algorithm analysis tools every ML practitioner should master:

  • 混淆矩阵

  • ROC 曲线

  • k 倍交叉验证

在第五章中,你将探索如何使用这些工具来验证一个模型。

混淆矩阵

One of the most important outputs of the ML model is the confusion matrix . You saw the following confusion matrix in Chapter 3 when you ran a Weka classifier in the cloud:001   === Confusion Matrix === 002 003     a  b  c   <-- classified as 004    50  0  0 |  a = Iris-setosa 005     0 49  1 |  b = Iris-versicolor 006     0  2 48 |  c = Iris-virginica The confusion matrix is a two-dimensional plot with a row and column for each class. The example above had three classes. You can generate a confusion matrix for any number of dataset classes. Figure 4-18 shows a generic 2-class confusion matrix.img/468661_1_En_4_Fig18_HTML.jpg Figure 4-18

一个 2 类一般混淆矩阵

混淆矩阵中的每个元素都显示了实际类是行,预测类是列的测试实例的数量。好的结果对应于沿着矩阵对角线的大数。在 2 类混淆矩阵中,对角线值代表真阳性和真阴性。

Glancing at the values not on the main diagonal can give you excellent feedback on how the model is performing, or more specifically, when the model is getting “confused”. You can gain the following insights from the 3-class confusion matrix shown earlier:

  • 2 例海滨鸢尾(c 型)被误分类为杂色鸢尾(b 型)。

  • 1 例杂色鸢尾(b 型)被误诊为海滨鸢尾(c 型)。

  • 所有 50 例鸢尾-圣淘沙被正确分类。

每次运行分类器时,ML-Gate 2 最佳实践是对照您预先确定的 mo del 可接受的值来检查混淆矩阵结果。

ROC 曲线

ROC 代表受试者操作者特征。ROC 曲线起源于第二次世界大战,被雷达操作员用于统计建模噪声环境中的假阳性和假阴性检测。由于其历史背景,ROC 曲线具有比大多数其他方法更好的统计背景。ROC 是医学和生物学中的标准度量。

The ROC curve has become very popular in ML to help evaluate the effectiveness of the models we create. ROC curves plot the true positive rate on the Y-axis and the false positive rate along the X-axis. Figure 4-19 shows a typical ROC curve.img/468661_1_En_4_Fig19_HTML.jpg Figure 4-19

受试者工作特征曲线

ROC curves have some interesting properties:

  • ROC 曲线的斜率是非递增的。斜率通常会减小。较陡的 ROC 曲线代表较好的分类。一个完美的分类器会产生一条垂直线摇摆曲线。

  • ROC 曲线上的每个点代表假阳性和假阴性之间不同的权衡或成本比率。

  • ROC 曲线切线的斜率定义了成本比率。

  • ROC 面积是 ROC 曲线下的面积。ROC 面积代表所有可能的成本比率的平均绩效。

The ROC area represents the area under the ROC curve. Table 4-5 shows the prediction level that is associated with the ML model given its corresponding ROC area.Table 4-5

ROC 区域预测水平

|

ROC 区域

|

预测水平

|
| --- | --- |
| One | 完美的 |
| Zero point nine | 优秀的 |
| Zero point eight | 好的 |
| Zero point seven | 普通的 |
| Zero point six | 穷人 |
| Zero point five | 完全随机 |
| < 0.5 | 病人 |

In the next chapter, you will use the Weka ML environment to graph multiple ROC curves representing multiple algorithms. Such graphs are very useful for comparing algorithms. When graphing multiple ROC curves, you can gain the following additional insights:

  • 如果两条 ROC 曲线不相交,一种方法优于另一种方法,您应该选择其相应的算法。

  • 如果两条 ROC 曲线相交,一种方法(算法)对某些成本比率更好,另一种方法(算法)对其他成本比率更好。

正如您将看到的,ML 环境使多 ROC 曲线可视化变得容易。

k 倍交叉验证

在现实世界中,我们似乎永远没有足够的数据。可用于训练和测试我们的模型的数据量通常是有限的。你看到 MNIST 的标准训练方法是 60,000 个已定义的实例用于训练,另外 10,000 个实例用于测试。这种方法被称为 维持方法 ,因为您出于测试目的保留了部分数据。拿出三分之一的数据进行测试是很常见的。因为数据集很大,所以维持方法很适合 MNIST。对于较小的数据集,这可能会有问题。你如何知道数据的哪一部分是可靠的?

选择一组特定的数据进行测试会导致偏差。例如,如果您运气不好,某个特定的类在训练数据中完全缺失,当它出现在测试数据中时,您怎么能期望分类器预测这样的值呢?针对由选择用于维持的特定样本引起的偏差,解决方案是重复该过程若干(K)次,其中 K 可以是任何数字,例如 3、5 或 10。如果你希望用三分之二的数据进行训练,用三分之一的数据进行测试,那么 K 等于三。如果你希望十分之九的时间训练,十分之一的时间测试,那么 K 等于十。

This approach is called k-fold cross-validation. Figure 4-20 shows the example of a 5-fold cross-validation process.img/468661_1_En_4_Fig20_HTML.jpg Figure 4-20

五重交叉验证法

When you perform an n-fold cross-validation, you are actually performing multiple (K) passes of the training and validation cycle. The resulting accuracies of each pass are averaged to obtain the mean accuracy for the model.

K 倍交叉验证是一个简单但强大的概念。预测学习技术的错误率的标准方法是使用 10 重交叉验证,其中数据集被随机分成 10 个部分。10 重交叉验证应该是每个 ML-Gate 2 模型评估的一部分。

大量测试表明,K=10 给出了最佳结果,与数据集大小无关。

4.12 Java 源代码

用于创建 ML 模型的所有流行 CML 算法的 Java 源代码都是现成的。怀卡托大学为 Java ML 算法的发展做出了巨大的贡献,最新版本的算法可以在 Weka 3.8 中获得。源代码也可以在 Subversion 存储库中找到:

https://SVN . CMS . waikato . AC . NZ/SVN/WEKA/branches/stability-3-8/WEKA/src/main/Java/WEKA/

Apache Commons Math 还包括几个集群 ML 算法的 Java 代码:

https://commons . Apache . org/proper/commons-math/user guide/ml . html

本节给出了算法的概述,如果您想详细研究它们,您将知道在 Weka Subversion 存储库中何处可以找到它们。如果您对某个特定的算法感兴趣,查看它的 Java 源代码会非常有帮助。这些算法是在无数项目中使用的稳定的产品代码。您可以从他们的实现中学到很多东西,包括他们对 Java 集合、线程和继承的使用。

The base directory of the Subversion repository includes several folders:

  • 核心 文件夹包含 Weka 代码。

  • 文件夹包含分类算法。

*** 聚类器 文件夹包含聚类算法。**

**Java 文件结构是分层的。这些算法继承自其他底层算法。例如,如果您希望实现随机林算法,则在构建随机林时,将包括以下每个文件:

RandomForest.java will set the base classifier as RandomTree:001   /** 002    * Constructor that sets base classifier to RandomTree 003    / 004   public RandomForest() { 005       RandomTree rTree = new RandomTree(); 006       rTree.setDoNotCheckCapabilities(true); 007       super.setClassifier(rTree); 008       super.setRepresentCopiesUsingWeights(true); 009       setNumIterations(defaultNumberOfIterations()); 010   } The RandomTree.java class will extend the AbstractClassifier class:001   /* 002    * Constructor for Random Tree that extends AbstractClassifier 003    / 004   public class RandomTree extends AbstractClassifier implements OptionHandler, 005      WeightedInstancesHandler, Randomizable, Drawable, PartitionGenerator { 006   } The AbstractClassifier.java class will implement the Classfier class:001   /* 002    * Abstract classifier. All schemes for numeric or nominal prediction in Weka 003    * extend this class. Note that a classifier MUST either implement 004    * distributionForInstance() or classifyInstance(). 005    / 006   public abstract class AbstractClassifier implements Classifier, BatchPredictor, 007       Cloneable, Serializable, OptionHandler, CapabilitiesHandler, RevisionHandler, 008       CapabilitiesIgnorer, CommandlineRunnable { 009   } Classifier.java 001   /* 002    * Classifier interface. All schemes for numeric or nominal prediction in 003    * Weka implement this interface. Note that a classifier MUST either implement 004    * distributionForInstance() or classifyInstance(). 005    */ 006   public interface Classifier { 007   }

要查看任何 CML 算法的 Java 代码,只需浏览存储库,进入 分类器聚类器 文件夹。

分类算法

Within the classifiers folder, the algorithms fall into three categories:

  • 贝叶斯 :包含朴素贝叶斯算法的几种变体。

  • pmml :预测模型标记语言是一种基于 XML 的交换格式。此文件夹包含基于 PMML 的模型,如 SVM 和回归算法。

  • :包含所有基于决策树的算法,如随机森林。

Figure 4-21 shows an expanded view of the key classifier algorithms.img/468661_1_En_4_Fig21_HTML.jpg Figure 4-21

Java 分类器算法(Weka Subversion 存储库)

在图 4-8 中列出的最有用的分类器包含在存储库中。图 4-21 显示朴素贝叶斯、随机森林、SVM 源代码都包含在 分类器 目录中。

聚类算法

Figure 4-22 shows the Java clustering algorithms available in Weka.img/468661_1_En_4_Fig22_HTML.jpg Figure 4-22

Java 集群器(Weka Subversion 仓库)

在图 4-8 中,您可以看到 k-means 和 DBSCAN 是用于无标签数据聚类问题的常用算法。这些算法的源代码在 SimpleKMeans.java 的和 DensityBasedCluster.java 的内。****

正如您看到的分类算法一样,聚类算法也建立在目录中其他更高级别的聚类类之上,例如【Cluster.java】heiarchicalclusterer**。java

Java 算法修改

我之前说过 CML 算法是商品。Weka Subversion 存储库中 Java 算法的源代码显示算法代码已经稳定了好几年。Weka 库中的所有 Java 代码都是在 GNU 通用公共许可证下授权的。代码是免费的,您可以根据许可条款分发或修改它。

【www.gnu.org/licenses/】

Due to advances in the Java platform, there are several areas where these algorithms could be improved:

  • Lambda 表达式:添加了 lambda 表达式 正在开始重塑 Java。Lambda 表达式允许 Java API 库中的新功能。例如,lambda 表达式简化了对每个 样式操作的 处理,允许我们更好地利用多核环境的并行处理能力。通过引入 lambda 表达式,有机会提高大多数 Java 算法的性能。

  • Stream API:Java 8 中引入的新的 Stream API 允许我们以更强大的方式操作数据。新的流 API 与 Java 集合类和 lambda 表达式协同工作。新的流 API 可以处理高级数据查询,并提供更高的效率,尤其是对于大型数据集。

  • 并发:如果你查看 Java 代码,你会发现很多算法都使用 JavaThreadPoolExecutor来处理它们的多线程操作。ThreadPoolExecutor是组成 JavaExecutorService的服务之一。JDK 7 看到了一个新服务的引入, ForkJoinPoolForkJoinPool 类支持并行编程的实现,使得线程可以在多个 CPU/GPU 上运行。一个 ForkJoin 任务背后的主要思想是分治策略,非常适合决策树家族的算法,包括随机森林。更新 Java 算法以利用 ForkJoin 可以显著提高性能。

这些潜在的增强是与性能相关的改进。正如在第二章中所讨论的,基于云的提供商使得按需扩展 CPU 资源变得容易。因此,在云中构建模型时,添加 CPU 资源通常比优化算法以利用最新的 JAVA API 特性更容易。这些增强在模型构建时 CPU 约束有限的环境中非常有用,比如在移动或嵌入式设备上构建模型。**********

五、机器学习环境

  • 介绍模型创建阶段所需的步骤。

  • 回顾基于 Java 的 ML 环境,包括 RapidMiner 和 KNIME Java ML 环境的高级概述。

  • 提供详细的回顾,包括 Weka ML 环境的完整设置说明。

  • 使用 Weka 实现七个最重要的 CML 模型。

  • 使用三种聚类算法对旧忠实间歇泉数据集进行聚类。

  • 使用四种分类算法对大型 PAMAP2_Dataset 进行分类。

  • 回顾四种分类算法的精度性能。

  • 使用 Weka KnowledgeFlow 创建代表四条多重 ROC 曲线的组合图。

  • 演示如何导入和导出 Weka ML 模型。

5.1 概述

In Chapter 3, you saw how easy it is to create ML and DL solutions using cloud-based APIs. In this chapter, you will bring the solution to the desktop. Java-based ML environments allow you to create your own models using your own computing resources. This provides two huge advantages:

  • 创建模型所需的计算资源不会产生增量成本。

  • 您保留对自己创建的模型的控制。这可以带来竞争优势。

在这一章中,我将介绍几种基于 Java 的 ML 环境,但重点将主要放在 Weka 环境上。如果您决定使用其他 ML 环境之一,那么关于数据导入、支持的算法和模型创建/导入/导出的详细实现步骤应该是相似的。

ML 门

在 ML-Gates 方法中,ML 环境最重要的任务是创建您将在应用程序中使用的 ML 模型。

创建最佳模型是一个迭代过程。你在第四章看到了如何选择最佳算法。在本章中,您将探索如何通过调整算法的可用参数来创建最佳模型。

Figure 5-1 shows the key steps involved with the model at ML-Gates 3 and ML-Gates 2.img/468661_1_En_5_Fig1_HTML.jpg Figure 5-1

ML-Gates 3/2 模型活动

许多 ML 环境可以完成这些任务。Java 包的数量更少,我接下来会涉及到。

5.2 Java ML 环境

In Chapter 1, you saw how widespread Java has become. I also discussed the build vs. buy decision process for data science platforms.

你的主要目标之一是在边缘应用 ML 解决方案。这要求您生产轻量级的模型,可以部署到便携式设备中,比如移动电话。Java ML 环境满足这些要求。

Java ML environments check all the boxes:

  • 它们是免费和开源的。

  • 你可以很容易地生产出轻量级的模型。

  • 如果需要更高的计算资源,可以在桌面或云中运行 Java ML 环境。

  • 很容易导出该模型,以便在移动设备或小型计算机(如 Raspberry Pi)中使用。

实际上,Java ML 环境就像 ML 管道中的一个中间件。ML 环境创建的模型将输入数据与用户应用程序连接起来。

Table 5-1 shows a summary of the Java-based ML environments.Table 5-1

Java ML 环境

|

名字

|

描述

|

笔记

|
| --- | --- | --- |
| 新西兰黑秧鸡 | 怀卡托知识分析环境 | 新西兰怀卡托大学开发的 ML 平台。包括 GUI、命令行界面(CLI)和 Java API。Weka 可以说是最流行的 ML 环境。Weka 是一个很好的 ML 环境,你可以为 Android 导出模型。Weka 是免费和开源的。 |
| 克尼姆 | 康斯坦茨信息挖掘器 | 康斯坦茨大学(德国)开发了 KNIME。它专注于药学研究和商业智能。KNIME 的 GUI 基于 Eclipse。KNIME 还包含一个 API 接口。 |
| 快一点 | 快一点 | 德国多特蒙德技术大学开发了 RapidMiner。RapidMiner 包含一个 GUI 和一个 Java API。RapidMiner 支持数据处理、可视化、建模和算法。RapidMiner 有免费和商业发行版。 |
| 埃尔基 | 开发 KDD 应用程序的环境 | 慕尼黑 Ludwig Maximillion 大学开发的数据挖掘工作台。ELKI 专注于从数据(KDD)应用中发现数据和知识。ELKI 提供了一个迷你 GUI、CLI 和 Java API。ELKI 是研究软件。 |
| Java-ML | Java 机器学习库 | Java-ML 是 ML 算法的集合。Java-ML 不包含图形用户界面。 |
| DL4J 系列 | 深度学习 4 Java | DL4J 是 Skymind 的 Java 深度学习库。DL4J 不支持 CML 算法。更多详情请参见第一章。 |

The first five entries in Table 5-1 are mainly Java-based CML environments, and I will discuss them briefly next, before taking a deep dive into Weka. The last entry, DL4J, is a dedicated Java DL environment. Table 5-2 provides links for each of the Java ML environments.Table 5-2

Java ML 环境链接

|

名字

|

|
| --- | --- |
| 新西兰黑秧鸡 | 【www . cs . waikato . AC . NZ/ml/WEKA/ |
| 克尼姆 | 【www.knime.com/knime-analytics-platform】 |
| 快一点 | 【https://rapidminer.com/】 |
| 埃尔基 | 【https://elki-project.github.io/】 |
| Java-ML | 【http://java-ml.sourceforge.net/】 |
| DL4J 系列 | 【https://deeplearning4j.org/index.html】 |

There are several factors to consider in choosing the best Java ML environment. The factors include

  • 许可和商业条款:你应该喜欢免费的开源软件包,它允许你创建可用于商业应用的模型。

  • 算法的可用性:你应该寻找支持第四章中讨论的七个最重要算法的包。

  • 持续支持:你应该寻找一个用户社区或者创作者的长期承诺。

  • 模型的可移植性:您应该寻找导出模型的能力,这样任何设备上的 Java 客户端都可以使用您创建的模型。这有助于你在边缘实现 ML。

  • 灵活性:Java 随着每个主要版本的发布而不断发展。你需要一个基于 Java 的 ML 环境,它可以随着语言的发展而发展。也许在将来,我们会看到 ML 特性直接包含在 Java 中,就像 JSON 和其他特性现在是包含的候选者一样。

新西兰黑秧鸡

Weka 是怀卡托知识分析环境的缩写。新西兰的怀卡托大学创造了 Weka。有趣的是,Weka 也是新西兰一种不会飞的鸟(Gallirallus Australis)的名字,因此有了这个标志。新西兰似乎有许多可爱的不会飞的鸟。

ML 环境 Weka 已经存在一段时间了。它于 1997 年移植到 Java,已经成为数据挖掘行业的中流砥柱。2005 年,Weka 在 SIGKDD 会议上获得了 ACM 颁发的数据挖掘和知识发现服务奖。将 Weka 迁移到 Java 的决定让它保持了相关性。

最近,Weka 增加了一个包管理器。许多第三方软件包和算法都可以通过软件包管理器获得。所有重要的 CML 算法都适用于 Weka。你将在本章的后面探索 Weka 算法。

怀卡托大学维护了一个稳定版本(目前是 3.8.2)和一个开发版本(3.9.2),支持 Weka。与 Android Studio 不同,Weka 的发布并不频繁。运行开发渠道版本是安全的,它包括一些有用的 GUI 改进和对 DL4J 的支持。随着 Weka 获得 ML 社区的支持,在流行的论坛上寻找问题的帮助变得越来越容易,例如 Stack Overflow 和 YouTube 视频。

Weka 有一个友好的许可证,GNU 通用公共许可证(GPL)。因此,有可能研究算法如何工作并修改它们。

Weka GUI 看起来过时了。Weka GUIs 和可视化工具远没有 RapidMiner 那么流畅。然而,在引擎盖下,它什么都不缺。Weka 是一个非常强大的 ML 环境,可以提供您的 ML 应用程序所需的模型。尽管相对于 RapidMiner,它的 GUI 较差,但 Weka 检查了所有的复选框。

为了解决 Weka 的一个弱点,在本章的后面,我将讨论一个 Weka 插件来改进 Weka 制图功能。

快一点

RapidMiner is an incredible ML environment. Recall according to Figure 1-4, RapidMiner is a leader in data science platforms. Java-based RapidMiner excels at the following:

  • RapidMiner 快如闪电。

  • RapidMiner 有很多工具。

  • RapidMiner 在准备数据方面非常出色。

  • RapidMiner 允许您构建预测 ML 模型。

Figure 5-2 shows a screenshot of the RapidMiner main interface.img/468661_1_En_5_Fig2_HTML.png Figure 5-2

RapidMiner 主界面

如图 5-2 所示,RapidMiner 有一个漂亮的现代 GUI。RapidMiner 的易用性使其越来越受欢迎。RapidMiner 拥有一个庞大的用户社区和所有与广泛流行相关的常见支持资源。

RapidMiner 的核心是开源的 Java 代码,可以在 GitHub 的【https://github.com/rapidminer/rapidminer-studio】??下载。

正如你在第四章中看到的 Weka,所有的 ML 算法 Java 代码都是 core RapidMiner 的一部分,可以在 GitHub 库获得。仔细观察就会发现算法的 Java 代码基础是不一样的,尽管你可以期望算法达到几乎相似的结果。在许多算法情况下,RapidMiner 算法实现依赖于较少的继承,并且更容易理解。

除了 RapidMiner GUI 的优势之外,RapidMiner 和 Weka 之间的其他主要区别是许可和商业定价条款。RapidMiner 是根据 GNU AGPL 3.0 许可证授权的。它有免费和商业产品。

【https://opensource.org/licenses/AGPL-3.0】

RapidMiner Studio is free to download. Table 5-3 shows a summary of the RapidMiner commercial pricing tiers, which vary depending on data rows and number of processors used.Table 5-3

快速最小定价

|

名字

|

数据行数

|

处理器数量

|

价格(每用户/年)

|
| --- | --- | --- | --- |
| 自由的 | Ten thousand | one | 自由的 |
| 小的 | One hundred thousand | Two | $2,500 |
| 中等 | One million | four | $5,000 |
| 大的 | 无限的 | 无限的 | $10,000 |

RapidMiner 免费层还包括针对大数据行大小的 30 天免费试用。这使您有机会了解 RapidMiner 在大型数据 ML 项目中的表现。一万个数据行或实例看起来很多,但实际上,CML 项目超过这个数量是很常见的。在本章的稍后部分,您将会看到您的 PAMAP2_Dataset 分类需要中级许可才能使用 RapidMiner 完成。这是一笔不小的成本,尤其是对于没有大资源的独立开发者。RapidMiner 许可成本是您选择 Weka 的主要原因。

就灵活性而言,Weka 和 RapidMiner 都提供了 jar 文件库,您可以将它们集成到您的 Java 项目中。这允许您在 Java 应用程序中利用预构建的模型。

Weka 和 RapidMiner 都有自己的方法来实现模型生成。对于任何软件平台,都有学习如何使用它们的初始时间投资。幸运的是,ML-Gates 中此阶段涉及的高级步骤是相同的。

克尼姆

Like RapidMiner, KNIME was included a leader among the data science platforms shown in Figure 1-4. Some key selling points for KNIME:

  • KNIME 是数据科学家的工具箱。

  • KNIME 包含 2000 多个模块。

  • KNIME 是一个开放的平台。

  • KNIME 可以在本地、服务器或云中运行,这正是您所寻求的灵活性。

The latest free-download version of KNIME is 3.6.0. KNIME is licensed under GNU GPL Version 3. KNIME has a very intuitive workbench that is similar to Weka. The GUI is very comprehensive, which make KNIME useful for people who wish to explore ML but do not want to code. Figure 5-3 shows the KNIME workbench.img/468661_1_En_5_Fig3_HTML.png Figure 5-3

knime work bench(knime work bench)

KNIME 界面看起来非常类似于 RapidMiner,特别是在知识流区域,用户可以用图形连接模块以形成流程。

KNIME 使用 PMML(预测模型标记语言)来导出模型。PMML 是一个流行的标准。你看到它被引用为一些 Weka 分类算法的类别标题。PMML 在导出用于 Android 移动设备的预建模型方面没有那么灵活。因此,Weka 仍然是您首选的 ML 环境。

埃尔基

ELKI 是一个擅长集群和离群点检测的 Java 平台。Weka 和 RapidMiner 是通用框架,而 ELKI 只做一件事,而且做得很好:集群。它包含了大量的聚类算法。如果通用框架中包含的基本聚类算法不足以解决您的 ML 聚类问题,ELKI 可能是解决方案。

ELKI 专注于研究和教育。它有助于解决现实世界中的聚类问题,如聚类鲸鱼的位置和重新平衡公共自行车共享计划。

ELKI 的一个独特特性是使用 SVG 进行可伸缩图形输出,使用 Apache Batik 渲染用户界面。如果您需要无损、高质量、可伸缩的图形输出来解决集群问题,ELKI 是一个很好的选择。

通用框架在聚类方面做得很好,你将在本章后面看到,但是如果你需要高级的聚类算法,请记住 ELKI。

Java-ML

Java-ML 是一组打包到 jar 库中的基于 Java 的 ML 算法。该库的最新版本是 2012 年发布的 0.1.7。该库包括一些基本的聚类和分类算法。Java-ML 带有 GNU GPL 2.0 许可证。Java-ML 不包括任何图形用户界面。Java-ML 库不会特别有用,除非您正在寻找不依赖于怀卡托大学或 RapidMiner 许可证的开源 Java ML 算法。

5.3 Weka 安装

要安装 Weka,请访问 Weka 下载页面并为您的平台选择一个软件包:

【www.cs.waikato.ac.nz/ml/weka/downloading.html】

有没有 Java 都可以下载 Weka。如第一章所示,独立于 Java 安装管理 Weka,可以让你知道你运行的是哪个版本的 Java。

There are two current versions of Weka:

  • 3.8.2 是 Weka 最新的稳定版本。

  • 3.9.2 是 Weka 的最新开发版本。

Weka 遵循 Linux 版本编号模型。小数点后的偶数数字(如 3.8.2)表示稳定版本,奇数数字(如 3.9.2)表示开发版本。

Weka 团队维护着总结每个新版本中的错误修复和新特性的链接。要查看 3.9.2 中的新功能,请查看此处显示的文档部分:

https://wiki . Pentaho . com/display/Data Mining/Pentaho+数据+挖掘+社区+文档

Weka 开发版通常非常安全。

After you decide on a version, the download page contains packages for the three major platforms: Windows, Mac O/S, and Linux. Choose your package and install Weka.

    在你的系统上安装 Java。

    下载你想要的 Weka 包。

    将 zip 文件解压到名为 weka-3-9-2 的新目录中。

    设置 Java CLASSPATH 环境变量。CLASSPATH 环境变量告诉 Java 在哪里寻找要包含的类。

    换到目录,用 java -jar weka.jar 运行 Weka。

The Weka logo, Figure 5-4, appears during the initialization.img/468661_1_En_5_Fig4_HTML.jpg Figure 5-4

保留徽标

After the Weka initialization completes, the main Weka GUI chooser appears, as shown in Figure 5-5.img/468661_1_En_5_Fig5_HTML.jpg Figure 5-5

Weka GUI 选择器

在启动主要的 Weka 应用程序之前,您需要配置 Weka。

Weka 配置

Weka is mostly ready to go after the initial install. I will address a few configuration updates next. Figure 5-6 shows the contents of the main Weka directory after you unzip the install file.img/468661_1_En_5_Fig6_HTML.jpg Figure 5-6

Weka.jar

The weka.jar file is of interest for two reasons:

  • weka.jar 文件包含 weka 中算法的所有 Java 源代码。你在第四章中看到了如何在在线 Subversion 资源库中探索它们。通过解压 weka.jar 文件,您可以在本地浏览它们。

  • Weka 为许多 GUI 配置属性使用一个名为 Visualize.props 的文件。为了修改配置,您必须制作此文件的本地副本。

In order to view and modify the contents of the weka.jar file, you need to unzip the jar file. The 7-Zip utility can unzip jar files. Figure 5-7 shows the 7-Zip utility download page. The download is available at www.7-zip.org/download.html .img/468661_1_En_5_Fig7_HTML.jpg Figure 5-7

7-Zip 解压缩工具

Install the 7-Zip utility on the platform of your choice and then unzip the weka.jar file. Figure 5-8 shows the contents of the unzipped weka.jar.img/468661_1_En_5_Fig8_HTML.jpg Figure 5-8

Weka.jar 内容

Weka.jar 包括聚类算法、分类器算法的目录,以及 gui 目录,其中包含了你要修改的visualize . props文件。

Java 参数设置

One of the issues with Java is high memory usage. Weka always displays a status box at the bottom of the Weka Explorer window. The status box displays messages about what is happening within Weka. Right-clicking inside the status box brings up a menu with two helpful options:

  • 内存信息 :显示 Weka 可用的内存量

  • 运行垃圾收集器 :强制 Java 垃圾收集器在后台执行垃圾收集任务

You can use these options to monitor the Weka memory usage. If you should get Out Of Memory errors, you should increase the heap size for your Java engine. The default setting of 64MB is usually too small. You can set the memory for Java using the –Xmx option in the Java command line. For example, increase the Java memory to 1024MB with the following:001   java -Xmx1024m -jar weka.jar If you are running Windows and wish to make the change globally, you can set the javaOpts parameter in the RunWeka.ini file like so:001   javaOpts= -Xmx1040m If you get Class Not Found errors, you will need to verify your CLASSPATH variable settings. The best way to confirm your CLASSPATH setting is to use the Weka Sysinfo display, shown in Figure 5-9.img/468661_1_En_5_Fig9_HTML.jpg Figure 5-9

Weka 帮助➤系统信息显示

除了 java.class.path 设置外,Weka Sysinfo 页面还显示了 WEKA_HOMEmemory.max 设置。

修改 Weka。道具文件

如果你不喜欢 Weka 的默认设置,你可以调整 。道具 文件修改 Weka 行为。有很多。prop 文件来配置 Weka。

The following steps show how to modify the Visualize.props file to change the default colors of the X-axis and Y-axis from green to black. The responsible .props file for charts and graphs in Weka is weka/gui/visualize/Visualize.props.

    关闭 Weka。

    提取 。道具 文件来自 weka.jar ,使用可以处理 ZIP 文件的存档管理器,比如 Windows 下的 7-Zip。

    放置此 。道具 文件中的$ WEKA _ HOME/道具

    打开本地 。道具 文件带文本编辑器,确保 CRLF 和 BOM 字符对于你的平台是正确的。

    修改您想要更改的参数。属性名在“=”的左边,属性值在右边。

    保存文件并重启 Weka。

Figure 5-10 shows the local copy of the Visualize.props file you are updating.img/468661_1_En_5_Fig10_HTML.jpg Figure 5-10

Weka Visualize.props 本地文件副本

There are many customizable values inside the Weka .props files. The following listing shows line 009 with the updated axis color setting:001   # Properties for visualization 002   # 003   # Version: $Revision: 5015 $ 004 005   # Maximum precision for numeric values 006   weka.gui.visualize.precision=10 007 008   # Colour for the axis in the 2D plot (can use R,G,B format) 009   weka.gui.visualize.Plot2D.axisColour=black 010 011   # Colour for the background of the 2D plot (can use R,G,B format) 012   weka.gui.visualize.Plot2D.backgroundColour=white 013 014   # The JFrame (needs to implement the interface weka.gui.visualize.InstanceInfo) 015   # for displaying Instance information. 016   weka.gui.visualize.Plot2D.instanceInfoFrame=weka.gui.visualize.InstanceInfoFrame 017 018   # Defaults for margin curve plots 019   weka.gui.visualize.VisualizePanel.MarginCurve.XDimension=Margin 020   weka.gui.visualize.VisualizePanel.MarginCurve.YDimension=Cumulative 021   weka.gui.visualize.VisualizePanel.MarginCurve.ColourDimension=Margin

使用这种方法,大多数 Weka 配置都是可定制的。但是,有一些设置可以直接从 GUI 选择器中获得。

Weka 设置

Figure 5-11 shows the Weka main settings available under the Program menu selection in the Weka GUI Chooser.img/468661_1_En_5_Fig11_HTML.jpg Figure 5-11

Weka 主要设置

只有两种设置可用:GUI 的 LookAndFeel 和通信的 SocketTimeout 。对于 Windows 平台,首选 LookAndFeel 设置为Windows look and feel。没有必要改变这个默认的socket time out值。

Weka 软件包管理器

Weka recently introduced a package manager. When you initially run Weka, there are many preinstalled algorithms for clustering and classification. There are also many uninstalled packages that are available for installation with the package manager. Figure 5-12 shows the Weka package manager available from the Weka GUI Chooser.img/468661_1_En_5_Fig12_HTML.jpg Figure 5-12

Weka 软件包管理器选择器

当您启动软件包管理器时,Weka 会让您选择显示已安装的和可用的软件包。

For these projects, you must install the following two packages using the package manager:

  • jFreeChart:Weka 的图形化扩展

  • DBSCAN:一种基于密度的聚类算法

图 5-13 显示了 jFreeChart 的安装,它提供了比基本 Weka 渲染器更好的图表渲染。在本章的后面,您将使用 jFreeChart 来呈现多 ROC 曲线比较图。此加载项不是必需的;内置的 Weka 渲染器可以很好地工作,但是 jFreeChart 提供了一个更有吸引力的图表选项。

Figure 5-14 shows that package manager and highlights the recently installed DBSCAN algorithm. You will use the DBSCAN algorithm in a clustering example later in the chapter.img/468661_1_En_5_Fig13_HTML.jpg Figure 5-13

weka 包管理器和 jfreechart 扩展

img/468661_1_En_5_Fig14_HTML.jpg Figure 5-14

Weka 软件包管理器和 DBSCAN 算法

5.4 Weka 概述

Weka is a comprehensive suite of Java class libraries. The Weka package implements many state-of-the-art machine learning and data mining algorithms. Table 5-4 shows a summary of the Weka modules available from the GUI Chooser, shown earlier in Figure 5-5.Table 5-4

Weka 模块

|

Weka 模块

|

描述

|
| --- | --- |
| 探险家 | Explorer 是一个使用 Weka 探索数据的环境。Explorer 是 Weka 的主要图形用户界面。Weka Explorer 包括主要的 Weka 包和一个可视化工具。Weka 的主要特性包括过滤器、分类器、聚类器、关联和属性选择。 |
| 实验者 | Weka Experimenter 是一个用于执行实验和在学习方案之间进行统计测试的环境。 |
| 知识流 | Weka KnowledgeFlow 是一个支持与 Explorer 相同功能的环境,但包含一个拖放界面。 |
| 工作台 | Weka Workbench 是一个一体化的应用程序,它在用户可选的透视图中结合了其他应用程序。 |
| 简单 CLI | Weka 团队建议使用 CLI 来深入了解 Weka 的用法。大多数关键功能都可以从 GUI 界面获得,但是 CLI 的一个优点是它需要的内存少得多。如果您发现自己遇到了内存不足的错误,CLI 界面是一个可能的解决方案。 |

As shown in Table 5-4, there is some redundancy in the Weka modules. You are going to focus on the following three Weka modules because they are more than sufficient to create the models you need for your Java applications.

  • Weka Explorer

  • Weka 知识流

  • 微卡简易 CLI

我已经排除了实验者和工作台。在本章的后面,您将使用知识流模块来比较不同算法的多条 ROC 曲线。实验者也可以这样做,但是即使 Weka 没有最好的图形界面,我还是更喜欢知识流模块的图形方式。如果您正在为 Weka 模块寻找一个定制的透视图,您可以使用工作台模块。

Weka 文档

Weka 团队确实以随每个版本分发的 PDF 文件的形式提供了官方文档,并且怀卡托大学为想要学习 Weka 的开发人员提供了许多视频和支持资源。Weka 手册有 340 多页,如果你想认真了解 Weka,这是必不可少的读物。

The following represent the official Weka documentation from the Weka creators:

  • Weka manual:当前版本的 Weka manual(如【WekaManual-3-8-2.pdf】【WekaManual-3-9-2.pdf】)始终包含在发行版中。对于任何特定的 Weka 版本,手动文件名为WekaManual.pdf

  • Weka book:Weka 团队已经出版了一本书, 数据挖掘——实用的机器学习工具和技术 ,作者是 Witten、Frank 和 Hall。这本书是一本非常好的 ML 参考书。虽然它没有详细介绍 Weka,但它确实涵盖了数据、算法和一般 ML 理论的许多方面。

  • YouTube:Weka YouTube 频道, WekaMOOC ,包含许多有用的 Weka 操作视频。

Weka Explorer

The Explorer is the main Weka interface. Figure 5-15 shows the Weka Explorer upon initialization.img/468661_1_En_5_Fig15_HTML.jpg Figure 5-15

Weka Explorer

Across the top of the Explorer, you will see tabs for each of the key steps you need to accomplish during the model creation phase:

  • 预处理 :“过滤器”是 Weka 对其一套数据预处理例程使用的词。您可以对数据应用过滤器,为分类或聚类做准备。

  • 分类: 分类 选项卡允许您选择分类算法,调整参数,并训练可用于以后预测的分类器。

*** 聚类:聚类 选项卡允许您选择一个聚类算法,调整其参数,并对一个未标记的数据集进行聚类。

*   ***属性***:***属性*** 选项卡允许您选择预测的最佳属性。

*   ***可视化***:***可视化*** 选项卡提供数据集的可视化。2D 图形式的可视化矩阵代表每一对属性。** 

**### Weka 过滤器

You load and prepare your data during ML-Gate 4, the preprocessing phase. Weka uses the term filters to describe the process of transforming your data. In Chapter 2, you explored data preprocessing in general. Within Weka, you have an additional set of internal filters you can use to prepare your data for model building. Table 5-5 shows a summary of the Weka filters grouped by filter type.Table 5-5

Weka 过滤器

|

过滤方式

|

过滤器名称

|
| --- | --- |
| 一般 | 所有过滤器 |
| 一般 | 多重过滤器 |
| 一般 | 重命名 |
| 监督属性 | AddClassification,AttributeSelection,ClassConditionProbabilties,ClassOrder,Discretize,MergeNominalValues,NominalToBinary,PartitionMembership |
| 监督实例 | 类别平衡器、重新取样、展开子取样、分层移除折叠 |
| 无监督属性 | Add,AddCluster,AddExpression,AddID,AddNoise,AddUserFields,AddValues,CartesianProduct,Center,ChangeDateFormat,ClassAssigner,ClusterMembership,Copy,DateToNumeric,Discretize,FixedDictionaryStringToWordVector,InterquartileRange,KernelFilter,MakeIndicator,MathExpression,mergeinfrequentnominalvaluests,MergeManyValues,MergeTwoValues,NominalToBinary,NominalToString,Normalize,NumericCleaner,NumericToBinary,NumericToDate,Numeric |
| 无监督实例 | NonSparseToSparse,Randomize,RemoveDuplicates,RemoveFolds,RemoveFrequentValues,RemoveMisclassified,RemovePercentage,RemoveRange,RemoveWithValues,Resample,ReservoirSample,SparseToNonSparse,SubsetByExpression |

正如你所看到的,有大量的过滤器可用于 Weka 的数据预处理,特别是用于无监督学习的无标签数据。

You can apply filter to data in Weka by pressing the Choose button under the filter section at the top of the Preprocess tab, shown in Figure 5-15.

像所有好的 ML 环境一样,Weka 包含了大量用于数据预处理的 Java 类。如果没有找到您需要的过滤器,您可以修改现有的 Weka 过滤器 Java 代码来创建您自己的自定义过滤器。解压weka-src . jar文件,访问 Weka 过滤器 Java 代码。

在本章后面的分类示例中,您将使用 Wekanumeric nominal过滤器将属性的数据类型从数值型转换为名义型。

如果在构建模型之前需要一个 Java 类来修改数据,Weka 可能会为您提供一个 Java 类过滤器。如果没有,您可以通过修改现有的 Weka 过滤器轻松创建自己的过滤器。

Weka Explorer 主要选项

Weka Explorer 是奇迹发生的地方。您可以使用资源管理器进行分类或聚类。请注意,在使用 预处理 选项卡打开数据集之前,Weka Explorer 中的 分类聚类 选项卡处于禁用状态。

Within the Classify and Cluster tabs at the top of the Weka Explorer are three important configuration sections you will frequently use in Weka:

  • 算法选项

  • 测试选项

  • 用于分类的属性预测值选择(标签)

Figure 5-16 shows these areas highlighted within the Weka Classify tab.img/468661_1_En_5_Fig16_HTML.jpg Figure 5-16

Weka Explorer 分类选项

确认这三个设置后,按下 开始 按钮,Weka 将使用选定的算法进行分类或聚类。

Weka 知识流

The Weka KnowledgeFlow is an alternative graphical front-end to core Weka. KnowledgeFlow implements a dataflow-inspired graphical interface for Weka. Figure 5-17 shows a predefined KnowledgeFlow template opened in Weka KnowledgeFlow. All of the Weka filters, classifiers, clusterers, and data tools are available in the KnowledgeFlow. KnowledgeFlow also includes some extra tools.img/468661_1_En_5_Fig17_HTML.jpg Figure 5-17

Weka 知识流模板

使用 KnowledgeFlow,您可以从调色板中选择 Weka 步骤,并将其放置到布局画布上。Weka 构建模块可以连接在一起,形成一个知识流,可以处理和分析数据。

GUI 的左侧包含所有可用的 Weka 模块。您可以将这些模块作为节点放在画布上。您可以通过右键单击访问其配置参数来单独配置每个节点。您通过连接节点来创建流。执行一个流会产生结果,通常是一个模型生成,或者经常是可视化。

在本章的后面,你将会看到如何用不同的算法来比较多个模型。您将使用 Weka KnowledgeFlow 来比较多个聚类算法,然后使用 KnowledgeFlow 通过生成多个 ROC 曲线来评估多个分类器。

微卡简易 CLI

It is very easy to use graphical tools like KnowledgeFlow to build ML models. However, Java GUI applications often require a large amount of memory and system resources, resources you might prefer to reserve for your data, algorithms, and models. Figure 5-18 shows an alternative to KnowledgeFlow, the Weka Simple CLI Shell.img/468661_1_En_5_Fig18_HTML.jpg Figure 5-18

微卡简易 CLI Shell

Weka Simple CLI Shell 提供对所有 Weka 类的访问,包括算法(分类器和聚类器)和过滤器。这是一个简单的 Weka shell,具有独立的输出和命令行。

在第三章中,当您在 AWS cloud 中运行 Weka 时,您看到了 Weka 命令行界面的示例。简单的 CLI Shell 在本地桌面 Weka 环境中提供了相同的功能。

The following commands are available in the Simple CLI:

  • java[]:用给定的参数调用 Java 类

  • 中断 :友好地停止当前线程,如运行分类器

  • 杀死 :以不友好的方式停止当前线程

  • :清除屏幕

*** 能力[]:列出指定类的能力

*   ***退出*** :退出简单的 CLI Shell

*   ***帮助*** :提供可用命令的概述** 

**The Weka Simple CLI Shell is powerful because all of the filters and implementations of the algorithms have a uniform command-line interface. The following example shows how to train and test a random forest classifier with multiple filters from the command line. The MultiFilter operation handles the concatenation of filters.001   java -classpath weka.jar weka.classifiers.meta.FilteredClassifier -t data/ReutersCorn-train.arff -T data/ReutersCorn-test.arff -F "weka.filters.MultiFilter -F weka.filters.unsupervised.attribute.StringToWordVector -F weka.filters.unsupervised.attribute.Standardize" -W weka.classifiers.trees.RandomForest -- -I 100 It is also possible to train and save a model using the –t and –d options:001   java -classpath weka.jar weka.classifiers.meta.MultiClassClassifier -t data/iris.arff -d rf.model -W weka.classifiers.trees.RandomForest -- -I 100 A serialized model can also be loaded and used for predictions using the –serialized option to load the model and the –i option to load the input data:001   java -classpath weka.jar weka.filters.supervised.attribute.AddClassification -serialized rf.model -classification -i data/iris.arff -o predict-iris.arff

如果您试图在命令行中将太多的函数串在一起,事情会变得复杂。如果您希望加载模型、训练模型、应用过滤器和保存模型,使用 Weka KnowledgeFlow 界面连接各个节点会更容易。接下来您将看到如何做到这一点。

5.5 Weka 聚类算法

在第四章中,我讨论了聚类,即在无标签数据集中发现结构的过程。像大多数好的 ML 环境一样,Weka 有大量的聚类算法。

In this section, you will see how to implement clustering for the three most useful clustering ML algorithms as presented in Chapter 4:

  • k 均值聚类

  • 期望最大化聚类

  • 基于密度的聚类(DBSCAN)

如果您有兴趣探索其他聚类算法,只需替换您选择的算法。

使用 DBSCAN 进行聚类

DBSCAN 算法是 Weka 软件包管理器中的一个“可用”软件包。安装 DBSCAN 聚类算法后,它将作为 Weka 软件包中的一个聚类选项。

对于这个聚类示例,您将使用旧的 Faithful geyser 数据集。原始数据集可在www . stat . CMU . edu/~ Larry/all-of-statistics/= data/faithful . dat获取。

Old Faithful is the famous geyser in Yellowstone National Park that erupts regularly approximately once per hour. The dataset, collected in 1990, includes 272 observations on two variables. The two variables are

  • 喷发时间:以分钟为单位表示喷发时间的数值

  • 等待时间:以分钟为单位,代表到下一次喷发的等待时间的数值

Table 5-6 shows the first ten instances of the dataset. The original data file name is old-faithful-data.dat. It does not contain a header row and contains fields separated by spaces. The modified file used in this example is old-faithful-data.csv. The file is contained in the book resources in the Chapter 5 folder. It does contain a header row and comma-separated values. The OpenCalc spreadsheet program created the CSV file.Table 5-6

老忠实喷泉数据集(前 10 个实例),(阿扎利尼和鲍曼,1990 年)

|

实例 ID

|

喷发时间

|

等待时间

|
| --- | --- | --- |
| one | Three point six | Seventy-nine |
| Two | One point eight | Fifty-four |
| three | Three point three three three | Seventy-four |
| four | Two point two eight three | Sixty-two |
| five | Four point five three three | eighty-five |
| six | Two point eight eight three | Fifty-five |
| seven | Four point seven | Eighty-eight |
| eight | Three point six | eighty-five |
| nine | One point nine five | Fifty-one |
| Ten | Four point three five | eighty-five |

Using the Weka Explorer , it is straightforward to perform a DBSCAN cluster on the data, as shown in the steps below.

    从 Weka GUI 选择器启动 Weka Explorer 应用程序。

    预处理 页签中,点击 打开文件 ,打开old-faithful-data . CSV文件。您可能需要告诉 Weka CSV 加载程序,这些值以“,”分隔,并且NoHeaderRowPresent为假。当数据加载时,您将看到实例的摘要,包括两个属性:爆发和等待。

    点击 集群 标签。

    下,点击 选择 按钮选择算法。

*** 5.

从可用的聚类分析算法列表中选择 DBSCAN 算法。如果 DBSCAN 不可用,您将需要使用 Weka 软件包管理器安装它。

 *   6.

单击 DBSCAN 算法框中的文本。您将能够输入 DBSCAN 算法参数。为 Epsilon 输入. 11,为 NumPts 输入 6。点击 ***确定*** 。

 *   7.

点击 ***开始*** 对数据集执行 DBSCAN 聚类算法。处理完成后,将显示结果。

 **

**Figure 5-19 shows the completed DBSCAN clustering results.img/468661_1_En_5_Fig19_HTML.jpg Figure 5-19

旧忠实数据集的 DBSCAN 聚类

结果显示,该算法为所有 272 个实例识别出两个聚类。集群 0 总共接收了 175 个实例,而集群 1 接收了 97 个实例。

Each time you run a cluster or classification in Weka, the Results list on the left panel updates with a new entry. Right-clicking a results entry provides the option to visualize the results. You can also click the Visualize tab at the top of the Weka Explorer. Figure 5-20 shows the visualization of the two DBSCAN clusters. When you first click the Visualize tab, you will see a matrix of visualizations. Weka prepares charts for all combinations of the attributes. In this case, the one you are interested in maps the waiting time and eruption time on the X and Y axes. You can select this specific chart from the matrix, or you can use the X and Y drop-down boxes to populate the desired attributes for the X and Y axes.img/468661_1_En_5_Fig20_HTML.jpg Figure 5-20

DBSCAN 聚类的可视化

You can visualize any two of the attributes, one on the X-axis and another on the Y-axis. In this case, there are actually four attributes:

  • 喷发时间间隔

  • 等待时间间隔

  • 实例 ID

  • 一个新创建的属性,用于保存生成的分类 ID。实际上,您现在已经有了一个带标签的数据集,稍后您将利用它。

可视化数据时,选择将喷发和等待时间放在轴上的图。绘制其他属性并不特别有趣。选择正确的属性后,如图 5-20 所示,可视化提供了关键的洞察力。由该算法识别的两个聚类被颜色编码。

你可以从可视化中获得的关键见解是,这两个不同的集群代表了老忠实间歇泉运行的两种“模式”。

You can adjust the algorithm parameters if you wish to fine-tune the clusters. Notice that some of the data points in the middle area are borderline in determining to which cluster they belong. Figure 5-21 shows adjustments to the DBSCAN algorithm parameters. Some algorithms have many parameters; the DBSCAN algorithm only has two parameters.img/468661_1_En_5_Fig21_HTML.jpg Figure 5-21

DBSCAN 算法参数调整

By changing the epsilon parameter and the numPoints parameter, you can tighten up the tolerance of the clusters. After changing the parameters, click OK and then press Start to commence another clustering. Figure 5-22 shows the new results.img/468661_1_En_5_Fig22_HTML.jpg Figure 5-22

更新的 DBSCAN 聚类结果

In this case, the algorithm identified noise in the data. In total, 11 instances fell in the boundary area. Right-click the newest DBSCAN result in the results list to show the new visualization, shown in Figure 5-23.img/468661_1_En_5_Fig23_HTML.jpg Figure 5-23

由 DBSCAN 识别的数据中的噪声

圈出的数据点没有聚类到两个聚类中的任何一个。在本例中,您有更紧密的集群。通过调整算法参数,您实际上使用了 DBSCAN 算法来识别异常值,这是该算法的优势之一,如果您还记得第四章的话。

知识流聚类

您已经看到了基于密度的聚类算法 DBSCAN 在对旧的忠实数据集进行聚类时的表现。现在让我们比较来自另外两种聚类算法 k-means 和 EM 的结果。您可以使用 Weka KnowledgeFlow 应用程序来简化比较过程,而不是像在 Weka Explorer 中使用 DBSCAN 那样运行独立的测试。

虽然知识流图形用户界面没有你在图 5-2 和图 5-3 中看到的 RapidMiner 和 KNIME 那么时尚,但知识流应用程序具有相同的功能。

The KnowledgeFlow application contains several very useful templates you can use to build layouts. KnowledgeFlow includes the following templates:

  • 交叉验证

  • 学习并保存模型

  • 两个分类器的 ROC 曲线

  • 增量学习和评估朴素贝叶斯

  • 比较两个集群

  • 两种属性选择方案

  • 将各种图表保存到文件中

  • 可视化预测边界

  • 将作业参数化

可以加载、修改和保存布局。知识流布局使用。kf 分机。书籍资源包括两种布局,您可以加载这两种布局来比较我们讨论的所有三种聚类算法。

Figure 5-24 shows the two layouts available with the book resource download: cluster-3-csv-cross-fold.kf uses k-fold cross-validation while cluster-3-csv-split.kf uses a simple split of the data for training and testing. Both of the KnowledgeFlow examples load the CSV dataset old-faithful-data.csv.img/468661_1_En_5_Fig24_HTML.jpg Figure 5-24

知识流布局:比较三种聚类算法

构建知识流的过程很简单。您只需从左侧面板中选择节点,并将它们添加到画布中。知识流应用程序将节点组织成可扩展的类别,包括数据源、过滤器、分类器、聚类器、可视化等。

When nodes placed onto the canvas, there are two configuration operations:

  • 双击节点将提供对节点配置参数的访问,包括算法参数。

  • 右键单击一个节点将提供对节点选项的访问,包括将该节点连接到其他节点的重要任务。

图 5-23 显示了加载到 Weka KnowledgeFlow 应用程序中的cluster-3-CSV-splt . KF

Descriptive notes can also be included on the canvas, as shown in Figure 5-25.img/468661_1_En_5_Fig25_HTML.jpg Figure 5-25

知识流布局:三个集群比较

The following steps illustrate how to create the three-cluster comparison starting with a blank canvas:

    将以下节点添加到知识流画布,如图 5-25 所示进行排列:

    【csvloader】

    ** 集群中,

    -K-表示 集群者,

    DBSCAN Clusterer、

    3 xclusterperformanceevaluator

    【文本查看器】**
    *** 2.

    双击 CSVLoader ,将文件名设置为old-faithful-data . CSV文件。

    * 3.

    右键点击 CSVLoader ,选择 数据集 。将 数据集 连接器拖到trainttestsplitmaker上。

    * 4.

    双击trainttestsplitmaker,将训练百分比设置为 66%或您选择的数字。

    * 5.

    右键单击trainttestsplitmaker,选择 trainingSet ,拖动 trainingSet 连接器到 EM Clusterer 节点。对其他两个集群重复上述步骤。

    * 6.

    右键单击TrainTestSplitMaker,选择 testSet ,拖动 testSet 连接器到 EM Clusterer 节点,对另外两个 Clusterer 重复上述操作。

    * 7.

    右键单击 EM Clusterer 节点,选择 batchClusterer ,拖动 batchClusterer 连接器到第一个clustererperperformanceevaluator。对其他两个集群器节点重复上述操作。

    * 8.

    右键单击每个clusterperformanceevaluator,选择文本,将文本连接符拖动到 TextViewer

    **

**知识流完全配置后,您可以通过单击布局顶部的右侧播放箭头来执行该流。在流程执行时,知识流会在底部面板中记录进度状态。

When all of the tasks successfully complete, KnowledgeFlow will mark status as OK, as shown in Figure 5-25. At this point, you can right-click the TextViewer to show the results. Figure 5-26 shows the Result List.img/468661_1_En_5_Fig26_HTML.jpg Figure 5-26

知识流文本查看器结果

结果列表 包括三种聚类算法的报告:DBSCAN、EM 和 k-means。

Weka KnowledgeFlow 接口为您提供了一种非常有用的方法来试验聚类算法。您可以轻松地双击一个聚类算法,更新其参数,然后重新运行流程。在决定哪种算法最适合您的 CML 聚类问题时,它是一个非常有用的工具。

5.6 Weka 分类算法

实现聚类算法来发现未标记数据中的隐藏模式,就像你在 Old Faithful 中看到的那样,非常有趣。然而,分类问题展示了 CML 算法更实际的应用。接下来,您将回顾四种常用分类算法,并了解它们对第二章中的 PAMAP2_Dataset 的分类效果。

在你开始之前,你必须确定你有一个明确的问题。

在这一部分中,您的目标是构建一个模型,该模型可以根据一个人携带的设备的传感器数据来预测他当前的活动。在第六章中,您将创建一个 Android 应用程序,它可以通过使用预构建的模型进行预测来准确地确定设备用户的当前活动状态。Android 移动设备具有与 PAMAP2_Dataset 集合中的参与者所使用的专用硬件类似的传感器功能。如果您构建了一个相当准确的模型,您应该能够预测移动设备用户的当前活动。这种活动监控应用可能会在医疗保健、健身或安全应用方面有潜在用途。

预处理(数据清理)

回想一下,PAMAP2_Dataset 是一个大型的带标签数据集,由佩戴传感器的受试者在执行 19 种不同活动时生成。

数据集包含来自多个主题的数据。并非所有的受试者都记录了所有的活动。为了训练您的模型,您将使用来自 主题 101 的数据。数据集提供了一个文档【PerformedActivitiesSummary.pdf】,用来汇总每个主体的活动。

You will clean the dataset to produce a subset that is appropriate for your well-defined problem. There are two reasons why you want to clean the dataset:

  • 以减小数据集的大小。这些文件非常大,其中包含大量冗余信息。

  • 您的目标 Android 设备没有原始数据收集中受试者使用的所有传感器。保留 Android 设备无法复制的传感器数据毫无意义。

表 2-4 显示了原始数据集的结构。数据集附带的文件记录了这个结构。原始数据集文件很大。它们每个都包含超过 300,000 个实例(行)和 54 个属性(列)。在继续创建模型之前,您需要清理数据。

**Follow the steps below to produce the cleaned dataset, subject101-cleaned.csv. Note that the column numbers shown are 1-relative values.

    在 Open Office Calc 中打开原来的 subject101.dat 文件,将 CSV 文件另存为 subject101.csv 。图 2-5 显示了加载到打开的 Office Calc 电子表格中的数据集。Calc 将原来的subject 101 . dat文件转换为逗号分隔的版本,subject 101 . CSV。您将清理这个 CSV 文件。

    删除时间戳属性(列 1)。该数据集不打算作为时间序列数据。每个实例都可以独立作为当前活动的预测器。

    删除心率属性(第 2 列)缺少值(NaN)的任何实例。收集的传感器提供快速数据流,只有十分之一的样本包括心率。当缺少此属性时,对数据进行筛选会减小数据的大小,但不会降低数据的重要性。

    删除心率属性(第 2 列)。你无法在 Android 上使用这个属性。

    删除第 21-37 列,胸部传感器数据。Android 设备只有一个传感器,所以我们假设它是基于手的。基于手的传感器数据包括在列 4-20 中。

    删除列 38-54,脚传感器数据。Android 设备只有一个传感器,所以我们假设它是基于手的。基于手的传感器数据包括在列 4-20 中。

    在基于手的传感器数据中,您只需要保存加速度计、陀螺仪和磁力计数据。删除第 1、5-7 和 14-17 栏。

    添加一个标题行来描述剩余的 10 列。

The resulting cleaned file has only 10 attributes (columns) and 22,846 instances. It is much smaller at 1.8MB compared to the original file of 138MB. The first few records of the new structure of subject101-cleaned.csv are shown below, including the header row:001   activityID,accelX,accelY,accelZ,gyroX,gyroY,gyroZ,magnetX,magnetY,magnetZ 002   1,2.301,7.25857,6.09259,-0.0699614,-0.01875,0.004568,9.15626,-67.1825,-20.0857 003   1,2.24615,7.4818,5.55219,-0.431227,0.002686,-0.06237,9.14612,-67.3936,-20.5508 004   1,2.3,7.10681,6.09309,0.07569,-0.0307922,0.005245,9.69163,-67.0898,-21.2481 005   1,2.49455,7.52335,6.17157,-0.259058,-0.267895,-0.03858,9.58694,-67.0882,-20.8997 006   1,2.71654,8.30596,4.78671,0.377115,-0.0236877,-0.02095,8.59622,-67.1486,-20.1947 007   1,2.54954,7.63122,5.55623,-0.487667,-0.0199,-0.0894,9.00159,-66.0543,-22.5021 008   1,2.82407,6.1449,5.06502,-0.781563,0.198873,-0.213285,10.5845,-63.7955,-27.5879 009   1,2.73626,7.94195,6.52017,-0.472414,0.279868,0.03655,12.2658,-64.6618,-27.0379 010   1,2.38894,7.4883,6.40103,0.3579,1.04661,0.346204,12.1033,-62.2186,-30.1344 011   1,1.8132,6.85639,7.35672,0.360442,1.2873,0.1226,14.9204,-62.7273,-28.6676 012   1,0.0125249,5.2733,6.95022,0.440524,1.19843,0.1064,16.6466,-63.2981,-25.9161 013   1,-0.530751,7.62191,6.04895,0.179548,1.05112,0.23129,18.111,-64.9924,-19.2388 014   1,-1.65419,7.6992,5.22362,1.51583,0.83644,0.283502,18.1058,-65.8251,-13.6928 015   1,-1.09215,7.20128,5.19524,1.22541,0.65619,0.19038,17.0806,-68.1161,-8.61366

该文件在第一列包含重要的 ActivityID 。这个属性就是标签。列 2-10 包含加速度计(X,Y,Z)、陀螺仪(X,Y,Z)和磁力计(X,Y,Z)数据。

Table 5-7 shows a list of the ActivityIDs and their occurrences in the cleaned dataset. There are 22,846 total instances in the cleaned dataset, which should be a sufficient dataset size to produce a good model. The Android app will use the model to predict these ActivityIDs based on the device sensor input.Table 5-7

活动 ID 事件-主题 101

|

ActivityID(活动 ID)

|

活动名称

|

实例数量

|
| --- | --- | --- |
| one | 说谎的 | Two point four eight six |
| Two | 坐着的 | Two thousand one hundred and forty-six |
| three | 直立的 | One thousand nine hundred and eighty-four |
| four | 步行 | Two thousand and thirty-five |
| five | 运转 | One thousand nine hundred and forty-one |
| six | 自行车运动 | Two thousand one hundred and fifty-six |
| seven | 北欧式行走 | One thousand eight hundred and fifty-two |
| Twelve | 上升的楼梯 | One thousand four hundred and fifty-two |
| Thirteen | 下楼梯 | One thousand three hundred and sixty-two |
| Sixteen | 用真空吸尘器打扫 | Two thousand and ninety-seven |
| Seventeen | 熨烫 | Two thousand one hundred and fifty-five |
| Twenty-four | 跳绳 | One thousand one hundred and eighty |

有了一个更小、更相关的数据文件,现在就可以将subject 101-cleaned . CSV文件加载到 Weka 中了。

启动 Weka,从 GUI 选择器中选择 Weka Explorer,点击 预处理 标签下的 打开文件 。浏览到subject 101-cleaned . CSV的位置并选中。

因为您导入了 CSV 文件,所以您无法完全控制如何处理属性的数据类型。对于这个数据集,所有的属性都是数字,除了activity id 是一个名义值。回想一下表 5-7 ,每个值代表一项活动。要纠正这个问题,您需要使用 Weka 过滤器 将数值 ActivityID 属性转换为名义数据类型。

Figure 5-27 shows the Weka Explorer after the data import and after the ActivityID attribute was converted to a nominal data type.img/468661_1_En_5_Fig27_HTML.jpg Figure 5-27

已使用过滤器清理 PAMAP2_Dataset

Figure 5-26 shows the Weka NumericToNominal filter applied to Attribute1. Note that in the filter option box, the filter only applies to the first attribute.

如果将 CSV 数据导入 Weka,然后应用预处理过滤器,将数据重新保存为 ARFF 格式会很有帮助。ARFF 文件格式可以将数据类型与数据一起存储,因此在该过程的后续阶段不需要数据转换过滤器。

数据现在可以进行分类了。接下来,使用随机森林算法开始分类分析。

分类:随机森林算法

一旦数据准备好了,对数据进行分类就很容易了。在第四章中,轶事证据表明 RF 算法通常表现最佳。您将看到这是否适用于清理后的 PAMAP 数据集。

To classify data in the Weka Explorer, follow these steps:

    在 Weka 浏览器中选择 分类 标签。

    按下 选择 按钮选择分类算法。

    选择测试选项。您将尝试 2/3 分割和 10 倍交叉验证来评估所选的算法。

    选择 ActivityID 作为属性进行分类。

    如果需要,在选项框中单击以更改任何特定于算法的选项。

    按下 开始 按钮,等待分类完成。这可能很快,也可能需要很长时间,具体取决于数据大小、属性数量、算法复杂性或迭代等算法选项。

    点击 结果列表 查看结果,包括分类准确率和混淆矩阵。

Each algorithm has its own parameters with which you can experiment. For RF, one of the most important parameters is iterations, which determines how many decision trees the algorithm will use. Figure 5-28 shows the RF algorithm option box.img/468661_1_En_5_Fig28_HTML.jpg Figure 5-28

随机森林算法选项

迭代 的默认值为 100。对于您的测试,您将运行四个测试,使用迭代的值 10 和 100,并使用两个测试选项,2/3 分割和 10 倍交叉验证。

Figure 5-29 shows the results of one RF classification with iterations=100 and using the 10-fold cross-validation test option.img/468661_1_En_5_Fig29_HTML.jpg Figure 5-29

随机森林算法分类

Because your predictive attribute is a nominal data type, Weka provided a confusion matrix. The confusion matrix is included last. You can scroll back through the results window to see the classification accuracy. Right-click the Results List entry if you wish to save the results to a file. The following results show that the RF classification was very successful.001   === Run information === 002 003   Scheme: weka.classifiers.trees.RandomForest -P 100 -I 100 -K 0 -M 1.0 -V 0.001 -S 1 004   Relation:     subject101-cleaned-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst 005   Instances:    22846 006   Attributes:   10: activityID, accelX, accelY, accelZ, gyroX, 007                     gyroY, gyroZ, magnetX, magnetY, magnetZ 008   Test mode:    10-fold cross-validation 009 010   === Classifier model (full training set) === 011 012   RandomForest 013   Bagging with 100 iterations and base learner 014   weka.classifiers.trees.RandomTree -K 0 -M 1.0 -V 0.001 -S 1 -do-not-check-capabilities 015   Time taken to build model: 16.45 seconds 016 017   === Stratified cross-validation === 018   === Summary === 019 020   Correctly Classified Instances       20678               90.5104 % 021   Incorrectly Classified Instances      2168                9.4896 % 022   Kappa statistic                          0.8961 023   Mean absolute error                      0.0405 024   Root mean squared error                  0.12 025   Relative absolute error                 26.6251 % 026   Root relative squared error             43.4728 % 027   Total Number of Instances            22846 028 029   === Confusion Matrix === 030 031       a    b    c    d    e    f    g    h    i    j    k    l   <-- classified as 032    2433   17   15    1    2    2    4    2    2    3    0    5 |    a = 1 033      27 2041   14    3    1    6    9   10    4   18    7    6 |    b = 2 034      14    6 1910    5    2    7   11    4    7    2   12    4 |    c = 3 035      56    2    2 1737    1    0   34   99   38   58    8    0 |    d = 4 036      20    2    0    2 1856    5    5    9    2    9   23    8 |    e = 5 037      10    0    2    2   10 2026   21    2   13   18   51    1 |    f = 6 038      14    8    1   55   11   24 1615   28   19   25   22   30 |    g = 7 039       0    3    2  137    6    5   31 1064   86  105    7    6 |    h = 12 040       1    2    3   53    1    7   42   61 1063  120    7    2 |    i = 13 041       0    3    9   33   14   42   37   22   23 1886   10   18 |    j = 16 042       3    6   10    6    8   22   24    4    3   12 2051    6 |    k = 17 043      29    3   11   11   36    7   41    2    8    5   31  996 |    l = 24

分类准确率为 90.5%。如果你向下看混淆矩阵的对角线,从相对较大的值可以明显看出,RF 算法做得非常好。

您可以在主对角线外看到一些相对较大的数字,例如 039 行上的 137 实例。这些实例表示 ActivityID 12(上楼梯)被错误地归类为 ActivityID 4(步行)。下一个最高的数字是 120 个实例(行 040 ),代表活动 13(下楼梯),被错误地分类为活动 ID 16(真空清洁)。

RF 算法达到的 90%的准确率很好地表明,你的 Android 应用程序将成功地对用户的活动进行分类。接下来,您将看到其他分类算法是否能与 RF 的性能相匹配。

分类:K-最近邻

回想一下,KNN 算法是一种懒惰学习算法。Weka 包含了 KNN 的一个优秀的修改版本,叫做 KStar,或 K。你可以从怀卡托大学的研究论文中了解 K的细节以及它是如何改善 KNN 的:

www . cs . waikato . AC . NZ/~ ml/publications/1995/cleary 95-kstar . pdf

KStar is available under the lazy folder when you select Choose under the classifier section of the Weka Explorer. Figure 5-30 shows the default KStar options.img/468661_1_En_5_Fig30_HTML.jpg Figure 5-30

Weka KNN 算法(KStar)选项

Classifying the subject101-cleaned.arff data with the KStar algorithm achieves the following results:001   === Run information === 002 003   Scheme:       weka.classifiers.lazy.KStar -B 20 -M a 004   Relation:     subject101-cleaned-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst 005   Instances:    22846 006   Attributes:   10 007   Test mode:    split 66.0% train, remainder test 008 009   === Classifier model (full training set) === 010 011   KStar options : -B 20 -M a 012   Time taken to build model: 0 seconds 013 014   === Evaluation on test split === 015 016   Time taken to test model on test split: 2512.94 seconds 017 018   === Summary === 019 020   Correctly Classified Instances        6434               82.827  % 021   Incorrectly Classified Instances      1334               17.173  % 022   Kappa statistic                          0.8119 023   Mean absolute error                      0.0339 024   Root mean squared error                  0.1435 025   Relative absolute error                 22.2521 % 026   Root relative squared error             51.9942 % 027   Total Number of Instances             7768 028 029   === Confusion Matrix === 030 031      a   b   c   d   e   f   g   h   i   j   k   l   <-- classified as 032    806  20   9   2   0   0   1   0   2   0   1   0 |   a = 1 033     11 689   8   4   0   3   4   0   1   1   0   1 |   b = 2 034      4   4 669   3   1   1   3   0   0   1   1   1 |   c = 3 035     17   7  25 566   2   2  10  35  11  11   3   2 |   d = 4 036      4   2   7   4 612   3   5   5   2   7   2   6 |   e = 5 037      7   4   2   2   6 677   4   1   7   6  20   0 |   f = 6 038      5  15   9  37   5  27 447  13  19  20  16  16 |   g = 7 039      0  11  22  74   0   6  11 305  35  28   3   4 |   h = 12 040      0   8  46  40   0   8   9  31 289  28   4   1 |   i = 13 041      0  10  24  53   3  30  13  22  46 512   3   3 |   j = 16 042      3  11  23   7  13  54  11   7   4  20 563  11 |   k = 17 043     12   5  19  10  13   4  14   4   6   7   0 299 |   l = 24

KStar 算法达到了令人印象深刻的 82.8%的准确率。混淆矩阵主对角线看起来很干净,包含的数字比主对角线上的错误分类多得多。

KNN 式算法的主要问题是大型数据集的测试时间。您有一个大型数据集,如果仔细观察,您会发现该模型需要 2500 多秒(41 分钟)来对数据进行分类(Windows 桌面中的英特尔 i7 CPU)。因此,使用 10 倍交叉验证测试选项是不可行的。相反,您指定了分割(2/3 训练,1/3 测试)测试选项。使用 10 重交叉验证将花费大约 10 倍的时间。

总的来说,KNN 的精确度与射频相当,但是对于这个数据集来说,预测所花费的时间是有问题的。

分类:朴素贝叶斯

NB 算法是基于概率的分类方法。要在 Weka 中使用 NB 进行分类,请从分类器 选择 部分选择算法。如果朴素贝叶斯不可用,请确保选择 活动 ID 作为要分类的属性。朴素贝叶斯要求属性是名义数据类型,只有 ActivityID 符合这个标准。

Recall from Chapter 4, NB is well suited for 2-class classification. In order to use NB for multi-class data, you need to use the kernel trick. Figure 5-31 shows the kernel setting in the NB options screen. You need to set useKernelEstimator to true. Failure to do this will result in random output from the classifier.img/468661_1_En_5_Fig31_HTML.jpg Figure 5-31

朴素贝叶斯内核设置选项

Start the classification and you will see the following naive Bayes classification results :001   === Run information === 002 003   Scheme:       weka.classifiers.bayes.NaiveBayes -K 004   Relation:     subject101-cleaned-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst 005   Instances:    22846 006   Attributes:   10 007   Test mode:    split 66.0% train, remainder test 008 009   === Classifier model (full training set) === 010 011   Naive Bayes Classifier 012   Time taken to build model: 0.09 seconds 013 014   === Evaluation on test split === 015 016   Time taken to test model on test split: 25.44 seconds 017 018   === Summary === 019 020   Correctly Classified Instances        5644               72.6571 % 021   Incorrectly Classified Instances      2124               27.3429 % 022   Kappa statistic                          0.7004 023   Mean absolute error                      0.0578 024   Root mean squared error                  0.1803 025   Relative absolute error                 37.9502 % 026   Root relative squared error             65.3628 % 027   Total Number of Instances             7768 028 029   === Confusion Matrix === 030 031      a   b   c   d   e   f   g   h   i   j   k   l   <-- classified as 032    762  21  15   0   7   3   5   1   2   6  16   3 |   a = 1 033      0 635  25   6   0   4   5   1   6   9  22   9 |   b = 2 034      1  15 603   7   7  12  16   0  16   5   6   0 |   c = 3 035     17  31  16 406  16   8  21  67  42  53  10   4 |   d = 4 036      6   8   5   3 540   4  12   5   6  22  22  26 |   e = 5 037      6  13   6   1   6 660   4   1   8   4  27   0 |   f = 6 038      6  23   5  67  38  34 292  29  30  29  42  34 |   g = 7 039      0  24  15  96   5  12  31 201  62  39  10   4 |   h = 12 040      0  27  15  60   6  19   8  38 234  38  18   1 |   i = 13 041      0  11   9  54  14  33  32  11  22 508  12  13 |   j = 16 042      2  23  13   3  24  84  13   0   5   4 542  14 |   k = 17 043      8   9  22   5  25   6  21   0  14  11  11 261 |   l = 243

该算法达到了 72.7%的准确率。还不错,但不如射频和 KNN。然而,NB 确实比 KNN 快得多,使用 2/3 分割测试模式仅用了 25 秒就完成了分类。

分类:支持向量机

相对于神经网络 DL 算法,SVM 算法越来越受欢迎。Weka 提供了 SMO(序列最小优化)算法来实现支持向量分类器。

If you run the SMO algorithm using default options , the results will be poor. Weka makes it easy to tune the algorithm options. Figure 5-32 shows the option panel for the SMO algorithm. In order to achieve better results, change the following options:

  • 设置复杂度参数 c = 2.0。

  • 将校准器设置为 SMO。

  • 将公差参数更改为 0.1。

  • 使用默认参数将内核设置为 PUK。

img/468661_1_En_5_Fig32_HTML.jpg Figure 5-32

Weka SMO 算法选项

The SMO classifier output :001   === Run information === 002 003   Scheme:       weka.classifiers.functions.SMO -C 2.0 -L 0.1 -P 1.0E-12 -N 0 -V -1 -W 1 -K "weka.classifiers.functions.supportVector.Puk -O 1.0 -S 1.0 -C 250007" -calibrator "weka.classifiers.functions.SMO -C 1.0 -L 0.001 -P 1.0E-12 -N 0 -V -1 -W 1 -K "weka.classifiers.functions.supportVector.PolyKernel -E 1.0 -C 250007" -calibrator "weka.classifiers.functions.Logistic -R 1.0E-8 -M -1 -num-decimal-places 4"" 004   Relation:     subject101-cleaned-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst 005   Instances:    22846 006   Attributes:   10 007   Test mode:    split 66.0% train, remainder test 008 009   === Classifier model (full training set) === 010 011   SMO 012   Kernel used: 013     Puk kernel 014   Classifier for classes: 1, 2 015   BinarySMO 016   Time taken to build model: 108.91 seconds 017 018   === Evaluation on test split === 019 020   Time taken to test model on test split: 28.28 seconds 021 022   === Summary === 023 024   Correctly Classified Instances        6426               82.724  % 025   Incorrectly Classified Instances      1342               17.276  % 026   Kappa statistic                          0.8107 027   Mean absolute error                      0.1399 028   Root mean squared error                  0.2571 029   Relative absolute error                 91.8675 % 030   Root relative squared error             93.177  % 031   Total Number of Instances             7768 032 033   === Confusion Matrix === 034 035      a   b   c   d   e   f   g   h   i   j   k   l   <-- classified as 036    801   5  21   0   0   4   1   1   8   0   0   0 |   a = 1 037     19 665  14   3   0   6   3   5   1   3   1   2 |   b = 2 038      2  15 640   8   1   5   7   2   5   1   2   0 |   c = 3 039      2   4  14 493   8   1  22  45  20  70  12   0 |   d = 4 040      0   0   9   2 605  13   1   5   1   4  18   1 |   e = 5 041      3  12   6   2   2 658   4   0   4  14  30   1 |   f = 6 042      7  28   2  35   8  25 456  33  11   5   8  11 |   g = 7 043      1  11  20  68   0   2   7 297  29  60   3   1 |   h = 12 044      0   6  12  28   0   2  21  66 260  64   5   0 |   i = 13 045      0   5  14  15   6  23  16  10  10 618   1   1 |   j = 16 046      1  15  23   3   1  29   9   5   2   4 633   2 |   k = 17 047      2   6  28   7  10   5  12   2   6   9   6 300 |   l = 24

Weka SMO 算法在清理后的数据集上达到了 82.7%的准确率。结果与 KNN 算法大致相同,但是对于 22,000 多个实例,训练和测试所用的时间仅为 2 分钟。接下来,您将更详细地了解这些分类算法的结果。

5.7 Weka 模型评估

评估 ML 模型时,需要考虑许多因素。

You are trying to place ML models at the edge, so you need to think carefully about how your model affects the limited resources of the target device. While accuracy is the most visible performance measure, build time and test time also are important. Table 5-8 shows a summary of the classifier’s performance for the subject101-cleaned.arff dataset.Table 5-8

分类-算法性能摘要

|

算法

|

训练方法

|

构建时间(秒。)

|

测试时间(秒。)

|

准确度(%)

|
| --- | --- | --- | --- | --- |
| 射频 (i=10) | 十倍交叉值。 | One point seven | NR | 87.7% |
| 射频 (i=10) | 2/3 分割 | One point eight | Zero point two | 86.4% |
| 射频 (i=100) | 十倍交叉值。 | Sixteen point five | NR | 90.5% |
| 射频 (i=100) | 2/3 分割 | Sixteen point five | One point three | 90.0% |
| 近邻算法 | 十倍交叉值。 | 地下城与勇士 | 地下城与勇士 | 地下城与勇士 |
| 近邻算法 | 2/3 分割 | Zero point one | Two thousand five hundred and thirteen | 82.8% |
| 朴素贝叶斯 | 十倍交叉值。 | Zero point one | NR | 72.9% |
| 朴素贝叶斯 | 2/3 分割 | Zero point one | Twenty-five point four | 72.7% |
| SVM/SMO (c=2) | 十倍交叉值。 | One hundred and eleven | NR | 83.4% |
| SVM/SMO (c=2) | 2/3 分割 | One hundred and nine | Twenty-eight | 82.7% |

请注意 DNF(未完成)为 KNN 输入的 10 倍测试选项。这意味着它中止了操作,因为花费的时间太长。

注意具有 10 倍交叉验证的测试时间的 NR(未报告)条目。使用 k 倍交叉验证测试选项时,Weka 不报告总训练时间。然而,如果您回忆图 4-10 ,您可以将测试训练时间乘以 k 来确定测试时间的估计值,假设您使用 90/10 分割进行 10 倍交叉验证。

A summary of observations from the table of results:

  • RF 可获得最佳精度结果。

  • 考虑到精度与训练/测试时间的权衡,RF 处于最佳状态。

  • 在分割上使用 10 倍交叉验证测试选项将分类器的准确性提高了 1%。

  • KNN 测试时间很长。由于算法的惰性,该算法对每个预测执行大量的计算。

  • SVM/SMO 的培训时间很长。这是因为该算法创建了如此多的支持向量。

这些发现证实了图 4-17 中所示算法的相对性能。尽管只有 RF 达到了 90%的准确度,但通过进一步调整算法选项,所有算法的结果都可能得到改善。

在选择最佳模型时,我还没有讨论的另一个非常重要的因素是模型大小。您需要一个可以存储在边缘设备中的模型。由于其尺寸,这种设备通常具有有限的存储器和 CPU 资源。我将在第六章中进一步讨论这个重要因素。

多重 ROC 曲线

除了算法准确性之外,让我们看看您的分类结果的 ROC 曲线。ROC 曲线绘制了真阳性率(TPR)对假阳性率(FPR)的曲线。ROC 曲线在两类情况下工作得最好,但是您可以通过挑出一类并与其他类进行比较来将类似于subject 101-cleaned . ARFF的多类问题转化为两类情况。

您将使用 Weka 知识流应用程序来生成 ROC 比较图。从 Weka GUI 选择器中打开知识流窗口,并从图书资源中打开 Classify-4.kf 文件。

Classify-4.kf  is a knowledge flow example that performs the following actions when executed:

  • subject 101-cleaned . ARFF加载数据。

  • 它准备对数据进行 10 重交叉验证,以发送给 RF 和 NB 分类器。

  • 它准备将数据分成 2/3 份发送到 KNN 和 SVM/SMO 分类器。这些分类器需要更长的时间来测试实例,所以要避免 10 重交叉验证测试选项。

  • 四个分类器执行它们的分类。

  • 结果被发送到图表模块,该模块可以显示多个 ROC 曲线的图像。

  • 结果也保存在文本文件中。

Figure 5-33 shows the Classify-4.kf  layout including the status window after the flow executes.img/468661_1_En_5_Fig33_HTML.jpg Figure 5-33

知识流聚类多 ROC 输出

Before executing the flow, click the following nodes to set or confirm their parameters:

    点击 ARFFLoader ,验证数据文件为subject 101-cleaned . ARFF

    单击 类分配器 并验证 ActivityID 是类属性。

    单击 类别值选择器 并选择用于 ROC 曲线的类别。在示例中,您选择了第 3 类(站立)。这就是为 2 级 ROC 曲线绘制多级数据的方法。

    选择 FoldMakerSplitMaker 节点,设置 10 折和 2/3 分割的测试分割。

    单击四个算法节点中的每一个,并按照前面的讨论设置参数。

    点击ModelPerformanceChart节点,将渲染器设置为 JFreeChart,如图 5-34 所示。

img/468661_1_En_5_Fig34_HTML.jpg Figure 5-34

将渲染器设置为 JFreeChart

Execute the flow and wait for the results to complete. The KNN algorithm will be last due to its long testing times. When everything completes, right-click the ImageViewer node and show results, as in Figure 5-35.img/468661_1_En_5_Fig35_HTML.jpg Figure 5-35

Weka ROC 曲线比较(类别:3)

回想从第章第四部分开始,要解读多条 ROC 曲线,直竖线是最好的。对于这个特殊的类=3,射频和 SVM/SMO 算法看起来很棒。NB 算法是滞后的,这是合理的,因为它具有最低的百分比准确性。

精确度和 ROC 曲线结果让您相信,这些模型在整合到您的最终应用中时能够发挥作用。

5.8 Weka 导入和导出

能够 加载//保存 模型是 Weka 最有用的功能之一。在下一章中,当您将预训练的 CML 模型部署到设备时,您将进一步探索这一点。

Models can be loaded and saved in the Weka Explorer by right-clicking a model in the Weka Explorer Results list. Figure 5-36 shows the Save Model drop-down dialog box.img/468661_1_En_5_Fig36_HTML.jpg Figure 5-36

Weka Explorer:保存模型

Weka saves models as serialized Java objects with the .model extension. You can import saved Weka models into your Java applications by using the Weka Java API. Once imported, the model enables you to make predictions. In Chapter 6, you will explore the size and structure of .model files further.

在设备上使用预构建的 CML 模型的一个关键问题是模型的大小。无论何时构建和导出模型,模型大小和模型精度都是您必须仔细考虑的权衡因素。我将在下一章详细讨论这一点。

In addition to saving models, Weka allows you to save data files with a variety of formats. When you click the Save button in the Weka Explorer Preprocess tab, the following file formats are available:

  • ARFF 文件导出

  • ARFF 数据文件(*。飞机救援消防)

  • ARFF 数据文件(*.arff.gz)

  • C4.5 文件格式(*。姓名)

  • CSV 文件(*。csv)

  • 纯文本或二进制序列化字典文件(*。字典)

  • JSON 数据文件(*。json)

  • JSON 数据文件(*.json.gz)

  • libsvm data files (*.libsvm)

这是一个特别有用的功能,因为它允许您在格式之间转换文件。例如,在旧的忠实集群示例中,您从在 中导入数据集开始。csv 格式。完成聚类过程后,您可以在?? 导出数据,包括聚类结果。arff 格式。

The following excerpt shows the first 15 instances of the Old Faithful dataset after clustering, in .arff  format. Notice that the dataset includes four attributes including a Cluster attribute as the last column of the comma-separated dataset.001   @relation old-faithful_clustered 002 003   @attribute Instance_number numeric 004   @attribute eruptions numeric 005   @attribute waiting numeric 006   @attribute Cluster {cluster0,cluster1} 007 008   @data 009   0,3.6,79,cluster0 010   1,1.8,54,cluster1 011   2,3.333,74,cluster0 012   3,2.283,62,cluster1 013   4,4.533,85,cluster0 014   5,2.883,55,cluster1 015   6,4.7,88,cluster0 016   7,3.6,85,cluster0 017   8,1.95,51,cluster1 018   9,4.35,85,cluster0 019   10,1.833,54,cluster1 020   11,3.917,84,cluster0 021   12,4.2,78,cluster0 022   13,1.75,47,cluster1 023   14,4.7,83,cluster0 024   15,2.167,52,cluster1 In the next chapter, you will explore how to use this saved .arff  file to create the Old Faithful (Figure 5-37) Classifier app for mobile.img/468661_1_En_5_Fig37_HTML.jpg Figure 5-37

黄石国家公园的老忠实喷泉(portfolio.timdimacchia.com 蒂姆·迪马克提供)**********

六、集成模型

  • 管理 ML 模型。

  • 执行灵敏度分析,以在模型精度和模型大小之间做出最佳权衡。

  • 回顾 Weka Java API 的关键方面。该 API 允许您打开预先训练的模型,并在 Java 中进行预测。

  • 使用 Eclipse 项目创建一个 Weka API 库,可以用于 Java 和 Android 应用程序。

  • 概述预训练 ML 模型与 Android 和 Raspberry Pi 的集成技术。

  • 复习 Java 代码,在流行的设备平台上处理传感器数据。

  • 实现树莓派的老忠实 ML app。

  • 为 Android 实现活动跟踪器 ML 分类应用程序。

6.1 导言

令人惊讶的是,现在的应用商店里有这么多可用的应用。事实上,有这么多,它已经变得很难穿过噪音,并建立一个存在。如今,应用商店中只有一小部分应用使用 ML,但这种情况正在改变。

机器学习是 app 开发的未来。正如我们已经学会将网络性能设计到我们的应用程序中一样,我们现在必须学会将 ML 性能设计到应用程序中,包括考虑模型大小、模型准确性和预测延迟。

在这最后一章中,您将学习模型集成和部署。

Figure 6-1 shows the ML-Gates 1 and 0 steps for this critical phase.img/468661_1_En_6_Fig1_HTML.jpg Figure 6-1

ML-Gate 1/0,模型集成/部署

这最后两个 ML-gate 代表 ML 开发管道的“业务端”。它们代表了管道中的最后步骤,在这些步骤中,您会意识到在处理数据、算法和模型的早期阶段所做的所有艰苦工作的好处。模型集成和部署是最明显的阶段,这些阶段使您能够将应用程序货币化。

6.2 管理模型

In ML application development, the model is one of your key assets. You must carefully consider how to handle the model, including

  • 模型规模考虑因素

  • 模型版本控制

  • 更新模型

模型可能会变得非常大,您需要首先确保您创建的模型可以物理地驻留在您的目标设备上。

设备限制

When you use ML models from the cloud providers, you simply rely on network connectivity and a cloud provider API to access models and make predictions. Storing prebuilt models on devices is a different approach, requiring you to understand the limitations of the target device. Table 6-1 shows the typical hardware storage specifications for two Java devices, Android and Raspberry Pi.Table 6-1

设备处理/存储摘要

|

规格

|

机器人

|

树莓派

|
| --- | --- | --- |
| 设备种类 | 中端设备,如 Moto X4 (2018) | 皮 3B+ (2017) |
| 操作系统 | Android 8.1(奥利奥) | Linux 操作系统 |
| 中央处理器 | 八核 ARM Cortex-A53 2.2 GHz | 4x ARM Cortex-A53,1.2 GHz |
| 国家政治保卫局。参见 OGPU | 肾上腺素 508 | Broadcom 视频会议四 |
| 内部闪光灯 | 32GB | 不适用的 |
| 随机存取存储 | 3GB RAM | 1gb DDR 2(900 MHz) |
| 外部闪光灯 | microSD,最高 256GB | microSD,最高 256GB |

虽然这些设备的架构和 CPU 技术有些相似,但该表显示,典型的 Android 设备比 Pi 3B+具有更高的处理能力和存储容量。

The device specifications for Android vary widely. Table 6-1 shows a typical mid-tier device and the latest revision Raspberry Pi, the Pi 3B+. Both devices support external SD cards for storage. On the Pi, you must use this external storage for your application code and the ML model. On Android devices, there is also internal storage, typically 32GB, sometimes up to 64GB or higher on the flagship phones. There are several reasons to use Android internal storage for ML models:

  • 对于读取操作,内部存储的性能是外部存储的 3 倍。对于写操作,这种差异通常并不明显。

  • 很多安卓设备都不支持外置 SD 卡。

  • 在最近的 Android 版本中,外部存储权限变得越来越严格。

在 Android 设备上看到大小超过 300MB 的应用程序是很常见的。这并不意味着您应该创建尺寸相匹配的模型。庞大的模型很难管理。大型模型的主要缺点是加载它们所花费的时间。你会看到,对于 Android,最好的方法是在后台线程上加载模型,你希望加载操作在几秒钟内完成。在“项目”一章中,您将在应用程序启动时加载 ML 模型,同时显示启动闪屏。

最佳模型尺寸

In Chapter 5, you saw model accuracy, model training, and model testing times varied for each of the classification algorithms discussed. There is an additional factor, model size, which is equally important to consider. Table 6-2 shows the relative priority of these factors.Table 6-2

模型创建因素

|

因素

|

优先

|

理由

|
| --- | --- | --- |
| 模型训练时间 | 低的 | 训练时间很重要;然而,当您在边缘的应用程序中部署静态模型时,优先级较低,因为您总是可以应用更多的资源(甚至可能在云中)来训练模型。 |
| 模型测试时间 | 中等 | 如果算法生成的复杂模型需要相对较长的测试时间,这可能会导致设备在进行预测时出现延迟或性能问题。 |
| 模型精度 | 高的 | 模型精度必须足以产生明确定义的问题所需的结果。 |
| 模型尺寸 | 高的 | 将预训练的 ML 模型部署到设备上时,模型的大小必须与目标设备的内存和处理资源一致。 |

Weka allows you to save models by right-clicking on a Result List item after a classification completes. Table 6-3 shows the size of several models created using the specified model options. There are two entries for RF algorithm, one representing ten iterations (i=10) and another representing one hundred iterations (i=100).Table 6-3

模型大小汇总,各种分类算法

|

算法

|

选择

|

模型尺寸

|

准确度(%)

|
| --- | --- | --- | --- |
| 随机森林 | i=10 | 5.5 兆字节 | 87.7% |
| 随机森林 | i=100 | 55.2 兆字节 | 90.5% |
| KNN-kstars | 默认 | 3.6 兆字节 | 82.8% |
| 朴素贝叶斯 | 内核默认值 | 51 KB | 72.9% |
| SVM/SMO | c=2 | 51.9 兆字节 | 83.4% |

To understand how the factors interrelate, you can perform a sensitivity analysis. Consider the RF algorithm. You know the number of iterations, i, is a key variable for determining how deep or how many trees the algorithm produces. More iterations means more trees, which results in each of the following:

  • 更高的精确度

  • 更长的创建时间

  • 更大的模型尺寸

You can use the Weka ML environment to run a series of model creations to see how these factors relate. Figure 6-2 shows a sensitivity analysis plotting model accuracy against model size for varying settings of the iteration (i) parameter.img/468661_1_En_6_Fig2_HTML.jpg Figure 6-2

灵敏度分析、模型大小与模型精确度

使用 RF 算法时,您会立即注意到迭代次数(I)和模型大小之间的关系是线性的。例如,在所有其他参数相同的情况下,i=5 的模型的大小为 2.76 MB,i=50 的模型的大小为 27.6MB。如图 6-2 所示,准确性并不相同。在本例中,RF 模型达到了大约 90%的精度上限。就模型大小而言,90MB 模型(i=150)不会比 40MB 模型(i=75)产生更高的精度。

曲线上的最佳点是曲线拐点处的切线。你可以看到这个点位于 i=10 和 i=25 之间。i=10 的值在模型大小仅为 5.5MB 的情况下产生了相当好的精度,所以让我们继续这个配置。注意,这些精度值不包括 10 倍训练;采用这种测试方法可以进一步提高准确性。

影响模型大小的另一个因素是数据集大小。您使用的 PAMAP2_dataset 很大。subject 101-cleaned . ARFF包含 22846 个实例。当您删除无用的列(属性)时,您已经对数据集执行了 特征缩减 (也称为维度缩减)。但是,请考虑是否要减少数据集中的实例数量。这可能会导致模型尺寸减小,但可能会牺牲准确性。

Figure 6-3 shows a second sensitivity analysis to help you explore this effect. This chart plots the number of training instances vs. the model size, using a constant value of ten iterations (i=10) and reducing the training instances by filtering the dataset input file.img/468661_1_En_6_Fig3_HTML.jpg Figure 6-3

数据大小敏感性分析

图 6-3 显示了具有不同训练实例大小的四个模型。图左侧的三个点代表完整数据集的子集。与模型大小的关系不是线性的,因为您可以观察到曲线中的弯曲。曲线的斜率表示训练实例的效用。随着图右侧的斜率减小,每个训练实例的效用也降低。这也与精度上限有关。

问题是,您应该删除哪些实例?所有的 ML 环境,包括 Weka,都有过滤器来帮助减少实例,尽量减少数据集类的完整性。

Of course, reducing the training data will eventually reduce accuracy. Finding the right balance is a trade-off decision, and you can use the sensitivity analysis to help you choose the most efficient point along the curves.

优化设备的模型尺寸包括对所选算法的关键参数进行灵敏度分析。创建模型以观察它们的大小,然后沿着灵敏度曲线选择切点以进行最佳权衡。

每种算法都有自己的缩放属性。对于这里显示的灵敏度分析,您只考虑了一个算法(RF)和一个参数(迭代)。像 Weka 这样的 ML 环境使得实验参数来优化你的模型变得很容易。

DL 算法的一个巨大优势是,一般来说,它们的大小不会像 RF 算法那样与数据集的大小成线性比例关系。诸如 CNN 和 RNN 算法之类的 DL 算法使用隐藏层。随着数据集的增大,隐藏图层的数量不会增加。DL 型号变得“更智能”,但尺寸却没有相应增加。

模型版本控制

一旦创建,您应该将您的 ML 模型视为有价值的资产。尽管您没有在创建过程中编写代码,但是在管理它们时,您应该将它们视为代码等价物。这意味着 ML 模型被置于版本控制之下,就像您的应用程序源代码一样。

Whether or not you store the actual model, a serialized Java object in the case of Weka’s model export, depends on if the model is reproducible deterministically. Ideally, you should be able to reproduce any of your models from the input components, including

  • 资料组

  • 输入配置,包括过滤器或预处理

  • 算法选择

  • 算法参数

对于可重现的确定性模型,没有必要存储模型本身。相反,您可以选择存储输入组件。当创建时间很长时,例如使用 KNN 算法处理大型数据集时,存储模型本身以及输入组件是有意义的。

The following tools are free and open source, and promise to allow you to seamlessly deploy and manage models in a scalable, reliable, and cost-optimized way:

这些工具支持与 AWS 和 GCP 等云提供商的集成。它们通过保证所有基于模型的资产的可再现性来解决版本控制问题。

更新模型

当您开始部署您的 ML 应用程序时,要考虑的一个关键方面是您将来如何更新模型。本章后面的示例项目将在应用程序启动时直接从项目的资产目录中加载 ML 模型。当开始 ML 应用程序开发时,这是最简单的方法,但是在将来升级应用程序-模型组合时,这是最不灵活的方法。

A more flexible architecture is to abstract the model from the app. This provides the opportunity to update the model in the future without the need to rebuild the application. Table 6-4 summarizes some of the approaches for model management.Table 6-4

模型管理方法

|

方法

|

描述

|

赞成/反对

|
| --- | --- | --- |
| 植入的 | 将模型包含在项目资产中。 | 简单,但最不灵活的方法。 |
| [计] 下载 | 不要将模型存储在设备上,而是在应用程序初始化时从云中下载。 | 需要网络连接。适合非常小的型号。 |
| 惰性装载 | 您可以将标准的图像加载方法应用于 ML 模型。这是前两种方法的混合组合。 | 有许多图书馆可供使用。灵活,但不适合大型模型。 |
| sync adapter??ContentManager** | 可以使用内置的 Android 网络同步( SyncAdapter )和内容共享( ContentManager )类。 | 高灵活性。后台服务架构。 |
| 推送消息 | 使用推送服务交付模型更新,例如 Google 的 Firebase 云消息(FCM ),或者 MQTT 等开源替代服务。 | 低延迟。后台服务架构。 |
| 实时流 | 使用这种方法,模型会随着新数据的出现而不断更新。 | 与预建模型截然不同的架构。 |

如果您希望采用延迟加载或推送消息的方法,在作者的 Android 项目手册中有针对每种方法的示例项目,可以很容易地进行调整以支持 ML 模型:

【https://github.com/apress/practical-android】

在接下来的专题章节中,为了简单起见,你将使用嵌入式模型方法。对于生产应用,首选表 6-4 中更先进的方法。

管理模型:最佳实践

A summary of best practices for creating and handling prebuilt models for on-device ML applications:

  • 最佳模型大小取决于输入数据集大小、属性复杂性和目标设备硬件能力。

  • 准备模型灵敏度分析,绘制模型精度与模型尺寸的关系图。在算法上限左侧的曲线上选择一个点。

  • 准备模型敏感性分析,绘制训练实例数量与模型大小的关系图。选择曲线上斜率较高的点。

  • 对于 Android 和 Raspberry Pi 设备,一个好的模型大小指南是 5MB -50MB。如果您正在考虑更大的 CML 模型,请确保您获得了足够大的准确性,以证明更大的尺寸是合理的。

  • 使用版本控制来管理所有的源数据、算法选择、算法参数和部署的模型。

  • 决定您将使用哪种架构来更新您的应用程序所使用的模型。

在接下来的部分中,您将探索 Weka Java API,如何加载模型,以及如何在设备上进行预测。

6.3 Weka Java API

您已经看到了从简单的 CLI 和各种 Weka GUI 应用程序(包括 Explorer 和 KnowledgeFlow)访问 Weka 分类器和聚类器是多么容易。当您可以从 Java 代码中访问 Weka 类时,真正的力量就释放出来了。所有的 Weka 类都可以从 Java APIs 访问。

The Weka Java APIs allow you to do the following from Java code:

  • 设置选项。

  • 创建和管理数据集属性和实例。

  • 加载和保存 ARFF 或 CSV 格式的数据。

  • 加载并保存序列化模型。

  • 将大量 Weka 过滤器中的任何一个应用于数据集。

  • 使用任意 Weka 算法对数据集进行分类或聚类。

  • 选择属性作为分类标签。

  • 可视化数据集,尽管 Android 平台不提供该功能。

只需几行 Java 代码就可以复制您使用 Weka Explorer 执行的大多数任务。

接下来,我将回顾一些最重要的 Java API 操作,首先使用通用的 Java API,然后专门针对 Android 平台。

加载数据

您将 ML 模型放在边缘的方法意味着您通常将加载在更高性能的桌面或服务器机器上创建的预训练模型。但是,有时可能需要在边缘加载数据集。

The Weka API allows you to load CSV or ARFF data files, just as you did in the Weka desktop environment. The following code demonstrates loading CSV and ARFF files using the API:001   import weka.core.converters.ConverterUtils.DataSource; 002   import weka.core.Instances; 003   // 004   // Load ARFF file 005   // 006   DataSource sourceARFF = new DataSource("/your-directory/your-data.arff"); 007   Instances dataARFF = sourceARFF.getDataSet(); 008   // 009   // Load CSV file 010   // 011   DataSource sourceCSV = new DataSource("/your-directory/your-data.csv"); 012   Instances dataCSV = sourceCSV.getDataSet();

你使用 实例 对象来存储数据。您可以在运行分类或聚类分析算法之前对数据应用筛选器。Weka API 支持您在基于 GUI 的桌面环境中使用的相同过滤器和算法选项。

使用选项

The Weka API supports options using String Arrays with the following two approaches:001   // Manually create the String Array of options: 002   // 003   String[] options1 = new String[2]; 004   options1[0] = "-R"; 005   options1[1] = "1"; 006   // 007   // or, you can automatically create the options String Array using splitOptions: 008   // 009   String[] options2 = weka.core.Utils.splitOptions("-R 1");

一旦定义了选项 字符串数组 ,就可以将它们应用到过滤器或算法中,如下例所示。

应用过滤器

You can apply filters to classes, attributes, or instances. If you have an Instances object containing the dataset called data, you can apply a filter as follows:001   import weka.core.Instances; 002   import weka.filters.Filter; 003   import weka.filters.unsupervised.attribute.Remove; 004   import weka.core.converters.ConverterUtils.DataSource; 005 006   // Load Data 007   DataSource source = new DataSource("/your-directory/your-data.arff"); 008   Instances data = source.getDataSet(); 009 010   // Set the options for "range" and "first attribute" 011   String[] options = new String[2]; 012   options[0] = "-R"; 013   options[1] = "1"; 014 015   // Create a new instance of the "remove" filter and set the options 016   Remove remove = new Remove(); 017   remove.setOptions(options); 018   remove.setInputFormat(data); 019 020   // Apply the filter to the data object 021   Instances newData = Filter.useFilter(data, remove);

在这个例子中,您正在从 数据 中删除第一个属性(列),并且更新存储在 newData 对象中。

设置标签属性

As you saw in Chapter 2, the label attribute can be any of the attributes in the dataset. Often, it is the first attribute, while some datasets include it as the last. It is a best practice to specify the label attribute in your Java code. The Weka API provides the setClassIndex to set the label attribute for classification:001   // Set the class attribute (Label) as the first class 002   dataTest.setClassIndex(0);

始终仔细检查类索引的数据类型是否正确,尤其是在读入 CSV 数据时。回想一下前面的 PAMAP2_dataset,您需要使用 Weka 过滤器将标注属性(类索引)转换为正确的名义类型。ARFF 文件指定了数据类型,因此不需要转换过滤器。

构建分类器

Building a classifier with the Weka API is a simple process requiring only a few lines of code, first specifying the options and then passing the options and the data to the classifier’s buildClassifier method.001   import weka.classifiers.trees.J48; 002 003   // Set the option for "unpruned tree" 004   String[] options = new String[1]; 005   options[0] = "-U"; 006 007   // Specify the tree classifier 008   J48 tree = new J48(); 009   tree.setOptions(options); 010   tree.buildClassifier(data);

所有的 Weka 分类器都在 API 中可用,包括第四章中讨论的四个最重要的分类器。

培训和测试

The Weka API allows you to train and test classifiers. You can train a classifier by passing training data (Instances object) to the buildClassifier method. The evaluateModel method allows you to test a trained classifier.001   import weka.core.Instances; 002   import weka.classifiers.Evaluation; 003   import weka.classifiers.trees.J48; 004   import weka.classifiers.Classifier; 005 006   Instances train = 007   Instances test =   008 009   // Train classifier 010   try { 011       Classifier cls = new J48(); 012       cls.buildClassifier(train); 013 014       // Evaluate the classifier 015       Evaluation eval = new Evaluation(train); 016       eval.evaluateModel(cls, test); 017       System.out.println(eval.toSummaryString("\nResults\n======\n", false)); 018   } catch (Exception e) { 019       // Handle Weka exception 020       e.printStackTrace(); 021   }

您通常不会在边缘设备上训练分类器,但是拥有这种能力是很好的。

构建集群

Building a clusterer with the Weka API is also straightforward. You can use the buildClusterer method of the clusterer object to train the clusterer.001   import weka.clusterers.EM; 002 003   // Set the options for max iterations 004   String[] options = new String[2]; 005   options[0] = "-I"; 006   options[1] = "10"; 007 008   // Instantiate the EM Clusterer instance 009   EM clusterer = new EM(); 010   clusterer.setOptions(options); 011   clusterer.buildClusterer(data);

您可以使用evaluateClusterer方法评估一个集群器。

加载模型

In Chapter 5, you saw how to save models created in the Weka ML environment. Now you can use the Weka API to load these pretrained models. Use the Java InputStream class to specify the model filename, and then provide the stream to the Weka API SerializationHelper class.001   // Define a Weka Classifier Object 002   Classifier mClassifier = null; 003 004   // Load the Classifier from local storage 005   try { 006       File wekaModelFileUnix = new File("/path/modelname.model"); 007       FileInputStream fis = new FileInputStream(wekaModelFileUnix); 008       mClassifier = weka.core.SerializationHelper.read(fis); 009   } catch (Exception e) { 010       // Handle Weka model failed to load 011       e.printStackTrace(); 012}

在本章的后面,您将利用这种方法为 Android 加载 Weka 库模型。

做预测

You can use the Weka API to make predictions, or to say it more formally, to classify a sample. The classifyInstance method is available for all of the classifiers.013   import weka.core.Instances; 014   import weka.core.converters.ConverterUtils.DataSource; 015   import weka.classifiers.Classifier; 016 017   // Load unlabeled data 018   DataSource source = new DataSource("/your-directory/your-unlabeled-data.arff"); 019   Instances unlabeled = source.getDataSet(); 020 021   Classifier mClassifier = null; 022 023   // set class attribute 024   unlabeled.setClassIndex(unlabeled.numAttributes() - 1); 025 026   // classify the instances 027   for (int i = 0; i < unlabeled.numInstances(); i++) { 028        double clsLabel = mClassifier.classifyInstance(unlabeled.instance(i)); 029 030   }

你将在本章的后面使用这个逻辑来实现活动跟踪器 Android 应用程序。

6.4 安卓版 Weka

在 Android 设备上使用 Weka ML 库最有用的方法是将库移植到 Android。这项任务并不琐碎,但一旦完成,Android 的一个 Weka.jar 文件就是一份持续赠送的礼物。

在整个 ML-Gates 管道中使用相同版本的 Weka 非常重要。如果在桌面上使用最新稳定版本的 Weka 创建 ML 模型,则必须在设备上使用相同版本的 Weka 以确保兼容性,尤其是在打开序列化的预训练模型时。Weka 是稳定的,所以这不会造成大问题。

The main issue with porting Weka to Android is Weka's integration with the following Java packages:

  • AWT:本机系统 GUI 代码的 Java 接口

  • Swing:一个纯 Java GUI,它使用 AWT 创建窗口,然后在窗口中操作对象

  • Net Beans:用于开发 Java 应用程序的模块化组件平台

Weka 依赖这些软件包来实现 GUI 相关的功能。Android 如此出色的原因之一是它不使用任何 GUI 包。当然,这也是 Weka 难以移植到 Android 的原因。

幸运的是,在 Android 上你不需要 Weka 的 GUI 功能。您只需要访问数据实用程序、过滤器、算法和序列化方法。然而,在您可以为 Android 构建 Weka 库之前,您需要解决由于使用这些包而导致的 Android 上的构建问题。

书籍资源包括您将用于 Android 项目的 Weka jar 文件:

WEKA-Android-3-8-1 . jar??]

简单的方法是获取 Weka jar 文件,并简单地将其添加到您的 Android Weka 项目中。

为了演示如何为 Android 构建Weka-Android-3-8-1 . jar库,本书参考资料包括一个完整的 Eclipse 项目。该项目也可以在作者的 GitHub 页面上获得:

WEKA-Android-3-8-1 . zip??]

【https://github . com/wick apps/WEKA-Android-3-8-1

在将 Weka 库移植到 Android 时,Eclipse 项目有助于探索解决许多与 GUI 相关的编译错误所需的代码更新。如果您需要为不同的 Weka 版本创建库文件,该项目也可以作为指南。

在 Eclipse 中创建 Android Weka 库

You have two approaches to port Weka to Android.

  • 自下而上的方法:决定你到底需要哪些功能,比如七个最有用的 ML 算法。从底层开始,识别这些算法的特定类,并开始只包含那些类,逐步解决任何需要的依赖性问题。当所有的依赖关系都解决后,您的库将拥有最少的功能集。

  • 自顶向下的方法:从顶部开始,包括 Android 构建的所有明显的 Weka 类(不包括知识流)。当您将项目作为 Android 项目导入 Eclipse 时,大量错误将需要手动解决。

本节将演示后一种方法。自顶向下的方法比自底向上的方法需要更多的努力,但是一旦你解决了所有的问题,你将拥有一个更灵活、更强大的 Android 项目库。该库将支持所有的 Weka 过滤器和算法,在新版本 Weka 发布之前,您不需要重新构建该库。

The following steps summarize the initial setup process for porting Weka to Android:

  • 从支持 Java 7 的最新版本 Weka 开始(稍后会有更多内容),版本 3.8.1。导航到 weka-src.jar 文件。用 7Zip 实用程序解压文件。导航到src->main->Java->WEKA。在做了一些修改后,您将把这个基本目录导入 Eclipse。

  • 删除所有的 gui 目录,以下文件除外,因为这些文件与其中包含的对象高度相关,所以需要保留:

    genericpropertiesgreator . excludes

    GenericPropertiesCreator.java

    genericpropertiesgreator . props

    HierarchyPropertyParser.java

    装载机. java

    Logger.java

    TaskLogger.java

******* 删除整个 知识流 目录。Android 上不需要 知识流 应用。

*   删除基础目录下的两个文件,***plugin manager . props***和【Run.java】**。**

***   打开 Eclipse。

*   创建一个新的 Android 项目,命名为***Android-Weka-3-8-1***。

*   将项目设置为 ***库项目。*** 的设置是在 ***Java 构建路径*** 中设置的。

*   新项目高亮显示后,选择 ***【导入】- >通用- >文件系统**-*。导入前面创建的 ***weka*** 基础目录。******** 

****Android Weka 项目现在已经建立,但是在您成功地为 Android 构建 Weka 库之前,还有许多错误需要解决。

最新版本的 Weka 需要 Matrix Toolkit for Java(【mtj】)库。Matrix Toolkit for Java 是一个用于执行数值线性代数的开源 Java 软件库。以下是 for Matrix Toolkit for Java 资源库的链接:

https://github . com/fommil/matrix-toolkit-Java

从图书资源中复制 mtj-1.0.1.jar 库文件,或者从 Maven 资源库中下载库文件:

https://mvn repository . com/artifact/com . Google code . matrix-toolkits-Java/mtj/1 . 0 . 1

Maven 资源库还包括 Maven 或 Gradle 构建的说明。将 mtj-1.0.1.jar 作为外部库文件添加到 Eclipse 项目中。

You may notice that there are many errors related to the Java handing of Vectors and ArrayLists in the code. The latest versions of Weka rely heavily on ArrayLists. Table 6-5 shows the Weka Java requirements. Java 7 (1.7) is the minimum Java version required for the Weka version 3.8.1. The newest stable version of Weka is 3.8.2 which requires Java 8 (1.8).Table 6-5

Weka 版本 Java 要求

|   |

Java 版本

|
| --- | --- |
|

One point four

|

One point five

|

one point six

|

One point seven

|

One point eight

|
| --- | --- | --- | --- | --- |
| Weka 版本 | ❤️.4 | X | X | X | X | X |
| 3.4.x | X | X | X | X | X |
| 3.5.x | 3.5.0-3.5.2 | >3.5.2 | X | X | X |
| 3.6.x |   | X | X | X | X |
| 3.7.x |   | 3.7.0 | >3.7.0 | >3.7.13 | X |
| 3.8.x |   |   |   | 3.8.1 | >3.8.1 |
| 3.9.x |   |   |   | 3.9.1 | >3.9.1 |

但是,请记住,Android 还不支持完整的 Java 8 (1.8)。Android 确实支持 Java 8 的一些特性。Android 对 Java 8 的最新支持可以在这里找到:

【https://developer.android.com/studio/write/java8-support】

表格中突出显示的单元格显示了最佳设置:Weka 版本 3.8.1 运行在 Java 版本 1.7 上,Android 支持 Java 版本 1.7。

To minimize the compile errors for Weka on Android, set the Eclipse compiler compliance level to Java version 1.7 as shown in Figure 6-4. The default value is usually Java 6 (1.6).img/468661_1_En_6_Fig4_HTML.jpg Figure 6-4

Eclipse Java 编译器设置

At this point, you have resolved many build errors, but there are still many build issues that you need to manually resolve. Most of the remaining errors are due to dependencies on the PackageManager or PluginManager classes. The errors can be resolved with the following resolution hierarchy:

  • 删除有问题的文件。

  • 删除类中的方法或函数。

  • 通过修改有问题的方法或函数中的代码来解决错误。这是最后一招,当前面两种方法导致更多的依赖问题时,就需要使用这一招。

With all errors in the Android Eclipse project resolved, you are ready to export the Weka library for Android. Choose File➤Export➤Jar Library from the Eclipse main menu. Figure 6-5 shows the export.img/468661_1_En_6_Fig5_HTML.jpg Figure 6-5

Eclipse 导出 Weka 库文件

库文件的大小只有 3.3MB,尽管它包含了 Android 所需的所有 Weka Java API 类。该库的内存占用量小,非常适合移动设备。该库在大小/性能平衡方面可以与任何移动 ML 库相媲美。

接下来,您将探索如何为设备 ML 应用程序使用该库。

在 Android Studio 中添加 Weka 库

Add the Weka ML library to Android Studio with these steps:

  • 在你的 Android Studio 项目的 app 级别创建一个 libs 目录。

  • Android-Weka-3-8-1 . jar文件复制/粘贴到 libs 目录中。

  • 右键点击Android-Weka-3-8-1 . jar文件,然后点击 添加为库 ,如图 6-6 所示。

img/468661_1_En_6_Fig6_HTML.jpg Figure 6-6

Android Studio 添加库

Weka API 将从 Android Java 应用程序中获得。

Figure 6-7 shows a project in Android Studio after the library has been imported. On the left side you can see the exploded Weka directory structure, and at the top of the right side panel you can see several library imports required by the application to handle the requested Weka API classes.img/468661_1_En_6_Fig7_HTML.jpg Figure 6-7

Android Studio 的 Weka 库

6.5 Android 集成

The Android Weka library makes it easy to integrate ML for Android. In this section, you will implement two simple Android apps to demonstrate the following basic ML integrations:

  • Weka Model Create :这个应用程序将演示在 Android 中直接从数据创建 ML 模型。

  • Weka 模型加载:这个应用程序将加载一个预训练的 ML 模型,并用批处理数据集实例测试该模型。

第一个项目是 Weka API 功能的有用演示。第二个项目是一个更实用的架构,原因在前面的章节中讨论过。

项目:Weka 模型创建

For this project, you will include the following two data files, derived from the Old Faithful geyser clustering example in Chapter 5, as part of the app’s assets. Although you are including the data files directly in the project, the app could just as easily download these text files from the cloud using a network operation.

  • old faithful _ train . arff:章节 5 聚类示例中生成的 ARFF 数据文件的子集,包含前 201 个实例。

  • old faithful _ test . arff:第五章聚类示例中生成的 ARFF 数据文件的子集,它包含数据集的最后 71 个实例。

这个 Weka 模型创建应用程序将使用第一个文件作为训练数据,从头开始构建一个模型。请注意,如果您想用单个数据文件实现应用程序,您可以使用过滤器来执行文件分割。使用过滤器也可以进行 k 倍交叉验证。

这个 app 技术上是一个分类 app。旧的忠实数据最初是一个聚类问题,但是回想一下当 DBSCAN 算法完成聚类操作时,您保存了结果,包括新分配的 clusterID 到新的 ARFF 文件。测试模型时,使用已知的分类分配来确定分类器的准确性。

Table 6-6 shows the project summary.Table 6-6

Weka 模型创建项目摘要

|

项目名称:Weka 模型创建

来源:WEKA _ model _ create . zip

类型:Android

注意:创建一个随机森林模型,用训练数据集训练它,用测试数据集评估分类器,并在 TextView 中显示结果。

|
| --- |
|

文件

|

描述

|
| --- | --- |
| app->libs->WEKA-Android-3-8-1 . jar??] | Eclipse 项目生成的用于 Android 的 Weka jar 文件。 |
| app->src->main->Java->MainActivity.java | 主 Java 源代码文件。该项目只有一个活动。 |
| 【应用】>【src】>【main】>【RES】>【layout】activity _ main . XML | 单屏幕显示输出的布局文件。 |
| 【应用】>【src】>【main】>【RES】>【raw】old faithful _ train . ARFF | 训练数据集,ARFF 格式的 201 个实例。 |
| 【应用】>【src】>【main】>【RES】>【raw】old faithful _ test . ARFF | 测试数据集,ARFF 格式的 71 个实例。 |
| 【应用】>【src】>【main】>【RES】【雄激素固定。xml | 清单文件。 |

您可以使用简单的复制粘贴将三个外部文件(Weka jar 库和 ARFF 文件)导入到相应的 Android Studio 目录中。您将使用其中一个 ARFF 文件来训练模型,并使用第二个文件来测试模型。这与您在桌面 Weka Explorer 中选择 分割测试选项 的方法相同。

The key points of MainActivity.java are as follows:

  • Weka 在第 6-10 行导入,由 Android-Weka-3-8-1.jar 文件提供。

  • 第 31 行和第 32 行使用的 setClassIndex 方法将属性标签设置为训练数据集和测试数据集的最后一个类。

  • 在第 24 和 28 行,数据被加载到每个数据集文件的 实例 对象中。

  • RF 模型在第 40 行创建。

  • RF 模型在线 42 处被训练。

  • RF 模型采用默认选项,因为您没有指定任何附加选项,如本章前面所示。

Listing 6-1 shows the complete MainActivity.java code.001   package android.wickham.com.WekaModelCreate; 002 003   import android.app.Activity; 004   import android.os.Bundle; 005   import android.widget.TextView; 006   import weka.classifiers.Classifier; 007   import weka.classifiers.evaluation.Evaluation; 008   import weka.classifiers.trees.RandomForest; 009   import weka.core.Instances; 010   import weka.core.converters.ConverterUtils.DataSource; 011 012   public class MainActivity extends Activity { 013 014       @Override 015       protected void onCreate(Bundle savedInstanceState) { 016           super.onCreate(savedInstanceState); 017           setContentView(R.layout.activity_main); 018 019           DataSource sourceTrain, sourceTest = null; 020 021           try { 022               // Load the Training data 023               sourceTrain = new DataSource(getResources().openRawResource(R.raw.oldfaithful_train)); 024               Instances dataTrain = sourceTrain.getDataSet(); 025 026               // Load the Test data 027               sourceTest = new DataSource(getResources().openRawResource(R.raw.oldfaithful_test)); 028               Instances dataTest = sourceTest.getDataSet(); 029 030               // Set the class attribute (Label) as the last class 031               if (dataTrain.classIndex() == -1) dataTrain.setClassIndex(dataTrain.numAttributes() - 1); 032               if (dataTest.classIndex() == -1) dataTest.setClassIndex(dataTest.numAttributes() - 1); 033 034               // Fill the summary information for the dataTrain set 035               int attrs = dataTrain.numAttributes(); 036               int classes = dataTrain.numClasses(); 037               int insts = dataTrain.numInstances(); 038 039               // Setup a Random Forest classifier 040               Classifier rf = new RandomForest(); 041               // Train the RF classifier 042               rf.buildClassifier(dataTrain); 043 044               // Evaluate the classifier and print the results 045               Evaluation eval = new Evaluation(dataTest); 046               eval.evaluateModel(rf, dataTest); 047 048               // Show the results 049               TextView tv_attrs = (TextView) findViewById(R.id.attrs); 050               tv_attrs.setText(String.valueOf(attrs)); 051               TextView tv_classes = (TextView) findViewById(R.id.classes); 052               tv_classes.setText(String.valueOf(classes)); 053               TextView tv_insts = (TextView) findViewById(R.id.insts); 054               tv_insts.setText(String.valueOf(insts)); 055               TextView results = (TextView) findViewById(R.id.results); 056               results.setText((CharSequence) eval.toSummaryString()); 057 058           } catch (Exception e) { 059               e.printStackTrace(); 060           } 061       } 062   } Listing 6-1

威卡模式创造 MainActivity.java

In this example, you create a RF classifier because of its generally superior performance, but you have a complete Weka jar file, so you could choose any of the classification or clustering algorithms. The following code excerpt shows how to use the Weka API to instantiate each of the seven most useful CML algorithms presented in Chapter 4:001   // Set up a Random Forest classifier 002   Classifier rf = new RandomForest(); 003 004   // Other classifiers or clusterers can be defined as follows 005   Classifier nb = new NaiveBayes(); 006   Classifier knn = new KStar(); 007   Classifier svm = new SMO(); 008   Clusterer EM = new EM(); 009   Clusterer KMeans = new SimpleKMeans(); 010   Clusterer DBSCAN = new MakeDensityBasedClusterer();

图 6-8 显示了该应用在 Android Studio 仿真器或设备上运行时的屏幕截图。

The numAttributes, numClasses, and numInstances methods of the dataTrain class provide a summary of the training data set. The evaluateModel method (line 46) of the classifier provides the classifier results.img/468661_1_En_6_Fig8_HTML.jpg Figure 6-8

Android 应用程序:Weka 模型创建

分类器实现了 100%的分类结果——RF 算法在这个数据集上的表现令人印象深刻!

请注意,该应用程序只有 1.7MB,并且只包含 62 行 Java 代码(其中大部分代码只是显示结果所必需的)。这说明了 CML 对于边缘设备的效率。评估测试数据时,RF 模型在内存中。可以保存序列化的模型,甚至可以将从源数据创建的模型上传到云中。

在下一个示例中,您将进一步提高复杂性,处理更大的数据集,并加载预训练模型,而不是直接从数据源在设备上创建模型。

项目:Weka 模型加载

在这个项目中,您将把一个大得多的模型直接加载到应用程序中。您将在流程的每个阶段包含一些时间戳,以便检查性能。Android 有一些复杂的性能基准测试工具,但是您将只使用一个简单的时间戳。目标是确定 Android 上的库性能对于典型用例是否足够。

In Chapter 5, you created the following two models using the RF algorithm for subject101 of the large PAMAP2_Dataset:

  • RF _ i10 _ cross . model:RF 迭代参数 i=10,模型大小约 5MB。使用 K-fold 交叉验证来训练模型。

  • RF _ i100 . model:RF 迭代参数 i=100,模型大小约为 55MB。分割数据(2/3 训练和 1/3 测试)用于训练模型。

In this app, you will load these models directly into Android using the Weka API. Table 6-7 shows the project summary for the app.Table 6-7

Weka 模型加载项目摘要

|

项目名称:Weka 模型加载

来源:WEKA _ model _ load . zip

类型:Android

注意:将预训练的模型加载到应用程序中,并对从文件中加载的 5000 个实例进行批量分类,以测试分类器。

|
| --- |
|

文件

|

描述

|
| --- | --- |
| app->libs->WEKA-Android-3-8-1 . jar??] | Eclipse 项目生成的用于 Android 的 Weka jar 文件。 |
| app->src->main->assets->RF _ i10 _ cross . model | 射频预训练模型。 |
| app->src->main->Java->MainActivity.java | 应用程序的主 Java 文件。该项目只有一个活动。 |
| 【应用】>【src】>【main】>【RES】>【layout】activity _ main . XML | 单屏幕显示输出的布局文件。 |
| 【应用】>【src】>【main】>【RES】>【raw】>RF _ i10 _ cross . model | 预训练 RF 模型的第二个副本,用于演示从原始目录的访问。 |
| 【应用】>【src】>【main】>【RES】>【raw】>subject 101 _ cleaned _ 5k . ARFF | 用 5,000 个实例测试分类模型的 ARFF 文件。 |
| 【应用】>【src】>【main】>【RES】【雄激素固定。xml | 清单文件。 |

在 Weka 桌面环境中创建模型之后,您可以直接将它们复制到 Android Studio 项目中。请记住,Weka 的桌面版本必须与 Android 库文件匹配,在这种情况下,Weka 发布版本为 3.8.1。

There are two methods to load pretrained models in Android:

  • 资产管理器:使用 Android 资产管理器,从项目的 资产 目录中加载模型。

  • 原始文件:从 app 的原始存储空间加载模型。

The following code excerpt shows how to load models using each approach. In each case, you use the Weka SerializationHelper class.001   // In Android, we have two ways we can load models directly from the file system 002 003   // The following code uses the AssetManager to load the model 004   // from the app->src->main->assets folder 005 006   AssetManager assetManager = getAssets(); 007   InputStream is = assetManager.open("rf_i10_cross.model"); 008   rf = (Classifier) weka.core.SerializationHelper.read(is); 009 010   // Alternatively, use the next line to load the model 011   // directly from the app->src->main->res->raw folder 012 013   rf = (Classifier) weka.core.SerializationHelper.read(getResources().openRawResource(R.raw.rf_i10_cross));

在命名保存的模型时,包含用作文件名一部分的算法是一个很好的做法。当您打开模型,并需要实例化一个匹配的算法分类器或聚类器时,这变得更加容易。可以使用 数组列表 操作从. model 文件中导出算法类型。

Because of the large model size, for this app, you wish to benchmark the following operations:

  • 加载模型所用的时间

  • 加载包含 5,000 个测试数据实例的文件所用的时间(ARFF 格式)

  • 用 5,000 个测试实例评估模型所花费的时间(批量测试)

You will use the following function for time-stamping the operations performed by the app:001   public String getCurrentTimeStamp() { 002       return new SimpleDateFormat("HH:mm:ss.SSS").format(new Date()); 003   }

时间戳提供毫秒级的分辨率,因此您可以很好地了解分类器的执行速度。

Listing 6-2 shows the MainActivity.java of the application. The key code highlights:

  • 应用程序在第 26 行从本地存储中读取训练数据集。

  • 标签属性在第 30 行设置。

  • 应用程序在第 38 行将模型加载到一个 RF 对象中。

  • 应用程序在第 49 行评估分类器。

  • StringBuilder 类构建应用程序输出。应用程序最终在第 56 行显示输出。 StringBuilder 类在第 55 行检索分类器功能。

001   package android.wickham.com.WekaModelLoad; 002 003   import ... 004 005   import weka.classifiers.Classifier; 006   import weka.classifiers.evaluation.Evaluation; 007   import weka.core.Instances; 008   import weka.core.converters.ConverterUtils; 009 010   public class MainActivity extends Activity { 011 012       @Override 013       protected void onCreate(Bundle savedInstanceState) { 014           super.onCreate(savedInstanceState); 015           setContentView(R.layout.activity_main); 016 017           ConverterUtils.DataSource sourceTrain, sourceTest = null; 018 019           StringBuilder builder = new StringBuilder(); 020           TextView results = (TextView) findViewById(R.id.results); 021 022           try { 023               // Load the Test data 024               builder.append("\n" + getCurrentTimeStamp() + ": Loading test data"); 025               sourceTest = new ConverterUtils.DataSource(getResources().openRawResource(R.raw.subject101_cleaned_5k)); 026               Instances dataTest = sourceTest.getDataSet(); 027               builder.append("\n" + getCurrentTimeStamp() + ": Test data load complete"); 028 029               // Set the class attribute (Label) as the first class 030               dataTest.setClassIndex(0); 031 032               Classifier rf; 033 034               builder.append("\n" + getCurrentTimeStamp() + ": Loading model"); 035               // The following code utilizes the AssetManager to load the model from the app->src->main->assets folder 036               AssetManager assetManager = getAssets(); 037               InputStream is = assetManager.open("rf_i10_cross.model"); 038               rf = (Classifier) weka.core.SerializationHelper.read(is); 039 040               // Alternatively, use the next line to load the model from the app->src->main->res->raw folder 041               // rf = (Classifier) weka.core.SerializationHelper.read(getResources().openRawResource(R.raw.rf_i10_cross)); 042 043               builder.append("\n" + getCurrentTimeStamp() + ": Model load complete"); 044               Toast.makeText(this, "Model loaded.", Toast.LENGTH_SHORT).show(); 045 046               // Evaluate the classifier 047               builder.append("\n" + getCurrentTimeStamp() + ": Starting classifier evaluation"); 048               Evaluation eval = new Evaluation(dataTest); 049               eval.evaluateModel(rf, dataTest); 050               builder.append("\n" + getCurrentTimeStamp() + ": Classifier evaluation complete"); 051 052               // Show the results 053               builder.append("\n\nModel summary: " +  eval.toSummaryString()); 054               // Add the classifier capabilities 055               builder.append("\nRF Model capabilities:\n" +  rf.getCapabilities().toString()); 056               results.setText((CharSequence) builder.toString()); 057 058           } catch (Exception e) { 059               e.printStackTrace(); 060           } 061       } 062 063       public String getCurrentTimeStamp() { 064           return new SimpleDateFormat("HH:mm:ss.SSS").format(new Date()); 065       } 066   } Listing 6-2

Weka 模型加载 MainActivity.java

该应用程序正在使用预训练模型对 5,000 个实例进行批量分类。如果您可以通过这个批处理操作获得不错的性能,那么您可以确信该架构足以对单个实例进行分类。

Figure 6-9 shows a screenshot of the app after it has finished its task.img/468661_1_En_6_Fig9_HTML.jpg Figure 6-9

Weka 模型负载

所示的应用程序运行在 Android Studio 仿真器中。模型加载时间约为 1.5 秒,评估时间不到半秒。这些似乎是很好的结果。在下一节中,您将进一步探究性能。

批次分类的准确性非常高:在 5,000 个错误分类的实例中只有 11 个。这很可能是因为测试数据是最初用于建立模型的训练数据的子集。

Weka Model Load Android 应用程序证明,您可以在 Android 上加载大型、预训练的模型,并高效地进行批量分类。

6.6 Android Weka 型号性能

Several factors contribute to the overall performance of ML models on devices, including

  • 模型尺寸

  • 模型复杂性

  • 设备的 CPU 和内存容量

  • 模型的应用程序代码集成

The Weka Model Load app provides timestamps. You can run the app on different devices to benchmark the relative performance. Table 6-8 shows a calculated summary of the timestamps for three operations:

  • 测试数据加载时间(加载 5000 个测试数据实例)

  • 模型加载时间(加载 5MB RF PAMAP2 subject101 模型)

  • 分类器评估

A special version of the app was created to run on the Amazon Fire Phone and Raspberry Pi. The app also ran in the Android studio Emulator and on a few devices, including the Moto X4, Sony Xperia, and an older Nexus tablet.Table 6-8

Android Weka ML 型号性能对比

|

设备

|

测试数据加载时间(5K)(秒。)

|

模型加载时间(5MB)(秒。)

|

分类器评估时间(秒。)

|
| --- | --- | --- | --- |
| Android Studio 仿真器 | Zero point two eight | One point five six | Zero point three six |
| 摩托罗拉 X4 | Zero point two | One point two seven | Zero point six four |
| 索尼体验 | Zero point one six | One point one six | Zero point four five |
| Nexus 7 平板电脑 | One point five one | Three point five two | One point seven one |
| 亚马逊消防电话 | Zero point four seven | Two point seven six | Zero point nine three |
| 树莓 Pi 3b+ | Zero point six two | Three point four four | Zero point eight two |

Summary of the performance results:

  • 对于 CPU 速度更快的新设备,分类时间不到 0.5 秒。

  • 任何设备的内存都不是问题。5MB 型号很容易加载到内存中,尽管对于 CPU 速度较慢的设备来说没有那么快。

  • 亚马逊 Fire 手机不再是一款相关的 Android 设备。它很旧,缺乏现代的 Android 版本,硬件规格也过时了。然而,你的代码在这个设备上运行良好的能力证明了重要的一点。

有时,您可能需要在不包含 Google Play 服务的 Android 设备上部署 CML 解决方案。您为 Android 部署的 CML 解决方案不需要任何 Google 服务,甚至不需要网络连接。

  • Android Studio 模拟器在对 5000 个实例进行分类时表现最佳。结果令人惊讶,因为通常你不会期望仿真器胜过实际的硬件。但是,请记住,分类器评估主要是 CPU 密集型操作(算法处理),桌面的 CPU 比目标移动设备强大得多。

  • 模型加载时间非常合理。典型的应用程序将对单个实例进行增量分类,正如您将在下一个示例中看到的,这将是一个比 5,000 个实例的批量分类快得多的操作。

那么,当您加载更大的模型时,性能会发生什么变化呢?您可能会发现这样的情况:您希望以牺牲更大的模型尺寸为代价来获得更高的精度。

When you built the RF model for i=10 iterations, you also built one for i=100 iterations. Recall it took much longer to create and the size was much larger, approximately 55MB. Table 6-9 shows a model load time comparison for the smaller and larger models.Table 6-9

Android Weka ML 型号性能对比

|

设备

|

模型加载时间(5MB 模型 RF i=10)(秒。)

|

模型加载时间(50MB 模型 RF i=100)(秒。)

|
| --- | --- | --- |
| Android Studio 仿真器 | One point five six | Twelve point six one |
| 摩托罗拉 X4 | One point two seven | Nine point nine eight |
| 索尼体验 | One point one six | Nine point four two |

There are several points to consider when creating and loading models of this increased order of magnitude:

  • 虽然模型大了十倍,但是加载时间并不是线性的。在这种情况下,对于这些设备,加载时间大约要长八倍。

  • 这种尺寸的模型大约需要 10 秒钟加载。这太长了,无法在应用程序初始化期间隐藏。大型模型将需要表 6-4 中讨论的模型管理策略之一。

  • 整合这种规模数量级的模型是可行的,但您首先需要确定它们提供了足够高的精度优势。

现在,您对模型在 Android 移动设备上的性能有了一些信心,让我们将目标受众扩展到其他 Java 设备。

6.7 树莓 Pi 集成

回到第一章,你看到了 Java 设备的市场是巨大的;据甲骨文称,超过 30 亿台设备运行 Java。Raspberry Pi 是一个非常流行的可以运行 Java 的设备。在本节中,您将把 CML 模型部署到 Raspberry Pi。

熟悉 Pi 的开发人员也会熟悉 Arduino。Arduino 设备占用空间较小,因此不适合运行 Java。但是,如果您有 Arduino 应用程序,您可以使用开源 RXTX 库用 Java 控制这些设备。使用这个库,基于 Java 的主设备(如 Pi)可以处理 ML 操作,并与 Arduino 设备进行通信,以收集数据或输出模型结果。RXTX 库和其他信息可从以下网站获得:

【https://github . com/xtx/xtx】

【http://xtx . qbang . org/wiki/index . PHP/FAQ

Table 6-1 showed the basic hardware specifications of the Raspberry Pi 3 model b+. A quick glance at the table shows that the Pi has about one-half the processing and storage capability compared to a mid-tier Android device. Figure 6-10 shows the Raspberry Pi 3 model b+ and highlights some of the key interfaces.img/468661_1_En_6_Fig10_HTML.jpg Figure 6-10

Raspberry Pi 3 模型 b+和接口摘要

Raspberry Pi 极具吸引力,因为它价格低廉,并且具有许多有用的功能和接口,包括 HDMI、4xUSB、USB 供电、Micro SD 卡、GPIO 引脚接口、Wifi、千兆以太网、蓝牙和 BLE。完整的规格列表可在此处找到:

【www.raspberrypi.org/products/raspberry-pi-3-model-b-plus/】

All of these features make the Pi an interesting choice for many ML applications.

  • Pi 是 kiosk 应用程序的绝佳选择。您可以纵向或横向连接 HDMI 显示器,并直接从 Java 应用程序驱动它们。

  • 您可以将小型显示器直接连接到 Pi。从双线液晶显示器到 7 英寸触摸屏,应有尽有。

  • 你可以连接无数的按钮,传感器,发光二极管等。并从 Java 应用程序中控制它们。传感器可用于运动、加速度、温度、水、风等。

  • Raspberry Pi 通过 HDMI 端口旁边的头部连接支持外部摄像头。在您的 Pi 中添加相机模块,为 ML 应用程序使用的图片和视频数据收集打开了大门。

  • 您可以将无线 USB 小键盘和键盘连接到 Raspberry Pi。这些设备可以控制软件应用程序,即使该应用程序没有监视器或显示器。

  • 树莓派有无数的潜在用途。快速的互联网搜索揭示了开发人员正在用树莓 Pi 做的许多惊人的事情。

ML 的 Raspberry Pi 设置

设置 Raspberry Pi 很容易,并且有许多在线支持资源可用。官方 Raspberry Pi 设置指南可从以下网址获得

https://projects . raspberry pi . org/en/projects/raspberry-pi-setting-up

为 ML 集成设置 Raspberry Pi 3 model b+不需要任何特殊步骤。操作系统和所有应用软件都存储在微型 SD 卡上。Pi 支持很多操作系统,安装时你会选择官方的 Raspbian 操作系统。Raspbian 是 Debian 为 ARM CPUs 开发的一个非官方端口,它是当今最流行的 Raspberry Pi 操作系统。它非常类似于使用 Ubuntu,并且支持 Apache、Nginx、Java、Python 和 MySQL。

The steps below summarize the Raspberry Pi setup. Refer to the official link for the detailed setup steps.

    下载树莓派 NOOBS(新的开箱即用软件)安装管理器,并将其复制到微型 SD 卡。

    将 microSD 卡插入 Pi。

    连接显示器和键盘,并使用 USB 电源线打开 Pi 电源。

    遵循安装说明。选择Raspbian作为操作系统。好消息是 Raspbian 包含了 Java。

*** 5.

设置 Wifi 或互联网连接,以便您可以在 Raspbian 安装完成后更新所有软件包。

 *   6.

如果您想从另一台联网设备连接到 Pi,请设置 IP 地址。这不是必需的,因为您只需插入一个闪存驱动器并使用文件管理器复制文件,就可以将文件复制到 Pi 上。

 *   7.

登录 admin 用户并确认最新版本的 Java 可用。Raspbian 包含 Java,但是如果需要,下面的命令可以在 Raspberry Pi 上升级 Java。这些步骤包括删除 OpenJDK、获取密钥,然后安装最新的 Oracle Java 8。

 **

001   // Install the latest Java version 002   // First remove OpenJDK 003   sudo apt-get purge openjdk 004 005   // Add the digital key 006   sudo apt-key adv --recv-key --keyserver keyserver.ubuntu.com EEA14886 007   // Using an editor such as vi or vim, add the following lines to /etc/apt/sources.list 008   deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main 009   deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main 010 011   // install Java 8 012   sudo apt-get update 013   sudo apt-get install oracle-java8-installer 014   sudo apt-get install oracle-java8-set-default 015 016   // Remove the old Java(s) 017   sudo apt-get purge openjdk 018   sudo apt-get purge java7* 019   sudo apt-get autoremove 020 021   // Check for success, we should only see Java 8 022   java -version

Raspberry Pi GUI 注意事项

One of the main challenges when writing Java applications for the Raspberry Pi, especially for Android developers, is mastering the GUI limitation of pure Java. On the Raspberry Pi, you lack the following elements that make it so easy to implement GUI interfaces on Android:

  • Android 允许你用 XML 指定布局,并有许多图形工具来简化 GUI 设计。

  • Android 支持大量的小部件和类,比如布局、列表视图、约束布局以及无数的 GUI 元素和工具。

  • Android 平台可以自动支持各种屏幕尺寸,从小到非常大的设备。

  • 它提供了对 9 补丁图像文件的支持,使图像(如按钮)易于缩放。

  • Android Studio 为所有 XML 布局文件提供了“所见即所得”(wysiwyg)的视图。您可以通过简单地拖放 GUI 小部件元素来轻松创建 GUI。

For Java ML applications on the Raspberry Pi, you will use the Swing and AWT GUI classes available in Java. The Java GUI classes have several layout managers available. For the project, you will implement the GroupLayout Manager.

将 ML 功能放在 Raspberry Pi 设备的边缘是一个令人兴奋的新领域,这是由 Raspberry 设备功能及其对 Java 和轻量级 Weka API 库的支持实现的。

树莓 PI 的 Weka API 库

In order to use Weka on the Raspberry Pi, you need a Weka API jar file for Raspberry Pi that you can include in your application. You have two options, as shown in Table 6-10.Table 6-10

Raspberry Pi Weka API 库比较

|

图书馆

|

大小(MB)

|

描述

|
| --- | --- | --- |
| WEKA-src . jar | Ten point six | 随每个 Weka 稳定版本(如 Weka 3.8.1)分发的全功能 Weka API。 |
| WEKA-Android-3-8-1 . jar??] | Three point three | 本章前面你在 Eclipse 中为 Android 构建的 Weka API 的精简版本。 |

您有两个选择,因为您为 Android 构建的精简版本也可以在 Raspberry Pi 上运行。这种选择的优点是它更小。完整版的一个优点是你可以在 Raspberry Pi 上使用 Weka 的图形功能,比如可视化。接下来,您将在 Raspberry Pi 上实现 ML,使用Weka-Android-3-8-1 . jar库。

项目:树莓皮老忠实喷泉分类器

Printing out a screen filled with ML classifier statistics, as you did earlier for Android, is not a very compelling app.

最好的人工智能应用程序是那些能给用户带来引人注目的体验的应用程序,而用户从来没有意识到人工智能技术是实现这一结果的原因。

这个项目的目标是为 Raspberry Pi 实现一个基于 GUI 的应用程序,它集成了一个预训练的 ML 模型来进行预测。

在第五章中,您回顾了老忠实间歇泉数据集,并看到了聚类如何帮助您识别数据中的隐藏模式。间歇泉有两种“模式”,我们称之为“热模式”和“暖模式”地质学家可能对这种现象有更好的术语。更长的等待时间与更长的喷发时间相关联,这是有道理的。有趣的是这是两种截然不同的模式。

如果你去过黄石公园,你可能会记得公园管理处有一个简单的手写信息板,提示下次火山爆发的时间,大约每小时一次。

对于这个项目,您将为 Raspberry Pi 创建一个应用程序,它可以根据等待时间和喷发时间通知我们当前的间歇泉模式。您可以轻松地将这个 Pi 应用程序部署为 kiosk 应用程序,以取代手写信息板。

In the app, you will implement some simple requirements:

  • 用户将输入等待时间和爆发时间的值。

  • 用户将按下预测按钮来获得间歇泉模式的预测。

  • 该应用程序将在树莓派上运行。

  • 该应用程序将加载一个预构建的模型来处理预测。

  • 该应用程序将包括一些基本的图形用户界面元素。

该应用程序手动运行,但你可以用摄像机自动输入手动数据来检测火山爆发,或者可能添加按钮和计时器来帮助收集数据。

Table 6-11 shows the project summary.Table 6-11

Android 老忠实项目总结

|

项目:老忠实

来源:old _ faithful . zip

类型:树莓 Pi ML 应用

注意:这个项目是一个 Eclipse Java 项目,用来构建和导出old faithful . jar类,一个可以在 Raspberry Pi 设备上运行的分类器。

|
| --- |
|

文件

|

描述

|
| --- | --- |
| 【srcOldFaithful.java】> | 主 Java 类。包含了包括 GUI 代码在内的所有内容。从外部 Unix 文件系统目录加载模型和数据文件。 |
| old faithful->libsWeka-Android-3-8-1 . jar | Weka API 库文件。你可以用安卓版的树莓派。 |
| /home/pi/Java-proj/Weka/old _ faithful _ RF _ i10 . model | RF 模型,外部文件 |
| /home/pi/Java-proj/Weka/old _ faithful _ single _ instance . ARFF | 数据的单一实例。外存储器 |

除了主 Java 文件,项目还需要 Weka API 库,外部 Weka 。model 文件,在这个例子中是一个 RF 分类器,还有一个 ARFF 文件,我将在后面讨论。

应用概述

Before you review the project setup and Java code, you should launch the application to see how the app looks. You can launch the Java app on the desktop or on the Raspberry Pi with the following command:001   pi@raspberrypi:/Java-proj/Weka $ java -jar OldFaithful.jar You use the -jar option on the command line because this project build output is an executable jar file, OldFaithful.jar. When the jar file executes, the app displays the GUI shown in Figure 6-11. In this example, you entered two values and pressed the Predict button and the application informs you the geyser is in warm mode.img/468661_1_En_6_Fig11_HTML.jpg Figure 6-11

老忠实喷泉应用程序显示温暖模式

Entering some different data produces the hot mode result, as shown in Figure 6-12.img/468661_1_En_6_Fig12_HTML.jpg Figure 6-12

老忠实喷泉应用程序显示热模式

当您尝试不同的值时,您会注意到应用程序输出的模式与您在图 5-20 中得出的聚类结果非常一致。在第五章中,您使用了 DBSCAN 聚类算法来对旧的忠实数据集进行聚类。

通常,分类器是将 ML 模型集成到设备应用程序中最有用的方法。在这种情况下,集群帮助您识别出间歇泉有两种模式,现在您希望用户能够知道间歇泉处于哪种模式。换句话说,应用程序需要对新的数据实例进行分类。对数据进行聚类是识别隐藏模式的第一步;现在你需要建立一个分类器。

构建分类器模型

When you clustered the data using the DBSCAN algorithm, you also saved the output file, old_faithful.arff. This file contained four attributes, including the cluster_ID for each instance. You can now use this file as the input to build a classifier for the Raspberry Pi app. Follow these steps to build a RF classifier in the Weka desktop:

    打开 Weka Explorer 应用程序。

    预处理 选项卡下,选择 打开文件 打开old _ faithful . ARFF文件。观察到加载了 272 个实例。

    不需要过滤器,所以点击 分类 标签。

    分类器 下,从子菜单中选择 随机森林 算法。点击算法,改变 迭代次数= 10

*** 5.

在 ***测试选项*** 下,选择 ***交叉验证折叠数= 10*** 。

 *   6.

***启动*** 这个量词。当它完成的时候,观察准确率很高,大概接近 99%。

 *   7.

右键单击结果列表,用名称***old _ fiath ful _ RF _ i10 . model***保存模型。

 **

**To use this RF classification model with the application on Raspberry Pi, save the model on the Raspberry Pi in the same directory with the executable jar file and the external ARFF file (you will create these assets next) as shown:001   pi@raspberrypi:~/Java-proj/Weka $ pwd 002   /home/pi/Java-proj/Weka 003   pi@raspberrypi:~/Java-proj/Weka $ ls -lsart 004   total 3184 005     40 -rw------- 1 pi pi   38599 Jul 27 19:27 old_faithful_rf_i10.model 006      4 drwxr-xr-x 4 pi pi    4096 Jul 27 23:32 .. 007      4 -rw------- 1 pi pi     207 Jul 27 23:54 old_faithful_single_instance.arff 008   3132 -rw------- 1 pi pi 3205683 Jul 28 00:03 OldFaithful.jar 009      4 drwxr-xr-x 2 pi pi    4096 Jul 28 00:11 . 010   pi@raspberrypi:/Java-proj/Weka $ java -jar OldFaithful.jar

接下来,您将了解如何构建应用程序软件,包括 GUI、加载 Weka 模型以及用 Java 进行预测。

项目设置

To get started with the Old Faithful project for Raspberry Pi, import the Eclipse Java project (OldFaithful.zip) from the book resources, or follow these steps to create an Eclipse Java project from scratch:

    通过选择 文件新建Java 项目 启动一个新的 Eclipse 项目

    输入项目名称为

*** 3.

在新创建的项目中,在主项目文件夹下创建一个 ***libs*** 目录。

 *   4.

将***Weka-Android-3-8-1 . jar***文件复制到 ***libs*** 目录下。

 *   5.

在 ***项目属性*** 中,设置 Java 版本为 1.8。对于 Raspberry Pi,不像 Android 那样局限于 Java 7。

 *   6.

在 ***项目属性*** 中,点击 ***构建路径******管理构建路径*** 。

 *   7.

点击 ***库*** 选项卡。点击 ***添加 Jar*** 将***Weka-Android-3-8-1 . Jar***文件作为 Jar 文件包含进来。

 *   8.

在 ***Src*** 目录下,创建【OldFaithful.java】**主类。所有的应用程序代码都驻留在这个类中,您将在下一节中查看它。**

***   9.

编辑启动配置属性。将 ***主类*** 设置为 ***OldFaithful*** ,如图 6-13 所示。如果您未能设置启动配置 ***主类*** ,您将无法直接从命令行执行旧的忠实应用程序,因为主类将是未知的。

 ****

****img/468661_1_En_6_Fig13_HTML.jpg Figure 6-13

设置项目启动配置

Java 布局管理器

从 AWT 到 Swing,再到最近在 Java 8 中首次亮相的 JavaFX,Java 的 GUI 功能已经得到了逐步的改进。JavaFX 是一组图形和媒体包,帮助开发人员设计、创建、测试、调试和部署在不同平台上一致运行的应用程序。Java FX 与当今非常流行的 Web 和富媒体很好地集成在一起。

遗憾的是,Java FX 并不是一个轻量级的包,树莓 Pi 上的 Java 也没有包含它。可以添加,但是它不支持所有的库,并且实现起来有问题。正因如此,你会为老忠实 app 使用更成熟的 Swing GUI 库。Swing 完全支持所有设备平台。

Swing has several LayoutManagers, including the following:

  • 【边缘布置】

  • 【拳击版面】

  • 【cardlayout】

  • 【流动布局】

  • 【grid bag layout】

  • 网格布局

  • 【群布局】

  • 跳线布局

这些名称为可能的用例提供了一些见解,但是理解这些不同布局的功能的最简单的方法是查看它们。Oracle 维护了一个有用的链接,网址为

https://docs . Oracle . com/javase/tutorial/ui swing/layout/visual . html

如果你仔细观察图 6-12 所示的图形用户界面,你可以看到它由标签、文本输入框、按钮和显示分类结果的大字体边框文本框组成。这些 GUI 组件排列在一个 2 列 5 行的矩阵中。

您可以选择几个 Swing 布局管理器来基于期望的布局实现旧的忠实 GUI。如果您来自 Android 背景,您会发现 Swing 布局很难使用,主要是因为它们没有为使 GUI 看起来漂亮所需的间距、填充和一般样式提供太多控制。GroupLayout 管理器往往是最灵活的,因此您将实现它。

如果您发现无法实现 Java FX,并且 Swing 布局无法满足您的 GUI 需求,那么您可以考虑使用外部替代布局管理器。米格布局管理器是一个极好的选择。这是一个轻量级的 Java 库,比内置的 Swing 布局管理器灵活得多。图书馆的详情载于

**www.miglayout.com/

GUI 实现

应用程序的所有 Java 代码都包含在中。文件名保留了 Android 惯例,尽管这是一个 Raspberry Pi 应用程序,并且从技术上讲不是一个活动。您将在两个部分回顾代码:首先是与 GUI 相关的代码,然后是 ML 逻辑。

**Java Swing GUI 类允许您创建 JFrame 对象。你可以在任何框架中添加组件,比如 JLabelsJButtonsJTextFields ,这与 Android 的工作方式非常相似。为了控制组件的排列方式,Swing 允许您将前面显示的布局分配给 JFrames 。对于这个项目,您将使用 组布局

A summary of the key GUI code highlights:

  • 通过扩展 JFrame (第 001 行),在 Java Swing 中创建一个 GUI。

  • 定义组件,包括 JFrameGroupLayoutJButtonJLabelTitledBorderJTextField (第 002-011 行)。

  • 定义构造函数(第 013 行)。

  • 组布局 构建 GUI(第 034-055 行)。

  • 私有方法 setGeyserMode (第 066-100 行)用来自 ML 模型的新分类结果更新 GUI。您通过调用 替换 方法来更新 组布局 (第 097 行)。

Listing 6-3 shows all of the GUI-related code.001   public class OldFaithful extends JFrame { 002       static JFrame jf; 003       static GroupLayout layout; 004       static JTextField waitTime, eruptTime; 005       static JLabel priorLabel; 006       statis JButton classifyButton; 007       static TitledBorder tBorderWarm, tBorderHot, tBorderUnknown; 008       static Border borderOrange = BorderFactory.createLineBorder(Color.orange, 5, true); 009       static Border borderRed = BorderFactory.createLineBorder(Color.red, 5, true); 010       static Border borderGray = BorderFactory.createLineBorder(Color.gray, 5, true); 011       static String modeTitle = "Old Faithful Mode"; 012 013       public OldFaithful() { 014           super("OldFaithful"); 015           // Init Frame 016           JFrame.setDefaultLookAndFeelDecorated(true); 017           jf = new JFrame(); 018           jf.setTitle("Old Faithful Geyser Clasifier"); 019           jf.setResizable(true); 020           jf.setExtendedState(JFrame.MAXIMIZED_BOTH); 021           jf.setDefaultCloseOperation(EXIT_ON_CLOSE); 022           jf.setUndecorated(false);   // true for no title and menu 023           jf.setVisible(true); 024           layout = new GroupLayout(jf.getContentPane()); 025           jf.getContentPane().setLayout(layout); 026           layout.setAutoCreateGaps(true); 027           layout.setAutoCreateContainerGaps(true); 028 029           // Setup the labels 030           JLabel labelWait = new JLabel("Enter Waiting Time:"); 031           JLabel labelErupt = new JLabel("Enter Eruption Time:"); 032           JLabel labelResult = new JLabel("Results:"); 033 034           // Build the layout using the Swing GroupLayout 035           layout.setHorizontalGroup(layout.createSequentialGroup() 036               .addGroup(layout.createParallelGroup() 037                   .addComponent(labelWait) 038                   .addComponent(labelErupt)) 039               .addGroup(layout.createParallelGroup() 040                   .addComponent(waitTime) 041                   .addComponent(eruptTime) 042                   .addComponent(classifyButton) 043                   .addComponent(labelResult) 044                   .addComponent(priorLabel)) 045           ); 046           layout.setVerticalGroup(layout.createSequentialGroup() 047               .addGroup(layout.createParallelGroup() 048                   .addComponent(labelWait) 049                   .addComponent(waitTime)) 050               .addGroup(layout.createParallelGroup() 051                   .addComponent(labelErupt) 052                   .addComponent(eruptTime)) 053               .addComponent(classifyButton) 054               .addComponent(labelResult) 055               .addComponent(priorLabel) 056           ); 057 058           jf.pack(); 059           jf.validate(); 060           jf.repaint(); 061       } 062 063       // The main class includes the ML logic and is not shown in this listing 064       public static void main(String args[]){} 065 066       private static void setGeyserMode(int mode) { 067           // Udate the results depending on the mode the RF classifier has returned 068           JLabel label = null; 069           if (mode == 2) { 070               tBorderHot = BorderFactory.createTitledBorder(borderRed, 071                      modeTitle, 072                      TitledBorder.CENTER, 073                      TitledBorder.CENTER, 074                      Font.decode("Arial-bold-14")); 075               label  = new JLabel("   Hot Mode   "); 076               label.setFont(Font.decode("Arial-bold-28")); 077               label.setBorder(tBorderHot); 078           } else if (mode == 1) { 079               tBorderWarm = BorderFactory.createTitledBorder(borderOrange, 080                      modeTitle, 081                      TitledBorder.CENTER, 082                      TitledBorder.CENTER, 083                      Font.decode("Arial-bold-14")); 084               label  = new JLabel("   Warm Mode  "); 085               label.setFont(Font.decode("Arial-bold-28")); 086               label.setBorder(tBorderWarm); 087           } else { 088               tBorderUnknown = BorderFactory.createTitledBorder(borderGray, 089                      modeTitle, 090                      TitledBorder.CENTER, 091                      TitledBorder.CENTER, 092                      Font.decode("Arial-bold-14")); 093               label  = new JLabel(" Unknown Mode "); 094               label.setFont(Font.decode("Arial-bold-28")); 095               label.setBorder(tBorderUnknown); 096           } 097           layout.replace(priorLabel, label); 098           // reset the priorLabel so it can be updated next time 099           priorLabel = label; 100       } 101   } Listing 6-3

java:与 GUI 相关的代码

单实例数据文件

在本章的前面,您已经了解了如何通过加载包含许多实例的数据文件来进行批量预测,对于 PAMAP2_Dataset 示例,有 5,000 个实例。对于旧的忠实应用程序,不是批量分类,而是每次按下按钮时对单个实例进行分类。

加载单个实例 ARFF 文件是让应用程序了解数据结构的一种简单方法。将单实例数据文件视为数据的一种数据字典,这是我在第二章中讨论的最佳实践。如果更新数据结构或更改任何数据类型,则应该更新单实例数据文件。

Using the single instance ARFF file has two advantages:

  • 这种方法从应用程序代码中抽象出数据结构,使得代码更容易维护。

  • 外部文件方法简化了 ML 代码,因为没有必要在 Java 中定义所有的属性和数据类型。

Listing 6-4 shows the old_faithful_single_instance.arff file. You can easily create the file from the original ARFF file by simply deleting all of the instances except for one.001   @relation subject101-cleaned-weka.filters.unsupervised.attribute.NumericToNominal-Rfirst 002 003   @attribute activityID {1,2,3,4,5,6,7,12,13,16,17,24} 004   @attribute accelX numeric 005   @attribute accelY numeric 006   @attribute accelZ numeric 007   @attribute gyroX numeric 008   @attribute gyroY numeric 009   @attribute gyroZ numeric 010   @attribute magnetX numeric 011   @attribute magnetY numeric 012   @attribute magnetZ numeric 013 014   @data 015   1,2.30106,7.25857,6.09259,-0.069961,-0.018328,0.004582,9.15626,-67.1825,-20.0857 Listing 6-4

old _ faithful _ Single _ Instance . arff,单实例 ARFF 文件

从文件加载数据结构的另一种方法是使用 Weka API 属性实例 类在 Java 中手动定义该结构。

您需要部署与可执行 jar 文件和 ML 模型文件打包在一起的单实例 ARFF 文件。

ML 代码

清单 6-5 显示了所有的 ML 代码。它出奇的简短。正如所承诺的,你只需要加载模型并开始进行预测,而不是编写大量的代码。

Highlights of the ML code:

  • 主类运行构造函数(第 003 行)。本例中的构造函数执行大部分 GUI 设置。

  • 它加载单实例 ARFF 文件(行 005-011)。

  • 它加载分类器,一个在 Weka 中创建的 RF 模型(行 013-017)。

  • 它设置一个按钮来执行分类(行 019)。

  • 它实现了predict button pressed从两个 GUI 输入字段中读取值(第 031 行)

  • 它创建一个新实例进行分类,指定 爆发等待 值(第 037-043 行)。

  • 它对实例进行分类(第 046 行)。

  • 它根据分类结果设置间歇喷泉模式(第 048-050 行)。

The ML code resides in the public main class.001   public static void main(String args[]){ 002       // Run the constructor 003       new OldFaithful(); 004       try { 005           // Load a Test data instance so we can classify more easily 006           ConverterUtils.DataSource sourceTest = null; 007           String wekaDataStrUnix = "/home/pi/old_faithful_single_instance.arff"; 008           sourceTest = new ConverterUtils.DataSource(wekaDataStrUnix); 009           dataSet = sourceTest.getDataSet(); 010           // Set the class attribute (Label) as the last class, the ClusterID 011           dataSet.setClassIndex(3); 012 013           // Load the model, a RF model created from the ARFF data and saved in Weka Explorer 014           File wekaModelFileUnix = new File("/home/pi/old_faithful_rf_i10.model"); 015           FileInputStream fis = new FileInputStream(wekaModelFileUnix); 016           rf = (Classifier) weka.core.SerializationHelper.read(fis); 017           fis.close(); 018 019           // Classify button 020           JButton classifyButton = new JButton("Predict Geyser Mode"); 021           classifyButton.addActionListener(new ActionListener() { 022               public void actionPerformed(ActionEvent e) { 023                   predictButtonPressed(); 024               } 025           } ); 026       } catch (Exception e) { 027           e.printStackTrace(); 028       } 029   } 030 031   private static void predictButtonPressed() { 032       // Get a prediction from the classifer and update the Geyser Mode 033       try { 034           double wait = Double.valueOf(waitTime.getText()); 035           double erupt = Double.valueOf(eruptTime.getText()); 036 037           // Create a new instance to classify 038           Instance newInst = new DenseInstance(4); 039           newInst.setDataset(dataSet); 040           newInst.setValue(0, 0); 041           newInst.setValue(1, erupt); 042           newInst.setValue(2, wait); 043           newInst.setValue(3, 0); 044 045           // Classify the Instance 046           double result = rf.classifyInstance(newInst); 047 048           if (result == 1.0) setGeyserMode(1); 049           else if (result == 0.0) setGeyserMode(2); 050           else setGeyserMode(0); 051       } 052       catch (NumberFormatException e) { 053            //Not a double so set unknown mode 054           setGeyserMode(0); 055       } 056       catch (Exception e) { 057           e.printStackTrace(); 058       } 059   } Listing 6-5

MainActivity.java: ML 相关代码

ML 模型的异常处理

异常处理是应用程序开发中比较重要的方面之一。然而,大多数开发人员没有在这方面花费足够的时间。

在 ML 应用程序中,模型是应用程序的关键组件。模型的准确性非常重要,但是如果模型完全失败,产生一个异常怎么办?如果模型失败了,应用程序就失败了,你需要知道这些。在大多数例子中,包括上面的清单 6-5 ,您在模型异常的情况下打印出一个堆栈跟踪,但是没有采取任何其他的动作。对于驻留在 Raspberry Pi 设备或 Android 手机上的商业 ML 应用程序,您需要一种更健壮的方法。远程崩溃日志记录是一种解决方案。

远程崩溃日志背后的想法是收集帮助开发人员解决问题所需的必要信息,并在应用程序因崩溃而终止之前将其发送到远程服务器。

在 Android 设备上,有许多远程崩溃记录服务可用。最受欢迎的服务是谷歌的 Firebase Crashlytics。有关为 Android 设置 Crashlytics 的详细信息,请访问

firebase.google.com/docs/crashlytics/

还有许多第三方服务、库和后端服务器可用于实现 Android 崩溃日志记录。有关所有服务的总结,请参考作者 Android 书籍中的崩溃日志章节,网址为

github.com/apress/practical-android

在像 Raspberry Pi 这样的设备上,为日志和传感器数据收集设计的第三方服务可以很好地用于远程崩溃日志记录。其中最流行的是来自 Rapid 7 的 LogEntries ,它可以接受任何类型的 JSON 格式的数据作为有效负载:

logfactors . com

These services work by using the Java UncaughtExceptionHandler method. The following code shows how to use the handler to implement the DefaultExceptionHandler:001   public class DefaultExceptionHandler implements UncaughtExceptionHandler{ 002       private UncaughtExceptionHandler mDefaultExceptionHandler; 003 004       //constructor 005       public DefaultExceptionHandler(UncaughtExceptionHandler pDefaultExceptionHandler) 006       { 007           mDefaultExceptionHandler= pDefaultExceptionHandler; 008       } 009       public void uncaughtException(Thread t, Throwable e) { 010           //do some action like writing to file or upload somewhere 011 012           //call original handler 013           mStandardEH.uncaughtException(t, e); 014       } 015   }

这种方法使您有机会在应用程序由于未捕获的异常而终止之前执行一些操作。为了帮助理解为什么一个模型会产生一个异常,通常在异常发生时发送实例属性数据值给服务就足够了。

幸运的是,只要数据和数据类型匹配,Weka 模型故障很少发生,但是当不可避免的崩溃确实发生时,您需要远程崩溃日志记录来查看和分析有问题的数据,以便您可以修复问题。在许多情况下,问题可以通过更正应用程序代码来解决,而在一些罕见的情况下,您必须重新构建模型来消除异常。

为 Raspberry Pi 导出可运行的 jar 文件

Follow these steps to build the Old Faithful runnable jar file:

  • 清理项目并确认没有生成错误。

  • 确认启动配置中的 Java 主类设置如图 6-13 所示。

  • 在 Eclipse 主菜单中,选择 文件导出 ,如图 6-14 所示。

img/468661_1_En_6_Fig14_HTML.jpg Figure 6-14

导出可运行的 jar 文件

  • 点击 下一个 ,会看到如图 6-15 所示的 Runnable JAR 文件导出 画面。

img/468661_1_En_6_Fig15_HTML.jpg Figure 6-15

导出 OldFaithful.jar 文件

  • 确保 库处理 单选按钮选择了 将所需库打包成生成的 JAR 选项。这是必要的,以便 Weka API 库包含在导出的应用程序中。

导出完成后,runnable jar 文件和其他所需的外部文件将足以在任何兼容 Java 的设备上运行旧的忠实应用程序。

在 Raspberry Pi 上自动启动 ML 应用

One of the requirements for the Old Faithful project is to create a kiosk-mode app. Such apps typically have two characteristics:

  • Kiosk 应用程序通常支持显示器或某种类型的视觉输出,但通常没有键盘或鼠标等输入设备。

  • Kiosk 应用程序只有一个用途,在开机或复位时自动初始化。

On Raspberry Pi, there are several methods to achieve automatic start of the OldFaithful.jar file. You can use any of the following five Unix-based approaches to implement automatic start of any application:

  • rc.local :添加系统启动时启动的应用。

  • ??。bashrc :编辑 bash shell 启动文件,在启动时启动应用程序。

  • init.d tab :使用 init.d ,这个目录包含了很多系统服务的启动/停止脚本。

  • systemd :使用 systemd ,一个控制在 Unix 中启动的进程的标准进程。

  • crontab :当应用程序运行时,使用 cron 作业进行调度。

For running executable jar files, the first approach is the most simple and it works well. To configure automatic start on the Raspberry Pi for the OldFaithful.jar file, implement the following steps:

    放置所需的文件,

    old faithful . jar,

    **【old _ faithful _ single _ instance . ARFF】

    old _ faithful _ RF _ i10 . model

    进入 /home/pi/Weka 和你选择的另一个目录。**
    *** 2.

    进入 /etc 目录,用编辑器编辑 rc.local 文件:

    **【sudo nano/etc/RC . local】

    vi 编辑器是一种替代。***** 3.

    将下面一行添加到文件的末尾,在 之前,退出 0 :

    Java-jar/home/pi/Weka/old faithful . jar&

    退出 0;

    * 4.

    保存文件。不要忘记行尾的 && 允许命令在单独的进程中运行。没有它,引导过程将无法完成。

    * 5.

    通过设置 /etc/dhcpcd.conf 文件中的static _ IP _ address为 Pi 添加一个专用 IP 地址。这允许通过以太网连接访问设备,以保持对信息亭设备的访问。

    * 6.

    要禁用 Raspberry Pi 屏幕保护程序,请编辑以下文件:

    sudo nano ~/。config/LX session/lxd-pi/auto start

    该文件应与以下代码匹配:

    【lxppanel-profile lxd-pi】

    # @ x screen saver-no-splash

    @ point-rpi

    @xset s off

    @xset -dpms

    @xset s noblank

    * 7.

    使用 sudo reboot 重启 Pi 并测试更改。

    ****

****#### 项目总结

Raspberry Pi 上的老忠实项目是一个在设备上以 kiosk 模式运行的简单 ML 应用程序。然而,它展示了一个强大的设备 ML 架构,您可以为其他潜在的应用程序复制它。

Highlights of the Raspberry Pi ML architecture:

  • Pi 价格低廉,并且加载了连接选项。

  • Pi 运行 Java,库也很容易获得。

  • Weka API 在 PI 上运行良好。该设备的内存和处理能力使其能够处理高级 CML 问题。

6.8 传感器数据

传感器数据是 ML 应用的绝佳燃料。在第二章中,我介绍了手机可能是有史以来最伟大的数据收集设备。在本节中,您将研究设备功能,并探索如何使用传感器和第二章中介绍的 PAMAP2_Dataset 为 Android 实现 ML。

安卓传感器

You know that Android supports sensors, but a deep dive into the Android APIs reveals a surprising level of sensor coverage. Google divides the Android sensors into three categories: motion, environmental, and position. Table 6-12 shows a summary of the Android sensors. Most of the sensors have been in the platform since API level 14 (Android 4.0). Support for the proximity and humidity sensor is available beginning with API level 20 (Android 4.4).Table 6-12

Android 传感器支持

|

种类

|

传感器

|

Android 传感器类型

|
| --- | --- | --- |
| 移动 | 加速计 | 类型 _ 加速度计类型 _ 线性 _ 加速度 |
| 重力 | 类型 _ 重力 |
| 陀螺仪 | 类型 _ 陀螺仪 |
| 旋转矢量 | 类型 _ 旋转 _ 向量 |
| 环境的 | 气压计 | 类型 _ 压力 |
| 光度计 | 类型 _ 光 |
| 温度计 | 类型 _ 环境温度类型 _ 温度类型 _ 相对湿度 |
| 位置 | 方向 | 类型 _ 方向类型 _ 接近度 |
| 磁力计 | 类型 _ 磁场 |

The Sensor framework allows you to use any of the Android sensors. It includes the following classes:

  • SensorManager :使用此类创建传感器服务的实例。该类包含访问、列出、注册或注销传感器的各种方法。该类还提供了许多用于设置传感器精度和数据采集速率的常数。

  • 传感器 :使用这个类创建一个特定传感器的实例。该类还提供了确定传感器功能的方法。

  • SensorEvent :传感器事件对象允许您收集原始传感器数据。

  • SensorEventListener:使用此接口方法创建回调方法,在传感器值更改时接收通知。

The Android sensors are hardware dependent, so sensor availability varies from device to device and between Android versions. Use the following code to determine sensor availability:001   private SensorManager mSensorManager; 002   ... 003   mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 004   ... 005   List deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);

如果您希望缩小搜索范围,可以用另一个常量替换常量【TYPE _ ALL】,例如 TYPE_GYROSCOPETYPE_GRAVITY

在 Android Activity Tracker 项目中,您将详细研究如何实现 Android 传感器。

带传感器的树莓派

Figure 6-10 shows a picture of the Raspberry Pi. The GPIO interface makes the Pi an excellent device for ML with sensor data collection. The sensors are inexpensive, and you can connect many different types of sensors to the Raspberry Pi. Table 6-13 shows some of the sensor devices that you can connect.Table 6-13

Raspberry Pi 传感器摘要

|

种类

|

传感器

|

描述

|
| --- | --- | --- |
| 环境 | DHT11/DHT22 | 测量温度和湿度。 |
| DS18B20/ DS18S20 | 室外使用温度和湿度。 |
| BMP180 | 气压、温度和高度的气压计。 |
| MQ-2 | 气体传感器。甲烷、丁烷和烟雾。 |
| 移动 | 促进 | 低成本的运动传感器只有在物体移动时才会发出信号。 |
| HC-SR04 战斗机 | 超声波运动传感器。也可以测量距离。 |
| MPU-6050 | 陀螺仪检测沿三个轴的旋转。 |
| HMC5883L/GY-271 战斗机 | 指南针。 |
| 水 | YL-69 土壤湿度计湿度传感器 | 地面湿度传感器。适用于灌溉系统。 |
| 森 0193 | DFrobot 电容式地面湿度传感器。更精确,不会随着时间的推移而侵蚀。 |
| FC-37 +MCP3008 | 雨滴传感器。根据水量,电容会增加。 |
| YF-S201C | 水流量计。 |
| 重力 | HX-711 | 重量传感器和负载秤。 |
| 其他的 | Pulsesensor.com | 心跳和脉搏传感器。 |

The Raspberry Pi has sensors for almost anything you can imagine. The pulse sensor shown at the bottom of Table 6-13 was the result of a recent Kickstarter campaign. The mobile phone is a great data collection device, but for specialized dedicated data collection systems, the Pi takes it to another level.

对于专门的传感器驱动的数据应用,Raspberry Pi 与 Java 和 Weka API 库相结合,构成了一个低成本、功能强大的机器学习平台。

To implement sensors on the Raspberry Pi, you need a Java library to interface with the sensors. There are two options available:

  • PI4J:一个基于 Java 的 API,仅用于树莓 PI

  • 设备 I/O:一个基于 Java 的 API,可以支持许多设备

PI4J 项目是一个面向 Java 的开源库(3.0 版),使得从 Java 与设备进行交互变得很容易。PI4J 的使用说明(包括下载)可在pi4j.com/获得。

Accessing the GPIO and other Raspberry Pi interfaces from Java is very simple, as shown by the following code:001   import com.pi4j.io.gpio.GpioController; 002   import com.pi4j.io.gpio.GpioFactory; 003   import com.pi4j.io.gpio.GpioPinDigitalOutput; 004   import com.pi4j.io.gpio.PinState; 005   import com.pi4j.io.gpio.RaspiPin; 006 007   // create gpio controller 008   final GpioController gpio = GpioFactory.getInstance(); 009 010   // provision gpio pin #01 as an output pin and turn on 011   final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "MyLED", PinState.HIGH); 012 013   // set shutdown state for this pin 014   pin.setShutdownOptions(true, PinState.LOW); 015 016   // turn off gpio pin #01 017   pin.low(); 018 019   // toggle the current state of gpio pin #01 (should turn on) 020   pin.toggle();

PI4J 库和设备 I/O 之间有一些重叠。PI4J 的功能更加丰富。设备 I/O 库来自 Oracle,最初是 Java ME 嵌入式库的一部分。它也是一个开源的 Java 级 API,用于访问嵌入式设备上的通用设备外设。它位于 OpenJDK 项目下,文档位于

docs . Oracle . com/javame/8.0/API/dio/API/index . html

设备 I/O 库为每块板都提供了一个配置文件,因此您可以编写一次代码,并在任何 Java 设备上使用它,而不仅仅局限于 Raspberry Pi。PI4J 和设备 I/O 的主要区别在于 GPIO 映射。

The following is a Java code example using the Device I/O library:001   // 002   // Accessing the GPIO Pin number 12. 003   // 004 005   GPIOPin led = (GPIOPin)DeviceManager.open(12); 006 007   led.setValue(true) //Turns the LED on 008   led.setValue(false) //Turns the LED off 009   boolean status = led.getValue() //true if the LED is on To use Device I/O library you will need to download the Mercurial configuration management system and then clone the project. The name of the actual library is dio.jar:001   sudo apt-get install mercurial 002   hg clone http://hg.openjdk.java.net/dio/dev To run an application using Device I/O, you will need the following:

  • 任何带有 main 方法的标准 Java 类

  • java.policy ,一个包含权限配置的文件

  • dio.jar 库文件

  • libdio.so ,包含本机代码接口的链接库

  • dio.properties ,包含板特定配置的配置文件

传感器测量单位

When working with sensor data, it is important to keep close track of the unit of measure of the data. Sensor manufacturers can use a variety of different units of measure depending on many factors, including accuracy, local standards, country of origin, etc. Table 6-14 shows the unit of measure for some of the Android sensors.Table 6-14

Android 传感器测量单位

|

Android 传感器名称

|

度量单位

|

数据描述

|
| --- | --- | --- |
| 类型 _ 磁场 | 超声试验 | 沿三个轴的磁场强度,单位为微特斯拉 |
| 类型 _ 线性 _ 加速度 | 毫秒 2 | 三轴加速度 |
| 类型 _ 陀螺仪 | 车轮/秒 | 沿三轴的角速度 |
| 环境温度类型 | C | 周围空气温度 |
| 类型 _ 光 | lx | 照度,单位为勒克斯 |
| 类型 _ 压力 | 百帕或毫巴 | 环境空气压力 |
| 类型 _ 相对湿度 | % | 环境相对湿度 |
| 类型 _ 温度 | C | 设备温度 |

使用外部来源的数据时,在与您自己的设备数据混合之前,您需要确保单位一致。如果单位不同,您需要提供到基本数据格式的转换。

在 Android Activity Tracker 项目中,您将使用为 PAMAP2_Dataset 收集的数据。用于构建模型的干净数据包含加速度计、陀螺仪和磁场数据。原始收集设备使用的测量单位与 Android 传感器单位相匹配,因此无需转换。

项目:安卓活动跟踪器

In this project, you are creating an Android application that uses the RF model together with the Android sensors to provide a near real-time prediction of the current activity of the user. Table 6-15 shows the project summary.Table 6-15

Android 活动跟踪器项目总结

|

项目:Activity tracker source:Activity _ tracker . zip类型:Android Studio 项目注意:该项目使用来自 PAMAP2_dataset 的训练模型,结合近乎实时的 Android 传感器数据来确定设备用户的当前活动。

|
| --- |
|

文件

|

描述

|
| --- | --- |
| 【应用】>【libsweka-Android-3-8-1 . jar】 | Android 的 Weka API 库文件。 |
| app->src->main->javaMainActivity.java | 主应用程序源代码包含在这个文件中。 |
| 【app】>【src】>【main】>【RES】>【layout activity _ main . XML】 | 应用程序的主 GUI 布局文件。 |
| app->src->main->RES->rawrf _ i10 _ cross . model | 应用程序用来进行预测的 RF 模型。 |
| 【app】>【src】>【main】>【RES】>【rawsubject 101 _ single .【ARFF】 | 应用程序用来设置数据属性特性的单实例 ARFF 文件。 |

In this project, you want to create an application that gives you a near real-time display of the current activity. Figure 6-16 shows the screenshot of the application.img/468661_1_En_6_Fig16_HTML.jpg Figure 6-16

活动追踪器安卓应用截图

该应用程序显示加速度计、陀螺仪和磁力计的当前传感器值的实时读数。在屏幕底部,应用程序显示当前活动和当前活动 ID,一个介于 1 和 12 之间的整数。当您监控应用程序时,您将看到传感器值实时更新,而当前活动每秒更新两次。

应用架构

Figure 6-17 shows the architecture of the app.img/468661_1_En_6_Fig17_HTML.jpg Figure 6-17

活动跟踪器架构

The structure of the app is similar to the previous examples in terms of loading the model and making the prediction, but contains two additional constructs:

  • 实现SensorEventListener来处理来自加速度计、陀螺仪和磁力计的传入传感器数据。

  • 实现了一个 线程 来处理分类处理的时序。

In this app, you will load the RF model you created in Chapter 5, rf_i10_cross.model. You created the model from a cleaned version of the subject101 dataset. As a result, the model allows you to track the following activities. You define these activities as the String[], named activityID.001   activityID = new String[] { 002           "Other (transient)",    // 0 003           "Lying",                // 1 004           "Sitting",              // 2 005           "Standing",             // 3 006           "Walking",              // 4 007           "Running",              // 5 008           "Cycling",              // 6 009           "Nordic Walking",       // 7 010           "Ascending Stairs",     // 8 011           "Descending Stairs",    // 9 012           "Vacuum cleaning",      // 10 013           "Ironing",              // 11 014           "Rope jumping"          // 12 015   };

您使用这个 字符串[] 打印出结果活动。回想一下,原始数据集包含 24 个活动。期望您的模型对所有这些活动进行分类是不公平的,因为其中一半没有包含在训练数据集中。您排除了一些活动,因为所选主题没有执行这些活动,并且您在清理过程中排除了其他活动。

实现 Android 传感器

A key function of the app is to collect current data from the Android sensors. This is a two-step process:

  • 初始化

  • 实现传感器监听器

The initialization process involves creating objects for each of the three required sensors in the application onCreate method. The following code shows how to create these objects in Android and how to register the SensorEventListener. Keep in mind that you also need to register and unregister the SensorEventListener in the onPause and onResume methods (not shown).001   private SensorManager mSensorManager; 002   private Sensor mAccelerometer, mGyroscope, mMagnetometer; 003 004   mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 005 006   mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); 007   mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); 008   mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); 009 010   mSensorManager.registerListener(mSensorEventListener, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); In line 006, you create the accelerator object. In Android, there are two choices:

  • 传感器。类型 _ 直线 _ 加速器

  • 传感器。类型 _ 加速器

两者的区别在于包含了重力分量。线性加速器消除了重力对读数的影响。对初始数据的分析表明,这种测量方法符合初始数据收集协议,因此您可以在应用中使用这种传感器。

In line 010, you use the SENSOR_DELAY_NORMAL constant in the registerListener method. This value specifies the rate at which you receive samples from the sensors. Table 6-16 shows the options. When using sensors, there is some internal latency, so the typical observed sample rate is higher than the Android-specified value. In the app, you want to update the user’s current activity every 500 milliseconds (1/2 second). You have seen that you can classify a single sample at this rate, so SENSOR_DELAY_NORMAL is sufficient for the app. Note that the Android also uses the SENSOR_DELAY_NORMAL for some system functions, such as determining when the user rotates the device from portrait to landscape.Table 6-16

Android 传感器延迟常数

|

Constantname

|

默认常量值(微秒)

|

典型观察采样速率(毫秒)

|
| --- | --- | --- |
| 传感器 _ 延迟 _ 正常 | Two hundred thousand | Two hundred and twenty-five |
| 传感器 _ 延迟 _UI | Sixty thousand | seventy-eight |
| 传感器 _ 延时 _ 游戏 | Twenty thousand | Thirty-eight |
| 传感器 _ 延迟 _ 最快 | Zero | Twenty |

To receive sensor events, you need to implement the SensorEventListener. Android calls this listener to report sensor events for all of the registered sensors. In this app, you have three sensors registered. Even though you are using the least frequent sampling rate, SENSOR_DELAY_NORMAL, there will still be many events passed to this listener.001   private final SensorEventListener mSensorEventListener = new SensorEventListener() { 002       @Override 003       public void onSensorChanged(SensorEvent event) { 004           if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { 005               acc_X = event.values[0]; 006               acc_Y = event.values[1]; 007               acc_Z = event.values[2]; 008               tv_acc_X.setText(Float.toString(acc_X)); 009               tv_acc_Y.setText(Float.toString(acc_Y)); 010               tv_acc_Z.setText(Float.toString(acc_Z)); 011 012           } else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) { 013               gyro_X = event.values[0]; 014               gyro_Y = event.values[1]; 015               gyro_Z = event.values[2]; 016               tv_gyro_X.setText(Float.toString(gyro_X)); 017               tv_gyro_Y.setText(Float.toString(gyro_Y)); 018               tv_gyro_Z.setText(Float.toString(gyro_Z)); 019 020           } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { 021               mag_X = event.values[0]; 022               mag_Y = event.values[1]; 023               mag_Z = event.values[2]; 024               tv_mag_X.setText(Float.toString(mag_X)); 025               tv_mag_Y.setText(Float.toString(mag_Y)); 026               tv_mag_Z.setText(Float.toString(mag_Z)); 027           } 028       } 029 030       @Override 031       public void onAccuracyChanged(Sensor sensor, int i) { 032       } 033   }; Inside the listener, you decode the events by checking the event.sensors.getType() and then reading the values from the event.values[] array. Depending on the event type, the listener stores the X, Y, and Z sensor values into the following local variables:

  • 加速度计 : acc_X,acc_Y,acc_Z(行 005-007)

  • 陀螺仪 : gyro_X,gyro_Y,gyro _ Z(013-015 行)

  • 磁力计:磁力 X,磁力 Y,磁力 Z(021-023 行)

除了更新您将用作分类实例的局部变量之外,监听器还更新主应用程序 GUI 布局上的【TextView】字段。当您运行应用程序时,可以立即看到传感器生成了多少事件,因为您可以看到这些值变化如此频繁。

侦听器还要求您实现onAccuracyChanged方法(第 031 行)。您可以将此方法留空。

实现计时器

对于此应用程序,您希望显示从最近可用的传感器数据中得出的持续更新的活动预测。这要求您不断地将实例输入 ML 模型进行预测。您知道传感器数据更新间隔大约为 200 毫秒,因为您将传感器采样率设置为SENSOR _ DELAY _ NORMAL。您还知道可以使用 Weka API 和 RF 模型在大约 300-500 毫秒内对实例进行分类。

To accomplish the continuous classifications, you will implement a background thread and define the integer updateInterval = 500 milliseconds. The thread will run continuously until an error occurs. Each time through the main loop, a call is made to updateActivityStatus(), which performs the classification and displays the result. The timing is controlled by a call to the Thread.sleep(updateInterval) method. You are not actually using Java or Android Timer objects in this code, but the implementation is a simple and efficient way to implement continuously updating classifications.001   Thread m_statusThread; 002   Boolean m_statusThreadStop; 003   private static Integer updateInterval = 500; 004 005   public void createAndRunStatusThread(final Activity act) { 006       m_StatusThreadStop=false; 007       m_statusThread = new Thread(new Runnable() { 008           public void run() { 009               while(!m_StatusThreadStop) { 010                   try { 011                       act.runOnUiThread(new Runnable() { 012                           public void run() { 013                               updateActivityStatus(); 014                           } 015                       }); 016                       Thread.sleep(updateInterval); 017                   } 018                   catch(InterruptedException e) { 019                       m_StatusThreadStop = true; 020                       messageBox(act, "Exception in status thread: " + 021                                       e.toString() + " - " + 022                                       e.getMessage(), "createAndRunStatusThread Error"); 023                   } 024               } 025           } 026       }); 027       m_statusThread.start(); 028   }

代码的最后一部分是模型集成。

模型集成

As with the examples shown earlier in the chapter, the first step in model integration is to load the single instance data source, set the class attribute label, and load the prebuilt RF classifier model. The following code block shows the initialization steps performed on the Android onCreate method:001   // Load the Single Instance data source 002   sourceSingle = new ConverterUtils.DataSource(getResources().openRawResource(R.raw.subject101_single)); 003   dataSingle = sourceSingle.getDataSet(); 004 005   // Set the class attribute (Label) as the first class 006   dataSingle.setClassIndex(0); 007 008   // Load the pre-built Random Forest model 009   rf = (Classifier) weka.core.SerializationHelper.read(getResources().openRawResource(R.raw.rf_i10_cross)); With initialization complete, the only steps remaining are to build samples from the sensor data, classify them, and display the result. The actions are shown in updateActivityStatus(), which runs on the UI thread so it can display the result:001   private void updateActivityStatus() { 002       //Toast.makeText(MainActivity.this, "Button pressed.", Toast.LENGTH_SHORT).show(); 003       // Grab the most recent values and classify them 004       // Create a new Instance to classify 005       Instance newInst = new DenseInstance(10); 006       newInst.setDataset(dataSingle); 007       newInst.setValue(0,0);   // ActivityID 008       newInst.setValue(1,acc_X);  // Accelerometer X 009       newInst.setValue(2,acc_Y);  // Accelerometer Y 010       newInst.setValue(3,acc_Z);  // Accelerometer Z 011       newInst.setValue(4,gyro_X); // Gyroscope X 012       newInst.setValue(5,gyro_Y); // Gyroscope Y 013       newInst.setValue(6,gyro_Z); // Gyroscope Z 014       newInst.setValue(7,mag_X);  // Magnetometer X 015       newInst.setValue(8,mag_Y);  // Magnetometer Y 016       newInst.setValue(9,mag_Z);  // Magnetometer Z 017 018       // Classify the instance and display the result 019       try { 020           double res = rf.classifyInstance(newInst); 021           classifyResult.setText(activityID[(int) res] + ", " + String.valueOf(res)); 022       } catch (Exception e) { 023           e.printStackTrace(); 024       } 025   }

您使用 setValue 方法将最近的传感器值加载到新实例中,然后使用 Weka APIclassify instance方法从模型中检索结果。

改善结果

While running the app and monitoring the continuous classifier result, several things are apparent:

  • 传感器数据每 200 毫秒快速更新一次。这就是SensorEventListener正在努力工作的证据。

  • 有时,“活动结果”似乎不会更新。这是分类器返回与先前分类相同的结果的效果,例如当设备静止不动时。在这种状态下,传感器可能显示非常小的变化。

  • 活动分类不是很准确。虽然分类器在训练和测试数据中显示了大约 90%的准确性,但是当您使用该设备移动时,真实世界的体验似乎不会表现出这种程度的准确性。

  • 该应用程序非常灵敏,即使睡眠时间设置为 500 毫秒。如果需要更快的采样速率,可以缩短睡眠间隔。

这个应用程序演示了一个在 Android 上运行的高性能 CML 应用程序,它具有复杂的 RF 模型。的大小。apk 文件仅约为 3MB,说明该解决方案有多精益。

部署应用程序前的最后一步是看看是否可以改善分类结果。回想一下在第二章,我提到了利用学术研究论文的重要性。请参考以下文件:

Saez、Baldominos 和 Isazis 的跨个人身体活动识别的分类器算法的比较研究。

www.ncbi.nlm.nih.gov/pmc/articles/PMC5298639/

这篇最近的论文是在国家卫生研究院网站上的知识共享许可下发布的开放存取作品。在本文中,作者介绍了如何为 PAMAP2_Dataset 构建分类器。虽然作者没有在 Android 上实现实时分类器,但他们对这个数据集的分类器做了一些很好的研究,可以帮助改善你的结果。

A summary of the potential improvements for the Activity Tracker Android app:

  • 分类器不使用时序数据。也就是说,每个实例都是独立存在的。您可能会定义一个窗口,并在该窗口中实现时间序列学习。

  • 如果目标 Android 设备包含心率传感器,您可以包含心率数据并提高准确性。您在分类器/应用程序中包含了磁力计数据,但不清楚这对准确性有多大帮助。

  • 如果目标设备包括温度传感器,则可以包括体温数据。

  • 对于应用程序,您使用来自 subject101 的训练数据构建了分类器。对于一个完整的模型,您可以潜在地包括来自所有主题的训练数据。

  • 原始数据集包括位于身体不同位置的三个传感器。您在手部位置仅选择了一个传感器。根据您最感兴趣的活动,您可以包括多个传感器,或者选择来自另一个传感器的数据,例如脚。

机器学习的精神包括寻求持续改进,从最初的数据收集开始,一直到应用程序的部署。

6.9 Weka 许可说明

在第二章中,我讨论了 ML 帮助你的应用赚钱的潜力。在本章中,您使用 Weka Android 库在移动设备上开发了集成的 ML 应用程序。当您使用 Weka 或任何其他开源 ML 包来开发集成 ML 应用程序时,经常会出现关于许可和商业化问题的混淆。

首先,免责声明:本部分不构成法律意见。在决定您的 ML 应用许可和分发策略之前,请咨询专家。

You need to consider two important but separate issues:

  • 版权

  • 批准

关于版权,无论你是否正式注册,你创造的任何东西(即你的贡献)的版权都属于你。如果有人侵犯了你的版权,注册你的版权会让你更容易维权。

关于许可,由于开源许可的条件,情况更复杂。根据 GPL,一旦你生产了一个包含开源组件的商业应用程序,你必须将所有的“衍生”作品公之于众或者完全保密。通过遵守这些条款,当您与 Weka 合作时,在您的情况下,根据 GPL 许可,您为公共领域做出了贡献。例如,本书中的项目是衍生作品,有助于公共领域。

重要的问题是,什么是衍生作品?例如,当您导出旧的 Faithful runnable jar 文件时,您以 jar 格式包含了修改后的 Weka API 库。这个库当然是一个衍生作品,而应用程序本身通过 jar fie 包含成为一个衍生作品。

Derivative works:

  • 衍生作品是依赖于 Weka 的东西。

  • 衍生作品中实现的数据不必包含在 GPL 中。

  • Weka 制作的模型不是衍生作品。

  • 如果模型的应用依赖于您提供的特殊类,这些类是 Weka 的衍生作品,那么这些类必须包含在 GPL 或兼容的许可证中。

Many individuals and companies are not comfortable releasing their classes into the public domain. If you do not wish to make your classes available under the GPL or a compatible open source license, there are two options:

    您可以获得 Weka 商业许可证。

    您可以在您的包和 Weka 衍生作品之间添加一个抽象层。

商业 Weka 许可证是可用的。它们不包括受外部贡献者版权保护的 Weka 部分,并且有许多这样的部分,例如简单的逻辑分类器。潜在的 Weka 商业许可证持有人可能只对 Weka 的子集感兴趣,例如特定的分类器,这应该是请求的相关部分。

如果您希望使用 Weka,但不希望软件受 GPL 约束或获得商业许可证,您可以使用远程机器接口(RMI)远程调用它。这个增加的抽象层可以满足 GPL 许可条款,因为它从主应用程序中移除了派生状态。

Weka 是一个了不起的包。如果你用它创造了一些令人惊奇的东西,考虑在 GPL 下发布并发展公共领域。您的贡献可以帮助我们所有人成为更好的开发人员。********************

posted @ 2024-08-19 17:27  绝不原创的飞龙  阅读(2)  评论(0编辑  收藏  举报