Skip to content

Commit d939a92

Browse files
committed
Updated DecisionTree documentation. Added Java, Python examples.
1 parent d7e80c2 commit d939a92

1 file changed

Lines changed: 207 additions & 55 deletions

File tree

docs/mllib-decision-tree.md

Lines changed: 207 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,26 @@ displayTitle: <a href="mllib-guide.html">MLlib</a> - Decision Tree
77
* Table of contents
88
{:toc}
99

10-
Decision trees and their ensembles are popular methods for the machine learning tasks of
10+
[Decision trees](http://en.wikipedia.org/wiki/Decision_tree_learning)
11+
and their ensembles are popular methods for the machine learning tasks of
1112
classification and regression. Decision trees are widely used since they are easy to interpret,
12-
handle categorical variables, extend to the multiclass classification setting, do not require
13+
handle categorical features, extend to the multiclass classification setting, do not require
1314
feature scaling and are able to capture nonlinearities and feature interactions. Tree ensemble
14-
algorithms such as decision forest and boosting are among the top performers for classification and
15+
algorithms such as decision forests and boosting are among the top performers for classification and
1516
regression tasks.
1617

18+
MLlib supports decision trees for binary and multiclass classification and for regression,
19+
using both continuous and categorical features. The implementation partitions data by rows,
20+
allowing distributed training with millions of instances.
21+
1722
## Basic algorithm
1823

1924
The decision tree is a greedy algorithm that performs a recursive binary partitioning of the feature
20-
space by choosing a single element from the *best split set* where each element of the set maximizes
21-
the information gain at a tree node. In other words, the split chosen at each tree node is chosen
22-
from the set `$\underset{s}{\operatorname{argmax}} IG(D,s)$` where `$IG(D,s)$` is the information
23-
gain when a split `$s$` is applied to a dataset `$D$`.
25+
space. The tree predicts the same label for each bottommost (leaf) partition.
26+
Each partition is chosen greedily by selecting the *best split* from a set of possible splits,
27+
in order to maximize the information gain at a tree node. In other words, the split chosen at each
28+
tree node is chosen from the set `$\underset{s}{\operatorname{argmax}} IG(D,s)$` where `$IG(D,s)$`
29+
is the information gain when a split `$s$` is applied to a dataset `$D$`.
2430

2531
### Node impurity and information gain
2632

@@ -52,58 +58,73 @@ impurity measure for regression (variance).
5258
</tbody>
5359
</table>
5460

55-
The *information gain* is the difference in the parent node impurity and the weighted sum of the two
56-
child node impurities. Assuming that a split $s$ partitions the dataset `$D$` of size `$N$` into two
57-
datasets `$D_{left}$` and `$D_{right}$` of sizes `$N_{left}$` and `$N_{right}$`, respectively:
61+
The *information gain* is the difference between the parent node impurity and the weighted sum of
62+
the two child node impurities. Assuming that a split $s$ partitions the dataset `$D$` of size `$N$`
63+
into two datasets `$D_{left}$` and `$D_{right}$` of sizes `$N_{left}$` and `$N_{right}$`,
64+
respectively, the information gain is:
5865

5966
`$IG(D,s) = Impurity(D) - \frac{N_{left}}{N} Impurity(D_{left}) - \frac{N_{right}}{N} Impurity(D_{right})$`
6067

6168
### Split candidates
6269

6370
**Continuous features**
6471

65-
For small datasets in single machine implementations, the split candidates for each continuous
72+
For small datasets in single-machine implementations, the split candidates for each continuous
6673
feature are typically the unique values for the feature. Some implementations sort the feature
6774
values and then use the ordered unique values as split candidates for faster tree calculations.
6875

69-
Finding ordered unique feature values is computationally intensive for large distributed
70-
datasets. One can get an approximate set of split candidates by performing a quantile calculation
71-
over a sampled fraction of the data. The ordered splits create "bins" and the maximum number of such
72-
bins can be specified using the `maxBins` parameters.
76+
Sorting feature values is expensive for large distributed datasets.
77+
This implementation computes an approximate set of split candidates by performing a quantile
78+
calculation over a sampled fraction of the data.
79+
The ordered splits create "bins" and the maximum number of such
80+
bins can be specified using the `maxBins` parameter.
7381

7482
Note that the number of bins cannot be greater than the number of instances `$N$` (a rare scenario
7583
since the default `maxBins` value is 100). The tree algorithm automatically reduces the number of
7684
bins if the condition is not satisfied.
7785

7886
**Categorical features**
7987

80-
For `$M$` categorical feature values, one could come up with `$2^(M-1)-1$` split candidates. For
81-
binary classification, we can reduce the number of split candidates to `$M-1$` by ordering the
88+
For a categorical feature with `$M$` possible values (categories), one could come up with
89+
`$2^{M-1}-1$` split candidates. For binary classification and regression,
90+
we can reduce the number of split candidates to `$M-1$` by ordering the
8291
categorical feature values by the proportion of labels falling in one of the two classes (see
8392
Section 9.2.4 in
8493
[Elements of Statistical Machine Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/) for
8594
details). For example, for a binary classification problem with one categorical feature with three
86-
categories A, B and C with corresponding proportion of label 1 as 0.2, 0.6 and 0.4, the categorical
87-
features are ordered as A followed by C followed B or A, C, B. The two split candidates are A \| C, B
95+
categories A, B and C whose corresponding proportions of label 1 are 0.2, 0.6 and 0.4, the categorical
96+
features are ordered as A, C, B. The two split candidates are A \| C, B
8897
and A , C \| B where \| denotes the split. A similar heuristic is used for multiclass classification
89-
when `$2^(M-1)-1$` is greater than the number of bins -- the impurity for each categorical feature value
90-
is used for ordering.
98+
when `$2^{M-1}-1$` is greater than the `maxBins` parameter: the impurity for each categorical feature value
99+
is used for ordering. In multiclass classification, all `$2^{M-1}-1$` possible splits are used
100+
whenever possible.
101+
102+
Note that the `maxBins` parameter must be at least `$M_{max}$`, the maximum number of categories for
103+
any categorical feature.
91104

92105
### Stopping rule
93106

94107
The recursive tree construction is stopped at a node when one of the two conditions is met:
95108

96-
1. The node depth is equal to the `maxDepth` training parameter
109+
1. The node depth is equal to the `maxDepth` training parameter.
97110
2. No split candidate leads to an information gain at the node.
98111

99112
### Max memory requirements
100113

101-
For faster processing, the decision tree algorithm performs simultaneous histogram computations for all nodes at each level of the tree. This could lead to high memory requirements at deeper levels of the tree leading to memory overflow errors. To alleviate this problem, a 'maxMemoryInMB' training parameter is provided which specifies the maximum amount of memory at the workers (twice as much at the master) to be allocated to the histogram computation. The default value is conservatively chosen to be 128 MB to allow the decision algorithm to work in most scenarios. Once the memory requirements for a level-wise computation crosses the `maxMemoryInMB` threshold, the node training tasks at each subsequent level is split into smaller tasks.
114+
For faster processing, the decision tree algorithm performs simultaneous histogram computations for
115+
all nodes at each level of the tree. This could lead to high memory requirements at deeper levels
116+
of the tree, leading to memory overflow errors. To alleviate this problem, a `maxMemoryInMB`
117+
training parameter specifies the maximum amount of memory at the workers (twice as much at the
118+
master) to be allocated to the histogram computation. The default value is conservatively chosen to
119+
be 128 MB to allow the decision algorithm to work in most scenarios. Once the memory requirements
120+
for a level-wise computation cross the `maxMemoryInMB` threshold, the node training tasks at each
121+
subsequent level are split into smaller tasks.
102122

103123
### Practical limitations
104124

105125
1. The implemented algorithm reads both sparse and dense data. However, it is not optimized for sparse input.
106-
2. Python is not supported in this release.
126+
2. Computation scales approximately linearly in the number of training instances,
127+
in the number of features, and in the `maxBins` parameter.
107128

108129
## Examples
109130

@@ -114,35 +135,101 @@ perform classification using a decision tree using Gini impurity as an impurity
114135
maximum tree depth of 5. The training error is calculated to measure the algorithm accuracy.
115136

116137
<div class="codetabs">
138+
117139
<div data-lang="scala">
118140
{% highlight scala %}
119-
import org.apache.spark.SparkContext
120141
import org.apache.spark.mllib.tree.DecisionTree
121-
import org.apache.spark.mllib.regression.LabeledPoint
122-
import org.apache.spark.mllib.linalg.Vectors
123-
import org.apache.spark.mllib.tree.configuration.Algo._
124-
import org.apache.spark.mllib.tree.impurity.Gini
142+
import org.apache.spark.mllib.util.MLUtils
125143

126144
// Load and parse the data file
127-
val data = sc.textFile("data/mllib/sample_tree_data.csv")
128-
val parsedData = data.map { line =>
129-
val parts = line.split(',').map(_.toDouble)
130-
LabeledPoint(parts(0), Vectors.dense(parts.tail))
131-
}
145+
val data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
132146

133-
// Run training algorithm to build the model
147+
// Train a DecisionTree model.
148+
// Empty categoricalFeaturesInfo indicates all features are continuous.
149+
val numClasses = 2
150+
val categoricalFeaturesInfo = Map[Int, Int]()
151+
val impurity = "gini"
134152
val maxDepth = 5
135-
val model = DecisionTree.train(parsedData, Classification, Gini, maxDepth)
153+
val maxBins = 100
154+
155+
val model = DecisionTree.trainClassifier(data, numClasses, categoricalFeaturesInfo, impurity,
156+
maxDepth, maxBins)
136157

137-
// Evaluate model on training examples and compute training error
138-
val labelAndPreds = parsedData.map { point =>
158+
// Evaluate model on training instances and compute training error
159+
val labelAndPreds = data.map { point =>
139160
val prediction = model.predict(point.features)
140161
(point.label, prediction)
141162
}
142-
val trainErr = labelAndPreds.filter(r => r._1 != r._2).count.toDouble / parsedData.count
163+
val trainErr = labelAndPreds.filter(r => r._1 != r._2).count.toDouble / data.count
143164
println("Training Error = " + trainErr)
144165
{% endhighlight %}
145166
</div>
167+
168+
<div data-lang="java">
169+
{% highlight java %}
170+
import org.apache.spark.api.java.JavaPairRDD;
171+
import org.apache.spark.api.java.JavaRDD;
172+
import org.apache.spark.api.java.function.Function;
173+
import org.apache.spark.api.java.function.PairFunction;
174+
import org.apache.spark.mllib.regression.LabeledPoint;
175+
import org.apache.spark.mllib.tree.DecisionTree;
176+
import org.apache.spark.mllib.tree.model.DecisionTreeModel;
177+
import scala.Tuple2;
178+
179+
JavaRDD<LabeledPoint> data = ... // data set
180+
181+
// Train a DecisionTree model.
182+
// Empty categoricalFeaturesInfo indicates all features are continuous.
183+
Integer numClasses = ... // number of classes
184+
HashMap<Integer, Integer> categoricalFeaturesInfo = new HashMap<Integer, Integer>();
185+
String impurity = "gini";
186+
Integer maxDepth = 5;
187+
Integer maxBins = 100;
188+
189+
final DecisionTreeModel model = DecisionTree.trainClassifier(data.rdd(), numClasses,
190+
categoricalFeaturesInfo, impurity, maxDepth, maxBins);
191+
192+
// Evaluate model on training instances and compute training error
193+
JavaPairRDD<Double, Double> predictionAndLabel =
194+
data.mapToPair(new PairFunction<LabeledPoint, Double, Double>() {
195+
@Override public Tuple2<Double, Double> call(LabeledPoint p) {
196+
return new Tuple2<Double, Double>(model.predict(p.features()), p.label());
197+
}
198+
});
199+
Double trainErr = 1.0 * predictionAndLabel.filter(new Function<Tuple2<Double, Double>, Boolean>() {
200+
@Override public Boolean call(Tuple2<Double, Double> pl) {
201+
return pl._1() != pl._2();
202+
}
203+
}).count() / data.count();
204+
{% endhighlight %}
205+
</div>
206+
207+
<div data-lang="python">
208+
{% highlight python %}
209+
from pyspark.mllib.regression import LabeledPoint
210+
from pyspark.mllib.tree import DecisionTree
211+
from pyspark.mllib.util import MLUtils
212+
213+
# an RDD of LabeledPoint
214+
data = MLUtils.loadLibSVMFile(sc, 'data/mllib/sample_libsvm_data.txt')
215+
216+
# Train a DecisionTree model.
217+
# Empty categoricalFeaturesInfo indicates all features are continuous.
218+
model = DecisionTree.trainClassifier(data, numClasses=2, categoricalFeaturesInfo={},
219+
impurity='gini', maxDepth=5, maxBins=100)
220+
221+
# Evaluate model on training instances and compute training error
222+
predictions = model.predict(data.map(lambda x: x.features))
223+
labelsAndPredictions = data.map(lambda lp: lp.label).zip(predictions)
224+
trainErr = labelsAndPredictions.filter(lambda (v, p): v != p).count() / float(data.count())
225+
print('Training Error = ' + str(trainErr))
226+
{% endhighlight %}
227+
228+
Note: When making predictions for a dataset, it is more efficient to do batch prediction rather
229+
than separately calling `predict` on each data point. This is because the Python code makes calls
230+
to an underlying `DecisionTree` model in Scala.
231+
</div>
232+
146233
</div>
147234

148235
### Regression
@@ -153,33 +240,98 @@ depth of 5. The Mean Squared Error (MSE) is computed at the end to evaluate
153240
[goodness of fit](http://en.wikipedia.org/wiki/Goodness_of_fit).
154241

155242
<div class="codetabs">
243+
156244
<div data-lang="scala">
157245
{% highlight scala %}
158-
import org.apache.spark.SparkContext
159246
import org.apache.spark.mllib.tree.DecisionTree
160-
import org.apache.spark.mllib.regression.LabeledPoint
161-
import org.apache.spark.mllib.linalg.Vectors
162-
import org.apache.spark.mllib.tree.configuration.Algo._
163-
import org.apache.spark.mllib.tree.impurity.Variance
247+
import org.apache.spark.mllib.util.MLUtils
164248

165249
// Load and parse the data file
166-
val data = sc.textFile("data/mllib/sample_tree_data.csv")
167-
val parsedData = data.map { line =>
168-
val parts = line.split(',').map(_.toDouble)
169-
LabeledPoint(parts(0), Vectors.dense(parts.tail))
170-
}
250+
val data = MLUtils.loadLibSVMFile(sc, "data/mllib/sample_libsvm_data.txt")
171251

172-
// Run training algorithm to build the model
252+
// Train a DecisionTree model.
253+
// Empty categoricalFeaturesInfo indicates all features are continuous.
254+
val categoricalFeaturesInfo = Map[Int, Int]()
255+
val impurity = "variance"
173256
val maxDepth = 5
174-
val model = DecisionTree.train(parsedData, Regression, Variance, maxDepth)
257+
val maxBins = 100
175258

176-
// Evaluate model on training examples and compute training error
177-
val valuesAndPreds = parsedData.map { point =>
259+
val model = DecisionTree.trainRegressor(data, categoricalFeaturesInfo, impurity,
260+
maxDepth, maxBins)
261+
262+
// Evaluate model on training instances and compute training error
263+
val labelsAndPredictions = data.map { point =>
178264
val prediction = model.predict(point.features)
179265
(point.label, prediction)
180266
}
181-
val MSE = valuesAndPreds.map{ case(v, p) => math.pow((v - p), 2)}.mean()
182-
println("training Mean Squared Error = " + MSE)
267+
val trainMSE = labelsAndPredictions.map{ case(v, p) => math.pow((v - p), 2)}.mean()
268+
println("Training Mean Squared Error = " + trainMSE)
269+
{% endhighlight %}
270+
</div>
271+
272+
<div data-lang="java">
273+
{% highlight java %}
274+
import org.apache.spark.api.java.JavaPairRDD;
275+
import org.apache.spark.api.java.JavaRDD;
276+
import org.apache.spark.api.java.function.Function;
277+
import org.apache.spark.api.java.function.PairFunction;
278+
import org.apache.spark.mllib.regression.LabeledPoint;
279+
import org.apache.spark.mllib.tree.DecisionTree;
280+
import org.apache.spark.mllib.tree.model.DecisionTreeModel;
281+
import scala.Tuple2;
282+
283+
JavaRDD<LabeledPoint> data = ... // data set
284+
285+
// Train a DecisionTree model.
286+
// Empty categoricalFeaturesInfo indicates all features are continuous.
287+
HashMap<Integer, Integer> categoricalFeaturesInfo = new HashMap<Integer, Integer>();
288+
String impurity = "variance";
289+
Integer maxDepth = 5;
290+
Integer maxBins = 100;
291+
292+
final DecisionTreeModel model = DecisionTree.trainRegressor(data.rdd(),
293+
categoricalFeaturesInfo, impurity, maxDepth, maxBins);
294+
295+
// Evaluate model on training instances and compute training error
296+
JavaPairRDD<Double, Double> predictionAndLabel =
297+
data.mapToPair(new PairFunction<LabeledPoint, Double, Double>() {
298+
@Override public Tuple2<Double, Double> call(LabeledPoint p) {
299+
return new Tuple2<Double, Double>(model.predict(p.features()), p.label());
300+
}
301+
});
302+
Double trainMSE = predictionAndLabel.map(new Function<Tuple2<Double, Double>, Double>() {
303+
@Override public Double call(Tuple2<Double, Double> pl) {
304+
Double diff = pl._1() - pl._2();
305+
return diff * diff;
306+
}
307+
}).sum() / data.count();
308+
{% endhighlight %}
309+
</div>
310+
311+
<div data-lang="python">
312+
{% highlight python %}
313+
from pyspark.mllib.regression import LabeledPoint
314+
from pyspark.mllib.tree import DecisionTree
315+
from pyspark.mllib.util import MLUtils
316+
317+
# an RDD of LabeledPoint
318+
data = MLUtils.loadLibSVMFile(sc, 'data/mllib/sample_libsvm_data.txt')
319+
320+
# Train a DecisionTree model.
321+
# Empty categoricalFeaturesInfo indicates all features are continuous.
322+
model = DecisionTree.trainRegressor(data, categoricalFeaturesInfo={},
323+
impurity='variance', maxDepth=5, maxBins=100)
324+
325+
# Evaluate model on training instances and compute training error
326+
predictions = model.predict(data.map(lambda x: x.features))
327+
labelsAndPredictions = data.map(lambda lp: lp.label).zip(predictions)
328+
trainMSE = labelsAndPredictions.map(lambda (v, p): (v - p) * (v - p)).sum() / float(data.count())
329+
print('Training Mean Squared Error = ' + str(trainMSE))
183330
{% endhighlight %}
331+
332+
Note: When making predictions for a dataset, it is more efficient to do batch prediction rather
333+
than separately calling `predict` on each data point. This is because the Python code makes calls
334+
to an underlying `DecisionTree` model in Scala.
184335
</div>
336+
185337
</div>

0 commit comments

Comments
 (0)