Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
cd53eae
skeletal framework
manishamde Nov 28, 2013
92cedce
basic building blocks for intermediate RDD calculation. untested.
manishamde Dec 2, 2013
8bca1e2
additional code for creating intermediate RDD
manishamde Dec 9, 2013
0012a77
basic stump working
manishamde Dec 10, 2013
03f534c
some more tests
manishamde Dec 10, 2013
dad0afc
decison stump functionality working
manishamde Dec 15, 2013
4798aae
added gain stats class
manishamde Dec 15, 2013
80e8c66
working version of multi-level split calculation
manishamde Dec 16, 2013
b0eb866
added logic to handle leaf nodes
manishamde Dec 16, 2013
98ec8d5
tree building and prediction logic
manishamde Dec 22, 2013
02c595c
added command line parsing
manishamde Dec 22, 2013
733d6dd
fixed tests
manishamde Dec 22, 2013
154aa77
enums for configurations
manishamde Dec 23, 2013
b0e3e76
adding enum for feature type
manishamde Jan 12, 2014
c8f6d60
adding enum for feature type
manishamde Jan 12, 2014
e23c2e5
added regression support
manishamde Jan 19, 2014
53108ed
fixing index for highest bin
manishamde Jan 20, 2014
6df35b9
regression predict logic
manishamde Jan 21, 2014
dbb7ac1
categorical feature support
manishamde Jan 23, 2014
d504eb1
more tests for categorical features
manishamde Jan 23, 2014
6b7de78
minor refactoring and tests
manishamde Jan 26, 2014
b09dc98
minor refactoring
manishamde Jan 26, 2014
c0e522b
updated predict and split threshold logic
manishamde Jan 27, 2014
f067d68
minor cleanup
manishamde Jan 27, 2014
5841c28
unit tests for categorical features
manishamde Jan 27, 2014
0dd7659
basic doc
manishamde Jan 27, 2014
dd0c0d7
minor: some docs
manishamde Jan 27, 2014
9372779
code style: max line lenght <= 100
manishamde Feb 17, 2014
84f85d6
code documentation
manishamde Feb 28, 2014
d3023b3
adding more docs for nested methods
manishamde Mar 6, 2014
63e786b
added multiple train methods for java compatability
manishamde Mar 6, 2014
cd2c2b4
fixing code style based on feedback
manishamde Mar 7, 2014
eb8fcbe
minor code style updates
manishamde Mar 7, 2014
794ff4d
minor improvements to docs and style
manishamde Mar 10, 2014
d1ef4f6
more documentation
manishamde Mar 10, 2014
ad1fc21
incorporated mengxr's code style suggestions
manishamde Mar 11, 2014
62c2562
fixing comment indentation
manishamde Mar 11, 2014
6068356
ensuring num bins is always greater than max number of categories
manishamde Mar 12, 2014
2116360
removing dummy bin calculation for categorical variables
manishamde Mar 12, 2014
632818f
removing threshold for classification predict method
manishamde Mar 13, 2014
ff363a7
binary search for bins and while loop for categorical feature bins
manishamde Mar 17, 2014
4576b64
documentation and for to while loop conversion
manishamde Mar 23, 2014
24500c5
minor style updates
mengxr Mar 23, 2014
c487e6a
Merge pull request #1 from mengxr/dtree
manishamde Mar 23, 2014
f963ef5
making methods private
manishamde Mar 23, 2014
201702f
making some more methods private
manishamde Mar 23, 2014
62dc723
updating javadoc and converting helper methods to package private to …
manishamde Mar 24, 2014
e1dd86f
implementing code style suggestions
manishamde Mar 25, 2014
f536ae9
another pass on code style
mengxr Mar 31, 2014
7d54b4f
Merge pull request #4 from mengxr/dtree
manishamde Mar 31, 2014
1e8c704
remove numBins field in the Strategy class
manishamde Apr 1, 2014
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
enums for configurations
Signed-off-by: Manish Amde <manish9ue@gmail.com>
  • Loading branch information
manishamde committed Feb 28, 2014
commit 154aa77c925e44a92e8bbf2f55e43cab06e75006
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ import org.apache.spark.mllib.tree.model._
import org.apache.spark.{SparkContext, Logging}
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.tree.model.Split
import org.apache.spark.mllib.tree.impurity.Gini
import scala.util.control.Breaks._
import org.apache.spark.mllib.tree.configuration.Strategy
import org.apache.spark.mllib.tree.configuration.QuantileStrategy._


class DecisionTree(val strategy : Strategy) extends Serializable with Logging {
Expand All @@ -34,8 +35,6 @@ class DecisionTree(val strategy : Strategy) extends Serializable with Logging {
//Cache input RDD for speedup during multiple passes
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Put an extra space after "//".

input.cache()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the current implementation of other algorithms in MLlib, we let users to choose whether the data should be cached or not. How many passes does your algorithm need?


//TODO: Find all splits and bins using quantiles including support for categorical features, single-pass
//TODO: Think about broadcasting this
val (splits, bins) = DecisionTree.find_splits_bins(input, strategy)
logDebug("numSplits = " + bins(0).length)
strategy.numBins = bins(0).length
Expand Down Expand Up @@ -133,7 +132,7 @@ object DecisionTree extends Serializable with Logging {

@param input RDD of [[org.apache.spark.mllib.regression.LabeledPoint]] used as training data for DecisionTree
@param parentImpurities Impurities for all parent nodes for the current level
@param strategy [[org.apache.spark.mllib.tree.Strategy]] instance containing parameters for construction the DecisionTree
@param strategy [[org.apache.spark.mllib.tree.configuration.Strategy]] instance containing parameters for construction the DecisionTree
@param level Level of the tree
@param filters Filter for all nodes at a given level
@param splits possible splits for all features
Expand Down Expand Up @@ -406,27 +405,18 @@ object DecisionTree extends Serializable with Logging {
val (leftNodeAgg, rightNodeAgg) = extractLeftRightNodeAggregates(binData)
val gains = calculateGainsForAllNodeSplits(leftNodeAgg, rightNodeAgg, nodeImpurity)

//logDebug("gains.size = " + gains.size)
//logDebug("gains(0).size = " + gains(0).size)

val (bestFeatureIndex,bestSplitIndex, gainStats) = {
var bestFeatureIndex = 0
var bestSplitIndex = 0
//Initialization with infeasible values
var bestGainStats = new InformationGainStats(Double.MinValue,-1.0,-1.0,0,-1.0,0)
// var maxGain = Double.MinValue
// var leftSamples = Long.MinValue
// var rightSamples = Long.MinValue
for (featureIndex <- 0 until numFeatures) {
for (splitIndex <- 0 until numSplits - 1){
val gainStats = gains(featureIndex)(splitIndex)
//logDebug("featureIndex = " + featureIndex + ", splitIndex = " + splitIndex + ", gain = " + gain)
if(gainStats.gain > bestGainStats.gain) {
bestGainStats = gainStats
bestFeatureIndex = featureIndex
bestSplitIndex = splitIndex
//logDebug("bestFeatureIndex = " + bestFeatureIndex + ", bestSplitIndex = " + bestSplitIndex)
//logDebug( "gain stats = " + bestGainStats)
}
}
}
Expand Down Expand Up @@ -455,7 +445,7 @@ object DecisionTree extends Serializable with Logging {
Returns split and bins for decision tree calculation.

@param input RDD of [[org.apache.spark.mllib.regression.LabeledPoint]] used as training data for DecisionTree
@param strategy [[org.apache.spark.mllib.tree.Strategy]] instance containing parameters for construction the DecisionTree
@param strategy [[org.apache.spark.mllib.tree.configuration.Strategy]] instance containing parameters for construction the DecisionTree
@return a tuple of (splits,bins) where Split is an Array[Array[Split]] of size (numFeatures,numSplits-1) and bins is an
Array[Array[Bin]] of size (numFeatures,numSplits1)
*/
Expand Down Expand Up @@ -483,7 +473,7 @@ object DecisionTree extends Serializable with Logging {
logDebug("stride = " + stride)

strategy.quantileCalculationStrategy match {
case "sort" => {
case Sort => {
val splits = Array.ofDim[Split](numFeatures,numBins-1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove the extra space after "="

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

put an extra space after ","

val bins = Array.ofDim[Bin](numFeatures,numBins)

Expand Down Expand Up @@ -514,10 +504,10 @@ object DecisionTree extends Serializable with Logging {

(splits,bins)
}
case "minMax" => {
case MinMax => {
(Array.ofDim[Split](numFeatures,numBins),Array.ofDim[Bin](numFeatures,numBins+2))
}
case "approximateHistogram" => {
case ApproxHist => {
throw new UnsupportedOperationException("approximate histogram not supported yet.")
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ import org.apache.spark.mllib.tree.impurity.{Gini,Entropy,Variance}
import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.tree.model.DecisionTreeModel
import org.apache.spark.mllib.tree.configuration.Strategy
import org.apache.spark.mllib.tree.configuration.Algo._


object DecisionTreeRunner extends Logging {

val usage = """
Usage: DecisionTreeRunner <master>[slices] --kind <Classification,Regression> --trainDataDir path --testDataDir path [--maxDepth num] [--impurity <Gini,Entropy,Variance>] [--maxBins num]
Usage: DecisionTreeRunner <master>[slices] --algo <Classification,Regression> --trainDataDir path --testDataDir path --maxDepth num [--impurity <Gini,Entropy,Variance>] [--maxBins num]
"""


Expand All @@ -46,39 +49,49 @@ object DecisionTreeRunner extends Logging {
def isSwitch(s : String) = (s(0) == '-')
list match {
case Nil => map
case "--kind" :: string :: tail => nextOption(map ++ Map('kind -> string), tail)
case "--algo" :: string :: tail => nextOption(map ++ Map('algo -> string), tail)
case "--impurity" :: string :: tail => nextOption(map ++ Map('impurity -> string), tail)
case "--maxDepth" :: string :: tail => nextOption(map ++ Map('maxDepth -> string), tail)
case "--maxBins" :: string :: tail => nextOption(map ++ Map('maxBins -> string), tail)
case "--trainDataDir" :: string :: tail => nextOption(map ++ Map('trainDataDir -> string), tail)
case "--testDataDir" :: string :: tail => nextOption(map ++ Map('testDataDir -> string), tail)
case string :: Nil => nextOption(map ++ Map('infile -> string), list.tail)
case option :: tail => println("Unknown option "+option)
exit(1)
case option :: tail => logError("Unknown option "+option)
sys.exit(1)
}
}
val options = nextOption(Map(),arglist)
logDebug(options.toString())
//TODO: Add validation for input parameters

//Load training data
val trainData = loadLabeledData(sc, options.get('trainDataDir).get.toString)

val typeStr = options.get('type).toString
//TODO: Create enum
val impurityStr = options.getOrElse('impurity,if (typeStr == "classification") "Gini" else "Variance").toString
val impurity = {
impurityStr match {
//Figure out the type of algorithm
val algoStr = options.get('algo).get.toString
val algo = algoStr match {
case "Classification" => Classification
case "Regression" => Regression
}

//Identify the type of impurity
val impurityStr = options.getOrElse('impurity,if (algo == Classification) "Gini" else "Variance").toString
val impurity = impurityStr match {
case "Gini" => Gini
case "Entropy" => Entropy
case "Variance" => Variance
}
}

val maxDepth = options.getOrElse('maxDepth,"1").toString.toInt
val maxBins = options.getOrElse('maxBins,"100").toString.toInt

val strategy = new Strategy(kind = typeStr, impurity = Gini, maxDepth = maxDepth, maxBins = maxBins)
val strategy = new Strategy(algo = algo, impurity = impurity, maxDepth = maxDepth, maxBins = maxBins)
val model = new DecisionTree(strategy).train(trainData)

//Load test data
val testData = loadLabeledData(sc, options.get('testDataDir).get.toString)

//Measure algorithm accuracy
val accuracy = accuracyScore(model, testData)
logDebug("accuracy = " + accuracy)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.mllib.tree.configuration

object Algo extends Enumeration {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Algorithm Enumeration seems redundant given Impurity which implies the Algorithm anyway.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The various Enumeration classes in mllib.tree.configuration package are neat. A uniform design pattern for parameters and options should be used for MLLib and Spark, and this could be a start. Alternatively, if there is an existing pattern in use, it should be followed for decision tree as well.

type Algo = Value
val Classification, Regression = Value
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.mllib.tree.configuration

object QuantileStrategy extends Enumeration {
type QuantileStrategy = Value
val Sort, MinMax, ApproxHist = Value
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.mllib.tree
package org.apache.spark.mllib.tree.configuration

import org.apache.spark.mllib.tree.impurity.Impurity
import org.apache.spark.mllib.tree.configuration.Algo._
import org.apache.spark.mllib.tree.configuration.QuantileStrategy._

class Strategy (
val kind : String,
val algo : Algo,
val impurity : Impurity,
val maxDepth : Int,
val maxBins : Int,
val quantileCalculationStrategy : String = "sort") extends Serializable {
val quantileCalculationStrategy : QuantileStrategy = Sort) extends Serializable {

var numBins : Int = Int.MinValue

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.mllib.tree.impurity.{Entropy, Gini}
import org.apache.spark.mllib.tree.model.Filter
import org.apache.spark.mllib.tree.configuration.Strategy

class DecisionTreeSuite extends FunSuite with BeforeAndAfterAll {

Expand Down