0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018 package org.apache.spark.examples.mllib;
0019
0020
0021 import java.util.HashMap;
0022 import java.util.Map;
0023
0024 import scala.Tuple2;
0025
0026 import org.apache.spark.SparkConf;
0027 import org.apache.spark.api.java.JavaPairRDD;
0028 import org.apache.spark.api.java.JavaRDD;
0029 import org.apache.spark.api.java.JavaSparkContext;
0030 import org.apache.spark.mllib.regression.LabeledPoint;
0031 import org.apache.spark.mllib.tree.DecisionTree;
0032 import org.apache.spark.mllib.tree.model.DecisionTreeModel;
0033 import org.apache.spark.mllib.util.MLUtils;
0034
0035
0036 class JavaDecisionTreeClassificationExample {
0037
0038 public static void main(String[] args) {
0039
0040
0041 SparkConf sparkConf = new SparkConf().setAppName("JavaDecisionTreeClassificationExample");
0042 JavaSparkContext jsc = new JavaSparkContext(sparkConf);
0043
0044
0045 String datapath = "data/mllib/sample_libsvm_data.txt";
0046 JavaRDD<LabeledPoint> data = MLUtils.loadLibSVMFile(jsc.sc(), datapath).toJavaRDD();
0047
0048 JavaRDD<LabeledPoint>[] splits = data.randomSplit(new double[]{0.7, 0.3});
0049 JavaRDD<LabeledPoint> trainingData = splits[0];
0050 JavaRDD<LabeledPoint> testData = splits[1];
0051
0052
0053
0054 int numClasses = 2;
0055 Map<Integer, Integer> categoricalFeaturesInfo = new HashMap<>();
0056 String impurity = "gini";
0057 int maxDepth = 5;
0058 int maxBins = 32;
0059
0060
0061 DecisionTreeModel model = DecisionTree.trainClassifier(trainingData, numClasses,
0062 categoricalFeaturesInfo, impurity, maxDepth, maxBins);
0063
0064
0065 JavaPairRDD<Double, Double> predictionAndLabel =
0066 testData.mapToPair(p -> new Tuple2<>(model.predict(p.features()), p.label()));
0067 double testErr =
0068 predictionAndLabel.filter(pl -> !pl._1().equals(pl._2())).count() / (double) testData.count();
0069
0070 System.out.println("Test Error: " + testErr);
0071 System.out.println("Learned classification tree model:\n" + model.toDebugString());
0072
0073
0074 model.save(jsc.sc(), "target/tmp/myDecisionTreeClassificationModel");
0075 DecisionTreeModel sameModel = DecisionTreeModel
0076 .load(jsc.sc(), "target/tmp/myDecisionTreeClassificationModel");
0077
0078 }
0079 }