Apache Spark 2.x Machine Learning Cookbook(2)

第一章:使用Scala使用Spark进行实用的机器学习

在本章中,我们将介绍:
下载并安装JDK
下载并安装IntelliJ
下载并安装Spark
配置IntelliJ以使用Spark并运行Spark ML示例代码
从Spark运行示例ML代码
识别用于实际机器学习的数据源
使用带有IntelliJ IDE的Apache Spark 2.0运行您的第一个程序
如何将图形添加到Spark程序

介绍
随着集群计算的最新进展以及大数据的兴起,机器学习领域已被推到了计算的最前沿。 长期以来,对于实现大规模数据科学的交互式平台的需求一直是梦想,如今已成为现实。

以下三个领域共同推动并加速了交互式数据科学的发展:

Apache Spark:统一的数据科学技术平台,将快速的计算引擎和容错的数据结构结合到精心设计和集成的产品中
机器学习:人工智能的一个领域,它使机器能够模仿最初专门为人脑保留的某些任务
Scala:一种基于JVM的现代语言,以传统语言为基础,但是将功能和面向对象的概念结合在一起,而没有其他语言的冗长.

首先,我们需要设置开发环境,该环境将包括以下组件:

本章中的食谱将为您提供有关安装和配置IntelliJ IDE,Scala插件和Spark的详细说明。 设置好开发环境后,我们将继续运行Spark ML示例代码之一来测试设置。

Spark在统一技术栈中提供了易于使用的分布式框架,这使其成为数据科学项目的首选平台,而数据科学项目通常不需要最终可合并为解决方案的迭代算法。 这些算法由于其内部工作原理,会产生大量中间结果,这些中间结果需要在中间步骤中从一个阶段转到下一个阶段。 对于具有健壮的本地分布式机器学习库(MLlib)的交互式工具的需求,排除了大多数数据科学项目基于磁盘的方法。

Spark对集群计算有不同的方法。 它以技术堆栈而非生态系统的形式解决了该问题。 大量集中管理的库与可支持容错数据结构的闪电般快速的计算引擎相结合,使Spark有望取代Hadoop,成为首选的大数据分析平台。

Spark具有模块化方法,如下图所示:

机器学习
机器学习的目的是生产可以模仿人类智能并使传统上留给人类大脑的某些任务自动化的机器和设备。 机器学习算法的设计目的是在相对较短的时间内浏览非常大的数据集,并提供近似的答案,这将使人类花费更长的时间进行处理。

机器学习领域可以分为多种形式,从较高的层次上讲,可以分为监督学习和无监督学习。 监督学习算法是一类ML算法,它使用训练集(即标记的数据)来计算概率分布或图形模型,从而使他们无需进一步的人工干预即可对新数据点进行分类。 无监督学习是一种机器学习算法,用于从没有标签响应的输入数据组成的数据集中得出推论。

开箱即用,Spark提供了一套丰富的ML算法,无需进一步编码即可将其部署在大型数据集上。 下图将Spark的MLlib算法描述为思维导图。 Spark的MLlib旨在利用并行性,同时具有容错的分布式数据结构。 Spark将此类数据结构称为弹性分布式数据集或RDD:

scala
Scala是一种现代编程语言,正在替代Java和C ++等传统编程语言。 Scala是一种基于JVM的语言,它不仅提供了简洁的语法而没有传统的样板代码,而且将面向对象和函数式编程都结合到了一种极其清晰且功能强大的类型安全语言中。

Scala采用了一种灵活且富有表现力的方法,使其非常适合与Spark的MLlib进行交互。 Spark本身是用Scala编写的事实提供了有力的证据,表明Scala语言是一种全方位服务的编程语言,可用于创建对性能有很高要求的复杂系统代码。

Scala通过解决Java的一些缺点建立在Java的传统上,同时避免了全有或全无的方法。 Scala代码被编译成Java字节码,从而可以与丰富的Java库互换地共存。 将Java库与Scala结合使用(反之亦然)的能力为软件工程师提供了连续性和丰富的环境,使其可以构建现代而复杂的机器学习系统,而无需完全脱离Java传统和代码库。

Scala完全支持功能丰富的函数式编程范例,并具有对lambda,currying,类型接口,不可变性,惰性求值的标准支持,以及模式匹配范例,使人联想到Perl,而无需使用神秘的语法。 Scala支持对代数友好的数据类型,匿名函数,协方差,逆方差和高阶函数,因此它非常适合机器学习编程。

这是Scala中的hello world程序:

object HelloWorld extends App {
println("Hello World! ")
}

在Scala中编译和运行Hello World如下所示:

scalac HelloWorld.scala
scala HelloWorld

《 Apache Spark机器学习指南》采用了一种实用的方法,即为开发人员提供了多学科的观点。 本书重点介绍了机器学习,Apache Spark和Scala的相互作用和内聚性。 我们还采取了额外的步骤,教您如何设置和运行开发人员熟悉的全面开发环境,并提供您必须在交互式外壳中运行的代码段,而无需使用IDE提供的现代功能:

apache spark ---> machine learning -->IDE --->scala 

本书中使用的软件版本和库


下表提供了本书中使用的软件版本和库的详细列表。 如果您遵循本章介绍的安装说明,它将包括此处列出的大多数项目。 特定配方可能需要的其他任何JAR或库文件,都通过相应配方中的其他安装说明进行了介绍:

所需的其他JAR如下:

Miscellaneous      JARs Version
bliki-core     3.0.19
breeze-viz   0.12
Cloud9 1.5.0
Hadoop-streaming
2.2.0
JCommon
1.0.23
JFreeChart
1.0.19
lucene-analyzers-common
6.0.0
Lucene-Core
6.0.0
scopt
3.3.0
spark-streaming-flume-assembly
2.0.0
spark-streaming-kafka-0-8-assembly2.0.0
我们还在Spark 2.1.1上测试了本书中的所有食谱,并发现程序按预期执行。 建议出于学习目的,使用这些表中列出的软件版本和库。 为了跟上瞬息万变的Spark格局和文档,API指向本书中提到的Spark文档的链接指向最新版本的Spark 2.x.x,但配方中的API参考明确针对Spark 2.0.0。本书中提供的所有Spark文档链接都将指向Spark网站上的最新文档。 如果您希望查找特定版本的Spark(例如Spark 2.0.0)的文档,请使用以下URL在Spark网站上查找相关文档:

为了清楚起见,我们已使代码尽可能简单,而不是演示Scala的高级功能。

以下是开源数据列表,如果您想在此领域开发应用程序,则值得探索:

https://archive.ics.uci.edu/ml/index.php   ---UCI机器学习存储库

https://www.kaggle.com/competitions   -- Kaggle datasets

MLdata.org   -- MLdata.org

Google Trends  --http: /​/​www. ​google. ​com/​trends/explore .

The CIA World Factbook -- https: //www. cia. gov/library/publications/the-world-factbook/

See also

UCI machine learning repository: This is an extensive library with search
functionality. At the time of writing, there were more than 350 datasets. You can
click on the  https: //archive. ics. uci. edu/ml/index. html link to see all the
datasets or look for a specific set using a simple search (Ctrl + F).
Kaggle datasets: You need to create an account, but you can download any sets for
learning as well as for competing in machine learning competitions. The
https: //www. kaggle. com/competitions link provides details for exploring and
learning more about Kaggle, and the inner workings of machine learning
competitions.
MLdata.org: A public site open to all with a repository of datasets for machine
learning enthusiasts.
Google Trends: You can find statistics on search volume (as a proportion of total
search) for any given term since 2004 on  http: /​/​www. ​google. ​com/​trends/
explore .
The CIA World Factbook:
The  https: //www. cia. gov/library/publications/the-world-factbook/ link
provides information on the history, population, economy, government,
infrastructure, and military of 267 countries.

Other sources for machine learning data:
SMS spam data:  http: //www. dt. fee. unicamp. br/~tiago/smsspamcollection/
Financial dataset from Lending Club
https: //www. lendingclub. com/info/download-data. action
Research data from Yahoo  http: //webscope. sandbox. yahoo. com/index. php
Amazon AWS public dataset http: //aws. amazon. com/public-data-sets/
Labeled visual data from Image Net  http: //www. image-net. org
Census datasets  http: //www. census. gov
Compiled YouTube dataset  http: //netsg. cs. sfu. ca/youtubedata/
Collected rating data from the MovieLens site
http: //grouplens. org/datasets/movielens/
Enron dataset available to the public  http: //www. cs. cmu. edu/~enron/
Dataset for the classic book elements of statistical learning
http: //statweb. stanford. edu/~tibs/ElemStatLearn/data. htmlIMDB
Movie dataset  http: //www. imdb. com/interfaces
Million Song dataset  http: //labrosa. ee. columbia. edu/millionsong/
Dataset for speech and audio  http: //labrosa. ee. columbia. edu/projects/
Face recognition data  http: //www. face-rec. org/databases/
Social science data  http: //www. icpsr. umich. edu/icpsrweb/ICPSR/studies
Bulk datasets from Cornell University  http: //arxiv. org/help/bulk_data_s3
Project Guttenberg datasets
http: //www. gutenberg. org/wiki/Gutenberg: Offline_Catalogs
Datasets from World Bank  http: //data. worldbank. org
Lexical database from World Net  http: //wordnet. princeton. edu
Collision data from NYPD http: //nypd. openscrape. com/#/
Dataset for congressional row calls and others  http: //voteview. com/dwnl. htm
Large graph datasets from Stanford
http: //snap. stanford. edu/data/index. html
Rich set of data from datahub  https: //datahub. io/dataset
Yelp's academic dataset  https: //www. yelp. com/academic_dataset
Source of data from GitHub
https: //github. com/caesar0301/awesome-public-datasets
Dataset archives from Reddit  https: //www. reddit. com/r/datasets/
 

There are some specialized datasets (for example, text analytics in Spanish, and gene and
IMF data) that might be of some interest to you:
Datasets from Colombia (in Spanish):
http: //www. datos. gov. co/frm/buscador/frmBuscador. aspx
Dataset from cancer studies
http: //www. broadinstitute. org/cgi-bin/cancer/datasets. cgi
Research data from Pew  http: //www. pewinternet. org/datasets/
Data from the state of Illinois/USA  https: //data. illinois. gov
Data from freebase.com http: //www. freebase. com
Datasets from the UN and its associated agencies  http: //data. un. org
International Monetary Fund datasets  http: //www. imf. org/external/data. htm
UK government data  https: //data. gov. uk
Open data from Estonia
http: //pub. stat. ee/px-web. 2001/Dialog/statfile1. asp
Many ML libraries in R containing data that can be exported as CSV
https: //www. r-project. org
Gene expression datasets  http: //www. ncbi. nlm. nih. gov/geo/

 <dependencies>

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.2.2</version>
    </dependency>
    <!--spark-mllib-->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-mllib_2.11</artifactId>
        <version>2.2.2</version>
    </dependency>
        <dependency>
                <groupId>org.jfree</groupId>
                <artifactId>jfreechart</artifactId>
                <version>1.5.0</version>
            </dependency>

        

    </dependencies>


 

import org.apache.log4j.Logger
import org.apache.log4j.Level
import org.apache.spark.sql.SparkSession

object MyFirstSpark20 {
  def main(args: Array[String]): Unit = {
    Logger.getLogger("org").setLevel(Level.ERROR)
    val session: SparkSession = SparkSession.builder().master("local[*]").appName("myFirstSpark20").config("spark.sql.warehouse.dir", ".")
      .getOrCreate()
    session
    val x = Array(1.0,5.0,8.0,10.0,15.0,21.0,27.0,30.0,38.0,45.0,50.0,64.0)
    val y = Array(5.0,1.0,4.0,11.0,25.0,18.0,33.0,20.0,30.0,43.0,55.0,57.0)
    val xRDD = session.sparkContext.parallelize(x)
    val yRDD = session.sparkContext.parallelize(y)
    val zipRdd = xRDD.zip(yRDD)
    for (elem <- zipRdd.collect()) {
      println(elem)
    }
    val xSum: Double = xRDD.sum()
    val ySum: Double=yRDD.sum()
    val sumRdd = zipRdd.map(item=>item._1*item._2).sum
    val sumCount = zipRdd.count()
    println(xSum)
    println(ySum)
    println(sumRdd)
    println(sumCount)
    session.stop()
  }

}
import java.awt.Color

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession
import org.jfree.chart.plot.{PlotOrientation, XYPlot}
import org.jfree.chart.{ChartFactory, ChartFrame, JFreeChart}
import org.jfree.data.xy.{XYSeries, XYSeriesCollection}

import scala.util.Random


object MyChart {

  def show(chart: JFreeChart) {
    val frame = new ChartFrame("plot", chart)
    frame.pack()
    frame.setVisible(true)
  }

  def configurePlot(plot: XYPlot): Unit = {
    plot.setBackgroundPaint(Color.WHITE)
    plot.setDomainGridlinePaint(Color.BLACK)
    plot.setRangeGridlinePaint(Color.BLACK)
    plot.setOutlineVisible(false)
  }

  def main(args: Array[String]): Unit = {

    Logger.getLogger("org").setLevel(Level.ERROR)

    // setup SparkSession to use for interactions with Spark
    val spark = SparkSession
      .builder
      .master("local[*]")
      .appName("myChart")
      .config("spark.sql.warehouse.dir", ".")
      .getOrCreate()


    val data = spark.sparkContext.parallelize(Random.shuffle(1 to 15).zipWithIndex)

    data.foreach(println)

    val xy = new XYSeries("")
    data.collect().foreach{ case (y: Int, x: Int) => xy.add(x,y) }
    val dataset = new XYSeriesCollection(xy)

    val chart = ChartFactory.createXYLineChart(
      "MyChart",  // chart title
      "x",               // x axis label
      "y",                   // y axis label
      dataset,                   // data
      PlotOrientation.VERTICAL,
      false,                    // include legend
      true,                     // tooltips
      false                     // urls
    )

    val plot = chart.getXYPlot()
    configurePlot(plot)
    show(chart)
    spark.stop()
  }
}
发布了158 篇原创文章 · 获赞 28 · 访问量 33万+

猜你喜欢

转载自blog.csdn.net/wangjunji34478/article/details/105594054