Skip to content

Commit 64f8995

Browse files
committed
move decision tree guide to a separate file
1 parent 9fca001 commit 64f8995

2 files changed

Lines changed: 129 additions & 135 deletions

File tree

docs/mllib-classification-regression.md

Lines changed: 0 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -240,67 +240,6 @@ Here `$\mathop{sign}(\wv)$` is the vector consisting of the signs (`$\pm1$`) of
240240
of `$\wv$`.
241241
Also, note that `$A_{i:} \in \R^d$` is a row-vector, but the gradient is a column vector.
242242

243-
## Decision Tree Classification and Regression
244-
245-
Decision trees and their ensembles are popular methods for the machine learning tasks of classification and regression. Decision trees are widely used since they are easy to interpret, handle categorical variables, extend to the multi-class classification setting, do not require feature scaling and are able to capture non-linearities and feature interactions. Tree ensemble algorithms such as decision forest and boosting are among the top performers for classification and regression tasks.
246-
247-
### Basic Algorithm
248-
249-
The decision tree is a greedy algorithm that performs a recursive binary partitioning of the feature space by choosing a single element from the *best split set* where each element of the set maximimizes the information gain at a tree node. In other words, the split chosen at each tree node is chosen from the set `$\underset{s}{\operatorname{argmax}} IG(D,s)$` where `$IG(D,s)$` is the information gain when a split `$s$` is applied to a dataset `$D$`.
250-
251-
#### Node Impurity and Information Gain
252-
253-
The *node impurity* is a measure of the homogeneity of the labels at the node. The current implementation provides two impurity measures for classification (Gini index and entropy) and one impurity measure for regression (variance).
254-
255-
<table class="table">
256-
<thead>
257-
<tr><th>Impurity</th><th>Task</th><th>Formula</th><th>Description</th></tr>
258-
</thead>
259-
<tbody>
260-
<tr>
261-
<td>Gini index</td><td>Classification</td><td>$\sum_{i=1}^{M} f_i(1-f_i)$</td><td>$f_i$ is the frequency of label $i$ at a node and $M$ is the number of unique labels.</td>
262-
</tr>
263-
<tr>
264-
<td>Entropy</td><td>Classification</td><td>$\sum_{i=1}^{M} -f_ilog(f_i)$</td><td>$f_i$ is the frequency of label $i$ at a node and $M$ is the number of unique labels.</td>
265-
</tr>
266-
<tr>
267-
<td>Variance</td><td>Classification</td><td>$\frac{1}{n} \sum_{i=1}^{N} (x_i - \mu)^2$</td><td>$y_i$ is label for an instance, $N$ is the number of instances and $\mu$ is the mean given by $\frac{1}{N} \sum_{i=1}^n x_i$.</td>
268-
</tr>
269-
</tbody>
270-
</table>
271-
272-
The *information gain* is the difference in the parent node impurity and the weighted sum of the two child node impurities. Assuming that a split $s$ partitions the dataset `$D$` of size `$N$` into two datasets `$D_{left}$` and `$D_{right}$` of sizes `$N_{left}$` and `$N_{right}$`, respectively:
273-
274-
`$IG(D,s) = Impurity(D) - \frac{N_{left}}{N} Impurity(D_{left}) - \frac{N_{right}}{N} Impurity(D_{right})$`
275-
276-
#### Split Candidates
277-
278-
**Continuous Features**
279-
280-
For small datasets in single machine implementations, the split candidates for each continuous feature are typically the unique values for the feature. Some implementations sort the feature values and then use the ordered unique values as split candidates for faster tree calculations.
281-
282-
Finding ordered unique feature values is computationally intensive for large distributed datasets. One can get an approximate set of split candidates by performing a quantile calculation over a sampled fraction of the data. The ordered splits create "bins" and the maximum number of such bins can be specified using the `maxBins` parameters.
283-
284-
Note that the number of bins cannot be greater than the number of instances `$N$` (a rare scenario since the default `maxBins` value is 100). The tree algorithm automatically reduces the number of bins if the condition is not satisfied.
285-
286-
**Categorical Features**
287-
288-
For `$M$` categorical features, one could come up with `$2^M-1$` split candidates. However, for binary classification, the number of split candidates can be reduced to `$M-1$` by ordering the categorical feature values by the proportion of labels falling in one of the two classes (see Section 9.2.4 in [Elements of Statistical Machine Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/) for details). For example, for a binary classification problem with one categorical feature with three categories A, B and C with corresponding proportion of label 1 as 0.2, 0.6 and 0.4, the categorical features are orded as A followed by C followed B or A, B, C. The two split candidates are A \| C, B and A , B \| C where \| denotes the split.
289-
290-
#### Stopping Rule
291-
292-
The recursive tree construction is stopped at a node when one of the two conditions is met:
293-
294-
1. The node depth is equal to the `maxDepth` training paramemter
295-
2. No split candidate leads to an information gain at the node.
296-
297-
### Practical Limitations
298-
299-
The tree implementation stores an Array[Double] of size *O(#features \* #splits \* 2^maxDepth)* in memory for aggregating histograms over partitions. The current implementation might not scale to very deep trees since the memory requirement grows exponentially with tree depth.
300-
301-
Please drop us a line if you encounter any issues. We are planning to solve this problem in the near future and real-world examples will be great.
302-
303-
304243
## Implementation in MLlib
305244

306245
#### Linear Methods
@@ -331,13 +270,6 @@ gradient descent primitive in MLlib, see the
331270

332271
* [GradientDescent](api/mllib/index.html#org.apache.spark.mllib.optimization.GradientDescent)
333272

334-
#### Tree-based Methods
335-
336-
The decision tree algorithm supports binary classification and regression:
337-
338-
* [DecisionTee](api/mllib/index.html#org.apache.spark.mllib.tree.DecisionTree)
339-
340-
341273
# Usage in Scala
342274

343275
Following code snippets can be executed in `spark-shell`.
@@ -431,73 +363,6 @@ println("training Mean Squared Error = " + MSE)
431363
Similarly you can use RidgeRegressionWithSGD and LassoWithSGD and compare training
432364
[Mean Squared Errors](http://en.wikipedia.org/wiki/Mean_squared_error).
433365

434-
## Decision Tree
435-
436-
#### Classification
437-
438-
The example below demonstrates how to load a CSV file, parse it as an RDD of LabeledPoint and then perform classification using a decision tree using Gini index as an impurity measure and a maximum tree depth of 5. The training error is calculated to measure the algorithm accuracy.
439-
440-
{% highlight scala %}
441-
import org.apache.spark.SparkContext
442-
import org.apache.spark.mllib.tree.DecisionTree
443-
import org.apache.spark.mllib.regression.LabeledPoint
444-
import org.apache.spark.mllib.linalg.Vectors
445-
import org.apache.spark.mllib.tree.configuration.Algo._
446-
import org.apache.spark.mllib.tree.impurity.Gini
447-
448-
// Load and parse the data file
449-
val data = sc.textFile("mllib/data/sample_tree_data.csv")
450-
val parsedData = data.map { line =>
451-
val parts = line.split(',').map(_.toDouble)
452-
LabeledPoint(parts(0), Vectors.dense(parts.tail))
453-
}
454-
455-
// Run training algorithm to build the model
456-
val maxDepth = 5
457-
val model = DecisionTree.train(parsedData, Classification, Gini, maxDepth)
458-
459-
// Evaluate model on training examples and compute training error
460-
val labelAndPreds = parsedData.map { point =>
461-
val prediction = model.predict(point.features)
462-
(point.label, prediction)
463-
}
464-
val trainErr = labelAndPreds.filter(r => r._1 != r._2).count.toDouble / parsedData.count
465-
println("Training Error = " + trainErr)
466-
{% endhighlight %}
467-
468-
#### Regression
469-
470-
The example below demonstrates how to load a CSV file, parse it as an RDD of LabeledPoint and then perform regression using a decision tree using variance as an impurity measure and a maximum tree depth of 5. The Mean Squared Error is computed at the end to evaluate
471-
[goodness of fit](http://en.wikipedia.org/wiki/Goodness_of_fit).
472-
473-
{% highlight scala %}
474-
import org.apache.spark.SparkContext
475-
import org.apache.spark.mllib.tree.DecisionTree
476-
import org.apache.spark.mllib.regression.LabeledPoint
477-
import org.apache.spark.mllib.linalg.Vectors
478-
import org.apache.spark.mllib.tree.configuration.Algo._
479-
import org.apache.spark.mllib.tree.impurity.Variance
480-
481-
// Load and parse the data file
482-
val data = sc.textFile("mllib/data/sample_tree_data.csv")
483-
val parsedData = data.map { line =>
484-
val parts = line.split(',').map(_.toDouble)
485-
LabeledPoint(parts(0), Vectors.dense(parts.tail))
486-
}
487-
488-
// Run training algorithm to build the model
489-
val maxDepth = 5
490-
val model = DecisionTree.train(parsedData, Regression, Variance, maxDepth)
491-
492-
// Evaluate model on training examples and compute training error
493-
val valuesAndPreds = parsedData.map { point =>
494-
val prediction = model.predict(point.features)
495-
(point.label, prediction)
496-
}
497-
val MSE = valuesAndPreds.map{ case(v, p) => math.pow((v - p), 2)}.reduce(_ + _)/valuesAndPreds.count
498-
println("training Mean Squared Error = " + MSE)
499-
{% endhighlight %}
500-
501366

502367
# Usage in Java
503368

docs/mllib-decision-tree.md

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
---
2+
layout: global
3+
title: MLlib - Decision Tree
4+
---
5+
6+
Decision trees and their ensembles are popular methods for the machine learning tasks of classification and regression. Decision trees are widely used since they are easy to interpret, handle categorical variables, extend to the multi-class classification setting, do not require feature scaling and are able to capture non-linearities and feature interactions. Tree ensemble algorithms such as decision forest and boosting are among the top performers for classification and regression tasks.
7+
8+
## Basic Algorithm
9+
10+
The decision tree is a greedy algorithm that performs a recursive binary partitioning of the feature space by choosing a single element from the *best split set* where each element of the set maximimizes the information gain at a tree node. In other words, the split chosen at each tree node is chosen from the set `$\underset{s}{\operatorname{argmax}} IG(D,s)$` where `$IG(D,s)$` is the information gain when a split `$s$` is applied to a dataset `$D$`.
11+
12+
### Node Impurity and Information Gain
13+
14+
The *node impurity* is a measure of the homogeneity of the labels at the node. The current implementation provides two impurity measures for classification (Gini index and entropy) and one impurity measure for regression (variance).
15+
16+
<table class="table">
17+
<thead>
18+
<tr><th>Impurity</th><th>Task</th><th>Formula</th><th>Description</th></tr>
19+
</thead>
20+
<tbody>
21+
<tr>
22+
<td>Gini index</td><td>Classification</td><td>$\sum_{i=1}^{M} f_i(1-f_i)$</td><td>$f_i$ is the frequency of label $i$ at a node and $M$ is the number of unique labels.</td>
23+
</tr>
24+
<tr>
25+
<td>Entropy</td><td>Classification</td><td>$\sum_{i=1}^{M} -f_ilog(f_i)$</td><td>$f_i$ is the frequency of label $i$ at a node and $M$ is the number of unique labels.</td>
26+
</tr>
27+
<tr>
28+
<td>Variance</td><td>Classification</td><td>$\frac{1}{n} \sum_{i=1}^{N} (x_i - \mu)^2$</td><td>$y_i$ is label for an instance, $N$ is the number of instances and $\mu$ is the mean given by $\frac{1}{N} \sum_{i=1}^n x_i$.</td>
29+
</tr>
30+
</tbody>
31+
</table>
32+
33+
The *information gain* is the difference in the parent node impurity and the weighted sum of the two child node impurities. Assuming that a split $s$ partitions the dataset `$D$` of size `$N$` into two datasets `$D_{left}$` and `$D_{right}$` of sizes `$N_{left}$` and `$N_{right}$`, respectively:
34+
35+
`$IG(D,s) = Impurity(D) - \frac{N_{left}}{N} Impurity(D_{left}) - \frac{N_{right}}{N} Impurity(D_{right})$`
36+
37+
### Split Candidates
38+
39+
**Continuous Features**
40+
41+
For small datasets in single machine implementations, the split candidates for each continuous feature are typically the unique values for the feature. Some implementations sort the feature values and then use the ordered unique values as split candidates for faster tree calculations.
42+
43+
Finding ordered unique feature values is computationally intensive for large distributed datasets. One can get an approximate set of split candidates by performing a quantile calculation over a sampled fraction of the data. The ordered splits create "bins" and the maximum number of such bins can be specified using the `maxBins` parameters.
44+
45+
Note that the number of bins cannot be greater than the number of instances `$N$` (a rare scenario since the default `maxBins` value is 100). The tree algorithm automatically reduces the number of bins if the condition is not satisfied.
46+
47+
**Categorical Features**
48+
49+
For `$M$` categorical features, one could come up with `$2^M-1$` split candidates. However, for binary classification, the number of split candidates can be reduced to `$M-1$` by ordering the categorical feature values by the proportion of labels falling in one of the two classes (see Section 9.2.4 in [Elements of Statistical Machine Learning](http://statweb.stanford.edu/~tibs/ElemStatLearn/) for details). For example, for a binary classification problem with one categorical feature with three categories A, B and C with corresponding proportion of label 1 as 0.2, 0.6 and 0.4, the categorical features are orded as A followed by C followed B or A, B, C. The two split candidates are A \| C, B and A , B \| C where \| denotes the split.
50+
51+
### Stopping Rule
52+
53+
The recursive tree construction is stopped at a node when one of the two conditions is met:
54+
55+
1. The node depth is equal to the `maxDepth` training paramemter
56+
2. No split candidate leads to an information gain at the node.
57+
58+
### Practical Limitations
59+
60+
The tree implementation stores an Array[Double] of size *O(#features \* #splits \* 2^maxDepth)* in memory for aggregating histograms over partitions. The current implementation might not scale to very deep trees since the memory requirement grows exponentially with tree depth.
61+
62+
Please drop us a line if you encounter any issues. We are planning to solve this problem in the near future and real-world examples will be great.
63+
64+
## Examples
65+
66+
### Classification
67+
68+
The example below demonstrates how to load a CSV file, parse it as an RDD of LabeledPoint and then perform classification using a decision tree using Gini index as an impurity measure and a maximum tree depth of 5. The training error is calculated to measure the algorithm accuracy.
69+
70+
{% highlight scala %}
71+
import org.apache.spark.SparkContext
72+
import org.apache.spark.mllib.tree.DecisionTree
73+
import org.apache.spark.mllib.regression.LabeledPoint
74+
import org.apache.spark.mllib.linalg.Vectors
75+
import org.apache.spark.mllib.tree.configuration.Algo._
76+
import org.apache.spark.mllib.tree.impurity.Gini
77+
78+
// Load and parse the data file
79+
val data = sc.textFile("mllib/data/sample_tree_data.csv")
80+
val parsedData = data.map { line =>
81+
val parts = line.split(',').map(_.toDouble)
82+
LabeledPoint(parts(0), Vectors.dense(parts.tail))
83+
}
84+
85+
// Run training algorithm to build the model
86+
val maxDepth = 5
87+
val model = DecisionTree.train(parsedData, Classification, Gini, maxDepth)
88+
89+
// Evaluate model on training examples and compute training error
90+
val labelAndPreds = parsedData.map { point =>
91+
val prediction = model.predict(point.features)
92+
(point.label, prediction)
93+
}
94+
val trainErr = labelAndPreds.filter(r => r._1 != r._2).count.toDouble / parsedData.count
95+
println("Training Error = " + trainErr)
96+
{% endhighlight %}
97+
98+
### Regression
99+
100+
The example below demonstrates how to load a CSV file, parse it as an RDD of LabeledPoint and then perform regression using a decision tree using variance as an impurity measure and a maximum tree depth of 5. The Mean Squared Error is computed at the end to evaluate
101+
[goodness of fit](http://en.wikipedia.org/wiki/Goodness_of_fit).
102+
103+
{% highlight scala %}
104+
import org.apache.spark.SparkContext
105+
import org.apache.spark.mllib.tree.DecisionTree
106+
import org.apache.spark.mllib.regression.LabeledPoint
107+
import org.apache.spark.mllib.linalg.Vectors
108+
import org.apache.spark.mllib.tree.configuration.Algo._
109+
import org.apache.spark.mllib.tree.impurity.Variance
110+
111+
// Load and parse the data file
112+
val data = sc.textFile("mllib/data/sample_tree_data.csv")
113+
val parsedData = data.map { line =>
114+
val parts = line.split(',').map(_.toDouble)
115+
LabeledPoint(parts(0), Vectors.dense(parts.tail))
116+
}
117+
118+
// Run training algorithm to build the model
119+
val maxDepth = 5
120+
val model = DecisionTree.train(parsedData, Regression, Variance, maxDepth)
121+
122+
// Evaluate model on training examples and compute training error
123+
val valuesAndPreds = parsedData.map { point =>
124+
val prediction = model.predict(point.features)
125+
(point.label, prediction)
126+
}
127+
val MSE = valuesAndPreds.map{ case(v, p) => math.pow((v - p), 2)}.reduce(_ + _)/valuesAndPreds.count
128+
println("training Mean Squared Error = " + MSE)
129+
{% endhighlight %}

0 commit comments

Comments
 (0)