Github user jkbradley commented on a diff in the pull request:

    https://github.com/apache/spark/pull/5626#discussion_r28994127
  
    --- Diff: 
mllib/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala ---
    @@ -0,0 +1,225 @@
    +/*
    + * 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.ml.classification
    +
    +import com.github.fommil.netlib.BLAS.{getInstance => blas}
    +
    +import org.apache.spark.Logging
    +import org.apache.spark.annotation.AlphaComponent
    +import org.apache.spark.ml.impl.estimator.{PredictionModel, Predictor}
    +import org.apache.spark.ml.impl.tree._
    +import org.apache.spark.ml.param.{Param, Params, ParamMap}
    +import org.apache.spark.ml.regression.DecisionTreeRegressionModel
    +import org.apache.spark.ml.tree.{DecisionTreeModel, TreeEnsembleModel}
    +import org.apache.spark.ml.util.MetadataUtils
    +import org.apache.spark.mllib.linalg.Vector
    +import org.apache.spark.mllib.regression.LabeledPoint
    +import org.apache.spark.mllib.tree.{GradientBoostedTrees => OldGBT}
    +import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo}
    +import org.apache.spark.mllib.tree.loss.{Loss => OldLoss, LogLoss => 
OldLogLoss}
    +import org.apache.spark.mllib.tree.model.{GradientBoostedTreesModel => 
OldGBTModel}
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.sql.DataFrame
    +
    +
    +/**
    + * :: AlphaComponent ::
    + *
    + * [[http://en.wikipedia.org/wiki/Gradient_boosting Gradient-Boosted Trees 
(GBTs)]]
    + * learning algorithm for classification.
    + * It supports binary labels, as well as both continuous and categorical 
features.
    + * Note: Multiclass labels are not currently supported.
    + */
    +@AlphaComponent
    +final class GBTClassifier
    +  extends Predictor[Vector, GBTClassifier, GBTClassificationModel]
    +  with GBTParams with TreeClassifierParams with Logging {
    +
    +  // Override parameter setters from parent trait for Java API 
compatibility.
    +
    +  // Parameters from TreeClassifierParams:
    +
    +  override def setMaxDepth(value: Int): this.type = 
super.setMaxDepth(value)
    +
    +  override def setMaxBins(value: Int): this.type = super.setMaxBins(value)
    +
    +  override def setMinInstancesPerNode(value: Int): this.type =
    +    super.setMinInstancesPerNode(value)
    +
    +  override def setMinInfoGain(value: Double): this.type = 
super.setMinInfoGain(value)
    +
    +  override def setMaxMemoryInMB(value: Int): this.type = 
super.setMaxMemoryInMB(value)
    +
    +  override def setCacheNodeIds(value: Boolean): this.type = 
super.setCacheNodeIds(value)
    +
    +  override def setCheckpointInterval(value: Int): this.type = 
super.setCheckpointInterval(value)
    +
    +  /**
    +   * The impurity setting is ignored for GBT models.
    +   * Individual trees are built using impurity "Variance."
    +   */
    +  override def setImpurity(value: String): this.type = {
    +    logWarning("GBTClassifier.setImpurity should NOT be used")
    +    this
    +  }
    +
    +  // Parameters from TreeEnsembleParams:
    +
    +  override def setSubsamplingRate(value: Double): this.type = 
super.setSubsamplingRate(value)
    +
    +  override def setSeed(value: Long): this.type = {
    +    logWarning("The 'seed' parameter is currently ignored by Gradient 
Boosting.")
    +    super.setSeed(value)
    +  }
    +
    +  // Parameters from GBTParams:
    +
    +  override def setMaxIter(value: Int): this.type = super.setMaxIter(value)
    +
    +  override def setLearningRate(value: Double): this.type = 
super.setLearningRate(value)
    +
    +  // Parameters for GBTClassifier:
    +
    +  /**
    +   * Loss function which GBT tries to minimize. (case-insensitive)
    +   * Supported: "LogLoss"
    +   * (default = LogLoss)
    +   * @group param
    +   */
    +  val loss: Param[String] = new Param[String](this, "loss", "Loss function 
which GBT tries to" +
    +    " minimize (case-insensitive). Supported options: LogLoss")
    +
    +  setDefault(loss -> "logloss")
    +
    +  /** @group setParam */
    +  def setLoss(value: String): this.type = {
    +    val lossStr = value.toLowerCase
    +    require(GBTClassifier.supportedLosses.contains(lossStr), 
"GBTClassifier was given bad loss:" +
    +      s" $value. Supported options: 
${GBTClassifier.supportedLosses.mkString(", ")}")
    +    set(loss, lossStr)
    +    this
    +  }
    +
    +  /** @group getParam */
    +  def getLoss: String = getOrDefault(loss)
    +
    +  /** (private[ml]) Convert new loss to old loss. */
    +  override private[ml] def getOldLoss: OldLoss = {
    +    getLoss match {
    +      case "logloss" => OldLogLoss
    +      case _ =>
    +        // Should never happen because of check in setter method.
    +        throw new RuntimeException(s"GBTClassifier was given bad loss: 
$getLoss")
    +    }
    +  }
    +
    +  override protected def train(
    +      dataset: DataFrame,
    +      paramMap: ParamMap): GBTClassificationModel = {
    +    val categoricalFeatures: Map[Int, Int] =
    +      
MetadataUtils.getCategoricalFeatures(dataset.schema(paramMap(featuresCol)))
    +    val numClasses: Int = 
MetadataUtils.getNumClasses(dataset.schema(paramMap(labelCol))) match {
    +      case Some(n: Int) => n
    +      case None => throw new IllegalArgumentException("GBTClassifier was 
given input" +
    +        s" with invalid label column, without the number of classes 
specified.")
    +      // TODO: Automatically index labels.
    +    }
    +    require(numClasses == 2,
    +      s"GBTClassifier only supports binary classification but was given 
numClasses = $numClasses")
    +    val oldDataset: RDD[LabeledPoint] = extractLabeledPoints(dataset, 
paramMap)
    +    val boostingStrategy = 
super.getOldBoostingStrategy(categoricalFeatures, OldAlgo.Classification)
    +    val oldGBT = new OldGBT(boostingStrategy)
    +    val oldModel = oldGBT.run(oldDataset)
    +    GBTClassificationModel.fromOld(oldModel, this, paramMap, 
categoricalFeatures)
    +  }
    +}
    +
    +object GBTClassifier {
    +  // The losses below should be lowercase.
    +  /** Accessor for supported loss settings */
    +  final val supportedLosses: Array[String] = 
Array("logloss").map(_.toLowerCase)
    +}
    +
    +/**
    + * :: AlphaComponent ::
    + *
    + * [[http://en.wikipedia.org/wiki/Gradient_boosting Gradient-Boosted Trees 
(GBTs)]]
    + * model for classification.
    + * It supports binary labels, as well as both continuous and categorical 
features.
    + * Note: Multiclass labels are not currently supported.
    + * @param trees  Decision trees in the ensemble.
    + * @param treeWeights  Weights for the decision trees in the ensemble.
    + */
    +@AlphaComponent
    +final class GBTClassificationModel(
    +    override val parent: GBTClassifier,
    +    override val fittingParamMap: ParamMap,
    +    val trees: Array[DecisionTreeRegressionModel],
    --- End diff --
    
    Sort of.  Gradient boosting's "gradient" part comes from phrasing the 
problem as regression.
    
    scikit-learn trains 1 regression tree for each class, essentially doing a 1 
vs all approach to reduce multiclass to binary.  Those predictions can then be 
fed into the boosting algorithm via a multinomial logistic loss function.
    
    Just as in reducing multiclass to binary, we can take other approaches.  
E.g., if you use an error-correcting code-based approach, then it can make 
sense to train 1 tree per iteration, where each tree tries to separate some 
subset of classes out from the other classes.
    
    I have seen (a) scikit-learn's approach of 1-vs-all for gradient boosting 
and (b) the error-correcting approach for other boosting algorithms, but I have 
not seen someone write out the combination: gradient boosting + 
error-correcting.  It may be out there, and I'm sure we could work it out, with 
a bit of effort.
    
    So, this abstraction will work if we take the error-correcting approach.  
It could work for 1-vs-all if we keep a matching array indicating which class 
each tree is testing for, but then the ordering of the trees would be obscured. 
 For 1-vs-all, it might be best to store 
```Array[Array[DecisionTreeRegressionModel]]```


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at [email protected] or file a JIRA ticket
with INFRA.
---

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to