Java 机器学习实践指南(二)
三、利用云平台
-
提供 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. 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. 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 仪表板。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. 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. 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. 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 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. Figure 3-7
谷歌云 SDK 下载页面
Cloud SDK is available for all platforms. Figure 3-8 shows the Cloud SDK after successful installation. 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. 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 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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] 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] 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 java_base_version="8" 002 [ec2-user@ip-172-31-3-37 local] java_base_build="15" 004 [ec2-user@ip-172-31-3-37 local]{java_base_version}u java_build="b java_version_with_build="{java_build}" 007 008 [ec2-user@ip-172-31-3-37 local]{java_version_with_build}/336fa29ff2bb4ef291e347e091f7f4a7/jdk- 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] 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] pwd 002 /usr/local 003 [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] sudo unzip weka-3-8-2.zip 011 012 [ec2-user@ip-172.31.3.37] 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. 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. 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 . 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. 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. 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 vision.googleapis.com/v1/images:a… 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->rawaudio.raw | 存储在 /res/raw 文件夹中的样本音频文件,可以发送给 API 进行分类。音频文件是“布鲁克林大桥有多老了?” | | *app- > src- > mainAndroidManifest.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. 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. 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. Figure 3-29
GCP 创建服务帐户密钥
The Create service account key dialog box will be displayed, as shown in Figure 3-30. 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. 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": "accounts.google.com/o/oauth2/au…", 009 "token_uri": "accounts.google.com/o/oauth2/to…", 010 "auth_provider_x509_cert_url": "www.googleapis.com/oauth2/v1/c…", 011 "client_x509_cert_url": "www.googleapis.com/robot/v1/me…" 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. 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 record**和audio 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. 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. 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. 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. 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 万次写入。您可以在这篇博客文章中了解部署细节:
根据作者的说法,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. 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. 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. 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. 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. 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. 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. 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. 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.” 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. Figure 4-21
Java 分类器算法(Weka Subversion 存储库)
在图 4-8 中列出的最有用的分类器包含在存储库中。图 4-21 显示朴素贝叶斯、随机森林、SVM 源代码都包含在 分类器 目录中。
聚类算法
Figure 4-22 shows the Java clustering algorithms available in Weka. 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 通用公共许可证下授权的。代码是免费的,您可以根据许可条款分发或修改它。
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 看到了一个新服务的引入, ForkJoinPool 。 ForkJoinPool 类支持并行编程的实现,使得线程可以在多个 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. 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. 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 | 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. 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. Figure 5-4
保留徽标
After the Weka initialization completes, the main Weka GUI chooser appears, as shown in Figure 5-5. 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. 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 . 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. 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. Figure 5-9
Weka 帮助➤系统信息显示
除了 java.class.path 设置外,Weka Sysinfo 页面还显示了 WEKA_HOME 和 memory.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. 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: 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. 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. 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. Figure 5-13
weka 包管理器和 jfreechart 扩展
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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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。
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. 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 曲线绘制多级数据的方法。
-
选择 FoldMaker 和 SplitMaker 节点,设置 10 折和 2/3 分割的测试分割。
-
单击四个算法节点中的每一个,并按照前面的讨论设置参数。
-
点击ModelPerformanceChart节点,将渲染器设置为 JFreeChart,如图 5-34 所示。
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. 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. 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. Figure 5-37
黄石国家公园的老忠实喷泉(portfolio.timdimacchia.com 蒂姆·迪马克提供)**********