下面是一个例子仅供参考
我们对PCA后降维后的数据最直接的应用是聚类,比如kmeans算法:
这里提下不同类型变量相异度计算方法:
k均值算法的计算过程非常直观:
1、从D中随机取k个元素,作为k个簇的各自的中心。
2、分别计算剩下的元素到k个簇中心的相异度,将这些元素分别划归到相异度最低的簇。
3、根据聚类结果,重新计算k个簇各自的中心,计算方法是取簇中所有元素各自维度的算术平均数。
4、将D中全部元素按照新的中心重新聚类。
5、重复第4步,直到聚类结果不再变化。
6、将结果输出。
上代码,是基于spark MLlib的:
[mw_shl_code=scala,true]import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.mllib.clustering.KMeans
import org.apache.spark.mllib.linalg.Matrix
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.linalg.distributed.RowMatrix
import scala.util.Random
object PCA {
def getRandom(num: Int) = {
(for(i <- 1 to num ) yield "%1.1f".format(new Random().nextDouble()*10).toDouble ).toArray
}
def main(args: Array[String]): Unit = {
val line = 5
val conf =new SparkConf().setAppName("PCA");
val sc = new SparkContext(conf)
val data =(for(i <- 1 to line ) yield Vectors.dense(getRandom(10))).toArray
//我们产生一个5X10的矩阵
val dataRDD = sc.parallelize(data, 2)
//RowMatrix 分布式矩阵,RowMatrix.numRows,RowMatrix.numCols
val mat: RowMatrix = new RowMatrix(dataRDD)
val pc: Matrix = mat.computePrincipalComponents(3)//PCA只需要保留前3个特征
//得到的矩阵结果
val projected: RowMatrix = mat.multiply(pc)
val newdateRDD = projected.rows
// 打印出降维的数据
val numIterations = 20//迭代的次数
val ks:Array[Int] = Array(2,3,4,5)
ks.foreach(cluster => {
val model = KMeans.train(newdateRDD, cluster,numIterations,1)
val ssd = model.computeCost(newdateRDD)
println(" when k=" + cluster + " -> "+ ssd)
})
val Knum = 3 //将目标数据分成几类
//将参数,和训练数据传入,形成模型
val clusters1 = KMeans.train(dataRDD, Knum , numIterations)//训练原始数据
val clusters2 = KMeans.train(newdateRDD, Knum , numIterations)//训练降维数据
val collect = projected.rows.collect()
println("主成分投影列矩阵:")
collect.foreach { vector => println(vector) }
val source = mat.rows.collect()
println("原始投影列矩阵:")
source.foreach { vector => println(vector) }
/*println("原始数据中心分布:")
for (c <- clusters1.clusterCenters) {
println(" " + c.toString)
}
println("训练降维数据中心分布:")
for (c <- clusters2.clusterCenters) {
println(" " + c.toString)
}*/
for( i <- 0 to source.length - 1) {
println("训练原始数据:" + source(i).toString + "属于" + clusters1.predict(source(i)).toString + "类")
}
for( i <- 0 to collect.length -1) {
println("训练降维数据:" + collect(i).toString + "属于" + clusters2.predict(collect(i)).toString + "类")
}
}
}
[/mw_shl_code]
来自:
Python实现PCA降维算法及其应用
http://www.aboutyun.com/forum.php?mod=viewthread&tid=22452
|