0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018 package org.apache.spark.examples.ml;
0019
0020
0021 import org.apache.spark.ml.Pipeline;
0022 import org.apache.spark.ml.PipelineModel;
0023 import org.apache.spark.ml.PipelineStage;
0024 import org.apache.spark.ml.classification.RandomForestClassificationModel;
0025 import org.apache.spark.ml.classification.RandomForestClassifier;
0026 import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator;
0027 import org.apache.spark.ml.feature.*;
0028 import org.apache.spark.sql.Dataset;
0029 import org.apache.spark.sql.Row;
0030 import org.apache.spark.sql.SparkSession;
0031
0032
0033 public class JavaRandomForestClassifierExample {
0034 public static void main(String[] args) {
0035 SparkSession spark = SparkSession
0036 .builder()
0037 .appName("JavaRandomForestClassifierExample")
0038 .getOrCreate();
0039
0040
0041
0042 Dataset<Row> data = spark.read().format("libsvm").load("data/mllib/sample_libsvm_data.txt");
0043
0044
0045
0046 StringIndexerModel labelIndexer = new StringIndexer()
0047 .setInputCol("label")
0048 .setOutputCol("indexedLabel")
0049 .fit(data);
0050
0051
0052 VectorIndexerModel featureIndexer = new VectorIndexer()
0053 .setInputCol("features")
0054 .setOutputCol("indexedFeatures")
0055 .setMaxCategories(4)
0056 .fit(data);
0057
0058
0059 Dataset<Row>[] splits = data.randomSplit(new double[] {0.7, 0.3});
0060 Dataset<Row> trainingData = splits[0];
0061 Dataset<Row> testData = splits[1];
0062
0063
0064 RandomForestClassifier rf = new RandomForestClassifier()
0065 .setLabelCol("indexedLabel")
0066 .setFeaturesCol("indexedFeatures");
0067
0068
0069 IndexToString labelConverter = new IndexToString()
0070 .setInputCol("prediction")
0071 .setOutputCol("predictedLabel")
0072 .setLabels(labelIndexer.labelsArray()[0]);
0073
0074
0075 Pipeline pipeline = new Pipeline()
0076 .setStages(new PipelineStage[] {labelIndexer, featureIndexer, rf, labelConverter});
0077
0078
0079 PipelineModel model = pipeline.fit(trainingData);
0080
0081
0082 Dataset<Row> predictions = model.transform(testData);
0083
0084
0085 predictions.select("predictedLabel", "label", "features").show(5);
0086
0087
0088 MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()
0089 .setLabelCol("indexedLabel")
0090 .setPredictionCol("prediction")
0091 .setMetricName("accuracy");
0092 double accuracy = evaluator.evaluate(predictions);
0093 System.out.println("Test Error = " + (1.0 - accuracy));
0094
0095 RandomForestClassificationModel rfModel = (RandomForestClassificationModel)(model.stages()[2]);
0096 System.out.println("Learned classification forest model:\n" + rfModel.toDebugString());
0097
0098
0099 spark.stop();
0100 }
0101 }