Spark MLlib之机器学习(一)

来源:互联网 发布:杂牌液晶电视数据 编辑:程序博客网 时间:2024/03/28 20:21

1.定义

先看一下机器学习的定义,以下是Wikipedia的定义:
Machine learning is a scientific discipline that explores the construction and study of algorithms that can learn from data.
当然,要说的更接地气点儿,就是让机器会学习,那怎么样才能让机器学习呢?那就需要能从数据中学习的算法。简单讲,就是数据和算法。
在统计学中,有以下四种测量尺度:

Scale type

Description

Nominal Scale

=、≠

定义的类别,不是数值的。

如:male、female

Ordinal Scale

=、≠、<、>

等级类的,从最不重要的到最重要的。

如:公司员工的等级

Interval Scale

=、≠、<、>、+、-

Ordinal scale + 层级距离

分配给层级数据的数字的显示顺序,任何两个连续的值之间的差异是相同的。

如:60°C不是指2倍的30°C

Ratio Scale

=、≠、<、>、+、-、×、÷

连续成比例的数据。

如:$60是$30的2倍

 

数据的一个另一种分类就是很常见的:离散型数据和连续型数据。
在Spark中,有一个专门做机器学习的库——MLlib库。

2.向量

对于人类可以想象的再大维空间应该是三维空间,超过三维就是超空间了。这里三维数据点举例长:100,宽:50,高:200,即点(100,50,200)。
其中,点和向量是同一事物的不同叫法。而向量的维度被称作特征(feature)。
在Spark中,有local vectors和matrices,也有distributed matrices(分布式矩阵),分布式矩阵通过一个或多个RDD实现。local vector存的是double值,并放在一台机器上。
在MLlib中有两种local vector:稠密型和稀疏型。稠密型向量是一组数值,而稀疏型向量通过2个数组实现,一个数组存放非null值或非0值的数值的位置,一个数组存放的则是相应的非null值或非0值的数值。如:数据(100,50,200)用稠密向量存储表示为[100.0,50.0,200.0],用稀疏向量存储表示为(3,[0,1,2],[100.0,50.0,200.0])
示例:
>  import org.apache.spark.mllib.linalg.{Vectors,Vector}>  val dvPerson = Vectors.dense(100,50,200)>  val svPerson = Vectors.sparse(3,Array(0,1,2),Array(100,50,200))

它们的函数声明形式如下:

def dense(values: Array[Double]): Vectordef sparse(size: Int, indices: Array[Int], values: Array[Double]): Vector

3.LabeledPoint

Labeled point是一个local vector(sparse/dense),它有一个相关的标签。Labeled数据用于监督学习中,帮助实现训练算法。Labeled作为double值存储在LabeledPoint。即每一个分类标签,都映射一个double值。示例:

>  import org.apache.spark.mllib.linalg.{Vectors,Vector}>  import org.apache.spark.mllib.regression.LabeledPoint>  val willBuySUV = LabeledPoint(1.0,Vectors.dense(300.0,80,40))>  val willBuySUV = LabeledPoint(1.0,Vectors.sparse(3,Array(0,1,2),Array(300.0,80,40)))

4.矩阵

矩阵有多个向量组成,一个矩阵存在一台机器中的叫做local matrix,存在集群中叫做distributed matrix。
MLlib中有三种分布式矩阵:
 RowMatrix:每一行是一个vector
 IndexedRowMatrix:有行号
 CoordinateMatrix:它是一个简单的MatrixEntry矩阵。MatrixeEntry以行和列索引代表矩阵的一个数据。
示例:

> val people = Matrices.dense(3,2,Array(150d,60d,25d,300d,80d,40d))> val personRDD = sc.parallelize(List(Vectors.dense(150,60,25), Vectors.dense(300,80,40)))> import org.apache.spark.mllib.linalg.distributed.{IndexedRow, IndexedRowMatrix,RowMatrix, CoordinateMatrix,MatrixEntry}> val personMat = new RowMatrix(personRDD)> val personRDD = sc.parallelize(List(IndexedRow(0L, Vectors.dense(150,60,25)), IndexedRow(1L, Vectors.dense(300,80,40))))> val pirmat = new IndexedRowMatrix(personRDD)> val meRDD = sc.parallelize(List(MatrixEntry(0,0,150),MatrixEntry(1,0,60),MatrixEntry(2,0,25),MatrixEntry(0,1,300),MatrixEntry(1,1,80),MatrixEntry(2,1,40)))> val pcmat = new CoordinateMatrix(meRDD)

0 0