|
| 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.ml |
| 19 | + |
| 20 | +import scala.collection.mutable |
| 21 | +import scala.language.reflectiveCalls |
| 22 | + |
| 23 | +import scopt.OptionParser |
| 24 | + |
| 25 | +import org.apache.spark.ml.tree.DecisionTreeModel |
| 26 | +import org.apache.spark.{SparkConf, SparkContext} |
| 27 | +import org.apache.spark.examples.mllib.AbstractParams |
| 28 | +import org.apache.spark.ml.{Pipeline, PipelineStage} |
| 29 | +import org.apache.spark.ml.classification.{DecisionTreeClassificationModel, DecisionTreeClassifier} |
| 30 | +import org.apache.spark.ml.feature.{VectorIndexer, StringIndexer} |
| 31 | +import org.apache.spark.ml.regression.{DecisionTreeRegressionModel, DecisionTreeRegressor} |
| 32 | +import org.apache.spark.ml.util.MetadataUtils |
| 33 | +import org.apache.spark.mllib.evaluation.{RegressionMetrics, MulticlassMetrics} |
| 34 | +import org.apache.spark.mllib.linalg.Vector |
| 35 | +import org.apache.spark.mllib.regression.LabeledPoint |
| 36 | +import org.apache.spark.mllib.util.MLUtils |
| 37 | +import org.apache.spark.rdd.RDD |
| 38 | +import org.apache.spark.sql.types.StringType |
| 39 | +import org.apache.spark.sql.{SQLContext, DataFrame} |
| 40 | + |
| 41 | + |
| 42 | +/** |
| 43 | + * An example runner for decision trees. Run with |
| 44 | + * {{{ |
| 45 | + * ./bin/run-example ml.DecisionTreeExample [options] |
| 46 | + * }}} |
| 47 | + * If you use it as a template to create your own app, please use `spark-submit` to submit your app. |
| 48 | + */ |
| 49 | +object DecisionTreeExample { |
| 50 | + |
| 51 | + case class Params( |
| 52 | + input: String = null, |
| 53 | + testInput: String = "", |
| 54 | + dataFormat: String = "libsvm", |
| 55 | + algo: String = "Classification", |
| 56 | + maxDepth: Int = 5, |
| 57 | + maxBins: Int = 32, |
| 58 | + minInstancesPerNode: Int = 1, |
| 59 | + minInfoGain: Double = 0.0, |
| 60 | + numTrees: Int = 1, |
| 61 | + featureSubsetStrategy: String = "auto", |
| 62 | + fracTest: Double = 0.2, |
| 63 | + cacheNodeIds: Boolean = false, |
| 64 | + checkpointDir: Option[String] = None, |
| 65 | + checkpointInterval: Int = 10) extends AbstractParams[Params] |
| 66 | + |
| 67 | + def main(args: Array[String]) { |
| 68 | + val defaultParams = Params() |
| 69 | + |
| 70 | + val parser = new OptionParser[Params]("DecisionTreeExample") { |
| 71 | + head("DecisionTreeExample: an example decision tree app.") |
| 72 | + opt[String]("algo") |
| 73 | + .text(s"algorithm (Classification, Regression), default: ${defaultParams.algo}") |
| 74 | + .action((x, c) => c.copy(algo = x)) |
| 75 | + opt[Int]("maxDepth") |
| 76 | + .text(s"max depth of the tree, default: ${defaultParams.maxDepth}") |
| 77 | + .action((x, c) => c.copy(maxDepth = x)) |
| 78 | + opt[Int]("maxBins") |
| 79 | + .text(s"max number of bins, default: ${defaultParams.maxBins}") |
| 80 | + .action((x, c) => c.copy(maxBins = x)) |
| 81 | + opt[Int]("minInstancesPerNode") |
| 82 | + .text(s"min number of instances required at child nodes to create the parent split," + |
| 83 | + s" default: ${defaultParams.minInstancesPerNode}") |
| 84 | + .action((x, c) => c.copy(minInstancesPerNode = x)) |
| 85 | + opt[Double]("minInfoGain") |
| 86 | + .text(s"min info gain required to create a split, default: ${defaultParams.minInfoGain}") |
| 87 | + .action((x, c) => c.copy(minInfoGain = x)) |
| 88 | + opt[Double]("fracTest") |
| 89 | + .text(s"fraction of data to hold out for testing. If given option testInput, " + |
| 90 | + s"this option is ignored. default: ${defaultParams.fracTest}") |
| 91 | + .action((x, c) => c.copy(fracTest = x)) |
| 92 | + opt[Boolean]("cacheNodeIds") |
| 93 | + .text(s"whether to use node Id cache during training, " + |
| 94 | + s"default: ${defaultParams.cacheNodeIds}") |
| 95 | + .action((x, c) => c.copy(cacheNodeIds = x)) |
| 96 | + opt[String]("checkpointDir") |
| 97 | + .text(s"checkpoint directory where intermediate node Id caches will be stored, " + |
| 98 | + s"default: ${defaultParams.checkpointDir match { |
| 99 | + case Some(strVal) => strVal |
| 100 | + case None => "None" |
| 101 | + }}") |
| 102 | + .action((x, c) => c.copy(checkpointDir = Some(x))) |
| 103 | + opt[Int]("checkpointInterval") |
| 104 | + .text(s"how often to checkpoint the node Id cache, " + |
| 105 | + s"default: ${defaultParams.checkpointInterval}") |
| 106 | + .action((x, c) => c.copy(checkpointInterval = x)) |
| 107 | + opt[String]("testInput") |
| 108 | + .text(s"input path to test dataset. If given, option fracTest is ignored." + |
| 109 | + s" default: ${defaultParams.testInput}") |
| 110 | + .action((x, c) => c.copy(testInput = x)) |
| 111 | + opt[String]("<dataFormat>") |
| 112 | + .text("data format: libsvm (default), dense (deprecated in Spark v1.1)") |
| 113 | + .action((x, c) => c.copy(dataFormat = x)) |
| 114 | + arg[String]("<input>") |
| 115 | + .text("input path to labeled examples") |
| 116 | + .required() |
| 117 | + .action((x, c) => c.copy(input = x)) |
| 118 | + checkConfig { params => |
| 119 | + if (params.fracTest < 0 || params.fracTest > 1) { |
| 120 | + failure(s"fracTest ${params.fracTest} value incorrect; should be in [0,1].") |
| 121 | + } else { |
| 122 | + success |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + parser.parse(args, defaultParams).map { params => |
| 128 | + run(params) |
| 129 | + }.getOrElse { |
| 130 | + sys.exit(1) |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + /** Load a dataset from the given path, using the given format */ |
| 135 | + private[ml] def loadData( |
| 136 | + sc: SparkContext, |
| 137 | + path: String, |
| 138 | + format: String, |
| 139 | + expectedNumFeatures: Option[Int] = None): RDD[LabeledPoint] = { |
| 140 | + format match { |
| 141 | + case "dense" => MLUtils.loadLabeledPoints(sc, path) |
| 142 | + case "libsvm" => expectedNumFeatures match { |
| 143 | + case Some(numFeatures) => MLUtils.loadLibSVMFile(sc, path, numFeatures) |
| 144 | + case None => MLUtils.loadLibSVMFile(sc, path) |
| 145 | + } |
| 146 | + case _ => throw new IllegalArgumentException(s"Bad data format: $format") |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + /** |
| 151 | + * Load training and test data from files. |
| 152 | + * @param input Path to input dataset. |
| 153 | + * @param dataFormat "libsvm" or "dense" |
| 154 | + * @param testInput Path to test dataset. |
| 155 | + * @param algo Classification or Regression |
| 156 | + * @param fracTest Fraction of input data to hold out for testing. Ignored if testInput given. |
| 157 | + * @return (training dataset, test dataset) |
| 158 | + */ |
| 159 | + private[ml] def loadDatasets( |
| 160 | + sc: SparkContext, |
| 161 | + input: String, |
| 162 | + dataFormat: String, |
| 163 | + testInput: String, |
| 164 | + algo: String, |
| 165 | + fracTest: Double): (DataFrame, DataFrame) = { |
| 166 | + val sqlContext = new SQLContext(sc) |
| 167 | + import sqlContext.implicits._ |
| 168 | + |
| 169 | + // Load training data |
| 170 | + val origExamples: RDD[LabeledPoint] = loadData(sc, input, dataFormat) |
| 171 | + |
| 172 | + // Load or create test set |
| 173 | + val splits: Array[RDD[LabeledPoint]] = if (testInput != "") { |
| 174 | + // Load testInput. |
| 175 | + val numFeatures = origExamples.take(1)(0).features.size |
| 176 | + val origTestExamples: RDD[LabeledPoint] = loadData(sc, input, dataFormat, Some(numFeatures)) |
| 177 | + Array(origExamples, origTestExamples) |
| 178 | + } else { |
| 179 | + // Split input into training, test. |
| 180 | + origExamples.randomSplit(Array(1.0 - fracTest, fracTest), seed = 12345) |
| 181 | + } |
| 182 | + |
| 183 | + // For classification, convert labels to Strings since we will index them later with |
| 184 | + // StringIndexer. |
| 185 | + def labelsToStrings(data: DataFrame): DataFrame = { |
| 186 | + algo.toLowerCase match { |
| 187 | + case "classification" => |
| 188 | + data.withColumn("labelString", data("label").cast(StringType)) |
| 189 | + case "regression" => |
| 190 | + data |
| 191 | + case _ => |
| 192 | + throw new IllegalArgumentException("Algo ${params.algo} not supported.") |
| 193 | + } |
| 194 | + } |
| 195 | + val dataframes = splits.map(_.toDF()).map(labelsToStrings).map(_.cache()) |
| 196 | + |
| 197 | + (dataframes(0), dataframes(1)) |
| 198 | + } |
| 199 | + |
| 200 | + def run(params: Params) { |
| 201 | + val conf = new SparkConf().setAppName(s"DecisionTreeExample with $params") |
| 202 | + val sc = new SparkContext(conf) |
| 203 | + params.checkpointDir.foreach(sc.setCheckpointDir) |
| 204 | + val algo = params.algo.toLowerCase |
| 205 | + |
| 206 | + println(s"DecisionTreeExample with parameters:\n$params") |
| 207 | + |
| 208 | + // Load training and test data and cache it. |
| 209 | + val (training: DataFrame, test: DataFrame) = |
| 210 | + loadDatasets(sc, params.input, params.dataFormat, params.testInput, algo, params.fracTest) |
| 211 | + |
| 212 | + val numTraining = training.count() |
| 213 | + val numTest = test.count() |
| 214 | + val numFeatures = training.select("features").first().getAs[Vector](0).size |
| 215 | + println("Loaded data:") |
| 216 | + println(s" numTraining = $numTraining, numTest = $numTest") |
| 217 | + println(s" numFeatures = $numFeatures") |
| 218 | + |
| 219 | + // Set up Pipeline |
| 220 | + val stages = new mutable.ArrayBuffer[PipelineStage]() |
| 221 | + // (1) For classification, re-index classes. |
| 222 | + val labelColName = if (algo == "classification") "indexedLabel" else "label" |
| 223 | + if (algo == "classification") { |
| 224 | + val labelIndexer = new StringIndexer().setInputCol("labelString").setOutputCol(labelColName) |
| 225 | + stages += labelIndexer |
| 226 | + } |
| 227 | + // (2) Identify categorical features using VectorIndexer. |
| 228 | + // Features with more than maxCategories values will be treated as continuous. |
| 229 | + val featuresIndexer = new VectorIndexer().setInputCol("features") |
| 230 | + .setOutputCol("indexedFeatures").setMaxCategories(10) |
| 231 | + stages += featuresIndexer |
| 232 | + // (3) Learn DecisionTree |
| 233 | + val dt = algo match { |
| 234 | + case "classification" => |
| 235 | + new DecisionTreeClassifier().setFeaturesCol("indexedFeatures") |
| 236 | + .setLabelCol(labelColName) |
| 237 | + .setMaxDepth(params.maxDepth) |
| 238 | + .setMaxBins(params.maxBins) |
| 239 | + .setMinInstancesPerNode(params.minInstancesPerNode) |
| 240 | + .setMinInfoGain(params.minInfoGain) |
| 241 | + .setCacheNodeIds(params.cacheNodeIds) |
| 242 | + .setCheckpointInterval(params.checkpointInterval) |
| 243 | + case "regression" => |
| 244 | + new DecisionTreeRegressor().setFeaturesCol("indexedFeatures") |
| 245 | + .setLabelCol(labelColName) |
| 246 | + .setMaxDepth(params.maxDepth) |
| 247 | + .setMaxBins(params.maxBins) |
| 248 | + .setMinInstancesPerNode(params.minInstancesPerNode) |
| 249 | + .setMinInfoGain(params.minInfoGain) |
| 250 | + .setCacheNodeIds(params.cacheNodeIds) |
| 251 | + .setCheckpointInterval(params.checkpointInterval) |
| 252 | + case _ => throw new IllegalArgumentException("Algo ${params.algo} not supported.") |
| 253 | + } |
| 254 | + stages += dt |
| 255 | + val pipeline = new Pipeline().setStages(stages.toArray) |
| 256 | + |
| 257 | + // Fit the Pipeline |
| 258 | + val startTime = System.nanoTime() |
| 259 | + val pipelineModel = pipeline.fit(training) |
| 260 | + val elapsedTime = (System.nanoTime() - startTime) / 1e9 |
| 261 | + println(s"Training time: $elapsedTime seconds") |
| 262 | + |
| 263 | + // Get the trained Decision Tree from the fitted PipelineModel |
| 264 | + val treeModel: DecisionTreeModel = algo match { |
| 265 | + case "classification" => |
| 266 | + pipelineModel.getModel[DecisionTreeClassificationModel]( |
| 267 | + dt.asInstanceOf[DecisionTreeClassifier]) |
| 268 | + case "regression" => |
| 269 | + pipelineModel.getModel[DecisionTreeRegressionModel](dt.asInstanceOf[DecisionTreeRegressor]) |
| 270 | + case _ => throw new IllegalArgumentException("Algo ${params.algo} not supported.") |
| 271 | + } |
| 272 | + if (treeModel.numNodes < 20) { |
| 273 | + println(treeModel.toDebugString) // Print full model. |
| 274 | + } else { |
| 275 | + println(treeModel) // Print model summary. |
| 276 | + } |
| 277 | + |
| 278 | + // Predict on training |
| 279 | + val trainingFullPredictions = pipelineModel.transform(training).cache() |
| 280 | + val trainingPredictions = trainingFullPredictions.select("prediction") |
| 281 | + .map(_.getDouble(0)) |
| 282 | + val trainingLabels = trainingFullPredictions.select(labelColName).map(_.getDouble(0)) |
| 283 | + // Predict on test data |
| 284 | + val testFullPredictions = pipelineModel.transform(test).cache() |
| 285 | + val testPredictions = testFullPredictions.select("prediction") |
| 286 | + .map(_.getDouble(0)) |
| 287 | + val testLabels = testFullPredictions.select(labelColName).map(_.getDouble(0)) |
| 288 | + |
| 289 | + // For classification, print number of classes for reference. |
| 290 | + if (algo == "classification") { |
| 291 | + val numClasses = |
| 292 | + MetadataUtils.getNumClasses(trainingFullPredictions.schema(labelColName)) match { |
| 293 | + case Some(n) => n |
| 294 | + case None => throw new RuntimeException( |
| 295 | + "DecisionTreeExample had unknown failure when indexing labels for classification.") |
| 296 | + } |
| 297 | + println(s"numClasses = $numClasses.") |
| 298 | + } |
| 299 | + |
| 300 | + // Evaluate model on training, test data |
| 301 | + algo match { |
| 302 | + case "classification" => |
| 303 | + val trainingAccuracy = |
| 304 | + new MulticlassMetrics(trainingPredictions.zip(trainingLabels)).precision |
| 305 | + println(s"Train accuracy = $trainingAccuracy") |
| 306 | + val testAccuracy = |
| 307 | + new MulticlassMetrics(testPredictions.zip(testLabels)).precision |
| 308 | + println(s"Test accuracy = $testAccuracy") |
| 309 | + case "regression" => |
| 310 | + val trainingRMSE = |
| 311 | + new RegressionMetrics(trainingPredictions.zip(trainingLabels)).rootMeanSquaredError |
| 312 | + println(s"Training root mean squared error (RMSE) = $trainingRMSE") |
| 313 | + val testRMSE = |
| 314 | + new RegressionMetrics(testPredictions.zip(testLabels)).rootMeanSquaredError |
| 315 | + println(s"Test root mean squared error (RMSE) = $testRMSE") |
| 316 | + case _ => |
| 317 | + throw new IllegalArgumentException("Algo ${params.algo} not supported.") |
| 318 | + } |
| 319 | + |
| 320 | + sc.stop() |
| 321 | + } |
| 322 | +} |
0 commit comments