Back to home page

OSCL-LXR

 
 

    


0001 ---
0002 layout: global
0003 title: Decision Trees - RDD-based API
0004 displayTitle: Decision Trees - RDD-based API
0005 license: |
0006   Licensed to the Apache Software Foundation (ASF) under one or more
0007   contributor license agreements.  See the NOTICE file distributed with
0008   this work for additional information regarding copyright ownership.
0009   The ASF licenses this file to You under the Apache License, Version 2.0
0010   (the "License"); you may not use this file except in compliance with
0011   the License.  You may obtain a copy of the License at
0012  
0013      http://www.apache.org/licenses/LICENSE-2.0
0014  
0015   Unless required by applicable law or agreed to in writing, software
0016   distributed under the License is distributed on an "AS IS" BASIS,
0017   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0018   See the License for the specific language governing permissions and
0019   limitations under the License.
0020 ---
0021 
0022 * Table of contents
0023 {:toc}
0024 
0025 [Decision trees](http://en.wikipedia.org/wiki/Decision_tree_learning)
0026 and their ensembles are popular methods for the machine learning tasks of
0027 classification and regression. Decision trees are widely used since they are easy to interpret,
0028 handle categorical features, extend to the multiclass classification setting, do not require
0029 feature scaling, and are able to capture non-linearities and feature interactions. Tree ensemble
0030 algorithms such as random forests and boosting are among the top performers for classification and
0031 regression tasks.
0032 
0033 `spark.mllib` supports decision trees for binary and multiclass classification and for regression,
0034 using both continuous and categorical features. The implementation partitions data by rows,
0035 allowing distributed training with millions of instances.
0036 
0037 Ensembles of trees (Random Forests and Gradient-Boosted Trees) are described in the [Ensembles guide](mllib-ensembles.html).
0038 
0039 ## Basic algorithm
0040 
0041 The decision tree is a greedy algorithm that performs a recursive binary partitioning of the feature
0042 space.  The tree predicts the same label for each bottommost (leaf) partition.
0043 Each partition is chosen greedily by selecting the *best split* from a set of possible splits,
0044 in order to maximize the information gain at a tree node. In other words, the split chosen at each
0045 tree node is chosen from the set `$\underset{s}{\operatorname{argmax}} IG(D,s)$` where `$IG(D,s)$`
0046 is the information gain when a split `$s$` is applied to a dataset `$D$`.
0047 
0048 ### Node impurity and information gain
0049 
0050 The *node impurity* is a measure of the homogeneity of the labels at the node. The current
0051 implementation provides two impurity measures for classification (Gini impurity and entropy) and one
0052 impurity measure for regression (variance).
0053 
0054 <table class="table">
0055   <thead>
0056     <tr><th>Impurity</th><th>Task</th><th>Formula</th><th>Description</th></tr>
0057   </thead>
0058   <tbody>
0059     <tr>
0060       <td>Gini impurity</td>
0061           <td>Classification</td>
0062           <td>$\sum_{i=1}^{C} f_i(1-f_i)$</td><td>$f_i$ is the frequency of label $i$ at a node and $C$ is the number of unique labels.</td>
0063     </tr>
0064     <tr>
0065       <td>Entropy</td>
0066           <td>Classification</td>
0067           <td>$\sum_{i=1}^{C} -f_ilog(f_i)$</td><td>$f_i$ is the frequency of label $i$ at a node and $C$ is the number of unique labels.</td>
0068     </tr>
0069     <tr>
0070       <td>Variance</td>
0071           <td>Regression</td>
0072      <td>$\frac{1}{N} \sum_{i=1}^{N} (y_i - \mu)^2$</td><td>$y_i$ is label for an instance,
0073           $N$ is the number of instances and $\mu$ is the mean given by $\frac{1}{N} \sum_{i=1}^N y_i$.</td>
0074     </tr>
0075   </tbody>
0076 </table>
0077 
0078 The *information gain* is the difference between the parent node impurity and the weighted sum of
0079 the two child node impurities. Assuming that a split $s$ partitions the dataset `$D$` of size `$N$`
0080 into two datasets `$D_{left}$` and `$D_{right}$` of sizes `$N_{left}$` and `$N_{right}$`,
0081 respectively, the information gain is:
0082 
0083 `$IG(D,s) = Impurity(D) - \frac{N_{left}}{N} Impurity(D_{left}) - \frac{N_{right}}{N} Impurity(D_{right})$`
0084 
0085 ### Split candidates
0086 
0087 **Continuous features**
0088 
0089 For small datasets in single-machine implementations, the split candidates for each continuous
0090 feature are typically the unique values for the feature. Some implementations sort the feature
0091 values and then use the ordered unique values as split candidates for faster tree calculations.
0092 
0093 Sorting feature values is expensive for large distributed datasets.
0094 This implementation computes an approximate set of split candidates by performing a quantile
0095 calculation over a sampled fraction of the data.
0096 The ordered splits create "bins" and the maximum number of such
0097 bins can be specified using the `maxBins` parameter.
0098 
0099 Note that the number of bins cannot be greater than the number of instances `$N$` (a rare scenario
0100 since the default `maxBins` value is 32). The tree algorithm automatically reduces the number of
0101 bins if the condition is not satisfied.
0102 
0103 **Categorical features**
0104 
0105 For a categorical feature with `$M$` possible values (categories), one could come up with
0106 `$2^{M-1}-1$` split candidates. For binary (0/1) classification and regression,
0107 we can reduce the number of split candidates to `$M-1$` by ordering the
0108 categorical feature values by the average label. (See Section 9.2.4 in
0109 [Elements of Statistical Machine Learning](https://web.stanford.edu/~hastie/ElemStatLearn/) for
0110 details.) For example, for a binary classification problem with one categorical feature with three
0111 categories A, B and C whose corresponding proportions of label 1 are 0.2, 0.6 and 0.4, the categorical
0112 features are ordered as A, C, B. The two split candidates are A \| C, B
0113 and A , C \| B where \| denotes the split.
0114 
0115 In multiclass classification, all `$2^{M-1}-1$` possible splits are used whenever possible.
0116 When `$2^{M-1}-1$` is greater than the `maxBins` parameter, we use a (heuristic) method
0117 similar to the method used for binary classification and regression.
0118 The `$M$` categorical feature values are ordered by impurity,
0119 and the resulting `$M-1$` split candidates are considered.
0120 
0121 ### Stopping rule
0122 
0123 The recursive tree construction is stopped at a node when one of the following conditions is met:
0124 
0125 1. The node depth is equal to the `maxDepth` training parameter.
0126 2. No split candidate leads to an information gain greater than `minInfoGain`.
0127 3. No split candidate produces child nodes which each have at least `minInstancesPerNode` training instances.
0128 
0129 ## Usage tips
0130 
0131 We include a few guidelines for using decision trees by discussing the various parameters.
0132 The parameters are listed below roughly in order of descending importance.  New users should mainly consider the "Problem specification parameters" section and the `maxDepth` parameter.
0133 
0134 ### Problem specification parameters
0135 
0136 These parameters describe the problem you want to solve and your dataset.
0137 They should be specified and do not require tuning.
0138 
0139 * **`algo`**: Type of decision tree, either `Classification` or `Regression`.
0140 
0141 * **`numClasses`**: Number of classes (for `Classification` only).
0142 
0143 * **`categoricalFeaturesInfo`**: Specifies which features are categorical and how many categorical values each of those features can take.  This is given as a map from feature indices to feature arity (number of categories).  Any features not in this map are treated as continuous.
0144   * For example, `Map(0 -> 2, 4 -> 10)` specifies that feature `0` is binary (taking values `0` or `1`) and that feature `4` has 10 categories (values `{0, 1, ..., 9}`).  Note that feature indices are 0-based: features `0` and `4` are the 1st and 5th elements of an instance's feature vector.
0145   * Note that you do not have to specify `categoricalFeaturesInfo`.  The algorithm will still run and may get reasonable results.  However, performance should be better if categorical features are properly designated.
0146 
0147 ### Stopping criteria
0148 
0149 These parameters determine when the tree stops building (adding new nodes).
0150 When tuning these parameters, be careful to validate on held-out test data to avoid overfitting.
0151 
0152 * **`maxDepth`**: Maximum depth of a tree.  Deeper trees are more expressive (potentially allowing higher accuracy), but they are also more costly to train and are more likely to overfit.
0153 
0154 * **`minInstancesPerNode`**: For a node to be split further, each of its children must receive at least this number of training instances.  This is commonly used with [RandomForest](api/scala/org/apache/spark/mllib/tree/RandomForest$.html) since those are often trained deeper than individual trees.
0155 
0156 * **`minInfoGain`**: For a node to be split further, the split must improve at least this much (in terms of information gain).
0157 
0158 ### Tunable parameters
0159 
0160 These parameters may be tuned.  Be careful to validate on held-out test data when tuning in order to avoid overfitting.
0161 
0162 * **`maxBins`**: Number of bins used when discretizing continuous features.
0163   * Increasing `maxBins` allows the algorithm to consider more split candidates and make fine-grained split decisions.  However, it also increases computation and communication.
0164   * Note that the `maxBins` parameter must be at least the maximum number of categories `$M$` for any categorical feature.
0165 
0166 * **`maxMemoryInMB`**: Amount of memory to be used for collecting sufficient statistics.
0167   * The default value is conservatively chosen to be 256 MiB to allow the decision algorithm to work in most scenarios.  Increasing `maxMemoryInMB` can lead to faster training (if the memory is available) by allowing fewer passes over the data.  However, there may be decreasing returns as `maxMemoryInMB` grows since the amount of communication on each iteration can be proportional to `maxMemoryInMB`.
0168   * *Implementation details*: For faster processing, the decision tree algorithm collects statistics about groups of nodes to split (rather than 1 node at a time).  The number of nodes which can be handled in one group is determined by the memory requirements (which vary per features).  The `maxMemoryInMB` parameter specifies the memory limit in terms of megabytes which each worker can use for these statistics.
0169 
0170 * **`subsamplingRate`**: Fraction of the training data used for learning the decision tree.  This parameter is most relevant for training ensembles of trees (using [`RandomForest`](api/scala/org/apache/spark/mllib/tree/RandomForest$.html) and [`GradientBoostedTrees`](api/scala/org/apache/spark/mllib/tree/GradientBoostedTrees.html)), where it can be useful to subsample the original data.  For training a single decision tree, this parameter is less useful since the number of training instances is generally not the main constraint.
0171 
0172 * **`impurity`**: Impurity measure (discussed above) used to choose between candidate splits.  This measure must match the `algo` parameter.
0173 
0174 ### Caching and checkpointing
0175 
0176 MLlib 1.2 adds several features for scaling up to larger (deeper) trees and tree ensembles.  When `maxDepth` is set to be large, it can be useful to turn on node ID caching and checkpointing.  These parameters are also useful for [RandomForest](api/scala/org/apache/spark/mllib/tree/RandomForest$.html) when `numTrees` is set to be large.
0177 
0178 * **`useNodeIdCache`**: If this is set to true, the algorithm will avoid passing the current model (tree or trees) to executors on each iteration.
0179   * This can be useful with deep trees (speeding up computation on workers) and for large Random Forests (reducing communication on each iteration).
0180   * *Implementation details*: By default, the algorithm communicates the current model to executors so that executors can match training instances with tree nodes.  When this setting is turned on, then the algorithm will instead cache this information.
0181 
0182 Node ID caching generates a sequence of RDDs (1 per iteration).  This long lineage can cause performance problems, but checkpointing intermediate RDDs can alleviate those problems.
0183 Note that checkpointing is only applicable when `useNodeIdCache` is set to true.
0184 
0185 * **`checkpointDir`**: Directory for checkpointing node ID cache RDDs.
0186 
0187 * **`checkpointInterval`**: Frequency for checkpointing node ID cache RDDs.  Setting this too low will cause extra overhead from writing to HDFS; setting this too high can cause problems if executors fail and the RDD needs to be recomputed.
0188 
0189 ## Scaling
0190 
0191 Computation scales approximately linearly in the number of training instances,
0192 in the number of features, and in the `maxBins` parameter.
0193 Communication scales approximately linearly in the number of features and in `maxBins`.
0194 
0195 The implemented algorithm reads both sparse and dense data. However, it is not optimized for sparse input.
0196 
0197 ## Examples
0198 
0199 ### Classification
0200 
0201 The example below demonstrates how to load a
0202 [LIBSVM data file](http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/),
0203 parse it as an RDD of `LabeledPoint` and then
0204 perform classification using a decision tree with Gini impurity as an impurity measure and a
0205 maximum tree depth of 5. The test error is calculated to measure the algorithm accuracy.
0206 
0207 <div class="codetabs">
0208 
0209 <div data-lang="scala" markdown="1">
0210 Refer to the [`DecisionTree` Scala docs](api/scala/org/apache/spark/mllib/tree/DecisionTree.html) and [`DecisionTreeModel` Scala docs](api/scala/org/apache/spark/mllib/tree/model/DecisionTreeModel.html) for details on the API.
0211 
0212 {% include_example scala/org/apache/spark/examples/mllib/DecisionTreeClassificationExample.scala %}
0213 </div>
0214 
0215 <div data-lang="java" markdown="1">
0216 Refer to the [`DecisionTree` Java docs](api/java/org/apache/spark/mllib/tree/DecisionTree.html) and [`DecisionTreeModel` Java docs](api/java/org/apache/spark/mllib/tree/model/DecisionTreeModel.html) for details on the API.
0217 
0218 {% include_example java/org/apache/spark/examples/mllib/JavaDecisionTreeClassificationExample.java %}
0219 </div>
0220 
0221 <div data-lang="python" markdown="1">
0222 Refer to the [`DecisionTree` Python docs](api/python/pyspark.mllib.html#pyspark.mllib.tree.DecisionTree) and [`DecisionTreeModel` Python docs](api/python/pyspark.mllib.html#pyspark.mllib.tree.DecisionTreeModel) for more details on the API.
0223 
0224 {% include_example python/mllib/decision_tree_classification_example.py %}
0225 </div>
0226 
0227 </div>
0228 
0229 ### Regression
0230 
0231 The example below demonstrates how to load a
0232 [LIBSVM data file](http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/),
0233 parse it as an RDD of `LabeledPoint` and then
0234 perform regression using a decision tree with variance as an impurity measure and a maximum tree
0235 depth of 5. The Mean Squared Error (MSE) is computed at the end to evaluate
0236 [goodness of fit](http://en.wikipedia.org/wiki/Goodness_of_fit).
0237 
0238 <div class="codetabs">
0239 
0240 <div data-lang="scala" markdown="1">
0241 Refer to the [`DecisionTree` Scala docs](api/scala/org/apache/spark/mllib/tree/DecisionTree.html) and [`DecisionTreeModel` Scala docs](api/scala/org/apache/spark/mllib/tree/model/DecisionTreeModel.html) for details on the API.
0242 
0243 {% include_example scala/org/apache/spark/examples/mllib/DecisionTreeRegressionExample.scala %}
0244 </div>
0245 
0246 <div data-lang="java" markdown="1">
0247 Refer to the [`DecisionTree` Java docs](api/java/org/apache/spark/mllib/tree/DecisionTree.html) and [`DecisionTreeModel` Java docs](api/java/org/apache/spark/mllib/tree/model/DecisionTreeModel.html) for details on the API.
0248 
0249 {% include_example java/org/apache/spark/examples/mllib/JavaDecisionTreeRegressionExample.java %}
0250 </div>
0251 
0252 <div data-lang="python" markdown="1">
0253 Refer to the [`DecisionTree` Python docs](api/python/pyspark.mllib.html#pyspark.mllib.tree.DecisionTree) and [`DecisionTreeModel` Python docs](api/python/pyspark.mllib.html#pyspark.mllib.tree.DecisionTreeModel) for more details on the API.
0254 
0255 {% include_example python/mllib/decision_tree_regression_example.py %}
0256 </div>
0257 
0258 </div>