Guest User

Untitled

a guest
Jun 26th, 2017
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import org.apache.spark.api.java.*;
  2. import org.apache.spark.api.java.function.Function;
  3. import org.apache.spark.mllib.clustering.KMeans;
  4. import org.apache.spark.mllib.clustering.KMeansModel;
  5. import org.apache.spark.mllib.linalg.Vector;
  6. import org.apache.spark.mllib.linalg.Vectors;
  7. import org.apache.spark.SparkConf;
  8.  
  9. public class Kmeans {
  10. public static void main(String[] args) {
  11. SparkConf conf = new SparkConf().setAppName("K-means Example");
  12. JavaSparkContext sc = new JavaSparkContext(conf);
  13.  
  14. // Load and parse data
  15. String path = "data/mllib/kmeans_data.txt";
  16. JavaRDD<String> data = sc.textFile(path);
  17. JavaRDD<Vector> parsedData = data.map(
  18. new Function<String, Vector>() {
  19. public Vector call(String s) {
  20. String[] sarray = s.split(" ");
  21. double[] values = new double[sarray.length];
  22. for (int i = 0; i < sarray.length; i++)
  23. values[i] = Double.parseDouble(sarray[i]);
  24. return Vectors.dense(values);
  25. }
  26. }
  27. );
  28.  
  29. // Cluster the data into two classes using KMeans
  30. int numClusters = 2;
  31. int numIterations = 20;
  32. KMeansModel clusters = KMeans.train(parsedData.rdd(), numClusters, numIterations);
  33.  
  34. // Evaluate clustering by computing Within Set Sum of Squared Errors
  35. double WSSSE = clusters.computeCost(parsedData.rdd());
  36. System.out.println("Within Set Sum of Squared Errors = " + WSSSE);
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment