Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Licensed to the Apache Software Foundation (ASF) under one or more
0003  * contributor license agreements.  See the NOTICE file distributed with
0004  * this work for additional information regarding copyright ownership.
0005  * The ASF licenses this file to You under the Apache License, Version 2.0
0006  * (the "License"); you may not use this file except in compliance with
0007  * the License.  You may obtain a copy of the License at
0008  *
0009  *    http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  */
0017 
0018 package org.apache.spark.examples.mllib;
0019 
0020 // $example on$
0021 import java.util.Arrays;
0022 import java.util.List;
0023 // $example off$
0024 
0025 import org.apache.spark.SparkConf;
0026 import org.apache.spark.SparkContext;
0027 // $example on$
0028 import org.apache.spark.api.java.JavaRDD;
0029 import org.apache.spark.api.java.JavaSparkContext;
0030 import org.apache.spark.mllib.linalg.Matrix;
0031 import org.apache.spark.mllib.linalg.Vector;
0032 import org.apache.spark.mllib.linalg.Vectors;
0033 import org.apache.spark.mllib.linalg.distributed.RowMatrix;
0034 // $example off$
0035 
0036 /**
0037  * Example for compute principal components on a 'RowMatrix'.
0038  */
0039 public class JavaPCAExample {
0040   public static void main(String[] args) {
0041     SparkConf conf = new SparkConf().setAppName("PCA Example");
0042     SparkContext sc = new SparkContext(conf);
0043     JavaSparkContext jsc = JavaSparkContext.fromSparkContext(sc);
0044 
0045     // $example on$
0046     List<Vector> data = Arrays.asList(
0047             Vectors.sparse(5, new int[] {1, 3}, new double[] {1.0, 7.0}),
0048             Vectors.dense(2.0, 0.0, 3.0, 4.0, 5.0),
0049             Vectors.dense(4.0, 0.0, 0.0, 6.0, 7.0)
0050     );
0051 
0052     JavaRDD<Vector> rows = jsc.parallelize(data);
0053 
0054     // Create a RowMatrix from JavaRDD<Vector>.
0055     RowMatrix mat = new RowMatrix(rows.rdd());
0056 
0057     // Compute the top 4 principal components.
0058     // Principal components are stored in a local dense matrix.
0059     Matrix pc = mat.computePrincipalComponents(4);
0060 
0061     // Project the rows to the linear space spanned by the top 4 principal components.
0062     RowMatrix projected = mat.multiply(pc);
0063     // $example off$
0064     Vector[] collectPartitions = (Vector[])projected.rows().collect();
0065     System.out.println("Projected vector of principal component:");
0066     for (Vector vector : collectPartitions) {
0067       System.out.println("\t" + vector);
0068     }
0069     jsc.stop();
0070   }
0071 }