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 JavaDecisionTreeRegressionExample {
0037
0038 public static void main(String[] args) {
0039
0040
0041 SparkConf sparkConf = new SparkConf().setAppName("JavaDecisionTreeRegressionExample");
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 Map<Integer, Integer> categoricalFeaturesInfo = new HashMap<>();
0055 String impurity = "variance";
0056 int maxDepth = 5;
0057 int maxBins = 32;
0058
0059
0060 DecisionTreeModel model = DecisionTree.trainRegressor(trainingData,
0061 categoricalFeaturesInfo, impurity, maxDepth, maxBins);
0062
0063
0064 JavaPairRDD<Double, Double> predictionAndLabel =
0065 testData.mapToPair(p -> new Tuple2<>(model.predict(p.features()), p.label()));
0066 double testMSE = predictionAndLabel.mapToDouble(pl -> {
0067 double diff = pl._1() - pl._2();
0068 return diff * diff;
0069 }).mean();
0070 System.out.println("Test Mean Squared Error: " + testMSE);
0071 System.out.println("Learned regression tree model:\n" + model.toDebugString());
0072
0073
0074 model.save(jsc.sc(), "target/tmp/myDecisionTreeRegressionModel");
0075 DecisionTreeModel sameModel = DecisionTreeModel
0076 .load(jsc.sc(), "target/tmp/myDecisionTreeRegressionModel");
0077
0078 }
0079 }