Apache Spark决策树预测

时间:2016-11-27 03:08:27

标签: java apache-spark machine-learning decision-tree

我有以下使用决策树进行分类的代码。我需要将测试数据集的预测变为java数组并打印它们。有人可以帮我扩展这个代码。我需要一个预测标签和实际标签的二维数组,并打印预测标签。

public class DecisionTreeClass {
    public  static void main(String args[]){
        SparkConf sparkConf = new SparkConf().setAppName("DecisionTreeClass").setMaster("local[2]");
        JavaSparkContext jsc = new JavaSparkContext(sparkConf);


        // Load and parse the data file.
        String datapath = "/home/thamali/Desktop/tlib.txt";
        JavaRDD<LabeledPoint> data = MLUtils.loadLibSVMFile(jsc.sc(), datapath).toJavaRDD();//A training example used in supervised learning is called a “labeled point” in MLlib.
        // Split the data into training and test sets (30% held out for testing)
        JavaRDD<LabeledPoint>[] splits = data.randomSplit(new double[]{0.7, 0.3});
        JavaRDD<LabeledPoint> trainingData = splits[0];
        JavaRDD<LabeledPoint> testData = splits[1];

        // Set parameters.
        //  Empty categoricalFeaturesInfo indicates all features are continuous.
        Integer numClasses = 12;
        Map<Integer, Integer> categoricalFeaturesInfo = new HashMap();
        String impurity = "gini";
        Integer maxDepth = 5;
        Integer maxBins = 32;

        // Train a DecisionTree model for classification.
        final DecisionTreeModel model = DecisionTree.trainClassifier(trainingData, numClasses,
                categoricalFeaturesInfo, impurity, maxDepth, maxBins);

        // Evaluate model on test instances and compute test error
        JavaPairRDD<Double, Double> predictionAndLabel =
                testData.mapToPair(new PairFunction<LabeledPoint, Double, Double>() {
                    @Override
                    public Tuple2<Double, Double> call(LabeledPoint p) {
                        return new Tuple2(model.predict(p.features()), p.label());
                    }
                });

        Double testErr =
                1.0 * predictionAndLabel.filter(new Function<Tuple2<Double, Double>, Boolean>() {
                    @Override
                    public Boolean call(Tuple2<Double, Double> pl) {
                        return !pl._1().equals(pl._2());
                    }
                }).count() / testData.count();

        System.out.println("Test Error: " + testErr);
        System.out.println("Learned classification tree model:\n" + model.toDebugString());


    }

}

1 个答案:

答案 0 :(得分:1)

你基本上与预测和标签变量完全相同。如果您确实需要2d双数组的列表,可以将您使用的方法更改为:

JavaRDD<double[]> valuesAndPreds = testData.map(point -> new double[]{model.predict(point.features()), point.label()});

并在该引用上运行collect以获取2d双数组的列表。

List<double[]> values = valuesAndPreds.collect();

我会在这里查看文档:{​​{3}}。您还可以使用MulticlassMetrics等类更改数据以获得模型的其他静态性能度量。这需要将mapToPair函数更改为map函数并将泛型更改为对象。如下所示:

JavaRDD<Tuple2<Object, Object>> valuesAndPreds = testData().map(point -> new Tuple2<>(model.predict(point.features()), point.label()));

然后跑步:

MulticlassMetrics multiclassMetrics = new MulticlassMetrics(JavaRDD.toRDD(valuesAndPreds));

Spark的MLLib文档中记录了所有这些内容。此外,您提到需要打印结果。如果这是作业,我会让你弄清楚那一部分,因为从列表中学习如何做到这一点是一个很好的练习。

编辑:

另外,注意到你使用的是java 7,我的内容来自java 8.要回答关于如何变成2d双数组的主要问题,你可以这样做:

JavaRDD<double[]> valuesAndPreds = testData.map(new org.apache.spark.api.java.function.Function<LabeledPoint, double[]>() {
                @Override
                public double[] call(LabeledPoint point) {
                    return new double[]{model.predict(point.features()), point.label()};
                }
            });

然后运行collect,获取两个双打的列表。另外,要提示打印部分,请查看java.util.Arrays toString实现。

相关问题