|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.examples.mllib |
| 19 | + |
| 20 | +import scopt.OptionParser |
| 21 | + |
| 22 | +import org.apache.spark.{SparkConf, SparkContext} |
| 23 | +import org.apache.spark.SparkContext._ |
| 24 | +import org.apache.spark.mllib.linalg.Vector |
| 25 | +import org.apache.spark.mllib.regression.LabeledPoint |
| 26 | +import org.apache.spark.mllib.tree.{DecisionTree, impurity} |
| 27 | +import org.apache.spark.mllib.tree.configuration.{Algo, Strategy} |
| 28 | +import org.apache.spark.mllib.tree.configuration.Algo._ |
| 29 | +import org.apache.spark.mllib.tree.model.DecisionTreeModel |
| 30 | +import org.apache.spark.mllib.util.MLUtils |
| 31 | +import org.apache.spark.rdd.RDD |
| 32 | + |
| 33 | +/** |
| 34 | + * An example runner for decision tree. Run with |
| 35 | + * {{{ |
| 36 | + * ./bin/spark-example org.apache.spark.examples.mllib.DecisionTreeRunner [options] |
| 37 | + * }}} |
| 38 | + * If you use it as a template to create your own app, please use `spark-submit` to submit your app. |
| 39 | + */ |
| 40 | +object DecisionTreeRunner { |
| 41 | + |
| 42 | + object ImpurityType extends Enumeration { |
| 43 | + type ImpurityType = Value |
| 44 | + val Gini, Entropy, Variance = Value |
| 45 | + } |
| 46 | + |
| 47 | + import ImpurityType._ |
| 48 | + |
| 49 | + case class Params( |
| 50 | + input: String = null, |
| 51 | + algo: Algo = Classification, |
| 52 | + maxDepth: Int = 5, |
| 53 | + impurity: ImpurityType = Gini, |
| 54 | + maxBins: Int = 20) |
| 55 | + |
| 56 | + def main(args: Array[String]) { |
| 57 | + val defaultParams = Params() |
| 58 | + |
| 59 | + val parser = new OptionParser[Params]("DecisionTreeRunner") { |
| 60 | + head("DecisionTreeRunner: an example decision tree app.") |
| 61 | + opt[String]("algo") |
| 62 | + .text(s"algorithm (${Algo.values.mkString(",")}), default: ${defaultParams.algo}") |
| 63 | + .action((x, c) => c.copy(algo = Algo.withName(x))) |
| 64 | + opt[String]("impurity") |
| 65 | + .text(s"impurity type (${ImpurityType.values.mkString(",")}), " + |
| 66 | + s"default: ${defaultParams.impurity}") |
| 67 | + .action((x, c) => c.copy(impurity = ImpurityType.withName(x))) |
| 68 | + opt[Int]("maxDepth") |
| 69 | + .text(s"max depth of the tree, default: ${defaultParams.maxDepth}") |
| 70 | + .action((x, c) => c.copy(maxDepth = x)) |
| 71 | + opt[Int]("maxBins") |
| 72 | + .text(s"max number of bins, default: ${defaultParams.maxBins}") |
| 73 | + .action((x, c) => c.copy(maxBins = x)) |
| 74 | + arg[String]("<input>") |
| 75 | + .text("input paths to labeled examples in dense format (label,f0 f1 f2 ...)") |
| 76 | + .required() |
| 77 | + .action((x, c) => c.copy(input = x)) |
| 78 | + checkConfig { params => |
| 79 | + if (params.algo == Classification && |
| 80 | + (params.impurity == Gini || params.impurity == Entropy)) { |
| 81 | + success |
| 82 | + } else if (params.algo == Regression && params.impurity == Variance) { |
| 83 | + success |
| 84 | + } else { |
| 85 | + failure(s"Algo ${params.algo} is not compatible with impurity ${params.impurity}.") |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + parser.parse(args, defaultParams).map { params => |
| 91 | + run(params) |
| 92 | + }.getOrElse { |
| 93 | + sys.exit(1) |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + def run(params: Params) { |
| 98 | + val conf = new SparkConf().setAppName("DecisionTreeRunner") |
| 99 | + val sc = new SparkContext(conf) |
| 100 | + |
| 101 | + // Load training data and cache it. |
| 102 | + val examples = MLUtils.loadLabeledData(sc, params.input).cache() |
| 103 | + |
| 104 | + val splits = examples.randomSplit(Array(0.8, 0.2)) |
| 105 | + val training = splits(0).cache() |
| 106 | + val test = splits(1).cache() |
| 107 | + |
| 108 | + val numTraining = training.count() |
| 109 | + val numTest = test.count() |
| 110 | + |
| 111 | + println(s"numTraining = $numTraining, numTest = $numTest.") |
| 112 | + |
| 113 | + examples.unpersist(blocking = false) |
| 114 | + |
| 115 | + val impurityCalculator = params.impurity match { |
| 116 | + case Gini => impurity.Gini |
| 117 | + case Entropy => impurity.Entropy |
| 118 | + case Variance => impurity.Variance |
| 119 | + } |
| 120 | + |
| 121 | + val strategy = new Strategy(params.algo, impurityCalculator, params.maxDepth, params.maxBins) |
| 122 | + val model = DecisionTree.train(training, strategy) |
| 123 | + |
| 124 | + if (params.algo == Classification) { |
| 125 | + val accuracy = accuracyScore(model, test) |
| 126 | + println(s"Test accuracy = $accuracy.") |
| 127 | + } |
| 128 | + |
| 129 | + if (params.algo == Regression) { |
| 130 | + val mse = meanSquaredError(model, test) |
| 131 | + println(s"Test mean squared error = $mse.") |
| 132 | + } |
| 133 | + |
| 134 | + sc.stop() |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Calculates the classifier accuracy. |
| 139 | + */ |
| 140 | + private def accuracyScore( |
| 141 | + model: DecisionTreeModel, |
| 142 | + data: RDD[LabeledPoint], |
| 143 | + threshold: Double = 0.5): Double = { |
| 144 | + def predictedValue(features: Vector): Double = { |
| 145 | + if (model.predict(features) < threshold) 0.0 else 1.0 |
| 146 | + } |
| 147 | + val correctCount = data.filter(y => predictedValue(y.features) == y.label).count() |
| 148 | + val count = data.count() |
| 149 | + correctCount.toDouble / count |
| 150 | + } |
| 151 | + |
| 152 | + /** |
| 153 | + * Calculates the mean squared error for regression. |
| 154 | + */ |
| 155 | + private def meanSquaredError(tree: DecisionTreeModel, data: RDD[LabeledPoint]): Double = { |
| 156 | + data.map { y => |
| 157 | + val err = tree.predict(y.features) - y.label |
| 158 | + err * err |
| 159 | + }.mean() |
| 160 | + } |
| 161 | +} |
0 commit comments