SVD分解: \(A=U\Sigma V^T\),变换:\(\hat{A}=A\cdot V=U\Sigma\)

分解时先计算\(A^TA=U\Sigma^2U^T\),再进行SVD分解

/**
* Computes the top k principal components and a vector of proportions of
* variance explained by each principal component.
* Rows correspond to observations and columns correspond to variables.
* The principal components are stored a local matrix of size n-by-k.
* Each column corresponds for one principal component,
* and the columns are in descending order of component variance.
* The row data do not need to be "centered" first; it is not necessary for
* the mean of each column to be 0.
*
* @param k number of top principal components.
* @return a matrix of size n-by-k, whose columns are principal components, and
* a vector of values which indicate how much variance each principal component
* explains
*
* @note This cannot be computed on matrices with more than 65535 columns.
*/
@Since("1.6.0")
def computePrincipalComponentsAndExplainedVariance(k: Int): (Matrix, Vector) = {
val n = numCols().toInt
require(k > 0 && k <= n, s"k = $k out of range (0, n = $n]") // spark 分布式计算A^T A
val Cov = computeCovariance().asBreeze.asInstanceOf[BDM[Double]] // Breeze计算svd分解
val brzSvd.SVD(u: BDM[Double], s: BDV[Double], _) = brzSvd(Cov)
// explained varience 归一化成Ratio
val eigenSum = s.data.sum
val explainedVariance = s.data.map(_ / eigenSum)
// 返回U,∑
if (k == n) {
(Matrices.dense(n, k, u.data), Vectors.dense(explainedVariance))
} else {
(Matrices.dense(n, k, Arrays.copyOfRange(u.data, 0, n * k)),
Vectors.dense(Arrays.copyOfRange(explainedVariance, 0, k)))
}
}

计算R:

分布式计算\(R=A^TA\)

其中\(dim(A)=m\cdot n\),大数据场景下m会很大,但是n一般不会很大。所以计算结果\(R\)的维度也不会非常大,对\(R\)进行PCA分解的复杂度可控,单线程计算即可。

分布式计算自相关矩阵\(R\)的公式:

\[\begin{align*}
\text{calc } A^T A &:\\
&r_{ij} = \sum_{k=1}^m a_{ki}\cdot a_{kj}, \text{where }i,j\in 1,...,n\\
\text{So, }&\text{R} = \sum_{k=1}^m \vec{a}_k^T \vec{a}_k, \text{where }\vec{a}_k=[a_{k1},...,a_{kn}],\text{ $k^{th}$ row}
\end{align*}
\]

Spark代码:

/**
* Computes the Gramian matrix `A^T A`.
*
* @note This cannot be computed on matrices with more than 65535 columns.
*/
@Since("1.0.0")
def computeGramianMatrix(): Matrix = {
val n = numCols().toInt
checkNumColumns(n)
// Computes n*(n+1)/2, avoiding overflow in the multiplication.
// This succeeds when n <= 65535, which is checked above
val nt = if (n % 2 == 0) ((n / 2) * (n + 1)) else (n * ((n + 1) / 2)) // Compute the upper triangular part of the gram matrix.
val GU = rows.treeAggregate(new BDV[Double](nt))(
seqOp = (U, v) => {
BLAS.spr(1.0, v, U.data)
U
}, combOp = (U1, U2) => U1 += U2) RowMatrix.triuToFull(n, GU.data)
}

SVD分解:

调用Breeze的SVD库,得到\(U,\Sigma\)

    val brzSvd.SVD(u: BDM[Double], s: BDV[Double], _) = brzSvd(Cov)
// Explained variance 归一化
val eigenSum = s.data.sum
val explainedVariance = s.data.map(_ / eigenSum) if (k == n) {
(Matrices.dense(n, k, u.data), Vectors.dense(explainedVariance))
} else {
(Matrices.dense(n, k, Arrays.copyOfRange(u.data, 0, n * k)),
Vectors.dense(Arrays.copyOfRange(explainedVariance, 0, k)))
}

Explained Variance Ratio

explained variance ratio of each principal component. It indicates

the proportion of the dataset’s variance that lies along the axis of each principal component.

PCA in MLLib的更多相关文章

  1. Spark MLlib编程API入门系列之特征提取之主成分分析(PCA)

    不多说,直接上干货! 主成分分析(Principal Component Analysis,PCA), 将多个变量通过线性变换以选出较少个数重要变量的一种多元统计分析方法. 参考 http://blo ...

  2. 《Spark 官方文档》机器学习库(MLlib)指南

    spark-2.0.2 机器学习库(MLlib)指南 MLlib是Spark的机器学习(ML)库.旨在简化机器学习的工程实践工作,并方便扩展到更大规模.MLlib由一些通用的学习算法和工具组成,包括分 ...

  3. 《Spark MLlib机器学习实践》内容简介、目录

      http://product.dangdang.com/23829918.html Spark作为新兴的.应用范围最为广泛的大数据处理开源框架引起了广泛的关注,它吸引了大量程序设计和开发人员进行相 ...

  4. Spark入门实战系列--8.Spark MLlib(上)--机器学习及SparkMLlib简介

    [注]该系列文章以及使用到安装包/测试数据 可以在<倾情大奉送--Spark入门实战系列>获取 .机器学习概念 1.1 机器学习的定义 在维基百科上对机器学习提出以下几种定义: l“机器学 ...

  5. MLlib 编程指导-spark-1.2.0

    本文来自 http://spark.apache.org/docs/latest/mllib-guide.html 官方文档翻译 个人翻译 MLlib包括的算法和工具主要有:分类,回归,聚类,协同过滤 ...

  6. Spark MLlib数据类型

        MLlib支持几种数据类型:本地向量(local vectors),和存储在一个简单机器中的矩阵(matrices),以及由一个或多个RDDs组成的分布式矩阵. 1,本地向量(Local Ve ...

  7. PCA 降维

    http://f.dataguru.cn/spark-751832-1-1.html 我们可以利用PCA算法将向量的维数降低,从而实现特征转化.具体原理在<机器学习>课程中有详细的讲述.故 ...

  8. Spark 2.0 PCA主成份分析

    PCA在Spark2.0中用法比较简单,只需要设置: .setInputCol(“features”)//保证输入是特征值向量 .setOutputCol(“pcaFeatures”)//输出 .se ...

  9. Spark 学习笔记:(四)MLlib基础

    MLlib:Machine Learning Library.主要内容包括: 数据类型 统计工具 summary statistics correlations stratified sampling ...

随机推荐

  1. MySQL用户及权限管理

    查看用户 mysql>SELECT user, host FROM mysql.user; # 检索mysql数据库中的user表 % 表示所有主机的IP 查看当前用户 mysql> se ...

  2. python 字符串占位符的使用

    name2='我是{} 我的专业是 {}'.format('张三','计算机科学技术')print(name2)

  3. Spring Boot学习笔记:kafka应用

    Kafka作为众多Java消息中间件之一,有诸多优点.本文讲解Kafka的应用.学习一个新的知识点,建议先找一个demo,越简单越好的demo,跑通这个demo,了解大致原理,然后在分析细节,详细了解 ...

  4. mybatis 的查询某个字段的特定位数(模糊查询)

    获取特定的几位:1.取url字段后三位字符 select SUBSTRING(url, -3) from link; 2.取url字段前三位字符 select SUBSTRING(url, 3) fr ...

  5. mybatis学习 九 代理开发

    1.作用: 实现创建一个接口后把mapper.xml由mybatis生成接口的实现类,通过调用接口对象就可以获取 mapper.xml 中编写的 sql. 2.实现步骤: 2.1 创建一个接口 (1) ...

  6. 2018.12.15 spoj Substrings(后缀自动机)

    传送门 后缀自动机基础题. 求长度为iii的子串出现次数的最大值. 对原串建出samsamsam,然后用sizsizsiz更新每个maxlenmaxlenmaxlen的答案. 然后由于后缀链接将其转化 ...

  7. C++中各种时间类型的转换(包括MFC中的时间类型)

    平时写代码会经常遇到时间类型转换的问题,如时间戳转为格式化时间,或者反过来等,时间类型有的为time_t,还有FILETIME一堆,在这里记录下他们之间是如何转换的. 时间类型及其意义 FILETIM ...

  8. 利用xshell远程连接centos安装oracle11g时在图形界面登录

    1.首先给centos安装桌面环境.( yum groupinstall ‘GNOME Desktop’) 2.安装Xmanager软件 3.打开xshell,新建连接 填好主机和名称后,点击左侧连接 ...

  9. s4-介质访问控制子层-1 MAC子层

    数据链路层被分成了两个子层:MAC和LLC MAC子层要解决什么问题? 介质访问控制(Madia Access Control) 数据通信方式 单播(unicast):One - to - One ...

  10. 腾讯云 centos 一键安装nginx环境

    这里测试centos版本为7.4 进入命令行直接敲入一下代码 $ yum install nginx 根据提示 进行确认 下一步 即可安装完毕: 服务器默认根目录为 : /usr/share/ngin ...