diff --git a/README.md b/README.md
index c1f5210..97493a2 100644
--- a/README.md
+++ b/README.md
@@ -5,9 +5,9 @@
Introduction
============
-The machine learning algorithm library running on Kunpeng processors is an acceleration library that provides a rich set of high-level tools for machine learning algorithms. It is based on the original APIs of Apache [Spark 2.3.2](https://github.com/apache/spark/tree/v2.3.2), [breeze 0.13.1](https://github.com/scalanlp/breeze/tree/releases/v0.13.1) and [xgboost 1.1.0](https://github.com/dmlc/xgboost/tree/release_1.0.0). The acceleration library for greatly improves the computing power in big data scenarios.
+The machine learning algorithm library running on Kunpeng processors is an acceleration library that provides a rich set of high-level tools for machine learning algorithms. It is based on the original APIs of Apache [Spark 3.1.1](https://github.com/apache/spark/tree/v3.1.1). The acceleration library for greatly improves the computing power in big data scenarios.
-The library provides 21 machine learning algorithms: support vector machine (SVM), random forest classifier (RFC), gradient boosting decision tree (GBDT), decision tree (DT), K-means clustering, linear regression, logistic regression algorithm, principal component analysis (PCA), principal component analysis for Sparse Matrix(SPCA), singular value decomposition (SVD), latent dirichlet allocation (LDA), prefix-projected pattern prowth (Prefix-Span), alternating least squares (ALS), K-nearest neighbors (KNN), Covariance, Density-based spatial clustering of applicaitons with noise (DBSCAN), Pearson, Spearman, XGboost, Inverse Document Frequency(IDF), and SimRank. You can find the latest documentation on the project web page. This README file contains only basic setup instructions.
+The library provides 5 machine learning algorithms: latent dirichlet allocation (LDA), prefix-projected pattern prowth (Prefix-Span), alternating least squares (ALS), K-nearest neighbors (KNN), Density-based spatial clustering of applicaitons with noise (DBSCAN). You can find the latest documentation on the project web page. This README file contains only basic setup instructions.
You can find the latest documentation, including a programming guide, on the project web page. This README file only contains basic setup instructions.
@@ -21,17 +21,9 @@ Building And Packageing
mvn clean package
-(2) Build XGBoost project under the "Spark-ml-algo-lib/ml-xgboost/jvm-packages" directory:
+(2) Obtain "boostkit-ml-core_2.12-2.1.0-spark3.1.1.jar" under the "Spark-ml-algo-lib/ml-core/target" directory.
- mvn clean package
-
-(3) Obtain "boostkit-ml-core_2.11-2.1.0-spark2.3.2.jar" under the "Spark-ml-algo-lib/ml-core/target" directory.
-
- Obtain "boostkit-ml-acc_2.11-2.1.0-spark2.3.2.jar" under the "Spark-ml-algo-lib/ml-accelerator/target" directory.
-
- Obtain "boostkit-xgboost4j_2.11-2.1.0.jar" under the "Spark-ml-algo-lib/ml-xgboost/jvm-packages/boostkit-xgboost4j/target" directory.
-
- Obtain "boostkit-xgboost4j-spark2.3.2_2.11-2.1.0.jar" under the "Spark-ml-algo-lib/ml-xgboost/jvm-packages/boostkit-xgboost4j-spark/target" directory.
+ Obtain "boostkit-ml-acc_2.12-2.1.0-spark3.1.1.jar" under the "Spark-ml-algo-lib/ml-accelerator/target" directory.
Contribution Guidelines
diff --git a/ml-accelerator/pom.xml b/ml-accelerator/pom.xml
index 5c9f082..0af611b 100644
--- a/ml-accelerator/pom.xml
+++ b/ml-accelerator/pom.xml
@@ -6,7 +6,7 @@
4.0.0
- boostkit-ml-acc_2.11
+ boostkit-ml-acc_2.12
2.1.0
${project.artifactId}
Spark ml algo accelerator
@@ -14,14 +14,14 @@
org.apache.spark
- boostkit-ml-core_2.11
+ boostkit-ml-core_2.12
${project.version}
${spark.version}
org.apache.spark
- boostkit-ml-kernel-client_2.11
+ boostkit-ml-kernel-client_2.12
${project.version}
${spark.version}
compile
diff --git a/ml-accelerator/src/main/scala/breeze/optimize/FirstOrderMinimizerX.scala b/ml-accelerator/src/main/scala/breeze/optimize/FirstOrderMinimizerX.scala
deleted file mode 100644
index 053f103..0000000
--- a/ml-accelerator/src/main/scala/breeze/optimize/FirstOrderMinimizerX.scala
+++ /dev/null
@@ -1,291 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-
-package breeze.optimize
-
-import scala.language.implicitConversions
-
-import FirstOrderMinimizerX.ConvergenceCheck
-import breeze.linalg.norm
-import breeze.math.{MutableInnerProductModule, NormedModule}
-import breeze.util.Implicits._
-import breeze.util.SerializableLogging
-
-/**
- *
- * @author dlwh
- */
-abstract class FirstOrderMinimizerX[T, DF<:StochasticDiffFunction[T]]
-(val convergenceCheck: ConvergenceCheck[T])
-(implicit space: MutableInnerProductModule[T, Double])
- extends Minimizer[T, DF] with SerializableLogging {
-
- def this(maxIter: Int = -1, tolerance: Double = 1E-6,
- fvalMemory: Int = 100, relativeTolerance: Boolean = true)
- (implicit space: MutableInnerProductModule[T, Double]) =
- this(FirstOrderMinimizerX.defaultConvergenceCheckX[T]
- (maxIter, tolerance, relativeTolerance, fvalMemory))
-
- var inertiaCoefficient: Double = 0.5
- val momentumUpdateCoefficient : Double = 0.9
-
- def setInertiaCoefficient(a: Double): Unit = {
- this.inertiaCoefficient = a
- }
-
- /**
- * Any history the derived minimization function needs to do its updates.
- * typically an approximation
- * to the second derivative/hessian matrix.
- */
- type History
- type State = FirstOrderMinimizerX.State[T, convergenceCheck.Info, History]
-
-
-
-
- protected def initialHistory(f: DF, init: T): History
- protected def adjustFunction(f: DF): DF = f
- protected def adjust(newX: T, newGrad: T, newVal: Double): (Double, T) = (newVal, newGrad)
- protected def chooseDescentDirection(state: State, f: DF): T
- protected def takeStep(state: State, dir: T, stepSize: Double): T
- protected def updateHistory(newX: T, newGrad: T, newVal: Double, f: DF, oldState: State): History
- protected def updateTheta(f: DF, state: State): (T, T)
-
-
- protected def initialState(f: DF, init: T): State = {
- val x = init
- val history = initialHistory(f, init)
- val (value, grad) = calculateObjective(f, x, history)
- val (adjValue, adjGrad) = adjust(x, grad, value)
- import space._
- val copyInit = space.copy(init)
- copyInit -= copyInit
- FirstOrderMinimizerX.State(x,
- value,
- grad,
- adjValue,
- adjGrad,
- 0,
- adjValue,
- history,
- convergenceCheck.initialInfo,
- copyInit)
- }
-
-
- protected def calculateObjective(f: DF, x: T, history: History): (Double, T) = {
- f.calculate(x)
- }
-
- def infiniteIterations(f: DF, state: State): Iterator[State] = {
- var failedOnce = false
- val adjustedFun = adjustFunction(f)
- import space._
-
- Iterator.iterate(state) { state => try {
- val (x, currentMomentum) = updateTheta(adjustedFun, state)
- // the Func used to update the theta, sub class overide it.
- val (value, grad) = calculateObjective(adjustedFun, x, state.history)
- val (adjValue, adjGrad) = adjust(x, grad, value)
- val oneOffImprovement = (state.adjustedValue - adjValue)/
- (state.adjustedValue.abs max adjValue.abs max 1E-6 * state.initialAdjVal.abs)
- logger.info(f"Val and Grad Norm: $adjValue%.6g (rel: " +
- f"$oneOffImprovement%.3g) ${norm(adjGrad)}%.6g")
- val history = updateHistory(x, grad, value, adjustedFun, state)
- val newCInfo = convergenceCheck
- .update(x,
- grad,
- value,
- state,
- state.convergenceInfo)
- failedOnce = false
- FirstOrderMinimizerX
- .State(x,
- value,
- grad,
- adjValue,
- adjGrad,
- state.iter + 1,
- state.initialAdjVal,
- history,
- newCInfo,
- currentMomentum)
- } catch {
- case x: FirstOrderException if !failedOnce =>
- failedOnce = true
- logger.error(s"Failure! Resetting history: $x")
- state.copy(history = initialHistory(adjustedFun, state.x))
- case x: FirstOrderException =>
- logger.error("Failure again! Giving up and returning. " +
- "Maybe the objective is just poorly behaved?")
- state.copy(searchFailed = true)
- }
- }
- }
-
- def iterations(f: DF, init: T): Iterator[State] = {
- val adjustedFun = adjustFunction(f)
- infiniteIterations(f, initialState(adjustedFun, init))
- .takeUpToWhere{s =>
- convergenceCheck.apply(s, s.convergenceInfo) match {
- case Some(converged) =>
- logger.info(s"Converged because ${converged.reason}")
- true
- case None =>
- false
- }
- }
- }
-
- def minimize(f: DF, init: T): T = {
- minimizeAndReturnState(f, init).x
- }
-
-
- def minimizeAndReturnState(f: DF, init: T): State = {
- iterations(f, init).last
- }
-}
-
-
-object FirstOrderMinimizerX {
-
- /**
- * Tracks the information about the optimizer, including the current point,
- * its value, gradient, and then any history.
- * Also includes information for checking convergence.
- * @param x the current point being considered
- * @param value f(x)
- * @param grad f.gradientAt(x)
- * @param adjustedValue f(x) + r(x)
- * @param adjustedGradient f'(x) + r'(x)
- * @param iter what iteration number we are on.
- * @param initialAdjVal f(x_0) + r(x_0), used for checking convergence
- * @param history any information needed by the optimizer to do updates.
- * @param searchFailed did the line search fail?
- */
- case class State[+T, +ConvergenceInfo, +History](x: T,
- value: Double,
- grad: T,
- adjustedValue: Double,
- adjustedGradient: T,
- iter: Int,
- initialAdjVal: Double,
- history: History,
- convergenceInfo: ConvergenceInfo,
- momentum: T,
- searchFailed: Boolean = false) {
- }
-
- trait ConvergenceCheck[T] {
- type Info
- def initialInfo: Info
- def apply(state: State[T, _, _], info: Info): Option[ConvergenceReason]
- def update(newX: T,
- newGrad: T,
- newVal: Double,
- oldState: State[T, _, _],
- oldInfo: Info): Info
- def ||(otherCheck: ConvergenceCheck[T]):
- ConvergenceCheck[T] = orElse(otherCheck)
-
- def orElse(other: ConvergenceCheck[T]):
- ConvergenceCheck[T] = {
- SequenceConvergenceCheck(asChecks ++ other.asChecks)
- }
-
- protected def asChecks:
- IndexedSeq[ConvergenceCheck[T]] = IndexedSeq(this)
- }
-
- object ConvergenceCheck {
- implicit def fromPartialFunction[T](pf: PartialFunction[State[T, _, _], ConvergenceReason]):
- ConvergenceCheck[T] = new ConvergenceCheck[T] {
- override type Info = Unit
-
- def update(newX: T,
- newGrad: T,
- newVal: Double,
- oldState: State[T, _, _],
- oldInfo: Info):
- Info = oldInfo
-
- override def apply(state: State[T, _, _], info: Info):
- Option[ConvergenceReason] = pf.lift(state)
-
- override def initialInfo: Info = ()
- }
- }
-
- case class SequenceConvergenceCheck[T](checks: IndexedSeq[ConvergenceCheck[T]])
- extends ConvergenceCheck[T] {
- type Info = IndexedSeq[ConvergenceCheck[T]#Info]
-
- override def initialInfo: IndexedSeq[ConvergenceCheck[T]#Info] = checks.map(_.initialInfo)
-
- override def update(newX: T,
- newGrad: T,
- newVal: Double,
- oldState: State[T, _, _],
- oldInfo: Info):
- Info = {
- require(oldInfo.length == checks.length)
- (checks zip oldInfo).map { case (c, i) =>
- c.update(newX,
- newGrad,
- newVal,
- oldState,
- i.asInstanceOf[c.Info]) }
- }
-
- override def apply(state: State[T, _, _],
- info: IndexedSeq[ConvergenceCheck[T]#Info]): Option[ConvergenceReason] = {
- (checks zip info).iterator.flatMap { case (c, i) =>
- c(state, i.asInstanceOf[c.Info])}.toStream.headOption
- }
- }
-
-
- trait ConvergenceReason {
- def reason: String
- }
- case object MaxIterations extends ConvergenceReason {
- override def reason: String = "max iterations reached"
- }
-
- case object GradientConverged extends ConvergenceReason {
- override def reason: String = "gradient converged"
- }
-
- def maxIterationsReached[T](maxIter: Int):
- ConvergenceCheck[T] = ConvergenceCheck.fromPartialFunction {
- case s: State[_, _, _] if (s.iter >= maxIter && maxIter >= 0) =>
- MaxIterations
- }
-
- def gradientConverged[T](tolerance: Double, relative: Boolean = true)
- (implicit space: NormedModule[T, Double]): ConvergenceCheck[T] = {
- import space.normImpl
- ConvergenceCheck.fromPartialFunction[T] {
- case s: State[T, _, _] if (norm(s.adjustedGradient) < tolerance
- * (if (relative) s.adjustedValue else 1.0)) =>
- GradientConverged
- }
- }
-
-
- def defaultConvergenceCheckX[T](maxIter: Int, tolerance: Double,
- relative: Boolean = true, fvalMemory: Int = 20)
- (implicit space: NormedModule[T, Double]): ConvergenceCheck[T] =
- (
- maxIterationsReached[T](maxIter) ||
- gradientConverged[T](tolerance, relative)
- )
-
-}
diff --git a/ml-accelerator/src/main/scala/breeze/optimize/LBFGSX.scala b/ml-accelerator/src/main/scala/breeze/optimize/LBFGSX.scala
deleted file mode 100644
index e0b99d7..0000000
--- a/ml-accelerator/src/main/scala/breeze/optimize/LBFGSX.scala
+++ /dev/null
@@ -1,110 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-
-package breeze.optimize
-
-/*
- Copyright 2009 David Hall, Daniel Ramage
-
- Licensed 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.
-*/
-
-import breeze.linalg._
-import breeze.math.MutableInnerProductModule
-import breeze.optimize.FirstOrderMinimizerX.ConvergenceCheck
-import breeze.util.SerializableLogging
-
-/**
- * Port of LBFGS to Scala.
- *
- * Special note for LBFGS:
- * If you use it in published work, you must cite one of:
- * * J. Nocedal. Updating Quasi-Newton Matrices with Limited Storage
- * (1980), Mathematics of Computation 35, pp. 773-782.
- * * D.C. Liu and J. Nocedal. On the Limited mem Method for Large
- * Scale Optimization (1989), Mathematical Programming B, 45, 3,
- * pp. 503-528.
- *
- * @param m: The memory of the search. 3 to 7 is usually sufficient.
- */
-class LBFGSX[T](convergenceCheck: ConvergenceCheck[T], m: Int)
- (implicit space: MutableInnerProductModule[T, Double]) extends
- FirstOrderMinimizerX[T, DiffFunction[T]](convergenceCheck) with SerializableLogging {
-
- def this(maxIter: Int = -1, m: Int = 7, tolerance: Double = 1E-9)
- (implicit space: MutableInnerProductModule[T, Double]) =
- this(FirstOrderMinimizerX.defaultConvergenceCheckX(maxIter, tolerance), m )
- import space._
- require(m > 0)
-
- type History = LBFGSX.ApproximateInverseHessianX[T]
-
- override protected def adjustFunction(f: DiffFunction[T]): DiffFunction[T] = f.cached
-
- def takeStep(state: State, dir: T, stepSize: Double): T = state.x + dir * stepSize
- protected def initialHistory(f: DiffFunction[T], x: T):
- History = new LBFGSX.ApproximateInverseHessianX(m)
- protected def chooseDescentDirection(state: State, fn: DiffFunction[T]): T = {
- state.history * state.grad
- }
-
- protected def updateHistory(newX: T, newGrad: T, newVal: Double,
- f: DiffFunction[T], oldState: State): History = {
- oldState.history.updated(newX - oldState.x, newGrad -:- oldState.grad)
- }
-
-
- override def updateTheta(f: DiffFunction[T], state: State): (T, T) = {
- val adjustedFun = adjustFunction(f)
- val dir = chooseDescentDirection(state, adjustedFun)
- val currentMomentum = ACC
- .updateMomentum(state.momentum, dir, inertiaCoefficient, momentumUpdateCoefficient)(space)
- val stepSize = 1.0
- logger.info(f"Step Size: $stepSize%.4g")
- val x = takeStep(state, currentMomentum, stepSize)
- (x, currentMomentum)
- }
-}
-
-object LBFGSX {
- case class ApproximateInverseHessianX[T](m: Int,
- private[LBFGSX] val memStep: IndexedSeq[T] = IndexedSeq.empty,
- private[LBFGSX] val memGradDelta: IndexedSeq[T] = IndexedSeq.empty)
- (implicit space: MutableInnerProductModule[T, Double])
- extends NumericOps[ApproximateInverseHessianX[T]] {
-
- import space._
-
- def repr: ApproximateInverseHessianX[T] = this
-
- def updated(step: T, gradDelta: T): ApproximateInverseHessianX[T] = {
- val (a, b) = ACC.update(step, gradDelta, this.memStep, this.memGradDelta, m)(space)
- new ApproximateInverseHessianX(m, a, b)
- }
-
-
- def historyLength: Int = memStep.length
-
- def *(grad: T): T = {
- val a = ACC.getInverseOfHessian(grad, this.memStep, this.memGradDelta, m, historyLength)
- a
- }
- }
-
-}
-
diff --git a/ml-accelerator/src/main/scala/breeze/optimize/OWLQNX.scala b/ml-accelerator/src/main/scala/breeze/optimize/OWLQNX.scala
deleted file mode 100644
index 8e55560..0000000
--- a/ml-accelerator/src/main/scala/breeze/optimize/OWLQNX.scala
+++ /dev/null
@@ -1,97 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-
-package breeze.optimize
-
-import breeze.math._
-import breeze.numerics._
-import breeze.util._
-
-/**
- * Implements the Orthant-wise Limited Memory QuasiNewton method,
- * which is a variant of LBFGS that handles L1 regularization.
- *
- * Paper is Andrew and Gao (2007) Scalable Training of L1-Regularized Log-Linear Models
- *
- * @author dlwh
- */
-class OWLQNX[K, T](maxIter: Int, m: Int, l1reg: K => Double, tolerance: Double)
- (implicit space: MutableEnumeratedCoordinateField[T, K, Double])
- extends LBFGSX[T](maxIter, m, tolerance = tolerance) with SerializableLogging {
-
- def this(maxIter: Int, m: Int, l1reg: K => Double)
- (implicit space: MutableEnumeratedCoordinateField[T, K, Double])
- = this(maxIter, m, l1reg, 1E-8)
-
- def this(maxIter: Int, m: Int, l1reg: Double, tolerance: Double = 1E-8)
- (implicit space: MutableEnumeratedCoordinateField[T, K, Double])
- = this(maxIter, m, (_: K) => l1reg, tolerance)
-
- def this(maxIter: Int, m: Int, l1reg: Double)
- (implicit space: MutableEnumeratedCoordinateField[T, K, Double])
- = this(maxIter, m, (_: K) => l1reg, 1E-8)
-
- def this(maxIter: Int, m: Int)(implicit space: MutableEnumeratedCoordinateField[T, K, Double])
- = this(maxIter, m, (_: K) => 1.0, 1E-8)
-
- require(m > 0)
-
- import space._
-
- override def chooseDescentDirection(state: State, fn: DiffFunction[T]): T = {
- val descentDir = super.chooseDescentDirection(state.copy(grad = state.adjustedGradient), fn)
- val correctedDir = space.zipMapValues.map(descentDir, state.adjustedGradient, { case (d, g)
- => if (d * g < 0) d else 0.0 })
-
- correctedDir
- }
-
-
- // projects x to be on the same orthant as y
- // this basically requires that x'_i = x_i if sign(x_i) == sign(y_i), and 0 otherwise.
-
- override def takeStep(state: State, dir: T, stepSize: Double): T = {
- val stepped = state.x + dir * stepSize
- val orthant = computeOrthant(state.x, state.adjustedGradient)
- space.zipMapValues.map(stepped, orthant, { case (v, ov) =>
- v * I(math.signum(v) == math.signum(ov))
- })
- }
-
- // Adds in the regularization stuff to the gradient
- override def adjust(newX: T, newGrad: T, newVal: Double): (Double, T) = {
- var adjValue = newVal
- val res = space.zipMapKeyValues.mapActive(newX, newGrad, {case (i, xv, v) =>
- val l1regValue = l1reg(i)
- require(l1regValue >= 0.0)
-
- if(l1regValue == 0.0) {
- v
- } else {
- adjValue += Math.abs(l1regValue * xv)
- xv match {
- case 0.0 =>
- val delta_+ = v + l1regValue
- val delta_- = v - l1regValue
- if (delta_- > 0) delta_- else if (delta_+ < 0) delta_+ else 0.0
- case _ => v + math.signum(xv) * l1regValue
- }
- }
- })
- adjValue -> res
- }
-
- private def computeOrthant(x: T, grad: T) = {
- val orth = space.zipMapValues.map(x, grad, {case (v, gv) =>
- if (v != 0) math.signum(v)
- else math.signum(-gv)
- })
- orth
- }
-
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/DecisionTreeClassifier.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/DecisionTreeClassifier.scala
deleted file mode 100644
index 53ee5ee..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/DecisionTreeClassifier.scala
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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 org.apache.spark.annotation.Since
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.linalg.Vector
-import org.apache.spark.ml.param.ParamMap
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.DecisionForest
-import org.apache.spark.ml.util._
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo, Strategy => OldStrategy}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.Dataset
-
-
-/**
- * Decision tree learning algorithm (http://en.wikipedia.org/wiki/Decision_tree_learning)
- * for classification.
- * It supports both binary and multiclass labels, as well as both continuous and categorical
- * features.
- */
-@Since("1.4.0")
-class DecisionTreeClassifier @Since("1.4.0") (
- @Since("1.4.0") override val uid: String)
- extends ProbabilisticClassifier[Vector, DecisionTreeClassifier, DecisionTreeClassificationModel]
- with DecisionTreeClassifierParams with DefaultParamsWritable {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("dtc"))
-
- // Override parameter setters from parent trait for Java API compatibility.
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxDepth(value: Int): this.type = set(maxDepth, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxBins(value: Int): this.type = set(maxBins, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInstancesPerNode(value: Int): this.type = set(minInstancesPerNode, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInfoGain(value: Double): this.type = set(minInfoGain, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setMaxMemoryInMB(value: Int): this.type = set(maxMemoryInMB, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setCacheNodeIds(value: Boolean): this.type = set(cacheNodeIds, value)
-
- /**
- * Specifies how often to checkpoint the cached node IDs.
- * E.g. 10 means that the cache will get checkpointed every 10 iterations.
- * This is only used if cacheNodeIds is true and if the checkpoint directory is set in
- * [[org.apache.spark.SparkContext]].
- * Must be at least 1.
- * (default = 10)
- * @group setParam
- */
- @Since("1.4.0")
- override def setCheckpointInterval(value: Int): this.type = set(checkpointInterval, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setImpurity(value: String): this.type = set(impurity, value)
-
- /** @group setParam */
- @Since("1.6.0")
- override def setSeed(value: Long): this.type = set(seed, value)
-
- override protected def train(dataset: Dataset[_]): DecisionTreeClassificationModel = {
- val categoricalFeatures: Map[Int, Int] =
- MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
- val numClasses: Int = getNumClasses(dataset)
-
- if (isDefined(thresholds)) {
- require($(thresholds).length == numClasses, this.getClass.getSimpleName +
- ".train() called with non-matching numClasses and thresholds.length." +
- s" numClasses=$numClasses, but thresholds has length ${$(thresholds).length}")
- }
-
- val oldDataset: RDD[LabeledPoint] = extractLabeledPoints(dataset, numClasses)
- val strategy = getOldStrategy(categoricalFeatures, numClasses)
-
- val instr = Instrumentation.create(this, oldDataset)
- instr.logParams(params: _*)
-
- val trees = DecisionForest.run(oldDataset, strategy, numTrees = 1,
- featureSubsetStrategy = "all",
- seed = $(seed), instr = Some(instr), parentUID = Some(uid))
-
- val m = trees.head.asInstanceOf[DecisionTreeClassificationModel]
- instr.logSuccess(m)
- m
- }
-
- /** (private[ml]) Train a decision tree on an RDD */
- private[ml] def train(data: RDD[LabeledPoint],
- oldStrategy: OldStrategy): DecisionTreeClassificationModel = {
- val instr = Instrumentation.create(this, data)
- instr.logParams(params: _*)
-
- val trees = DecisionForest.run(data, oldStrategy, numTrees = 1,
- featureSubsetStrategy = "all",
- seed = 0L, instr = Some(instr), parentUID = Some(uid))
-
- val m = trees.head.asInstanceOf[DecisionTreeClassificationModel]
- instr.logSuccess(m)
- m
- }
-
- /** (private[ml]) Create a Strategy instance to use with the old API. */
- private[ml] def getOldStrategy(
- categoricalFeatures: Map[Int, Int],
- numClasses: Int): OldStrategy = {
- super.getOldStrategy(categoricalFeatures, numClasses, OldAlgo.Classification, getOldImpurity,
- subsamplingRate = 1.0)
- }
-
- @Since("1.4.1")
- override def copy(extra: ParamMap): DecisionTreeClassifier = defaultCopy(extra)
-}
-
-@Since("1.4.0")
-object DecisionTreeClassifier extends DefaultParamsReadable[DecisionTreeClassifier] {
- /** Accessor for supported impurities: entropy, gini */
- @Since("1.4.0")
- final val supportedImpurities: Array[String] = TreeClassifierParams.supportedImpurities
-
- @Since("2.0.0")
- override def load(path: String): DecisionTreeClassifier = super.load(path)
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala
deleted file mode 100644
index 9b62352..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/GBTClassifier.scala
+++ /dev/null
@@ -1,423 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.json4s.{DefaultFormats, JObject}
-import org.json4s.JsonDSL._
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.linalg.{DenseVector, SparseVector, Vector, Vectors}
-import org.apache.spark.ml.param.ParamMap
-import org.apache.spark.ml.regression.DecisionTreeRegressionModel
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.GradientBoostedTrees
-import org.apache.spark.ml.util._
-import org.apache.spark.ml.util.DefaultParamsReader.Metadata
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo}
-import org.apache.spark.mllib.tree.model.{GradientBoostedTreesModel => OldGBTModel}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{DataFrame, Dataset, Row}
-import org.apache.spark.sql.functions._
-
-/**
- * Gradient-Boosted Trees (GBTs) (http://en.wikipedia.org/wiki/Gradient_boosting)
- * learning algorithm for classification.
- * It supports binary labels, as well as both continuous and categorical features.
- *
- * The implementation is based upon: J.H. Friedman. "Stochastic Gradient Boosting." 1999.
- *
- * Notes on Gradient Boosting vs. TreeBoost:
- * - This implementation is for Stochastic Gradient Boosting, not for TreeBoost.
- * - Both algorithms learn tree ensembles by minimizing loss functions.
- * - TreeBoost (Friedman, 1999) additionally modifies the outputs at tree leaf nodes
- * based on the loss function, whereas the original gradient boosting method does not.
- * - We expect to implement TreeBoost in the future:
- * [https://issues.apache.org/jira/browse/SPARK-4240]
- *
- * @note Multiclass labels are not currently supported.
- */
-@Since("1.4.0")
-class GBTClassifier @Since("1.4.0") (
- @Since("1.4.0") override val uid: String)
- extends ProbabilisticClassifier[Vector, GBTClassifier, GBTClassificationModel]
- with GBTClassifierParams with DefaultParamsWritable with Logging {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("gbtc"))
-
- // Override parameter setters from parent trait for Java API compatibility.
-
- // Parameters from TreeClassifierParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxDepth(value: Int): this.type = set(maxDepth, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxBins(value: Int): this.type = set(maxBins, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInstancesPerNode(value: Int): this.type = set(minInstancesPerNode, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInfoGain(value: Double): this.type = set(minInfoGain, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setMaxMemoryInMB(value: Int): this.type = set(maxMemoryInMB, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setCacheNodeIds(value: Boolean): this.type = set(cacheNodeIds, value)
-
- /**
- * Specifies how often to checkpoint the cached node IDs.
- * E.g. 10 means that the cache will get checkpointed every 10 iterations.
- * This is only used if cacheNodeIds is true and if the checkpoint directory is set in
- * [[org.apache.spark.SparkContext]].
- * Must be at least 1.
- * (default = 10)
- * @group setParam
- */
- @Since("1.4.0")
- override def setCheckpointInterval(value: Int): this.type = set(checkpointInterval, value)
-
- /**
- * The impurity setting is ignored for GBT models.
- * Individual trees are built using impurity "Variance."
- *
- * @group setParam
- */
- @Since("1.4.0")
- override def setImpurity(value: String): this.type = {
- logWarning("GBTClassifier.setImpurity should NOT be used")
- this
- }
-
- // Parameters from TreeEnsembleParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSubsamplingRate(value: Double): this.type = set(subsamplingRate, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSeed(value: Long): this.type = set(seed, value)
-
- // Parameters from GBTParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxIter(value: Int): this.type = set(maxIter, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setStepSize(value: Double): this.type = set(stepSize, value)
-
- /** @group setParam */
- @Since("2.3.0")
- override def setFeatureSubsetStrategy(value: String): this.type =
- set(featureSubsetStrategy, value)
-
- // Parameters from GBTClassifierParams:
-
- /** @group setParam */
- @Since("1.4.0")
- def setLossType(value: String): this.type = set(lossType, value)
-
- override protected def train(dataset: Dataset[_]): GBTClassificationModel = {
- val categoricalFeatures: Map[Int, Int] =
- MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
- // We copy and modify this from Classifier.extractLabeledPoints since GBT only supports
- // 2 classes now. This lets us provide a more precise error message.
- val oldDataset: RDD[LabeledPoint] =
- dataset.select(col($(labelCol)), col($(featuresCol))).rdd.map {
- case Row(label: Double, features: Vector) =>
- require(label == 0 || label == 1, s"GBTClassifier was given" +
- s" dataset with invalid label $label. Labels must be in {0,1}; note that" +
- s" GBTClassifier currently only supports binary classification.")
- LabeledPoint(label, features)
- }
- val numFeatures = oldDataset.first().features.size
- val boostingStrategy = super.getOldBoostingStrategy(categoricalFeatures, OldAlgo.Classification)
-
- val numClasses = 2
- if (isDefined(thresholds)) {
- require($(thresholds).length == numClasses, this.getClass.getSimpleName +
- ".train() called with non-matching numClasses and thresholds.length." +
- s" numClasses=$numClasses, but thresholds has length ${$(thresholds).length}")
- }
-
- val instr = Instrumentation.create(this, oldDataset)
- instr.logParams(labelCol, featuresCol, predictionCol, impurity, lossType,
- maxDepth, maxBins, maxIter, maxMemoryInMB, minInfoGain, minInstancesPerNode,
- seed, stepSize, subsamplingRate, cacheNodeIds, checkpointInterval, featureSubsetStrategy)
- instr.logNumFeatures(numFeatures)
- instr.logNumClasses(numClasses)
-
- val (doUseAcc, setUseAccFlag) = super.getDoUseAcc
- val (baseLearners, learnerWeights) = if (setUseAccFlag) {
- GradientBoostedTrees.run(oldDataset, boostingStrategy,
- $(seed), $(featureSubsetStrategy), doUseAcc)
- } else {
- GradientBoostedTrees.run(oldDataset, boostingStrategy,
- $(seed), $(featureSubsetStrategy))
- }
-
- val m = new GBTClassificationModel(uid, baseLearners, learnerWeights, numFeatures)
- instr.logSuccess(m)
- m
- }
-
- @Since("1.4.1")
- override def copy(extra: ParamMap): GBTClassifier = defaultCopy(extra)
-}
-
-@Since("1.4.0")
-object GBTClassifier extends DefaultParamsReadable[GBTClassifier] {
-
- /** Accessor for supported loss settings: logistic */
- @Since("1.4.0")
- final val supportedLossTypes: Array[String] = GBTClassifierParams.supportedLossTypes
-
- @Since("2.0.0")
- override def load(path: String): GBTClassifier = super.load(path)
-}
-
-/**
- * Gradient-Boosted Trees (GBTs) (http://en.wikipedia.org/wiki/Gradient_boosting)
- * model for classification.
- * It supports binary labels, as well as both continuous and categorical features.
- *
- * @param _trees Decision trees in the ensemble.
- * @param _treeWeights Weights for the decision trees in the ensemble.
- *
- * @note Multiclass labels are not currently supported.
- */
-@Since("1.6.0")
-class GBTClassificationModel private[ml](
- @Since("1.6.0") override val uid: String,
- private val _trees: Array[DecisionTreeRegressionModel],
- private val _treeWeights: Array[Double],
- @Since("1.6.0") override val numFeatures: Int,
- @Since("2.2.0") override val numClasses: Int)
- extends ProbabilisticClassificationModel[Vector, GBTClassificationModel]
- with GBTClassifierParams with TreeEnsembleModel[DecisionTreeRegressionModel]
- with MLWritable with Serializable {
-
- require(_trees.nonEmpty, "GBTClassificationModel requires at least 1 tree.")
- require(_trees.length == _treeWeights.length, "GBTClassificationModel given trees, treeWeights" +
- s" of non-matching lengths (${_trees.length}, ${_treeWeights.length}, respectively).")
-
- /**
- * Construct a GBTClassificationModel
- *
- * @param _trees Decision trees in the ensemble.
- * @param _treeWeights Weights for the decision trees in the ensemble.
- * @param numFeatures The number of features.
- */
- private[ml] def this(
- uid: String,
- _trees: Array[DecisionTreeRegressionModel],
- _treeWeights: Array[Double],
- numFeatures: Int) =
- this(uid, _trees, _treeWeights, numFeatures, 2)
-
- /**
- * Construct a GBTClassificationModel
- *
- * @param _trees Decision trees in the ensemble.
- * @param _treeWeights Weights for the decision trees in the ensemble.
- */
- @Since("1.6.0")
- def this(uid: String, _trees: Array[DecisionTreeRegressionModel], _treeWeights: Array[Double]) =
- this(uid, _trees, _treeWeights, -1, 2)
-
- @Since("1.4.0")
- override def trees: Array[DecisionTreeRegressionModel] = _trees
-
- /**
- * Number of trees in ensemble
- */
- @Since("2.0.0")
- val getNumTrees: Int = trees.length
-
- @Since("1.4.0")
- override def treeWeights: Array[Double] = _treeWeights
-
- override protected def transformImpl(dataset: Dataset[_]): DataFrame = {
- val bcastModel = dataset.sparkSession.sparkContext.broadcast(this)
- val predictUDF = udf { (features: Any) =>
- bcastModel.value.predict(features.asInstanceOf[Vector])
- }
- dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
- }
-
- override protected def predict(features: Vector): Double = {
- // If thresholds defined, use predictRaw to get probabilities, otherwise use optimization
- if (isDefined(thresholds)) {
- super.predict(features)
- } else {
- if (margin(features) > 0.0) 1.0 else 0.0
- }
- }
-
- override protected def predictRaw(features: Vector): Vector = {
- val prediction: Double = margin(features)
- Vectors.dense(Array(-prediction, prediction))
- }
-
- override protected def raw2probabilityInPlace(rawPrediction: Vector): Vector = {
- rawPrediction match {
- case dv: DenseVector =>
- dv.values(0) = loss.computeProbability(dv.values(0))
- dv.values(1) = 1.0 - dv.values(0)
- dv
- case sv: SparseVector =>
- throw new RuntimeException("Unexpected error in GBTClassificationModel:" +
- " raw2probabilityInPlace encountered SparseVector")
- }
- }
-
- /** Number of trees in ensemble */
- val numTrees: Int = trees.length
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): GBTClassificationModel = {
- copyValues(new GBTClassificationModel(uid, _trees, _treeWeights, numFeatures, numClasses),
- extra).setParent(parent)
- }
-
- @Since("1.4.0")
- override def toString: String = {
- s"GBTClassificationModel (uid=$uid) with $numTrees trees"
- }
-
- /**
- * Estimate of the importance of each feature.
- *
- * Each feature's importance is the average of its importance across all trees in the ensemble
- * The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
- * (Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
- * and follows the implementation from scikit-learn.
-
- * See `DecisionTreeClassificationModel.featureImportances`
- */
- @Since("2.0.0")
- lazy val featureImportances: Vector = TreeEnsembleModel.featureImportances(trees, numFeatures)
-
- /** Raw prediction for the positive class. */
- private def margin(features: Vector): Double = {
- val treePredictions = _trees.map(_.rootNode.predictImpl(features).prediction)
- blas.ddot(numTrees, treePredictions, 1, _treeWeights, 1)
- }
-
- /** (private[ml]) Convert to a model in the old API */
- private[ml] def toOld: OldGBTModel = {
- new OldGBTModel(OldAlgo.Classification, _trees.map(_.toOld), _treeWeights)
- }
-
- // hard coded loss, which is not meant to be changed in the model
- private val loss = getOldLossType
-
- @Since("2.0.0")
- override def write: MLWriter = new GBTClassificationModel.GBTClassificationModelWriter(this)
-}
-
-@Since("2.0.0")
-object GBTClassificationModel extends MLReadable[GBTClassificationModel] {
-
- private val numFeaturesKey: String = "numFeatures"
- private val numTreesKey: String = "numTrees"
-
- @Since("2.0.0")
- override def read: MLReader[GBTClassificationModel] = new GBTClassificationModelReader
-
- @Since("2.0.0")
- override def load(path: String): GBTClassificationModel = super.load(path)
-
- private[GBTClassificationModel]
- class GBTClassificationModelWriter(instance: GBTClassificationModel) extends MLWriter {
-
- override protected def saveImpl(path: String): Unit = {
-
- val extraMetadata: JObject = Map(
- numFeaturesKey -> instance.numFeatures,
- numTreesKey -> instance.getNumTrees)
- EnsembleModelReadWrite.saveImpl(instance, path, sparkSession, extraMetadata)
- }
- }
-
- private class GBTClassificationModelReader extends MLReader[GBTClassificationModel] {
-
- /** Checked against metadata when loading model */
- private val className = classOf[GBTClassificationModel].getName
- private val treeClassName = classOf[DecisionTreeRegressionModel].getName
-
- override def load(path: String): GBTClassificationModel = {
- implicit val format = DefaultFormats
- val (metadata: Metadata, treesData: Array[(Metadata, Node)], treeWeights: Array[Double]) =
- EnsembleModelReadWrite.loadImpl(path, sparkSession, className, treeClassName)
- val numFeatures = (metadata.metadata \ numFeaturesKey).extract[Int]
- val numTrees = (metadata.metadata \ numTreesKey).extract[Int]
-
- val trees: Array[DecisionTreeRegressionModel] = treesData.map {
- case (treeMetadata, root) =>
- val tree =
- new DecisionTreeRegressionModel(treeMetadata.uid, root, numFeatures)
- DefaultParamsReader.getAndSetParams(tree, treeMetadata)
- tree
- }
- require(numTrees == trees.length, s"GBTClassificationModel.load expected $numTrees" +
- s" trees based on metadata but found ${trees.length} trees.")
- val model = new GBTClassificationModel(metadata.uid,
- trees, treeWeights, numFeatures)
- DefaultParamsReader.getAndSetParams(model, metadata)
- model
- }
- }
-
- /** Convert a model from the old API */
- private[ml] def fromOld(
- oldModel: OldGBTModel,
- parent: GBTClassifier,
- categoricalFeatures: Map[Int, Int],
- numFeatures: Int = -1,
- numClasses: Int = 2): GBTClassificationModel = {
- require(oldModel.algo == OldAlgo.Classification, "Cannot convert GradientBoostedTreesModel" +
- s" with algo=${oldModel.algo} (old API) to GBTClassificationModel (new API).")
- val newTrees = oldModel.trees.map { tree =>
- // parent for each tree is null since there is no good way to set this.
- DecisionTreeRegressionModel.fromOld(tree, null, categoricalFeatures)
- }
- val uid = if (parent != null) parent.uid else Identifiable.randomUID("gbtc")
- new GBTClassificationModel(uid, newTrees, oldModel.treeWeights, numFeatures, numClasses)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/LinearSVC.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/LinearSVC.scala
deleted file mode 100644
index 6689c08..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/LinearSVC.scala
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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 scala.collection.mutable
-
-import breeze.linalg.{DenseVector => BDV}
-import breeze.optimize.{CachedDiffFunction, OWLQNX => BreezeOWLQN}
-
-import org.apache.spark.SparkException
-import org.apache.spark.annotation.{Experimental, Since}
-import org.apache.spark.ml.StaticUtils
-import org.apache.spark.ml.feature.Instance
-import org.apache.spark.ml.linalg._
-import org.apache.spark.ml.optim.aggregator.HingeAggregatorX
-import org.apache.spark.ml.optim.loss.{L2Regularization, RDDLossFunctionX}
-import org.apache.spark.ml.param._
-import org.apache.spark.ml.util._
-import org.apache.spark.mllib.linalg.VectorImplicits._
-import org.apache.spark.mllib.stat.MultivariateOnlineSummarizer
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{Dataset, Row}
-import org.apache.spark.sql.functions.{col, lit}
-
-
-
-/**
- * :: Experimental ::
- *
- *
- * Linear SVM Classifier
- *
- * This binary classifier optimizes the Hinge Loss using the OWLQN optimizer.
- * Only supports L2 regularization currently.
- *
- */
-@Since("2.2.0")
-@Experimental
-class LinearSVC @Since("2.2.0") (
- @Since("2.2.0") override val uid: String)
- extends Classifier[Vector, LinearSVC, LinearSVCModel]
- with LinearSVCParams with DefaultParamsWritable {
-
- @Since("2.2.0")
- def this() = this(Identifiable.randomUID("linearsvc"))
-
- /**
- * Set the regularization parameter.
- * Default is 0.0.
- *
- * @group setParam
- */
-
-
- var ic = 0.5
- var iters = -1
- def setIc(a: Double): Unit = {
- this.ic = a
- }
-
- @Since("2.2.0")
- def setRegParam(value: Double): this.type = set(regParam, value)
- setDefault(regParam -> 0.0)
-
- /**
- * Set the maximum number of iterations.
- * Default is 100.
- *
- * @group setParam
- */
- @Since("2.2.0")
- def setMaxIter(value: Int): this.type = set(maxIter, value)
- setDefault(maxIter -> 100)
-
- /**
- * Whether to fit an intercept term.
- * Default is true.
- *
- * @group setParam
- */
- @Since("2.2.0")
- def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
- setDefault(fitIntercept -> true)
-
- /**
- * Set the convergence tolerance of iterations.
- * Smaller values will lead to higher accuracy at the cost of more iterations.
- * Default is 1E-6.
- *
- * @group setParam
- */
- @Since("2.2.0")
- def setTol(value: Double): this.type = set(tol, value)
- setDefault(tol -> 0.0)
-
- /**
- * Whether to standardize the training features before fitting the model.
- * Default is true.
- *
- * @group setParam
- */
- @Since("2.2.0")
- def setStandardization(value: Boolean): this.type = set(standardization, value)
- setDefault(standardization -> true)
-
- /**
- * Set the value of param [[weightCol]].
- * If this is not set or empty, we treat all instance weights as 1.0.
- * Default is not set, so all instances have weight one.
- *
- * @group setParam
- */
- @Since("2.2.0")
- def setWeightCol(value: String): this.type = set(weightCol, value)
-
- /**
- * Set threshold in binary classification.
- *
- * @group setParam
- */
- @Since("2.2.0")
- def setThreshold(value: Double): this.type = set(threshold, value)
- setDefault(threshold -> 0.0)
-
- /**
- * Suggested depth for treeAggregate (greater than or equal to 2).
- * If the dimensions of features or the number of partitions are large,
- * this param could be adjusted to a larger size.
- * Default is 2.
- *
- * @group expertSetParam
- */
- @Since("2.2.0")
- def setAggregationDepth(value: Int): this.type = set(aggregationDepth, value)
- setDefault(aggregationDepth -> 2)
-
- @Since("2.2.0")
- override def copy(extra: ParamMap): LinearSVC = defaultCopy(extra)
-
- override protected def train(dataset: Dataset[_]): LinearSVCModel = {
- val w = if (!isDefined(weightCol) || $(weightCol).isEmpty) lit(1.0) else col($(weightCol))
- val instances: RDD[Instance] =
- dataset.select(col($(labelCol)), w, col($(featuresCol))).rdd.map {
- case Row(label: Double, weight: Double, features: Vector) =>
- Instance(label, weight, features)
- }
-
- val instr = Instrumentation.create(this, instances)
- instr.logParams(regParam, maxIter, fitIntercept, tol, standardization, threshold,
- aggregationDepth)
-
- val (summarizer, labelSummarizer) = {
- val seqOp = (c: (MultivariateOnlineSummarizer, MultiClassSummarizer),
- instance: Instance) => {
- (c._1.add(instance.features, instance.weight),
- c._2.add(instance.label, instance.weight + StaticUtils.ZERO_DOUBLE))
- }
-
- val combOp = (c1: (MultivariateOnlineSummarizer, MultiClassSummarizer),
- c2: (MultivariateOnlineSummarizer, MultiClassSummarizer)) =>
- (c1._1.merge(c2._1), c1._2.merge(c2._2))
-
- instances.treeAggregate(
- (new MultivariateOnlineSummarizer, new MultiClassSummarizer)
- )(seqOp, combOp, $(aggregationDepth))
- }
-
- val histogram = labelSummarizer.histogram
- val numInvalid = labelSummarizer.countInvalid
- val numFeatures = summarizer.mean.size
- val numFeaturesPlusIntercept = if (getFitIntercept) numFeatures + 1 else numFeatures
-
- val numClasses = MetadataUtils.getNumClasses(dataset.schema($(labelCol))) match {
- case Some(n: Int) =>
- require(n >= histogram.length, s"Specified number of classes $n was " +
- s"less than the number of unique labels ${histogram.length}.")
- n
- case None => histogram.length
- }
- require(numClasses == 2, s"LinearSVC only supports binary classification." +
- s" $numClasses classes detected in $labelCol")
- instr.logNumClasses(numClasses)
- instr.logNumFeatures(numFeatures)
-
- val (coefficientVector, interceptVector, objectiveHistory) = {
- if (numInvalid != 0) {
- val msg = s"Classification labels should be in [0 to ${numClasses - 1}]. " +
- s"Found $numInvalid invalid labels."
- logError(msg)
- throw new SparkException(msg)
- }
-
- val featuresStd = summarizer.variance.toArray.map(math.sqrt)
- val getFeaturesStd = (j: Int) => featuresStd(j)
- val regParamL2 = $(regParam)
- val bcFeaturesStd = instances.context.broadcast(featuresStd.map{t => if (t!=0.0)1/t else 0.0})
- val regularization = if (regParamL2 != 0.0) {
- val shouldApply = (idx: Int) => idx >= 0 && idx < numFeatures
- Some(new L2Regularization(regParamL2, shouldApply,
- if ($(standardization)) None else Some(getFeaturesStd)))
- } else {
- None
- }
-
- val getAggregatorFunc = new HingeAggregatorX(bcFeaturesStd, $(fitIntercept))(_)
- val costFun = new RDDLossFunctionX(instances, getAggregatorFunc, regularization,
- $(aggregationDepth))
-
- def regParamL1Fun = (index: Int) => 0D
- val optimizer = new BreezeOWLQN[Int, BDV[Double]]($(maxIter), 10, regParamL1Fun, $(tol))
-
- var u = ic
- try {
- u = instances.sparkContext.getConf
- .getDouble("spark.boostkit.LinearSVC.inertiaCoefficient", ic)
- if (u < 0.0) {
- throw new Exception
- }
- }
- catch {
- case x: Exception =>
- throw new Exception("'spark.boostkit.LinearSVC.inertiaCoefficient' value is invalid")
- }
- this.ic = u
-
- optimizer.setInertiaCoefficient(ic)
- val initialCoefWithIntercept = Vectors.zeros(numFeaturesPlusIntercept)
-
- val states = optimizer.iterations(new CachedDiffFunction(costFun),
- initialCoefWithIntercept.asBreeze.toDenseVector)
-
- val scaledObjectiveHistory = mutable.ArrayBuilder.make[Double]
- var state: optimizer.State = null
- while (states.hasNext) {
- state = states.next()
- scaledObjectiveHistory += state.adjustedValue
- iters += 1
- }
-
- bcFeaturesStd.destroy(blocking = false)
- if (state == null) {
- val msg = s"${optimizer.getClass.getName} failed."
- logError(msg)
- throw new SparkException(msg)
- }
-
- /*
- The coefficients are trained in the scaled space; we're converting them back to
- the original space.
- Note that the intercept in scaled space and original space is the same;
- as a result, no scaling is needed.
- */
- val rawCoefficients = state.x.toArray
- val coefficientArray = Array.tabulate(numFeatures) { i =>
- if (featuresStd(i) != 0.0) {
- rawCoefficients(i) / featuresStd(i)
- } else {
- 0.0
- }
- }
-
- val intercept = if ($(fitIntercept)) {
- rawCoefficients(numFeaturesPlusIntercept - 1)
- } else {
- 0.0
- }
- (Vectors.dense(coefficientArray), intercept, scaledObjectiveHistory.result())
- }
-
- val model = copyValues(new LinearSVCModel(uid, coefficientVector, interceptVector))
- instr.logSuccess(model)
- model
- }
-
- def getIters: Int = iters
-}
-
-@Since("2.2.0")
-object LinearSVC extends DefaultParamsReadable[LinearSVC] {
-
- @Since("2.2.0")
- override def load(path: String): LinearSVC = super.load(path)
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/LogisticRegression.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/LogisticRegression.scala
deleted file mode 100644
index a47a709..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/LogisticRegression.scala
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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 java.util.Locale
-
-import scala.collection.mutable
-
-import breeze.linalg.{DenseVector => BDV}
-import breeze.optimize.{CachedDiffFunction, LBFGSL, OWLQNL}
-
-import org.apache.spark.SparkException
-import org.apache.spark.annotation.Since
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.StaticUtils
-import org.apache.spark.ml.feature.Instance
-import org.apache.spark.ml.linalg._
-import org.apache.spark.ml.optim.aggregator.LogisticAggregatorX
-import org.apache.spark.ml.optim.loss.{L2Regularization, RDDLossFunctionX}
-import org.apache.spark.ml.param._
-import org.apache.spark.ml.util._
-import org.apache.spark.mllib.linalg.VectorImplicits._
-import org.apache.spark.mllib.stat.MultivariateOnlineSummarizer
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{Dataset, Row}
-import org.apache.spark.sql.functions.{col, lit}
-import org.apache.spark.storage.StorageLevel
-
-/**
- * Logistic regression. Supports:
- * - Multinomial logistic (softmax) regression.
- * - Binomial logistic regression.
- *
- * This class supports fitting traditional logistic regression model by LBFGS/OWLQN and
- * bound (box) constrained logistic regression model by LBFGSB.
- */
-@Since("1.2.0")
-class LogisticRegression @Since("1.2.0") (
- @Since("1.4.0") override val uid: String)
- extends ProbabilisticClassifier[Vector, LogisticRegression, LogisticRegressionModel]
- with LogisticRegressionParams with DefaultParamsWritable with Logging {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("logreg"))
-
- /**
- * Set the regularization parameter.
- * Default is 0.0.
- *
- * @group setParam
- */
- @Since("1.2.0")
- def setRegParam(value: Double): this.type = set(regParam, value)
- setDefault(regParam -> 0.0)
-
- /**
- * Set the ElasticNet mixing parameter.
- * For alpha = 0, the penalty is an L2 penalty.
- * For alpha = 1, it is an L1 penalty.
- * For alpha in (0,1), the penalty is a combination of L1 and L2.
- * Default is 0.0 which is an L2 penalty.
- *
- * Note: Fitting under bound constrained optimization only supports L2 regularization,
- * so throws exception if this param is non-zero value.
- *
- * @group setParam
- */
- @Since("1.4.0")
- def setElasticNetParam(value: Double): this.type = set(elasticNetParam, value)
- setDefault(elasticNetParam -> 0.0)
-
- /**
- * Set the maximum number of iterations.
- * Default is 100.
- *
- * @group setParam
- */
- @Since("1.2.0")
- def setMaxIter(value: Int): this.type = set(maxIter, value)
- setDefault(maxIter -> 100)
-
- /**
- * Set the convergence tolerance of iterations.
- * Smaller value will lead to higher accuracy at the cost of more iterations.
- * Default is 1E-6.
- *
- * @group setParam
- */
- @Since("1.4.0")
- def setTol(value: Double): this.type = set(tol, value)
- setDefault(tol -> 1E-6)
-
- /**
- * Whether to fit an intercept term.
- * Default is true.
- *
- * @group setParam
- */
- @Since("1.4.0")
- def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
- setDefault(fitIntercept -> true)
-
- /**
- * Sets the value of param [[family]].
- * Default is "auto".
- *
- * @group setParam
- */
- @Since("2.1.0")
- def setFamily(value: String): this.type = set(family, value)
- setDefault(family -> "auto")
-
- /**
- * Whether to standardize the training features before fitting the model.
- * The coefficients of models will be always returned on the original scale,
- * so it will be transparent for users. Note that with/without standardization,
- * the models should be always converged to the same solution when no regularization
- * is applied. In R's GLMNET package, the default behavior is true as well.
- * Default is true.
- *
- * @group setParam
- */
- @Since("1.5.0")
- def setStandardization(value: Boolean): this.type = set(standardization, value)
- setDefault(standardization -> true)
-
- @Since("1.5.0")
- override def setThreshold(value: Double): this.type = super.setThreshold(value)
- setDefault(threshold -> 0.5)
-
- @Since("1.5.0")
- override def getThreshold: Double = super.getThreshold
-
- /**
- * Sets the value of param [[weightCol]].
- * If this is not set or empty, we treat all instance weights as 1.0.
- * Default is not set, so all instances have weight one.
- *
- * @group setParam
- */
- @Since("1.6.0")
- def setWeightCol(value: String): this.type = set(weightCol, value)
-
- @Since("1.5.0")
- override def setThresholds(value: Array[Double]): this.type = super.setThresholds(value)
-
- @Since("1.5.0")
- override def getThresholds: Array[Double] = super.getThresholds
-
- /**
- * Suggested depth for treeAggregate (greater than or equal to 2).
- * If the dimensions of features or the number of partitions are large,
- * this param could be adjusted to a larger size.
- * Default is 2.
- *
- * @group expertSetParam
- */
- @Since("2.1.0")
- def setAggregationDepth(value: Int): this.type = set(aggregationDepth, value)
- setDefault(aggregationDepth -> 2)
-
- /**
- * Set the lower bounds on coefficients if fitting under bound constrained optimization.
- *
- * @group expertSetParam
- */
- @Since("2.2.0")
- def setLowerBoundsOnCoefficients(value: Matrix): this.type = set(lowerBoundsOnCoefficients, value)
-
- /**
- * Set the upper bounds on coefficients if fitting under bound constrained optimization.
- *
- * @group expertSetParam
- */
- @Since("2.2.0")
- def setUpperBoundsOnCoefficients(value: Matrix): this.type = set(upperBoundsOnCoefficients, value)
-
- /**
- * Set the lower bounds on intercepts if fitting under bound constrained optimization.
- *
- * @group expertSetParam
- */
- @Since("2.2.0")
- def setLowerBoundsOnIntercepts(value: Vector): this.type = set(lowerBoundsOnIntercepts, value)
-
- /**
- * Set the upper bounds on intercepts if fitting under bound constrained optimization.
- *
- * @group expertSetParam
- */
- @Since("2.2.0")
- def setUpperBoundsOnIntercepts(value: Vector): this.type = set(upperBoundsOnIntercepts, value)
-
- private def assertBoundConstrainedOptimizationParamsValid(
- numCoefficientSets: Int,
- numFeatures: Int): Unit = {
- if (isSet(lowerBoundsOnCoefficients)) {
- require($(lowerBoundsOnCoefficients).numRows == numCoefficientSets &&
- $(lowerBoundsOnCoefficients).numCols == numFeatures,
- "The shape of LowerBoundsOnCoefficients must be compatible with (1, number of features) " +
- "for binomial regression, or (number of classes, number of features) for multinomial " +
- "regression, but found: " +
- s"(${getLowerBoundsOnCoefficients.numRows}, ${getLowerBoundsOnCoefficients.numCols}).")
- }
- if (isSet(upperBoundsOnCoefficients)) {
- require($(upperBoundsOnCoefficients).numRows == numCoefficientSets &&
- $(upperBoundsOnCoefficients).numCols == numFeatures,
- "The shape of upperBoundsOnCoefficients must be compatible with (1, number of features) " +
- "for binomial regression, or (number of classes, number of features) for multinomial " +
- "regression, but found: " +
- s"(${getUpperBoundsOnCoefficients.numRows}, ${getUpperBoundsOnCoefficients.numCols}).")
- }
- if (isSet(lowerBoundsOnIntercepts)) {
- require($(lowerBoundsOnIntercepts).size == numCoefficientSets, "The size of " +
- "lowerBoundsOnIntercepts must be equal to 1 for binomial regression, or the number of " +
- s"classes for multinomial regression, but found: ${getLowerBoundsOnIntercepts.size}.")
- }
- if (isSet(upperBoundsOnIntercepts)) {
- require($(upperBoundsOnIntercepts).size == numCoefficientSets, "The size of " +
- "upperBoundsOnIntercepts must be equal to 1 for binomial regression, or the number of " +
- s"classes for multinomial regression, but found: ${getUpperBoundsOnIntercepts.size}.")
- }
- if (isSet(lowerBoundsOnCoefficients) && isSet(upperBoundsOnCoefficients)) {
- require($(lowerBoundsOnCoefficients).toArray.zip($(upperBoundsOnCoefficients).toArray)
- .forall(x => x._1 <= x._2), "LowerBoundsOnCoefficients should always be " +
- "less than or equal to upperBoundsOnCoefficients, but found: " +
- s"lowerBoundsOnCoefficients = $getLowerBoundsOnCoefficients, " +
- s"upperBoundsOnCoefficients = $getUpperBoundsOnCoefficients.")
- }
- if (isSet(lowerBoundsOnIntercepts) && isSet(upperBoundsOnIntercepts)) {
- require($(lowerBoundsOnIntercepts).toArray.zip($(upperBoundsOnIntercepts).toArray)
- .forall(x => x._1 <= x._2), "LowerBoundsOnIntercepts should always be " +
- "less than or equal to upperBoundsOnIntercepts, but found: " +
- s"lowerBoundsOnIntercepts = $getLowerBoundsOnIntercepts, " +
- s"upperBoundsOnIntercepts = $getUpperBoundsOnIntercepts.")
- }
- }
-
- private var optInitialModel: Option[LogisticRegressionModel] = None
-
- private[spark] def setInitialModel(model: LogisticRegressionModel): this.type = {
- this.optInitialModel = Some(model)
- this
- }
-
- override protected[spark] def train(dataset: Dataset[_]): LogisticRegressionModel = {
- val handlePersistence = dataset.storageLevel == StorageLevel.NONE
- train(dataset, handlePersistence)
- }
-
- protected[spark] def train(
- dataset: Dataset[_],
- handlePersistence: Boolean): LogisticRegressionModel = {
- val w = if (!isDefined(weightCol) || $(weightCol).isEmpty) lit(1.0) else col($(weightCol))
- val instances: RDD[Instance] =
- dataset.select(col($(labelCol)), w, col($(featuresCol))).rdd.map {
- case Row(label: Double, weight: Double, features: Vector) =>
- Instance(label, weight + StaticUtils.ZERO_DOUBLE, features)
- }
-
- if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
-
- val instr = Instrumentation.create(this, instances)
- instr.logParams(regParam, elasticNetParam, standardization, threshold,
- maxIter, tol, fitIntercept)
-
- val (summarizer, labelSummarizer) = {
- val seqOp = (c: (MultivariateOnlineSummarizer, MultiClassSummarizer),
- instance: Instance) =>
- (c._1.add(instance.features, instance.weight), c._2.add(instance.label, instance.weight))
-
- val combOp = (c1: (MultivariateOnlineSummarizer, MultiClassSummarizer),
- c2: (MultivariateOnlineSummarizer, MultiClassSummarizer)) =>
- (c1._1.merge(c2._1), c1._2.merge(c2._2))
-
- instances.treeAggregate(
- (new MultivariateOnlineSummarizer, new MultiClassSummarizer)
- )(seqOp, combOp, $(aggregationDepth))
- }
-
- val histogram = labelSummarizer.histogram
- val numInvalid = labelSummarizer.countInvalid
- val numFeatures = summarizer.mean.size
- val numFeaturesPlusIntercept = if (getFitIntercept) numFeatures + 1 else numFeatures
-
- val numClasses = MetadataUtils.getNumClasses(dataset.schema($(labelCol))) match {
- case Some(n: Int) =>
- require(n >= histogram.length, s"Specified number of classes $n was " +
- s"less than the number of unique labels ${histogram.length}.")
- n
- case None => histogram.length
- }
-
- val isMultinomial = getFamily.toLowerCase(Locale.ROOT) match {
- case "binomial" =>
- require(numClasses == 1 || numClasses == 2, s"Binomial family only supports 1 or 2 " +
- s"outcome classes but found $numClasses.")
- false
- case "multinomial" => true
- case "auto" => numClasses > 2
- case other => throw new IllegalArgumentException(s"Unsupported family: $other")
- }
- val numCoefficientSets = if (isMultinomial) numClasses else 1
-
- // Check params interaction is valid if fitting under bound constrained optimization.
- if (usingBoundConstrainedOptimization) {
- assertBoundConstrainedOptimizationParamsValid(numCoefficientSets, numFeatures)
- }
-
- if (isDefined(thresholds)) {
- require($(thresholds).length == numClasses, this.getClass.getSimpleName +
- ".train() called with non-matching numClasses and thresholds.length." +
- s" numClasses=$numClasses, but thresholds has length ${$(thresholds).length}")
- }
-
- instr.logNumClasses(numClasses)
- instr.logNumFeatures(numFeatures)
-
- val (coefficientMatrix, interceptVector, objectiveHistory) = {
- if (numInvalid != 0) {
- val msg = s"Classification labels should be in [0 to ${numClasses - 1}]. " +
- s"Found $numInvalid invalid labels."
- logError(msg)
- throw new SparkException(msg)
- }
-
- val isConstantLabel = histogram.count(_ != 0.0) == 1
-
- if ($(fitIntercept) && isConstantLabel && !usingBoundConstrainedOptimization) {
- logWarning(s"All labels are the same value and fitIntercept=true, so the coefficients " +
- s"will be zeros. Training is not needed.")
- val constantLabelIndex = Vectors.dense(histogram).argmax
- val coefMatrix = new SparseMatrix(numCoefficientSets, numFeatures,
- new Array[Int](numCoefficientSets + 1), Array.empty[Int], Array.empty[Double],
- isTransposed = true).compressed
- val interceptVec = if (isMultinomial) {
- Vectors.sparse(numClasses, Seq((constantLabelIndex, Double.PositiveInfinity)))
- } else {
- Vectors.dense(if (numClasses == 2) Double.PositiveInfinity else Double.NegativeInfinity)
- }
- (coefMatrix, interceptVec, Array.empty[Double])
- } else {
- if (!$(fitIntercept) && isConstantLabel) {
- logWarning(s"All labels belong to a single class and fitIntercept=false. It's a " +
- s"dangerous ground, so the algorithm may not converge.")
- }
-
- val featuresMean = summarizer.mean.toArray
- val featuresStd = summarizer.variance.toArray.map(math.sqrt)
-
- if (!$(fitIntercept) && (0 until numFeatures).exists { i =>
- featuresStd(i) == 0.0 && featuresMean(i) != 0.0 }) {
- logWarning("Fitting LogisticRegressionModel without intercept on dataset with " +
- "constant nonzero column, Spark MLlib outputs zero coefficients for constant " +
- "nonzero columns. This behavior is the same as R glmnet but different from LIBSVM.")
- }
-
- val regParamL1 = $(elasticNetParam) * $(regParam)
- val regParamL2 = (1.0 - $(elasticNetParam)) * $(regParam)
-
- val bcFeaturesStd = instances.context.broadcast(featuresStd.map(t =>
- if (t != 0d) 1d / t else 0d))
- val getAggregatorFunc = new LogisticAggregatorX(bcFeaturesStd, numClasses, $(fitIntercept),
- multinomial = isMultinomial)(_)
- val getFeaturesStd = (j: Int) => if (j >= 0 && j < numCoefficientSets * numFeatures) {
- featuresStd(j / numCoefficientSets)
- } else {
- 0.0
- }
-
- val regularization = if (regParamL2 != 0.0) {
- val shouldApply = (idx: Int) => idx >= 0 && idx < numFeatures * numCoefficientSets
- Some(new L2Regularization(regParamL2, shouldApply,
- if ($(standardization)) None else Some(getFeaturesStd)))
- } else {
- None
- }
-
- val costFun = new RDDLossFunctionX(instances, getAggregatorFunc, regularization,
- $(aggregationDepth))
-
- val numCoeffsPlusIntercepts = numFeaturesPlusIntercept * numCoefficientSets
-
- val (lowerBounds, upperBounds): (Array[Double], Array[Double]) = {
- if (usingBoundConstrainedOptimization) {
- val lowerBounds = Array.fill[Double](numCoeffsPlusIntercepts)(Double.MinValue)
- val upperBounds = Array.fill[Double](numCoeffsPlusIntercepts)(Double.MaxValue)
- val isSetLowerBoundsOnCoefficients = isSet(lowerBoundsOnCoefficients)
- val isSetUpperBoundsOnCoefficients = isSet(upperBoundsOnCoefficients)
- val isSetLowerBoundsOnIntercepts = isSet(lowerBoundsOnIntercepts)
- val isSetUpperBoundsOnIntercepts = isSet(upperBoundsOnIntercepts)
-
- var i = 0
- while (i < numCoeffsPlusIntercepts) {
- val coefficientSetIndex = i % numCoefficientSets
- val featureIndex = i / numCoefficientSets
- if (featureIndex < numFeatures) {
- if (isSetLowerBoundsOnCoefficients) {
- lowerBounds(i) = $(lowerBoundsOnCoefficients)(
- coefficientSetIndex, featureIndex) * featuresStd(featureIndex)
- }
- if (isSetUpperBoundsOnCoefficients) {
- upperBounds(i) = $(upperBoundsOnCoefficients)(
- coefficientSetIndex, featureIndex) * featuresStd(featureIndex)
- }
- } else {
- if (isSetLowerBoundsOnIntercepts) {
- lowerBounds(i) = $(lowerBoundsOnIntercepts)(coefficientSetIndex)
- }
- if (isSetUpperBoundsOnIntercepts) {
- upperBounds(i) = $(upperBoundsOnIntercepts)(coefficientSetIndex)
- }
- }
- i += 1
- }
- (lowerBounds, upperBounds)
- } else {
- (null, null)
- }
- }
-
- val optimizer = if ($(elasticNetParam) == 0.0 || $(regParam) == 0.0) {
- if (lowerBounds != null && upperBounds != null) {
- new LBFGSL(BDV[Double](lowerBounds), BDV[Double](upperBounds), $(maxIter), 10, $(tol))
- } else {
- new LBFGSL($(maxIter), 10, $(tol))
- }
- } else {
- val standardizationParam = $(standardization)
- val effectiveL1Reg = Array.fill[Double](numCoeffsPlusIntercepts)(0d)
- .zipWithIndex.map{case (_, index) =>
- // Remove the L1 penalization on the intercept
- val isIntercept = $(fitIntercept) && index >= numFeatures * numCoefficientSets
- if (isIntercept) {
- 0.0
- } else {
- if (standardizationParam) {
- regParamL1
- } else {
- val featureIndex = index / numCoefficientSets
- // If `standardization` is false, we still standardize the data
- // to improve the rate of convergence; as a result, we have to
- // perform this reverse standardization by penalizing each component
- // differently to get effectively the same objective function when
- // the training dataset is not standardized.
- if (featuresStd(featureIndex) != 0.0) {
- regParamL1 / featuresStd(featureIndex)
- } else {
- 0.0
- }
- }
- }
- }
- new OWLQNL($(maxIter), 10, $(tol), BDV[Double](effectiveL1Reg))
- }
-
- /*
- The coefficients are laid out in column major order during training. Here we initialize
- a column major matrix of initial coefficients.
- */
- val initialCoefWithInterceptMatrix =
- Matrices.zeros(numCoefficientSets, numFeaturesPlusIntercept)
-
- val initialModelIsValid = optInitialModel match {
- case Some(_initialModel) =>
- val providedCoefs = _initialModel.coefficientMatrix
- val modelIsValid = (providedCoefs.numRows == numCoefficientSets) &&
- (providedCoefs.numCols == numFeatures) &&
- (_initialModel.interceptVector.size == numCoefficientSets) &&
- (_initialModel.getFitIntercept == $(fitIntercept))
- if (!modelIsValid) {
- logWarning(s"Initial coefficients will be ignored! Its dimensions " +
- s"(${providedCoefs.numRows}, ${providedCoefs.numCols}) did not match the " +
- s"expected size ($numCoefficientSets, $numFeatures)")
- }
- modelIsValid
- case None => false
- }
-
- if (initialModelIsValid) {
- val providedCoef = optInitialModel.get.coefficientMatrix
- providedCoef.foreachActive { (classIndex, featureIndex, value) =>
- // We need to scale the coefficients since they will be trained in the scaled space
- initialCoefWithInterceptMatrix.update(classIndex, featureIndex,
- value * featuresStd(featureIndex))
- }
- if ($(fitIntercept)) {
- optInitialModel.get.interceptVector.foreachActive { (classIndex, value) =>
- initialCoefWithInterceptMatrix.update(classIndex, numFeatures, value)
- }
- }
- } else if ($(fitIntercept) && isMultinomial) {
- /*
- For multinomial logistic regression, when we initialize the coefficients as zeros,
- it will converge faster if we initialize the intercepts such that
- it follows the distribution of the labels.
- {{{
- P(1) = \exp(b_1) / Z
- ...
- P(K) = \exp(b_K) / Z
- where Z = \sum_{k=1}^{K} \exp(b_k)
- }}}
- Since this doesn't have a unique solution, one of the solutions that satisfies the
- above equations is
- {{{
- \exp(b_k) = count_k * \exp(\lambda)
- b_k = \log(count_k) * \lambda
- }}}
- \lambda is a free parameter, so choose the phase \lambda such that the
- mean is centered. This yields
- {{{
- b_k = \log(count_k)
- b_k' = b_k - \mean(b_k)
- }}}
- */
- val rawIntercepts = histogram.map(math.log1p) // add 1 for smoothing (log1p(x) = log(1+x))
- val rawMean = rawIntercepts.sum / rawIntercepts.length
- rawIntercepts.indices.foreach { i =>
- initialCoefWithInterceptMatrix.update(i, numFeatures, rawIntercepts(i) - rawMean)
- }
- } else if ($(fitIntercept)) {
- /*
- For binary logistic regression, when we initialize the coefficients as zeros,
- it will converge faster if we initialize the intercept such that
- it follows the distribution of the labels.
-
- {{{
- P(0) = 1 / (1 + \exp(b)), and
- P(1) = \exp(b) / (1 + \exp(b))
- }}}, hence
- {{{
- b = \log{P(1) / P(0)} = \log{count_1 / count_0}
- }}}
- */
- initialCoefWithInterceptMatrix.update(0, numFeatures,
- math.log(histogram(1) / histogram(0)))
- }
-
- if (usingBoundConstrainedOptimization) {
- // Make sure all initial values locate in the corresponding bound.
- var i = 0
- while (i < numCoeffsPlusIntercepts) {
- val coefficientSetIndex = i % numCoefficientSets
- val featureIndex = i / numCoefficientSets
- if (initialCoefWithInterceptMatrix(coefficientSetIndex, featureIndex) < lowerBounds(i))
- {
- initialCoefWithInterceptMatrix.update(
- coefficientSetIndex, featureIndex, lowerBounds(i))
- } else if (
- initialCoefWithInterceptMatrix(coefficientSetIndex, featureIndex) > upperBounds(i))
- {
- initialCoefWithInterceptMatrix.update(
- coefficientSetIndex, featureIndex, upperBounds(i))
- }
- i += 1
- }
- }
-
- val states = optimizer.iterations(new CachedDiffFunction(costFun),
- new BDV[Double](initialCoefWithInterceptMatrix.toArray))
-
- /*
- Note that in Logistic Regression, the objective history (loss + regularization)
- is log-likelihood which is invariant under feature standardization. As a result,
- the objective history from optimizer is the same as the one in the original space.
- */
- val arrayBuilder = mutable.ArrayBuilder.make[Double]
- var state: optimizer.State = null
- while (states.hasNext) {
- state = states.next()
- arrayBuilder += state.adjustedValue
- }
- bcFeaturesStd.destroy(blocking = false)
-
- if (state == null) {
- val msg = s"${optimizer.getClass.getName} failed."
- logError(msg)
- throw new SparkException(msg)
- }
-
- /*
- The coefficients are trained in the scaled space; we're converting them back to
- the original space.
-
- Additionally, since the coefficients were laid out in column major order during training
- to avoid extra computation, we convert them back to row major before passing them to the
- model.
-
- Note that the intercept in scaled space and original space is the same;
- as a result, no scaling is needed.
- */
- val allCoefficients = state.x.toArray.clone()
- val allCoefMatrix = new DenseMatrix(numCoefficientSets, numFeaturesPlusIntercept,
- allCoefficients)
- val denseCoefficientMatrix = new DenseMatrix(numCoefficientSets, numFeatures,
- new Array[Double](numCoefficientSets * numFeatures), isTransposed = true)
- val interceptVec = if ($(fitIntercept) || !isMultinomial) {
- Vectors.zeros(numCoefficientSets)
- } else {
- Vectors.sparse(numCoefficientSets, Seq.empty)
- }
- // separate intercepts and coefficients from the combined matrix
- allCoefMatrix.foreachActive { (classIndex, featureIndex, value) =>
- val isIntercept = $(fitIntercept) && (featureIndex == numFeatures)
- if (!isIntercept && featuresStd(featureIndex) != 0.0) {
- denseCoefficientMatrix.update(classIndex, featureIndex,
- value / featuresStd(featureIndex))
- }
- if (isIntercept) interceptVec.toArray(classIndex) = value
- }
-
- if ($(regParam) == 0.0 && isMultinomial && !usingBoundConstrainedOptimization) {
- /*
- When no regularization is applied, the multinomial coefficients lack identifiability
- because we do not use a pivot class. We can add any constant value to the coefficients
- and get the same likelihood. So here, we choose the mean centered coefficients for
- reproducibility. This method follows the approach in glmnet, described here:
-
- Friedman, et al. "Regularization Paths for Generalized Linear Models via
- Coordinate Descent," https://core.ac.uk/download/files/153/6287975.pdf
- */
- val centers = Array.fill(numFeatures)(0.0)
- denseCoefficientMatrix.foreachActive { case (i, j, v) =>
- centers(j) += v
- }
- centers.transform(_ / numCoefficientSets)
- denseCoefficientMatrix.foreachActive { case (i, j, v) =>
- denseCoefficientMatrix.update(i, j, v - centers(j))
- }
- }
-
- // center the intercepts when using multinomial algorithm
- if ($(fitIntercept) && isMultinomial && !usingBoundConstrainedOptimization) {
- val interceptArray = interceptVec.toArray
- val interceptMean = interceptArray.sum / interceptArray.length
- (0 until interceptVec.size).foreach { i => interceptArray(i) -= interceptMean }
- }
- (denseCoefficientMatrix.compressed, interceptVec.compressed, arrayBuilder.result())
- }
- }
-
- if (handlePersistence) instances.unpersist()
-
- val model = copyValues(new LogisticRegressionModel(uid, coefficientMatrix, interceptVector,
- numClasses, isMultinomial))
-
- val (summaryModel, probabilityColName, predictionColName) = model.findSummaryModel()
- val logRegSummary = if (numClasses <= 2) {
- new BinaryLogisticRegressionTrainingSummaryImpl(
- summaryModel.transform(dataset),
- probabilityColName,
- predictionColName,
- $(labelCol),
- $(featuresCol),
- objectiveHistory)
- } else {
- new LogisticRegressionTrainingSummaryImpl(
- summaryModel.transform(dataset),
- probabilityColName,
- predictionColName,
- $(labelCol),
- $(featuresCol),
- objectiveHistory)
- }
- model.setSummary(Some(logRegSummary))
- instr.logSuccess(model)
- model
- }
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): LogisticRegression = defaultCopy(extra)
-}
-
-@Since("1.6.0")
-object LogisticRegression extends DefaultParamsReadable[LogisticRegression] {
-
- @Since("1.6.0")
- override def load(path: String): LogisticRegression = super.load(path)
-
- private[classification] val supportedFamilyNames =
- Array("auto", "binomial", "multinomial").map(_.toLowerCase(Locale.ROOT))
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/RandomForestClassifier.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/RandomForestClassifier.scala
deleted file mode 100644
index d2dd1ec..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/classification/RandomForestClassifier.scala
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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 org.json4s.{DefaultFormats, JObject}
-import org.json4s.JsonDSL._
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.linalg.{DenseVector, SparseVector, Vector, Vectors}
-import org.apache.spark.ml.param.ParamMap
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.RandomForest
-import org.apache.spark.ml.util._
-import org.apache.spark.ml.util.DefaultParamsReader.Metadata
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo}
-import org.apache.spark.mllib.tree.model.{RandomForestModel => OldRandomForestModel}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{DataFrame, Dataset}
-import org.apache.spark.sql.functions._
-
-
-/**
- * Random Forest learning algorithm for
- * classification.
- * It supports both binary and multiclass labels, as well as both continuous and categorical
- * features.
- */
-@Since("1.4.0")
-class RandomForestClassifier @Since("1.4.0") (
- @Since("1.4.0") override val uid: String)
- extends ProbabilisticClassifier[Vector, RandomForestClassifier, RandomForestClassificationModel]
- with RandomForestClassifierParams with DefaultParamsWritable {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("rfc"))
-
- // Override parameter setters from parent trait for Java API compatibility.
-
- // Parameters from TreeClassifierParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxDepth(value: Int): this.type = set(maxDepth, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxBins(value: Int): this.type = set(maxBins, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInstancesPerNode(value: Int): this.type = set(minInstancesPerNode, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInfoGain(value: Double): this.type = set(minInfoGain, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setMaxMemoryInMB(value: Int): this.type = set(maxMemoryInMB, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setCacheNodeIds(value: Boolean): this.type = set(cacheNodeIds, value)
-
- /**
- * Specifies how often to checkpoint the cached node IDs.
- * E.g. 10 means that the cache will get checkpointed every 10 iterations.
- * This is only used if cacheNodeIds is true and if the checkpoint directory is set in
- * [[org.apache.spark.SparkContext]].
- * Must be at least 1.
- * (default = 10)
- * @group setParam
- */
- @Since("1.4.0")
- override def setCheckpointInterval(value: Int): this.type = set(checkpointInterval, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setImpurity(value: String): this.type = set(impurity, value)
-
- // Parameters from TreeEnsembleParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSubsamplingRate(value: Double): this.type = set(subsamplingRate, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSeed(value: Long): this.type = set(seed, value)
-
- // Parameters from RandomForestParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setNumTrees(value: Int): this.type = set(numTrees, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setFeatureSubsetStrategy(value: String): this.type =
- set(featureSubsetStrategy, value)
-
- override protected def train(dataset: Dataset[_]): RandomForestClassificationModel = {
- val categoricalFeatures: Map[Int, Int] =
- MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
- val numClasses: Int = getNumClasses(dataset)
-
- if (isDefined(thresholds)) {
- require($(thresholds).length == numClasses, this.getClass.getSimpleName +
- ".train() called with non-matching numClasses and thresholds.length." +
- s" numClasses=$numClasses, but thresholds has length ${$(thresholds).length}")
- }
-
- val oldDataset: RDD[LabeledPoint] = extractLabeledPoints(dataset, numClasses)
- val strategy =
- super.getOldStrategy(categoricalFeatures, numClasses, OldAlgo.Classification, getOldImpurity)
-
- val instr = Instrumentation.create(this, oldDataset)
- instr.logParams(labelCol, featuresCol, predictionCol, probabilityCol, rawPredictionCol,
- impurity, numTrees, featureSubsetStrategy, maxDepth, maxBins, maxMemoryInMB, minInfoGain,
- minInstancesPerNode, seed, subsamplingRate, thresholds, cacheNodeIds, checkpointInterval)
-
- val trees = RandomForest
- .run(oldDataset, strategy, getNumTrees, getFeatureSubsetStrategy, getSeed, Some(instr))
- .map(_.asInstanceOf[DecisionTreeClassificationModel])
-
- val numFeatures = oldDataset.first().features.size
- val m = new RandomForestClassificationModel(uid, trees, numFeatures, numClasses)
- instr.logSuccess(m)
- m
- }
-
- @Since("1.4.1")
- override def copy(extra: ParamMap): RandomForestClassifier = defaultCopy(extra)
-}
-
-@Since("1.4.0")
-object RandomForestClassifier extends DefaultParamsReadable[RandomForestClassifier] {
- /** Accessor for supported impurity settings: entropy, gini */
- @Since("1.4.0")
- final val supportedImpurities: Array[String] = TreeClassifierParams.supportedImpurities
-
- /** Accessor for supported featureSubsetStrategy settings: auto, all, onethird, sqrt, log2 */
- @Since("1.4.0")
- final val supportedFeatureSubsetStrategies: Array[String] =
- TreeEnsembleParams.supportedFeatureSubsetStrategies
-
- @Since("2.0.0")
- override def load(path: String): RandomForestClassifier = super.load(path)
-}
-
-/**
- * Random Forest model for classification.
- * It supports both binary and multiclass labels, as well as both continuous and categorical
- * features.
- *
- * @param _trees Decision trees in the ensemble.
- * Warning: These have null parents.
- */
-@Since("1.4.0")
-class RandomForestClassificationModel private[ml] (
- @Since("1.5.0") override val uid: String,
- private val _trees: Array[DecisionTreeClassificationModel],
- @Since("1.6.0") override val numFeatures: Int,
- @Since("1.5.0") override val numClasses: Int)
- extends ProbabilisticClassificationModel[Vector, RandomForestClassificationModel]
- with RandomForestClassifierParams with TreeEnsembleModel[DecisionTreeClassificationModel]
- with MLWritable with Serializable {
-
- require(_trees.nonEmpty, "RandomForestClassificationModel requires at least 1 tree.")
-
- /**
- * Construct a random forest classification model, with all trees weighted equally.
- *
- * @param trees Component trees
- */
- private[ml] def this(
- trees: Array[DecisionTreeClassificationModel],
- numFeatures: Int,
- numClasses: Int) =
- this(Identifiable.randomUID("rfc"), trees, numFeatures, numClasses)
-
- @Since("1.4.0")
- override def trees: Array[DecisionTreeClassificationModel] = _trees
-
- // Note: We may add support for weights (based on tree performance) later on.
- private lazy val _treeWeights: Array[Double] = Array.fill[Double](_trees.length)(1.0)
-
- @Since("1.4.0")
- override def treeWeights: Array[Double] = _treeWeights
-
- override protected def transformImpl(dataset: Dataset[_]): DataFrame = {
- val bcastModel = dataset.sparkSession.sparkContext.broadcast(this)
- val predictUDF = udf { (features: Any) =>
- bcastModel.value.predict(features.asInstanceOf[Vector])
- }
- dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
- }
-
- override protected def predictRaw(features: Vector): Vector = {
- // TODO: When we add a generic Bagging class, handle transform there: SPARK-7128
- // Classifies using majority votes.
- // Ignore the tree weights since all are 1.0 for now.
- val votes = Array.fill[Double](numClasses)(0.0)
- _trees.view.foreach { tree =>
- val classCounts: Array[Double] = tree.rootNode.predictImpl(features).impurityStats.stats
- val total = classCounts.sum
- if (total != 0) {
- var i = 0
- while (i < numClasses) {
- votes(i) += classCounts(i) / total
- i += 1
- }
- }
- }
- Vectors.dense(votes)
- }
-
- override protected def raw2probabilityInPlace(rawPrediction: Vector): Vector = {
- rawPrediction match {
- case dv: DenseVector =>
- ProbabilisticClassificationModel.normalizeToProbabilitiesInPlace(dv)
- dv
- case sv: SparseVector =>
- throw new RuntimeException("Unexpected error in RandomForestClassificationModel:" +
- " raw2probabilityInPlace encountered SparseVector")
- }
- }
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): RandomForestClassificationModel = {
- copyValues(new RandomForestClassificationModel(uid, _trees, numFeatures, numClasses), extra)
- .setParent(parent)
- }
-
- @Since("1.4.0")
- override def toString: String = {
- s"RandomForestClassificationModel (uid=$uid) with $getNumTrees trees"
- }
-
- /**
- * Estimate of the importance of each feature.
- *
- * Each feature's importance is the average of its importance across all trees in the ensemble
- * The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
- * (Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
- * and follows the implementation from scikit-learn.
- *
- * @see `DecisionTreeClassificationModel.featureImportances`
- */
- @Since("1.5.0")
- lazy val featureImportances: Vector = TreeEnsembleModel.featureImportances(trees, numFeatures)
-
- /** (private[ml]) Convert to a model in the old API */
- private[ml] def toOld: OldRandomForestModel = {
- new OldRandomForestModel(OldAlgo.Classification, _trees.map(_.toOld))
- }
-
- @Since("2.0.0")
- override def write: MLWriter =
- new RandomForestClassificationModel.RandomForestClassificationModelWriter(this)
-}
-
-@Since("2.0.0")
-object RandomForestClassificationModel extends MLReadable[RandomForestClassificationModel] {
-
- @Since("2.0.0")
- override def read: MLReader[RandomForestClassificationModel] =
- new RandomForestClassificationModelReader
-
- @Since("2.0.0")
- override def load(path: String): RandomForestClassificationModel = super.load(path)
-
- private[RandomForestClassificationModel]
- class RandomForestClassificationModelWriter(instance: RandomForestClassificationModel)
- extends MLWriter {
-
- override protected def saveImpl(path: String): Unit = {
- // Note: numTrees is not currently used, but could be nice to store for fast querying.
- val extraMetadata: JObject = Map(
- "numFeatures" -> instance.numFeatures,
- "numClasses" -> instance.numClasses,
- "numTrees" -> instance.getNumTrees)
- EnsembleModelReadWrite.saveImpl(instance, path, sparkSession, extraMetadata)
- }
- }
-
- private class RandomForestClassificationModelReader
- extends MLReader[RandomForestClassificationModel] {
-
- /** Checked against metadata when loading model */
- private val className = classOf[RandomForestClassificationModel].getName
- private val treeClassName = classOf[DecisionTreeClassificationModel].getName
-
- override def load(path: String): RandomForestClassificationModel = {
- implicit val format = DefaultFormats
- val (metadata: Metadata, treesData: Array[(Metadata, Node)], _) =
- EnsembleModelReadWrite.loadImpl(path, sparkSession, className, treeClassName)
- val numFeatures = (metadata.metadata \ "numFeatures").extract[Int]
- val numClasses = (metadata.metadata \ "numClasses").extract[Int]
- val numTrees = (metadata.metadata \ "numTrees").extract[Int]
-
- val trees: Array[DecisionTreeClassificationModel] = treesData.map {
- case (treeMetadata, root) =>
- val tree =
- new DecisionTreeClassificationModel(treeMetadata.uid, root, numFeatures, numClasses)
- DefaultParamsReader.getAndSetParams(tree, treeMetadata)
- tree
- }
- require(numTrees == trees.length, s"RandomForestClassificationModel.load expected $numTrees" +
- s" trees based on metadata but found ${trees.length} trees.")
-
- val model = new RandomForestClassificationModel(metadata.uid, trees, numFeatures, numClasses)
- DefaultParamsReader.getAndSetParams(model, metadata)
- model
- }
- }
-
- /** Convert a model from the old API */
- private[ml] def fromOld(
- oldModel: OldRandomForestModel,
- parent: RandomForestClassifier,
- categoricalFeatures: Map[Int, Int],
- numClasses: Int,
- numFeatures: Int = -1): RandomForestClassificationModel = {
- require(oldModel.algo == OldAlgo.Classification, "Cannot convert RandomForestModel" +
- s" with algo=${oldModel.algo} (old API) to RandomForestClassificationModel (new API).")
- val newTrees = oldModel.trees.map { tree =>
- // parent for each tree is null since there is no good way to set this.
- DecisionTreeClassificationModel.fromOld(tree, null, categoricalFeatures)
- }
- val uid = if (parent != null) parent.uid else Identifiable.randomUID("rfc")
- new RandomForestClassificationModel(uid, newTrees, numFeatures, numClasses)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/feature/IDF.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/feature/IDF.scala
deleted file mode 100644
index 46a0730..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/feature/IDF.scala
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * 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.feature
-
-import org.apache.hadoop.fs.Path
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.ml._
-import org.apache.spark.ml.linalg.{Vector, VectorUDT}
-import org.apache.spark.ml.param._
-import org.apache.spark.ml.param.shared._
-import org.apache.spark.ml.util._
-import org.apache.spark.mllib.feature
-import org.apache.spark.mllib.linalg.{Vector => OldVector, Vectors => OldVectors}
-import org.apache.spark.mllib.util.MLUtils
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql._
-import org.apache.spark.sql.functions._
-import org.apache.spark.sql.types.StructType
-
-/**
- * Params for [[IDF]] and [[IDFModel]].
- */
-private[feature] trait IDFBase extends Params with HasInputCol with HasOutputCol {
-
- /**
- * The minimum number of documents in which a term should appear.
- * Default: 0
- * @group param
- */
- final val minDocFreq = new IntParam(
- this, "minDocFreq", "minimum number of documents in which a term should appear for filtering" +
- " (>= 0)", ParamValidators.gtEq(0))
-
- setDefault(minDocFreq -> 0)
-
- /** @group getParam */
- def getMinDocFreq: Int = $(minDocFreq)
-
- /**
- * Validate and transform the input schema.
- */
- protected def validateAndTransformSchema(schema: StructType): StructType = {
- SchemaUtils.checkColumnType(schema, $(inputCol), new VectorUDT)
- SchemaUtils.appendColumn(schema, $(outputCol), new VectorUDT)
- }
-}
-
-/**
- * Compute the Inverse Document Frequency (IDF) given a collection of documents.
- */
-@Since("1.4.0")
-final class IDF @Since("1.4.0") (@Since("1.4.0") override val uid: String)
- extends Estimator[IDFModel] with IDFBase with DefaultParamsWritable {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("idf"))
-
- /** @group setParam */
- @Since("1.4.0")
- def setInputCol(value: String): this.type = set(inputCol, value)
-
- /** @group setParam */
- @Since("1.4.0")
- def setOutputCol(value: String): this.type = set(outputCol, value)
-
- /** @group setParam */
- @Since("1.4.0")
- def setMinDocFreq(value: Int): this.type = set(minDocFreq, value)
-
- @Since("2.0.0")
- override def fit(dataset: Dataset[_]): IDFModel = {
- transformSchema(dataset.schema, logging = true)
- val input: RDD[OldVector] = dataset.select($(inputCol)).rdd.map {
- case Row(v: Vector) => OldVectors.fromML(v)
- }
- val idf = new feature.IDF($(minDocFreq)).fit(input)
- copyValues(new IDFModel(uid, idf).setParent(this))
- }
-
- @Since("1.4.0")
- override def transformSchema(schema: StructType): StructType = {
- validateAndTransformSchema(schema)
- }
-
- @Since("1.4.1")
- override def copy(extra: ParamMap): IDF = defaultCopy(extra)
-}
-
-@Since("1.6.0")
-object IDF extends DefaultParamsReadable[IDF] {
-
- @Since("1.6.0")
- override def load(path: String): IDF = super.load(path)
-}
-
-/**
- * Model fitted by [[IDF]].
- */
-@Since("1.4.0")
-class IDFModel private[ml] (
- @Since("1.4.0") override val uid: String,
- idfModel: feature.IDFModel)
- extends Model[IDFModel] with IDFBase with MLWritable {
-
- import IDFModel._
-
- /** @group setParam */
- @Since("1.4.0")
- def setInputCol(value: String): this.type = set(inputCol, value)
-
- /** @group setParam */
- @Since("1.4.0")
- def setOutputCol(value: String): this.type = set(outputCol, value)
-
- @Since("2.0.0")
- override def transform(dataset: Dataset[_]): DataFrame = {
- transformSchema(dataset.schema, logging = true)
- // TODO: Make the idfModel.transform natively in ml framework to avoid extra conversion.
- val idf = udf { vec: Vector => idfModel.transform(OldVectors.fromML(vec)).asML }
- dataset.withColumn($(outputCol), idf(col($(inputCol))))
- }
-
- @Since("1.4.0")
- override def transformSchema(schema: StructType): StructType = {
- validateAndTransformSchema(schema)
- }
-
- @Since("1.4.1")
- override def copy(extra: ParamMap): IDFModel = {
- val copied = new IDFModel(uid, idfModel)
- copyValues(copied, extra).setParent(parent)
- }
-
- /** Returns the IDF vector. */
- @Since("2.0.0")
- def idf: Vector = idfModel.idf.asML
-
- @Since("1.6.0")
- override def write: MLWriter = new IDFModelWriter(this)
-}
-
-@Since("1.6.0")
-object IDFModel extends MLReadable[IDFModel] {
-
- private[IDFModel] class IDFModelWriter(instance: IDFModel) extends MLWriter {
-
- private case class Data(idf: Vector)
-
- override protected def saveImpl(path: String): Unit = {
- DefaultParamsWriter.saveMetadata(instance, path, sc)
- val data = Data(instance.idf)
- val dataPath = new Path(path, "data").toString
- sparkSession.createDataFrame(Seq(data)).repartition(1).write.parquet(dataPath)
- }
- }
-
- private class IDFModelReader extends MLReader[IDFModel] {
-
- private val className = classOf[IDFModel].getName
-
- override def load(path: String): IDFModel = {
- val metadata = DefaultParamsReader.loadMetadata(path, sc, className)
- val dataPath = new Path(path, "data").toString
- val data = sparkSession.read.parquet(dataPath)
- val Row(idf: Vector) = MLUtils.convertVectorColumnsToML(data, "idf")
- .select("idf")
- .head()
- val model = new IDFModel(metadata.uid, new feature.IDFModel(OldVectors.fromML(idf)))
- DefaultParamsReader.getAndSetParams(model, metadata)
- model
- }
- }
-
- @Since("1.6.0")
- override def read: MLReader[IDFModel] = new IDFModelReader
-
- @Since("1.6.0")
- override def load(path: String): IDFModel = super.load(path)
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/fpm/PrefixSpan.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/fpm/PrefixSpan.scala
new file mode 100644
index 0000000..10a569a
--- /dev/null
+++ b/ml-accelerator/src/main/scala/org/apache/spark/ml/fpm/PrefixSpan.scala
@@ -0,0 +1,168 @@
+/*
+ * 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.fpm
+
+import org.apache.spark.annotation.Since
+import org.apache.spark.ml.param._
+import org.apache.spark.ml.util.Identifiable
+import org.apache.spark.ml.util.Instrumentation.instrumented
+import org.apache.spark.mllib.fpm.{PrefixSpan => mllibPrefixSpan}
+import org.apache.spark.sql.{DataFrame, Dataset, Row}
+import org.apache.spark.sql.functions.col
+import org.apache.spark.sql.types.{ArrayType, LongType, StructField, StructType}
+
+/**
+ * A parallel PrefixSpan algorithm to mine frequent sequential patterns.
+ * The PrefixSpan algorithm is described in J. Pei, et al., PrefixSpan: Mining Sequential Patterns
+ * Efficiently by Prefix-Projected Pattern Growth
+ * (see here ).
+ * This class is not yet an Estimator/Transformer, use `findFrequentSequentialPatterns` method to
+ * run the PrefixSpan algorithm.
+ *
+ * @see Sequential Pattern Mining
+ * (Wikipedia)
+ */
+@Since("2.4.0")
+final class PrefixSpan(@Since("2.4.0") override val uid: String) extends Params {
+
+ @Since("2.4.0")
+ def this() = this(Identifiable.randomUID("prefixSpan"))
+
+ /**
+ * Param for the minimal support level (default: `0.1`).
+ * Sequential patterns that appear more than (minSupport * size-of-the-dataset) times are
+ * identified as frequent sequential patterns.
+ * @group param
+ */
+ @Since("2.4.0")
+ val minSupport = new DoubleParam(this, "minSupport", "The minimal support level of the " +
+ "sequential pattern. Sequential pattern that appears more than " +
+ "(minSupport * size-of-the-dataset) " +
+ "times will be output.", ParamValidators.gtEq(0.0))
+
+ /** @group getParam */
+ @Since("2.4.0")
+ def getMinSupport: Double = $(minSupport)
+
+ /** @group setParam */
+ @Since("2.4.0")
+ def setMinSupport(value: Double): this.type = set(minSupport, value)
+
+ /**
+ * Param for the maximal pattern length (default: `10`).
+ * @group param
+ */
+ @Since("2.4.0")
+ val maxPatternLength = new IntParam(this, "maxPatternLength",
+ "The maximal length of the sequential pattern.",
+ ParamValidators.gt(0))
+
+ /** @group getParam */
+ @Since("2.4.0")
+ def getMaxPatternLength: Int = $(maxPatternLength)
+
+ /** @group setParam */
+ @Since("2.4.0")
+ def setMaxPatternLength(value: Int): this.type = set(maxPatternLength, value)
+
+ /**
+ * Param for the maximum number of items (including delimiters used in the internal storage
+ * format) allowed in a projected database before local processing (default: `32000000`).
+ * If a projected database exceeds this size, another iteration of distributed prefix growth
+ * is run.
+ * @group param
+ */
+ @Since("2.4.0")
+ val maxLocalProjDBSize = new LongParam(this, "maxLocalProjDBSize",
+ "The maximum number of items (including delimiters used in the internal storage format) " +
+ "allowed in a projected database before local processing. If a projected database exceeds " +
+ "this size, another iteration of distributed prefix growth is run.",
+ ParamValidators.gt(0))
+
+ /** @group getParam */
+ @Since("2.4.0")
+ def getMaxLocalProjDBSize: Long = $(maxLocalProjDBSize)
+
+ /** @group setParam */
+ @Since("2.4.0")
+ def setMaxLocalProjDBSize(value: Long): this.type = set(maxLocalProjDBSize, value)
+
+ /**
+ * Param for the name of the sequence column in dataset (default "sequence"), rows with
+ * nulls in this column are ignored.
+ * @group param
+ */
+ @Since("2.4.0")
+ val sequenceCol = new Param[String](this, "sequenceCol", "The name of the sequence column in " +
+ "dataset, rows with nulls in this column are ignored.")
+
+ /** @group getParam */
+ @Since("2.4.0")
+ def getSequenceCol: String = $(sequenceCol)
+
+ /** @group setParam */
+ @Since("2.4.0")
+ def setSequenceCol(value: String): this.type = set(sequenceCol, value)
+
+ setDefault(minSupport -> 0.1, maxPatternLength -> 10, maxLocalProjDBSize -> 32000000,
+ sequenceCol -> "sequence")
+
+ /**
+ * Finds the complete set of frequent sequential patterns in the input sequences of itemsets.
+ *
+ * @param dataset A dataset or a dataframe containing a sequence column which is
+ * {{{ArrayType(ArrayType(T))}}} type, T is the item type for the input dataset.
+ * @return A `DataFrame` that contains columns of sequence and corresponding frequency.
+ * The schema of it will be:
+ * - `sequence: ArrayType(ArrayType(T))` (T is the item type)
+ * - `freq: Long`
+ */
+ @Since("2.4.0")
+ def findFrequentSequentialPatterns(dataset: Dataset[_]): DataFrame = instrumented { instr =>
+ instr.logDataset(dataset)
+ instr.logParams(this, params: _*)
+
+ val sequenceColParam = $(sequenceCol)
+ val inputType = dataset.schema(sequenceColParam).dataType
+ require(inputType.isInstanceOf[ArrayType] &&
+ inputType.asInstanceOf[ArrayType].elementType.isInstanceOf[ArrayType],
+ s"The input column must be ArrayType and the array element type must also be ArrayType, " +
+ s"but got $inputType.")
+
+ val data = dataset.select(sequenceColParam)
+ val sequences = data.where(col(sequenceColParam).isNotNull).rdd
+ .map(r => r.getSeq[scala.collection.Seq[Any]](0).map(_.toArray).toArray)
+
+ val mllibPrefixSpan = new mllibPrefixSpan()
+ .setMinSupport($(minSupport))
+ .setMaxPatternLength($(maxPatternLength))
+ .setMaxLocalProjDBSize($(maxLocalProjDBSize))
+
+ val rows = mllibPrefixSpan.run(sequences).freqSequences.map(f => Row(f.sequence, f.freq))
+ val schema = StructType(Seq(
+ StructField("sequence", dataset.schema(sequenceColParam).dataType, nullable = false),
+ StructField("freq", LongType, nullable = false)))
+ val freqSequences = dataset.sparkSession.createDataFrame(rows, schema)
+
+ freqSequences
+ }
+
+ @Since("2.4.0")
+ override def copy(extra: ParamMap): PrefixSpan = defaultCopy(extra)
+
+}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/DifferentiableLossAggregatorX.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/DifferentiableLossAggregatorX.scala
deleted file mode 100644
index 48bc3b8..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/DifferentiableLossAggregatorX.scala
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.optim.aggregator
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-
-import org.apache.spark.ml.linalg.{BLAS, Vector, Vectors}
-
-/**
- * A parent trait for aggregators used in fitting MLlib models. This parent trait implements
- * some of the common code shared between concrete instances of aggregators. Subclasses of this
- * aggregator need only implement the `add` method.
- *
- * @tparam Datum The type of the instances added to the aggregator to update the loss and gradient.
- * @tparam Agg Specialization of [[DifferentiableLossAggregator]]. Classes that subclass this
- * type need to use this parameter to specify the concrete type of the aggregator.
- */
-private[ml] trait DifferentiableLossAggregatorX[
- Datum,
- Agg <: DifferentiableLossAggregatorX[Datum, Agg]] extends Serializable {
-
- self: Agg => // enforce classes that extend this to be the same type as `Agg`
-
- protected var weightSum: Double = 0.0
- protected var lossSum: Double = 0.0
-
- /** The dimension of the gradient array. */
- protected val dim: Int
-
- /** Array of gradient values that are mutated when new instances are added to the aggregator. */
- protected lazy val gradientSumArray: DoubleArrayList =
- DoubleArrayList.wrap(Array.ofDim[Double](dim))
-
- /** Add a single data point to this aggregator. */
- def add(instance: Datum): Agg
-
- /** Merge two aggregators. The `this` object will be modified in place and returned. */
- def merge(other: Agg): Agg = {
- require(dim == other.dim, s"Dimensions mismatch when merging with another " +
- s"${getClass.getSimpleName}. Expecting $dim but got ${other.dim}.")
-
- if (other.weightSum != 0) {
- weightSum += other.weightSum
- lossSum += other.lossSum
-
- var i = 0
- val localThisGradientSumArray = this.gradientSumArray
- val localOtherGradientSumArray = other.gradientSumArray
- while (i < dim) {
- val e = localThisGradientSumArray.getDouble(i)
- localThisGradientSumArray.set(i, e + localOtherGradientSumArray.getDouble(i))
- i += 1
- }
- }
- this
- }
-
- /** The current weighted averaged gradient. */
- def gradient: Vector = {
- require(weightSum > 0.0, s"The effective number of instances should be " +
- s"greater than 0.0, but was $weightSum.")
- val result = Vectors.dense(gradientSumArray.elements().clone())
- BLAS.scal(1.0 / weightSum, result)
- result
- }
-
- /** Weighted count of instances in this aggregator. */
- def weight: Double = weightSum
-
- /** The current loss value of this aggregator. */
- def loss: Double = {
- require(weightSum > 0.0, s"The effective number of instances should be " +
- s"greater than 0.0, but was $weightSum.")
- lossSum / weightSum
- }
-
-}
-
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/HingeAggregatorX.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/HingeAggregatorX.scala
deleted file mode 100644
index d4a4f1b..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/HingeAggregatorX.scala
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.optim.aggregator
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.ml.feature.Instance
-import org.apache.spark.ml.linalg._
-
-/**
- * HingeAggregator computes the gradient and loss for Hinge loss function as used in
- * binary classification for instances in sparse or dense vector in an online fashion.
- *
- * Two HingeAggregators can be merged together to have a summary of loss and gradient of
- * the corresponding joint dataset.
- *
- * This class standardizes feature values during computation using bcFeaturesStd.
- *
- * @param bcCoefficients The coefficients corresponding to the features.
- * @param fitIntercept Whether to fit an intercept term.
- * @param bcFeaturesStd The standard deviation values of the features.
- */
-private[ml] class HingeAggregatorX(
- bcFeaturesStd: Broadcast[Array[Double]],
- fitIntercept: Boolean)(bcCoefficients: Broadcast[Vector])
- extends DifferentiableLossAggregatorX[Instance, HingeAggregatorX] {
-
- private val numFeatures: Int = bcFeaturesStd.value.length
- private val numFeaturesPlusIntercept: Int = if (fitIntercept) numFeatures + 1 else numFeatures
- @transient private lazy val coefficientsArray = bcCoefficients.value match {
- case DenseVector(values) => values
- case _ => throw new IllegalArgumentException(s"coefficients only supports dense vector" +
- s" but got type ${bcCoefficients.value.getClass}.")
- }
- protected override val dim: Int = numFeaturesPlusIntercept
-
- /**
- * Add a new training instance to this HingeAggregator, and update the loss and gradient
- * of the objective function.
- *
- * @param instance The instance of data point to be added.
- * @return This HingeAggregator object.
- */
- def add(instance: Instance): this.type = {
- instance match { case Instance(label, weight, features) =>
- require(numFeatures == features.size, s"Dimensions mismatch when adding new instance." +
- s" Expecting $numFeatures but got ${features.size}.")
- require(weight >= 0.0, s"instance weight, $weight has to be >= 0.0")
-
- if (weight == 0.0) return this
- val localFeaturesStd = DoubleArrayList.wrap(bcFeaturesStd.value)
- val localCoefficients = DoubleArrayList.wrap(coefficientsArray)
- val localGradientSumArray = gradientSumArray
-
- val dotProduct = {
- var sum = 0.0
- features.foreachActive { (index, value) =>
- sum += localCoefficients.getDouble(index) * value * localFeaturesStd.getDouble(index)
- }
- if (fitIntercept) sum += localCoefficients.getDouble(numFeaturesPlusIntercept - 1)
- sum
- }
- // Our loss function with {0, 1} labels is max(0, 1 - (2y - 1) (f_w(x)))
- // Therefore the gradient is -(2y - 1)*x
- val labelScaled = 2 * label - 1.0
- val loss = if (1.0 > labelScaled * dotProduct) {
- (1.0 - labelScaled * dotProduct) * weight
- } else {
- 0.0
- }
-
- if (1.0 > labelScaled * dotProduct) {
- val gradientScale = -labelScaled * weight
- features.foreachActive { (index, value) =>
- val e = localGradientSumArray.getDouble(index)
- localGradientSumArray.set(index, e + value * gradientScale
- * localFeaturesStd.getDouble(index))
- }
- if (fitIntercept) {
- val e = localGradientSumArray.getDouble(localGradientSumArray.size() - 1)
- localGradientSumArray.set(localGradientSumArray.size() - 1, e + gradientScale)
- }
- }
-
- lossSum += loss
- weightSum += weight
- this
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/HuberAggregatorX.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/HuberAggregatorX.scala
deleted file mode 100644
index c35cdb5..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/HuberAggregatorX.scala
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.optim.aggregator
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.ml.feature.Instance
-import org.apache.spark.ml.linalg.{DenseVector, Vector}
-
-/**
- * HuberAggregator computes the gradient and loss for a huber loss function,
- * as used in robust regression for samples in sparse or dense vector in an online fashion.
- *
- * The huber loss function based on:
- * Art B. Owen (2006),
- * A robust hybrid of lasso and ridge regression .
- *
- * Two HuberAggregator can be merged together to have a summary of loss and gradient of
- * the corresponding joint dataset.
- *
- * The huber loss function is given by
- *
- *
- * $$
- * \begin{align}
- * \min_{w, \sigma}\frac{1}{2n}{\sum_{i=1}^n\left(\sigma +
- * H_m\left(\frac{X_{i}w - y_{i}}{\sigma}\right)\sigma\right) + \frac{1}{2}\lambda {||w||_2}^2}
- * \end{align}
- * $$
- *
- *
- * where
- *
- *
- * $$
- * \begin{align}
- * H_m(z) = \begin{cases}
- * z^2, & \text {if } |z| < \epsilon, \\
- * 2\epsilon|z| - \epsilon^2, & \text{otherwise}
- * \end{cases}
- * \end{align}
- * $$
- *
- *
- * It is advised to set the parameter $\epsilon$ to 1.35 to achieve 95% statistical efficiency
- * for normally distributed data. Please refer to chapter 2 of
- *
- * A robust hybrid of lasso and ridge regression for more detail.
- *
- * @param fitIntercept Whether to fit an intercept term.
- * @param epsilon The shape parameter to control the amount of robustness.
- * @param bcFeaturesStd The broadcast standard deviation values of the features.
- * @param bcParameters including three parts: the regression coefficients corresponding
- * to the features, the intercept (if fitIntercept is ture)
- * and the scale parameter (sigma).
- */
-private[ml] class HuberAggregatorX(
- fitIntercept: Boolean,
- epsilon: Double,
- bcFeaturesStd: Broadcast[Array[Double]])(bcParameters: Broadcast[Vector])
- extends DifferentiableLossAggregatorX[Instance, HuberAggregatorX] {
-
- protected override val dim: Int = bcParameters.value.size
- private val numFeatures: Int = if (fitIntercept) dim - 2 else dim - 1
-
- @transient private lazy val parametersArray = DoubleArrayList.wrap(bcParameters.value match {
- case DenseVector(values) => values
- case _ => throw new IllegalArgumentException(s"coefficients only supports dense vector but " +
- s"got type ${bcParameters.value.getClass}.)")
- })
- @transient private lazy val featuresStd = DoubleArrayList.wrap(bcFeaturesStd.value)
- @transient private lazy val sigma: Double = parametersArray.getDouble(dim - 1)
- @transient private lazy val intercept: Double = if (fitIntercept) {
- parametersArray.getDouble(dim - 2)
- } else {
- 0.0
- }
-
- /**
- * Add a new training instance to this HuberAggregator, and update the loss and gradient
- * of the objective function.
- *
- * @param instance The instance of data point to be added.
- * @return This HuberAggregator object.
- */
- def add(instance: Instance): HuberAggregatorX = {
- instance match { case Instance(label, weight, features) =>
- require(numFeatures == features.size, s"Dimensions mismatch when adding new sample." +
- s" Expecting $numFeatures but got ${features.size}.")
- require(weight >= 0.0, s"instance weight, $weight has to be >= 0.0")
-
- if (weight == 0.0) return this
- val localFeaturesStd = featuresStd
- val localCoefficients = parametersArray
- val localGradientSumArray = gradientSumArray
-
- val margin = {
- var sum = 0.0
- features.foreachActive { (index, value) =>
- sum += localCoefficients.getDouble(index) * value * localFeaturesStd.getDouble(index)
- }
- if (fitIntercept) sum += intercept
- sum
- }
- val linearLoss = label - margin
-
- if (math.abs(linearLoss) <= sigma * epsilon) {
- lossSum += 0.5 * weight * (sigma + math.pow(linearLoss, 2.0) / sigma)
- val linearLossDivSigma = linearLoss / sigma
-
- features.foreachActive { (index, value) =>
- localGradientSumArray.set(index, localGradientSumArray.getDouble(index)
- - 1.0 * weight * linearLossDivSigma * value * localFeaturesStd.getDouble(index))
- }
- if (fitIntercept) {
- localGradientSumArray.set(dim - 2, localGradientSumArray.getDouble(dim - 2)
- - 1.0 * weight * linearLossDivSigma)
- }
- localGradientSumArray.set(dim - 1, localGradientSumArray.getDouble(dim - 1)
- + 0.5 * weight * (1.0 - math.pow(linearLossDivSigma, 2.0)))
- } else {
- val sign = if (linearLoss >= 0) -1.0 else 1.0
- lossSum += 0.5 * weight *
- (sigma + 2.0 * epsilon * math.abs(linearLoss) - sigma * epsilon * epsilon)
-
- features.foreachActive { (index, value) =>
- localGradientSumArray.set(index, localGradientSumArray.getDouble(index)
- + weight * sign * epsilon * value * localFeaturesStd.getDouble(index))
- }
- if (fitIntercept) {
- localGradientSumArray.set(dim - 2, localGradientSumArray.getDouble(dim - 2)
- + weight * sign * epsilon)
- }
- localGradientSumArray.set(dim - 1, localGradientSumArray.getDouble(dim - 1)
- + 0.5 * weight * (1.0 - epsilon * epsilon))
- }
-
- weightSum += weight
- this
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/LeastSquaresAggregatorX.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/LeastSquaresAggregatorX.scala
deleted file mode 100644
index 9677969..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/LeastSquaresAggregatorX.scala
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.optim.aggregator
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.ml.feature.Instance
-import org.apache.spark.ml.linalg.{BLAS, Vector, Vectors}
-
-/**
- * LeastSquaresAggregator computes the gradient and loss for a Least-squared loss function,
- * as used in linear regression for samples in sparse or dense vector in an online fashion.
- *
- * Two LeastSquaresAggregator can be merged together to have a summary of loss and gradient of
- * the corresponding joint dataset.
- *
- * For improving the convergence rate during the optimization process, and also preventing against
- * features with very large variances exerting an overly large influence during model training,
- * package like R's GLMNET performs the scaling to unit variance and removing the mean to reduce
- * the condition number, and then trains the model in scaled space but returns the coefficients in
- * the original scale. See page 9 in http://cran.r-project.org/web/packages/glmnet/glmnet.pdf
- *
- * However, we don't want to apply the `StandardScaler` on the training dataset, and then cache
- * the standardized dataset since it will create a lot of overhead. As a result, we perform the
- * scaling implicitly when we compute the objective function. The following is the mathematical
- * derivation.
- *
- * Note that we don't deal with intercept by adding bias here, because the intercept
- * can be computed using closed form after the coefficients are converged.
- * See this discussion for detail.
- * http://stats.stackexchange.com/questions/13617/how-is-the-intercept-computed-in-glmnet
- *
- * When training with intercept enabled,
- * The objective function in the scaled space is given by
- *
- *
- * $$
- * L = 1/2n ||\sum_i w_i(x_i - \bar{x_i}) / \hat{x_i} - (y - \bar{y}) / \hat{y}||^2,
- * $$
- *
- *
- * where $\bar{x_i}$ is the mean of $x_i$, $\hat{x_i}$ is the standard deviation of $x_i$,
- * $\bar{y}$ is the mean of label, and $\hat{y}$ is the standard deviation of label.
- *
- * If we fitting the intercept disabled (that is forced through 0.0),
- * we can use the same equation except we set $\bar{y}$ and $\bar{x_i}$ to 0 instead
- * of the respective means.
- *
- * This can be rewritten as
- *
- *
- * $$
- * \begin{align}
- * L &= 1/2n ||\sum_i (w_i/\hat{x_i})x_i - \sum_i (w_i/\hat{x_i})\bar{x_i} - y / \hat{y}
- * + \bar{y} / \hat{y}||^2 \\
- * &= 1/2n ||\sum_i w_i^\prime x_i - y / \hat{y} + offset||^2 = 1/2n diff^2
- * \end{align}
- * $$
- *
- *
- * where $w_i^\prime$ is the effective coefficients defined by $w_i/\hat{x_i}$, offset is
- *
- *
- * $$
- * - \sum_i (w_i/\hat{x_i})\bar{x_i} + \bar{y} / \hat{y}.
- * $$
- *
- *
- * and diff is
- *
- *
- * $$
- * \sum_i w_i^\prime x_i - y / \hat{y} + offset
- * $$
- *
- *
- * Note that the effective coefficients and offset don't depend on training dataset,
- * so they can be precomputed.
- *
- * Now, the first derivative of the objective function in scaled space is
- *
- *
- * $$
- * \frac{\partial L}{\partial w_i} = diff/N (x_i - \bar{x_i}) / \hat{x_i}
- * $$
- *
- *
- * However, $(x_i - \bar{x_i})$ will densify the computation, so it's not
- * an ideal formula when the training dataset is sparse format.
- *
- * This can be addressed by adding the dense $\bar{x_i} / \hat{x_i}$ terms
- * in the end by keeping the sum of diff. The first derivative of total
- * objective function from all the samples is
- *
- *
- *
- * $$
- * \begin{align}
- * \frac{\partial L}{\partial w_i} &=
- * 1/N \sum_j diff_j (x_{ij} - \bar{x_i}) / \hat{x_i} \\
- * &= 1/N ((\sum_j diff_j x_{ij} / \hat{x_i}) - diffSum \bar{x_i} / \hat{x_i}) \\
- * &= 1/N ((\sum_j diff_j x_{ij} / \hat{x_i}) + correction_i)
- * \end{align}
- * $$
- *
- *
- * where $correction_i = - diffSum \bar{x_i} / \hat{x_i}$
- *
- * A simple math can show that diffSum is actually zero, so we don't even
- * need to add the correction terms in the end. From the definition of diff,
- *
- *
- * $$
- * \begin{align}
- * diffSum &= \sum_j (\sum_i w_i(x_{ij} - \bar{x_i})
- * / \hat{x_i} - (y_j - \bar{y}) / \hat{y}) \\
- * &= N * (\sum_i w_i(\bar{x_i} - \bar{x_i}) / \hat{x_i} - (\bar{y} - \bar{y}) / \hat{y}) \\
- * &= 0
- * \end{align}
- * $$
- *
- *
- * As a result, the first derivative of the total objective function only depends on
- * the training dataset, which can be easily computed in distributed fashion, and is
- * sparse format friendly.
- *
- *
- * $$
- * \frac{\partial L}{\partial w_i} = 1/N ((\sum_j diff_j x_{ij} / \hat{x_i})
- * $$
- *
- *
- * @note The constructor is curried, since the cost function will repeatedly create new versions
- * of this class for different coefficient vectors.
- *
- * @param labelStd The standard deviation value of the label.
- * @param labelMean The mean value of the label.
- * @param fitIntercept Whether to fit an intercept term.
- * @param bcFeaturesStd The broadcast standard deviation values of the features.
- * @param bcFeaturesMean The broadcast mean values of the features.
- * @param bcCoefficients The broadcast coefficients corresponding to the features.
- */
-private[ml] class LeastSquaresAggregatorX(
- labelStd: Double,
- labelMean: Double,
- fitIntercept: Boolean,
- bcFeaturesStd: Broadcast[Array[Double]],
- bcFeaturesMean: Broadcast[Array[Double]])(bcCoefficients: Broadcast[Vector])
- extends DifferentiableLossAggregatorX[Instance, LeastSquaresAggregatorX] {
- require(labelStd > 0.0, s"${this.getClass.getName} requires the label standard " +
- s"deviation to be positive.")
-
- private val numFeatures = bcFeaturesStd.value.length
- protected override val dim: Int = numFeatures
- // make transient so we do not serialize between aggregation stages
- @transient private lazy val featuresStd = DoubleArrayList.wrap(bcFeaturesStd.value)
- @transient private lazy val effectiveCoefAndOffset = {
- val coefficientsArray = bcCoefficients.value.toArray.clone()
- val featuresMean = bcFeaturesMean.value
- var sum = 0.0
- var i = 0
- val len = coefficientsArray.length
- while (i < len) {
- coefficientsArray(i) *= featuresStd.getDouble(i)
- sum += coefficientsArray(i) * featuresMean(i)
- i += 1
- }
- val offset = if (fitIntercept) labelMean / labelStd - sum else 0.0
- (Vectors.dense(coefficientsArray), offset)
- }
- // do not use tuple assignment above because it will circumvent the @transient tag
- @transient private lazy val effectiveCoefficientsVector = effectiveCoefAndOffset._1
- @transient private lazy val offset = effectiveCoefAndOffset._2
-
- /**
- * Add a new training instance to this LeastSquaresAggregator, and update the loss and gradient
- * of the objective function.
- *
- * @param instance The instance of data point to be added.
- * @return This LeastSquaresAggregator object.
- */
- def add(instance: Instance): LeastSquaresAggregatorX = {
- instance match { case Instance(label, weight, features) =>
- require(numFeatures == features.size, s"Dimensions mismatch when adding new sample." +
- s" Expecting $numFeatures but got ${features.size}.")
- require(weight >= 0.0, s"instance weight, $weight has to be >= 0.0")
-
- if (weight == 0.0) return this
-
- val diff = BLAS.dot(features, effectiveCoefficientsVector) - label / labelStd + offset
-
- if (diff != 0) {
- val localGradientSumArray = gradientSumArray
- val localFeaturesStd = featuresStd
- features.foreachActive { (index, value) =>
- localGradientSumArray.set(index, localGradientSumArray.getDouble(index)
- + weight * diff * value * localFeaturesStd.getDouble(index))
- }
- lossSum += weight * diff * diff / 2.0
- }
- weightSum += weight
- this
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/LogisticAggregatorX.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/LogisticAggregatorX.scala
deleted file mode 100644
index 6ac09f6..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/aggregator/LogisticAggregatorX.scala
+++ /dev/null
@@ -1,379 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.optim.aggregator
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.feature.Instance
-import org.apache.spark.ml.linalg.{DenseVector, Vector}
-import org.apache.spark.mllib.util.MLUtils
-
-/**
- * LogisticAggregator computes the gradient and loss for binary or multinomial logistic (softmax)
- * loss function, as used in classification for instances in sparse or dense vector in an online
- * fashion.
- *
- * Two LogisticAggregators can be merged together to have a summary of loss and gradient of
- * the corresponding joint dataset.
- *
- * For improving the convergence rate during the optimization process and also to prevent against
- * features with very large variances exerting an overly large influence during model training,
- * packages like R's GLMNET perform the scaling to unit variance and remove the mean in order to
- * reduce the condition number. The model is then trained in this scaled space, but returns the
- * coefficients in the original scale. See page 9 in
- * http://cran.r-project.org/web/packages/glmnet/glmnet.pdf
- *
- * However, we don't want to apply the [[org.apache.spark.ml.feature.StandardScaler]] on the
- * training dataset, and then cache the standardized dataset since it will create a lot of overhead.
- * As a result, we perform the scaling implicitly when we compute the objective function (though
- * we do not subtract the mean).
- *
- * Note that there is a difference between multinomial (softmax) and binary loss. The binary case
- * uses one outcome class as a "pivot" and regresses the other class against the pivot. In the
- * multinomial case, the softmax loss function is used to model each class probability
- * independently. Using softmax loss produces `K` sets of coefficients, while using a pivot class
- * produces `K - 1` sets of coefficients (a single coefficient vector in the binary case). In the
- * binary case, we can say that the coefficients are shared between the positive and negative
- * classes. When regularization is applied, multinomial (softmax) loss will produce a result
- * different from binary loss since the positive and negative don't share the coefficients while the
- * binary regression shares the coefficients between positive and negative.
- *
- * The following is a mathematical derivation for the multinomial (softmax) loss.
- *
- * The probability of the multinomial outcome $y$ taking on any of the K possible outcomes is:
- *
- *
- * $$
- * P(y_i=0|\vec{x}_i, \beta) = \frac{e^{\vec{x}_i^T \vec{\beta}_0}}{\sum_{k=0}^{K-1}
- * e^{\vec{x}_i^T \vec{\beta}_k}} \\
- * P(y_i=1|\vec{x}_i, \beta) = \frac{e^{\vec{x}_i^T \vec{\beta}_1}}{\sum_{k=0}^{K-1}
- * e^{\vec{x}_i^T \vec{\beta}_k}}\\
- * P(y_i=K-1|\vec{x}_i, \beta) = \frac{e^{\vec{x}_i^T \vec{\beta}_{K-1}}\,}{\sum_{k=0}^{K-1}
- * e^{\vec{x}_i^T \vec{\beta}_k}}
- * $$
- *
- *
- * The model coefficients $\beta = (\beta_0, \beta_1, \beta_2, ..., \beta_{K-1})$ become a matrix
- * which has dimension of $K \times (N+1)$ if the intercepts are added. If the intercepts are not
- * added, the dimension will be $K \times N$.
- *
- * Note that the coefficients in the model above lack identifiability. That is, any constant scalar
- * can be added to all of the coefficients and the probabilities remain the same.
- *
- *
- * $$
- * \begin{align}
- * \frac{e^{\vec{x}_i^T \left(\vec{\beta}_0 + \vec{c}\right)}}{\sum_{k=0}^{K-1}
- * e^{\vec{x}_i^T \left(\vec{\beta}_k + \vec{c}\right)}}
- * = \frac{e^{\vec{x}_i^T \vec{\beta}_0}e^{\vec{x}_i^T \vec{c}}\,}{e^{\vec{x}_i^T \vec{c}}
- * \sum_{k=0}^{K-1} e^{\vec{x}_i^T \vec{\beta}_k}}
- * = \frac{e^{\vec{x}_i^T \vec{\beta}_0}}{\sum_{k=0}^{K-1} e^{\vec{x}_i^T \vec{\beta}_k}}
- * \end{align}
- * $$
- *
- *
- * However, when regularization is added to the loss function, the coefficients are indeed
- * identifiable because there is only one set of coefficients which minimizes the regularization
- * term. When no regularization is applied, we choose the coefficients with the minimum L2
- * penalty for consistency and reproducibility. For further discussion see:
- *
- * Friedman, et al. "Regularization Paths for Generalized Linear Models via Coordinate Descent"
- *
- * The loss of objective function for a single instance of data (we do not include the
- * regularization term here for simplicity) can be written as
- *
- *
- * $$
- * \begin{align}
- * \ell\left(\beta, x_i\right) &= -log{P\left(y_i \middle| \vec{x}_i, \beta\right)} \\
- * &= log\left(\sum_{k=0}^{K-1}e^{\vec{x}_i^T \vec{\beta}_k}\right) - \vec{x}_i^T \vec{\beta}_y\\
- * &= log\left(\sum_{k=0}^{K-1} e^{margins_k}\right) - margins_y
- * \end{align}
- * $$
- *
- *
- * where ${margins}_k = \vec{x}_i^T \vec{\beta}_k$.
- *
- * For optimization, we have to calculate the first derivative of the loss function, and a simple
- * calculation shows that
- *
- *
- * $$
- * \begin{align}
- * \frac{\partial \ell(\beta, \vec{x}_i, w_i)}{\partial \beta_{j, k}}
- * &= x_{i,j} \cdot w_i \cdot \left(\frac{e^{\vec{x}_i \cdot \vec{\beta}_k}}{\sum_{k'=0}^{K-1}
- * e^{\vec{x}_i \cdot \vec{\beta}_{k'}}\,} - I_{y=k}\right) \\
- * &= x_{i, j} \cdot w_i \cdot multiplier_k
- * \end{align}
- * $$
- *
- *
- * where $w_i$ is the sample weight, $I_{y=k}$ is an indicator function
- *
- *
- * $$
- * I_{y=k} = \begin{cases}
- * 1 & y = k \\
- * 0 & else
- * \end{cases}
- * $$
- *
- *
- * and
- *
- *
- * $$
- * multiplier_k = \left(\frac{e^{\vec{x}_i \cdot \vec{\beta}_k}}{\sum_{k=0}^{K-1}
- * e^{\vec{x}_i \cdot \vec{\beta}_k}} - I_{y=k}\right)
- * $$
- *
- *
- * If any of margins is larger than 709.78, the numerical computation of multiplier and loss
- * function will suffer from arithmetic overflow. This issue occurs when there are outliers in
- * data which are far away from the hyperplane, and this will cause the failing of training once
- * infinity is introduced. Note that this is only a concern when max(margins) > 0.
- *
- * Fortunately, when max(margins) = maxMargin > 0, the loss function and the multiplier can
- * easily be rewritten into the following equivalent numerically stable formula.
- *
- *
- * $$
- * \ell\left(\beta, x\right) = log\left(\sum_{k=0}^{K-1} e^{margins_k - maxMargin}\right) -
- * margins_{y} + maxMargin
- * $$
- *
- *
- * Note that each term, $(margins_k - maxMargin)$ in the exponential is no greater than zero; as a
- * result, overflow will not happen with this formula.
- *
- * For $multiplier$, a similar trick can be applied as the following,
- *
- *
- * $$
- * multiplier_k = \left(\frac{e^{\vec{x}_i \cdot \vec{\beta}_k - maxMargin}}{\sum_{k'=0}^{K-1}
- * e^{\vec{x}_i \cdot \vec{\beta}_{k'} - maxMargin}} - I_{y=k}\right)
- * $$
- *
- *
- *
- * @param bcCoefficients The broadcast coefficients corresponding to the features.
- * @param bcFeaturesStd The broadcast standard deviation values of the features.
- * @param numClasses the number of possible outcomes for k classes classification problem in
- * Multinomial Logistic Regression.
- * @param fitIntercept Whether to fit an intercept term.
- * @param multinomial Whether to use multinomial (softmax) or binary loss
- * @note In order to avoid unnecessary computation during calculation of the gradient updates
- * we lay out the coefficients in column major order during training. This allows us to
- * perform feature standardization once, while still retaining sequential memory access
- * for speed. We convert back to row major order when we create the model,
- * since this form is optimal for the matrix operations used for prediction.
- */
-private[ml] class LogisticAggregatorX(
- bcFeaturesStd: Broadcast[Array[Double]],
- numClasses: Int,
- fitIntercept: Boolean,
- multinomial: Boolean)(bcCoefficients: Broadcast[Vector])
- extends DifferentiableLossAggregatorX[Instance, LogisticAggregatorX] with Logging {
-
- private val numFeatures = bcFeaturesStd.value.length
- private val numFeaturesPlusIntercept = if (fitIntercept) numFeatures + 1 else numFeatures
- private val coefficientSize = bcCoefficients.value.size
- protected override val dim: Int = coefficientSize
- if (multinomial) {
- require(numClasses == coefficientSize / numFeaturesPlusIntercept, s"The number of " +
- s"coefficients should be ${numClasses * numFeaturesPlusIntercept} but was $coefficientSize")
- } else {
- require(coefficientSize == numFeaturesPlusIntercept, s"Expected $numFeaturesPlusIntercept " +
- s"coefficients but got $coefficientSize")
- require(numClasses == 1 || numClasses == 2, s"Binary logistic aggregator requires numClasses " +
- s"in {1, 2} but found $numClasses.")
- }
-
- @transient private lazy val coefficientsArray = DoubleArrayList.wrap(bcCoefficients.value match {
- case DenseVector(values) => values
- case _ => throw new IllegalArgumentException(s"coefficients only supports dense vector but " +
- s"got type ${bcCoefficients.value.getClass}.)")
- })
- @transient private lazy val featuresStdArray = DoubleArrayList.wrap(bcFeaturesStd.value)
-
- if (multinomial && numClasses <= 2) {
- logInfo(s"Multinomial logistic regression for binary classification yields separate " +
- s"coefficients for positive and negative classes. When no regularization is applied, the" +
- s"result will be effectively the same as binary logistic regression. When regularization" +
- s"is applied, multinomial loss will produce a result different from binary loss.")
- }
-
- /** Update gradient and loss using binary loss function. */
- private def binaryUpdateInPlace(features: Vector, weight: Double, label: Double): Unit = {
-
- val localFeaturesStd = featuresStdArray
- val localCoefficients = coefficientsArray
- val localGradientArray = gradientSumArray
- val margin = - {
- var sum = 0.0
- features.foreachActive { (index, value) =>
- sum += localCoefficients.getDouble(index) * value * localFeaturesStd.getDouble(index)
- }
- if (fitIntercept) sum += localCoefficients.getDouble(numFeaturesPlusIntercept - 1)
- sum
- }
-
- val multiplier = weight * (1.0 / (1.0 + math.exp(margin)) - label)
-
- features.foreachActive { (index, value) =>
- localGradientArray.set(index, localGradientArray.getDouble(index)
- + multiplier * value * localFeaturesStd.getDouble(index))
- }
-
- if (fitIntercept) {
- localGradientArray.set(numFeaturesPlusIntercept - 1,
- localGradientArray.getDouble(numFeaturesPlusIntercept - 1) + multiplier)
- }
-
- if (label > 0) {
- // The following is equivalent to log(1 + exp(margin)) but more numerically stable.
- lossSum += weight * MLUtils.log1pExp(margin)
- } else {
- lossSum += weight * (MLUtils.log1pExp(margin) - margin)
- }
- }
-
- /** Update gradient and loss using multinomial (softmax) loss function. */
- private def multinomialUpdateInPlace(features: Vector, weight: Double, label: Double): Unit = {
- // TODO: use level 2 BLAS operations
- /*
- Note: this can still be used when numClasses = 2 for binary
- logistic regression without pivoting.
- */
- val localFeaturesStd = featuresStdArray
- val localCoefficients = coefficientsArray
- val localGradientArray = gradientSumArray
-
- // marginOfLabel is margins(label) in the formula
- var marginOfLabel = 0.0
- var maxMargin = Double.NegativeInfinity
-
- val margins = new Array[Double](numClasses)
- features.foreachActive { (index, value) =>
- val localFeaturesStdValue = localFeaturesStd.getDouble(index)
- if (localFeaturesStdValue != 0.0 && value != 0.0) {
- val stdValue = value * localFeaturesStdValue
- var j = 0
- while (j < numClasses) {
- margins(j) += localCoefficients.getDouble(index * numClasses + j) * stdValue
- j += 1
- }
- }
- }
- var i = 0
- while (i < numClasses) {
- if (fitIntercept) {
- margins(i) += localCoefficients.getDouble(numClasses * numFeatures + i)
- }
- if (i == label.toInt) marginOfLabel = margins(i)
- if (margins(i) > maxMargin) {
- maxMargin = margins(i)
- }
- i += 1
- }
-
- /**
- * When maxMargin is greater than 0, the original formula could cause overflow.
- * We address this by subtracting maxMargin from all the margins, so it's guaranteed
- * that all of the new margins will be smaller than zero to prevent arithmetic overflow.
- */
- val multipliers = new Array[Double](numClasses)
- val sum = {
- var temp = 0.0
- var i = 0
- while (i < numClasses) {
- if (maxMargin > 0) margins(i) -= maxMargin
- val exp = math.exp(margins(i))
- temp += exp
- multipliers(i) = exp
- i += 1
- }
- temp
- }
-
- margins.indices.foreach { i =>
- multipliers(i) = multipliers(i) / sum - (if (label == i) 1.0 else 0.0)
- }
- features.foreachActive { (index, value) =>
- val localFeaturesStdValue = localFeaturesStd.getDouble(index)
- if (localFeaturesStdValue != 0.0 && value != 0.0) {
- val stdValue = value * localFeaturesStdValue
- var j = 0
- while (j < numClasses) {
- val id = index * numClasses + j
- localGradientArray.set(id, localGradientArray.getDouble(id)
- + weight * multipliers(j) * stdValue)
- j += 1
- }
- }
- }
- if (fitIntercept) {
- var i = 0
- while (i < numClasses) {
- val id = numFeatures * numClasses + i
- localGradientArray.set(id, localGradientArray.getDouble(id)
- + weight * multipliers(i))
- i += 1
- }
- }
-
- val loss = if (maxMargin > 0) {
- math.log(sum) - marginOfLabel + maxMargin
- } else {
- math.log(sum) - marginOfLabel
- }
- lossSum += weight * loss
- }
-
- /**
- * Add a new training instance to this LogisticAggregator, and update the loss and gradient
- * of the objective function.
- *
- * @param instance The instance of data point to be added.
- * @return This LogisticAggregator object.
- */
- def add(instance: Instance): this.type = {
- instance match { case Instance(label, weight, features) =>
- require(numFeatures == features.size, s"Dimensions mismatch when adding new instance." +
- s" Expecting $numFeatures but got ${features.size}.")
- require(weight >= 0.0, s"instance weight, $weight has to be >= 0.0")
-
- if (weight == 0.0) return this
-
- if (multinomial) {
- multinomialUpdateInPlace(features, weight, label)
- } else {
- binaryUpdateInPlace(features, weight, label)
- }
- weightSum += weight
- this
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/loss/RDDLossFunctionX.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/loss/RDDLossFunctionX.scala
deleted file mode 100644
index c548b90..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/optim/loss/RDDLossFunctionX.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.optim.loss
-
-import scala.reflect.ClassTag
-
-import breeze.linalg.{DenseVector => BDV}
-import breeze.optimize.DiffFunction
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.ml.linalg.{BLAS, Vector, Vectors}
-import org.apache.spark.ml.optim.aggregator.DifferentiableLossAggregatorX
-import org.apache.spark.rdd.RDD
-
-/**
- * This class computes the gradient and loss of a differentiable loss function by mapping a
- * [[DifferentiableLossAggregatorX]] over an [[RDD]]. The loss function is the
- * sum of the loss computed on a single instance across all points in the RDD. Therefore, the actual
- * analytical form of the loss function is specified by the aggregator, which computes each points
- * contribution to the overall loss.
- *
- * A differentiable regularization component can also be added by providing a
- * [[DifferentiableRegularization]] loss function.
- *
- * @param instances RDD containing the data to compute the loss function over.
- * @param getAggregator A function which gets a new loss aggregator in every tree aggregate step.
- * @param regularization An option representing the regularization loss function to apply to the
- * coefficients.
- * @param aggregationDepth The aggregation depth of the tree aggregation step.
- * @tparam Agg Specialization of [[DifferentiableLossAggregatorX]], representing the concrete type
- * of the aggregator.
- */
-private[ml] class RDDLossFunctionX[
- T: ClassTag,
- Agg <: DifferentiableLossAggregatorX[T, Agg]: ClassTag](
- instances: RDD[T],
- getAggregator: (Broadcast[Vector] => Agg),
- regularization: Option[DifferentiableRegularization[Vector]],
- aggregationDepth: Int = 2)
- extends DiffFunction[BDV[Double]] {
-
- override def calculate(coefficients: BDV[Double]): (Double, BDV[Double]) = {
- val bcCoefficients = instances.context.broadcast(Vectors.fromBreeze(coefficients))
- val thisAgg = getAggregator(bcCoefficients)
- val seqOp = (agg: Agg, x: T) => agg.add(x)
- val combOp = (agg1: Agg, agg2: Agg) => agg1.merge(agg2)
- val newAgg = instances.treeAggregate(thisAgg)(seqOp, combOp, aggregationDepth)
- val gradient = newAgg.gradient
- val regLoss = regularization.map { regFun =>
- val (regLoss, regGradient) = regFun.calculate(Vectors.fromBreeze(coefficients))
- BLAS.axpy(1.0, regGradient, gradient)
- regLoss
- }.getOrElse(0.0)
- bcCoefficients.destroy(blocking = false)
- (newAgg.loss + regLoss, gradient.asBreeze.toDenseVector)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/recommendation/ALS.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/recommendation/ALS.scala
index 917bb52..e3c4bae 100644
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/recommendation/ALS.scala
+++ b/ml-accelerator/src/main/scala/org/apache/spark/ml/recommendation/ALS.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -38,17 +32,18 @@ import org.apache.hadoop.fs.Path
import org.json4s.DefaultFormats
import org.json4s.JsonDSL._
-import org.apache.spark.{Dependency, Partitioner, ShuffleDependency, SparkContext}
-import org.apache.spark.annotation.{DeveloperApi, Since}
+import org.apache.spark.{Partitioner, SparkException}
+import org.apache.spark.annotation.Since
import org.apache.spark.internal.Logging
-import org.apache.spark.ml.{Estimator, Model, StaticUtils}
+import org.apache.spark.ml.{Estimator, Model}
import org.apache.spark.ml.linalg.BLAS
import org.apache.spark.ml.param._
import org.apache.spark.ml.param.shared._
import org.apache.spark.ml.util._
+import org.apache.spark.ml.util.Instrumentation.instrumented
import org.apache.spark.mllib.linalg.CholeskyDecomposition
import org.apache.spark.mllib.optimization.NNLS
-import org.apache.spark.rdd.RDD
+import org.apache.spark.rdd.{DeterministicLevel, RDD}
import org.apache.spark.sql.{DataFrame, Dataset}
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types._
@@ -57,11 +52,11 @@ import org.apache.spark.util.{BoundedPriorityQueue, Utils}
import org.apache.spark.util.collection.{OpenHashMap, OpenHashSet, SortDataFormat, Sorter}
import org.apache.spark.util.random.XORShiftRandom
-
/**
* Common params for ALS and ALSModel.
*/
-private[recommendation] trait ALSModelParams extends Params with HasPredictionCol {
+private[recommendation] trait ALSModelParams extends Params with HasPredictionCol
+ with HasBlockSize {
/**
* Param for the column name for user ids. Ids must be integers. Other
* numeric types are supported for this column, but will be cast to integers as long as they
@@ -132,13 +127,15 @@ private[recommendation] trait ALSModelParams extends Params with HasPredictionCo
/** @group expertGetParam */
def getColdStartStrategy: String = $(coldStartStrategy).toLowerCase(Locale.ROOT)
+
+ setDefault(blockSize -> 4096)
}
/**
* Common params for ALS.
*/
private[recommendation] trait ALSParams extends ALSModelParams with HasMaxIter with HasRegParam
- with HasPredictionCol with HasCheckpointInterval with HasSeed {
+ with HasCheckpointInterval with HasSeed {
/**
* Param for rank of the matrix factorization (positive).
@@ -295,6 +292,15 @@ class ALSModel private[ml] (
@Since("2.2.0")
def setColdStartStrategy(value: String): this.type = set(coldStartStrategy, value)
+ /**
+ * Set block size for stacking input data in matrices.
+ * Default is 4096.
+ *
+ * @group expertSetParam
+ */
+ @Since("3.0.0")
+ def setBlockSize(value: Int): this.type = set(blockSize, value)
+
private val predict = udf { (featuresA: Seq[Float], featuresB: Seq[Float]) =>
if (featuresA != null && featuresB != null) {
var dotProduct = 0.0f
@@ -345,6 +351,11 @@ class ALSModel private[ml] (
@Since("1.6.0")
override def write: MLWriter = new ALSModel.ALSModelWriter(this)
+ @Since("3.0.0")
+ override def toString: String = {
+ s"ALSModel: uid=$uid, rank=$rank"
+ }
+
/**
* Returns top `numItems` items recommended for each user, for all users.
* @param numItems max number of recommendations for each user
@@ -353,7 +364,7 @@ class ALSModel private[ml] (
*/
@Since("2.2.0")
def recommendForAllUsers(numItems: Int): DataFrame = {
- recommendForAll(userFactors, itemFactors, $(userCol), $(itemCol), numItems)
+ recommendForAll(userFactors, itemFactors, $(userCol), $(itemCol), numItems, $(blockSize))
}
/**
@@ -368,7 +379,7 @@ class ALSModel private[ml] (
@Since("2.3.0")
def recommendForUserSubset(dataset: Dataset[_], numItems: Int): DataFrame = {
val srcFactorSubset = getSourceFactorSubset(dataset, userFactors, $(userCol))
- recommendForAll(srcFactorSubset, itemFactors, $(userCol), $(itemCol), numItems)
+ recommendForAll(srcFactorSubset, itemFactors, $(userCol), $(itemCol), numItems, $(blockSize))
}
/**
@@ -379,7 +390,7 @@ class ALSModel private[ml] (
*/
@Since("2.2.0")
def recommendForAllItems(numUsers: Int): DataFrame = {
- recommendForAll(itemFactors, userFactors, $(itemCol), $(userCol), numUsers)
+ recommendForAll(itemFactors, userFactors, $(itemCol), $(userCol), numUsers, $(blockSize))
}
/**
@@ -394,7 +405,7 @@ class ALSModel private[ml] (
@Since("2.3.0")
def recommendForItemSubset(dataset: Dataset[_], numUsers: Int): DataFrame = {
val srcFactorSubset = getSourceFactorSubset(dataset, itemFactors, $(itemCol))
- recommendForAll(srcFactorSubset, userFactors, $(itemCol), $(userCol), numUsers)
+ recommendForAll(srcFactorSubset, userFactors, $(itemCol), $(userCol), numUsers, $(blockSize))
}
/**
@@ -443,11 +454,12 @@ class ALSModel private[ml] (
dstFactors: DataFrame,
srcOutputColumn: String,
dstOutputColumn: String,
- num: Int): DataFrame = {
+ num: Int,
+ blockSize: Int): DataFrame = {
import srcFactors.sparkSession.implicits._
- val srcFactorsBlocked = blockify(srcFactors.as[(Int, Array[Float])])
- val dstFactorsBlocked = blockify(dstFactors.as[(Int, Array[Float])])
+ val srcFactorsBlocked = blockify(srcFactors.as[(Int, Array[Float])], blockSize)
+ val dstFactorsBlocked = blockify(dstFactors.as[(Int, Array[Float])], blockSize)
val ratings = srcFactorsBlocked.crossJoin(dstFactorsBlocked)
.as[(Seq[(Int, Array[Float])], Seq[(Int, Array[Float])])]
.flatMap { case (srcIter, dstIter) =>
@@ -485,11 +497,10 @@ class ALSModel private[ml] (
/**
* Blockifies factors to improve the efficiency of cross join
- * TODO: SPARK-20443 - expose blockSize as a param?
*/
private def blockify(
factors: Dataset[(Int, Array[Float])],
- blockSize: Int = 4096): Dataset[Seq[(Int, Array[Float])]] = {
+ blockSize: Int): Dataset[Seq[(Int, Array[Float])]] = {
import factors.sparkSession.implicits._
factors.mapPartitions(_.grouped(blockSize))
}
@@ -537,7 +548,7 @@ object ALSModel extends MLReadable[ALSModel] {
val model = new ALSModel(metadata.uid, rank, userFactors, itemFactors)
- DefaultParamsReader.getAndSetParams(model, metadata)
+ metadata.getAndSetParams(model)
model
}
}
@@ -564,13 +575,20 @@ object ALSModel extends MLReadable[ALSModel] {
*
* For implicit preference data, the algorithm used is based on
* "Collaborative Filtering for Implicit Feedback Datasets", available at
- * http://dx.doi.org/10.1109/ICDM.2008.22, adapted for the blocked approach used here.
+ * https://doi.org/10.1109/ICDM.2008.22, adapted for the blocked approach used here.
*
* Essentially instead of finding the low-rank approximations to the rating matrix `R`,
* this finds the approximations for a preference matrix `P` where the elements of `P` are 1 if
* r is greater than 0 and 0 if r is less than or equal to 0. The ratings then act as 'confidence'
* values related to strength of indicated user
* preferences rather than explicit ratings given to items.
+ *
+ * Note: the input rating dataset to the ALS implementation should be deterministic.
+ * Nondeterministic data can cause failure during fitting ALS model.
+ * For example, an order-sensitive operation like sampling after a repartition makes dataset
+ * output nondeterministic, like `dataset.repartition(2).sample(false, 0.5, 1618)`.
+ * Checkpointing sampled dataset or adding a sort before sampling can help make the dataset
+ * deterministic.
*/
@Since("1.3.0")
class ALS(@Since("1.4.0") override val uid: String) extends Estimator[ALSModel] with ALSParams
@@ -649,6 +667,15 @@ class ALS(@Since("1.4.0") override val uid: String) extends Estimator[ALSModel]
@Since("2.2.0")
def setColdStartStrategy(value: String): this.type = set(coldStartStrategy, value)
+ /**
+ * Set block size for stacking input data in matrices.
+ * Default is 4096.
+ *
+ * @group expertSetParam
+ */
+ @Since("3.0.0")
+ def setBlockSize(value: Int): this.type = set(blockSize, value)
+
/**
* Sets both numUserBlocks and numItemBlocks to the specific value.
*
@@ -661,10 +688,8 @@ class ALS(@Since("1.4.0") override val uid: String) extends Estimator[ALSModel]
this
}
-
-
@Since("2.0.0")
- override def fit(dataset: Dataset[_]): ALSModel = {
+ override def fit(dataset: Dataset[_]): ALSModel = instrumented { instr =>
transformSchema(dataset.schema)
import dataset.sparkSession.implicits._
@@ -676,11 +701,11 @@ class ALS(@Since("1.4.0") override val uid: String) extends Estimator[ALSModel]
Rating(row.getInt(0), row.getInt(1), row.getFloat(2))
}
-
- val instr = Instrumentation.create(this, ratings)
- instr.logParams(rank, numUserBlocks, numItemBlocks, implicitPrefs, alpha, userCol,
+ instr.logPipelineStage(this)
+ instr.logDataset(dataset)
+ instr.logParams(this, rank, numUserBlocks, numItemBlocks, implicitPrefs, alpha, userCol,
itemCol, ratingCol, predictionCol, maxIter, regParam, nonnegative, checkpointInterval,
- seed, intermediateStorageLevel, finalStorageLevel)
+ seed, intermediateStorageLevel, finalStorageLevel, blockSize)
val (userFactors, itemFactors) = ALS.train(ratings, rank = $(rank),
numUserBlocks = $(numUserBlocks), numItemBlocks = $(numItemBlocks),
@@ -691,8 +716,8 @@ class ALS(@Since("1.4.0") override val uid: String) extends Estimator[ALSModel]
checkpointInterval = $(checkpointInterval), seed = $(seed))
val userDF = userFactors.toDF("id", "features")
val itemDF = itemFactors.toDF("id", "features")
- val model = new ALSModel(uid, $(rank), userDF, itemDF).setParent(this)
- instr.logSuccess(model)
+ val model = new ALSModel(uid, $(rank), userDF, itemDF).setBlockSize($(blockSize))
+ .setParent(this)
copyValues(model)
}
@@ -707,21 +732,17 @@ class ALS(@Since("1.4.0") override val uid: String) extends Estimator[ALSModel]
/**
- * :: DeveloperApi ::
* An implementation of ALS that supports generic ID types, specialized for Int and Long. This is
* exposed as a developer API for users who do need other ID types. But it is not recommended
* because it increases the shuffle size and memory requirement during training. For simplicity,
* users and items must have the same type. The number of distinct users/items should be smaller
* than 2 billion.
*/
-@DeveloperApi
object ALS extends DefaultParamsReadable[ALS] with Logging {
/**
- * :: DeveloperApi ::
* Rating class for better code readability.
*/
- @DeveloperApi
case class Rating[@specialized(Int, Long) ID](user: ID, item: ID, rating: Float)
@Since("1.6.0")
@@ -804,7 +825,7 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
* Given a triangular matrix in the order of fillXtX above, compute the full symmetric square
* matrix that it represents, storing it into destMatrix.
*/
- private def fillAtA(triAtA: Array[Double], lambda: Double) {
+ private def fillAtA(triAtA: Array[Double], lambda: Double): Unit = {
var i = 0
var pos = 0
var a = 0.0
@@ -862,7 +883,7 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
}
/** Adds an observation. */
- def add(a: Array[Float], b: Double, c: Double = 1.0): this.type = {
+ def add(a: Array[Float], b: Double, c: Double = 1.0): NormalEquation = {
require(c >= 0.0)
require(a.length == k)
copyToDouble(a)
@@ -874,7 +895,7 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
}
/** Merges another normal equation object. */
- def merge(other: NormalEquation): this.type = {
+ def merge(other: NormalEquation): NormalEquation = {
require(other.k == k)
blas.daxpy(ata.length, 1.0, other.ata, 1, ata, 1)
blas.daxpy(atb.length, 1.0, other.atb, 1, atb, 1)
@@ -892,7 +913,6 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
val DEFAULT_UNPERSIST_CYCLE = 300
/**
- * :: DeveloperApi ::
* Implementation of the ALS algorithm.
*
* This implementation of the ALS factorization algorithm partitions the two sets of factors among
@@ -917,7 +937,6 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
* "block" as referring to a subset of an RDD containing the ratings rather than a contiguous
* submatrix of the ratings matrix.
*/
- @DeveloperApi
def train[ID: ClassTag]( // scalastyle:ignore
ratings: RDD[Rating[ID]],
rank: Int = 10,
@@ -964,7 +983,6 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
val joinIU = mergedIU.join(userInBlocks).persist()
joinIU.foreachPartition(_)
-
// Encoders for storing each user/item's partition ID and index within its partition using a
// single integer; used as an optimization
val userLocalIndexEncoder = new LocalIndexEncoder(userPart.numPartitions)
@@ -1017,6 +1035,7 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
case x: Exception =>
throw new Exception("'spark.boostkit.ALS.blockMaxRow' value is invalid")
}
+
if (implicitPrefs) {
val dataIterI = new Array[RDD[(Int, ALS.FactorBlock)]](unpersistCycle)
val dataIterU = new Array[RDD[(Int, ALS.FactorBlock)]](unpersistCycle)
@@ -1068,14 +1087,16 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
}
}
-
val userIdAndFactors = userInBlocks
.mapValues(_.srcIds)
.join(userFactors)
.mapPartitions({ items =>
items.flatMap { case (_, (ids, factors)) =>
- ids.view.zip(factors)
+ ids.iterator.zip(factors.iterator)
}
+ // Preserve the partitioning because IDs
+ // are consistent with the partitioners in userInBlocks
+ // and userFactors.
}, preservesPartitioning = true)
.setName("userFactors")
.persist(finalRDDStorageLevel)
@@ -1084,20 +1105,20 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
.join(itemFactors)
.mapPartitions({ items =>
items.flatMap { case (_, (ids, factors)) =>
- ids.view.zip(factors)
+ ids.iterator.zip(factors.iterator)
}
}, preservesPartitioning = true)
.setName("itemFactors")
.persist(finalRDDStorageLevel)
if (finalRDDStorageLevel != StorageLevel.NONE) {
userIdAndFactors.count()
- itemFactors.unpersist()
- itemIdAndFactors.count()
userInBlocks.unpersist()
userOutBlocks.unpersist()
- itemInBlocks.unpersist()
itemOutBlocks.unpersist()
blockRatings.unpersist()
+ itemIdAndFactors.count()
+ itemFactors.unpersist()
+ itemInBlocks.unpersist()
}
(userIdAndFactors, itemIdAndFactors)
}
@@ -1291,16 +1312,19 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
// elements distributed as Normal(0,1) and taking the absolute value, and then normalizing.
// This appears to create factorizations that have a slightly better reconstruction
// (<1%) compared picking elements uniformly at random in [0,1].
- inBlocks.map { case (srcBlockId, inBlock) =>
- val random = new XORShiftRandom(byteswap64(seed ^ srcBlockId))
- val factors = Array.fill(inBlock.srcIds.length) {
- val factor = Array.fill(rank)(random.nextGaussian().toFloat)
- val nrm = blas.snrm2(rank, factor, 1)
- blas.sscal(rank, 1.0f / nrm, factor, 1)
- factor
+ inBlocks.mapPartitions({ iter =>
+ iter.map {
+ case (srcBlockId, inBlock) =>
+ val random = new XORShiftRandom(byteswap64(seed ^ srcBlockId))
+ val factors = Array.fill(inBlock.srcIds.length) {
+ val factor = Array.fill(rank)(random.nextGaussian().toFloat)
+ val nrm = blas.snrm2(rank, factor, 1)
+ blas.sscal(rank, 1.0f / nrm, factor, 1)
+ factor
+ }
+ (srcBlockId, factors)
}
- (srcBlockId, factors)
- }
+ }, preservesPartitioning = true)
}
/**
@@ -1396,7 +1420,7 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
Iterator.empty
}
} ++ {
- builders.view.zipWithIndex.filter(_._1.size > 0).map { case (block, idx) =>
+ builders.iterator.zipWithIndex.filter(_._1.size > 0).map { case (block, idx) =>
val srcBlockId = idx % srcPart.numPartitions
val dstBlockId = idx / srcPart.numPartitions
((srcBlockId, dstBlockId), block.build())
@@ -1632,7 +1656,7 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
val dstIdSet = new OpenHashSet[ID](1 << 20)
dstIds.foreach(dstIdSet.add)
val sortedDstIds = new Array[ID](dstIdSet.size)
- var i = StaticUtils.ZERO_INT
+ var i = 0
var pos = dstIdSet.nextPos(0)
while (pos != -1) {
sortedDstIds(i) = dstIdSet.getValue(pos)
@@ -1784,6 +1808,7 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
ne.copyATA(d)
}
+
/**
* Encoder for storing (blockId, localIndex) into a single integer.
*
@@ -1827,31 +1852,4 @@ object ALS extends DefaultParamsReadable[ALS] with Logging {
* satisfies this requirement, we simply use a type alias here.
*/
private[recommendation] type ALSPartitioner = org.apache.spark.HashPartitioner
-
- /**
- * Private function to clean up all of the shuffles files from the dependencies and their parents.
- */
- private[spark] def cleanShuffleDependencies[T](
- sc: SparkContext,
- deps: Seq[Dependency[_]],
- blocking: Boolean = false): Unit = {
- // If there is no reference tracking we skip clean up.
- sc.cleaner.foreach { cleaner =>
- /**
- * Clean the shuffles & all of its parents.
- */
- def cleanEagerly(dep: Dependency[_]): Unit = {
- if (dep.isInstanceOf[ShuffleDependency[_, _, _]]) {
- val shuffleId = dep.asInstanceOf[ShuffleDependency[_, _, _]].shuffleId
- cleaner.doCleanupShuffle(shuffleId, blocking)
- }
- val rdd = dep.rdd
- val rddDeps = rdd.dependencies
- if (rdd.getStorageLevel == StorageLevel.NONE && rddDeps != null) {
- rddDeps.foreach(cleanEagerly)
- }
- }
- deps.foreach(cleanEagerly)
- }
- }
-}
+}
\ No newline at end of file
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/DecisionTreeRegressor.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/DecisionTreeRegressor.scala
deleted file mode 100644
index c6f1aa4..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/DecisionTreeRegressor.scala
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.regression
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-import it.unimi.dsi.fastutil.ints.{Int2ObjectOpenHashMap, IntArrayList}
-import it.unimi.dsi.fastutil.objects.ObjectArrayList
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.ml.Predictor
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.linalg.Vector
-import org.apache.spark.ml.param.ParamMap
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.DecisionForest
-import org.apache.spark.ml.tree.impl.DecisionTreeMetadata
-import org.apache.spark.ml.tree.impl.RandomForest4GBDTX
-import org.apache.spark.ml.tree.impl.TreePoint
-import org.apache.spark.ml.util._
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo, Strategy => OldStrategy}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.Dataset
-
-
-/**
- * Decision tree
- * learning algorithm for regression.
- * It supports both continuous and categorical features.
- */
-@Since("1.4.0")
-class DecisionTreeRegressor @Since("1.4.0") (@Since("1.4.0") override val uid: String)
- extends Predictor[Vector, DecisionTreeRegressor, DecisionTreeRegressionModel]
- with DecisionTreeRegressorParams with DefaultParamsWritable {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("dtr"))
-
- // Override parameter setters from parent trait for Java API compatibility.
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxDepth(value: Int): this.type = set(maxDepth, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxBins(value: Int): this.type = set(maxBins, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInstancesPerNode(value: Int): this.type = set(minInstancesPerNode, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInfoGain(value: Double): this.type = set(minInfoGain, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setMaxMemoryInMB(value: Int): this.type = set(maxMemoryInMB, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setCacheNodeIds(value: Boolean): this.type = set(cacheNodeIds, value)
-
- /**
- * Specifies how often to checkpoint the cached node IDs.
- * E.g. 10 means that the cache will get checkpointed every 10 iterations.
- * This is only used if cacheNodeIds is true and if the checkpoint directory is set in
- * [[org.apache.spark.SparkContext]].
- * Must be at least 1.
- * (default = 10)
- * @group setParam
- */
- @Since("1.4.0")
- override def setCheckpointInterval(value: Int): this.type = set(checkpointInterval, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setImpurity(value: String): this.type = set(impurity, value)
-
- /** @group setParam */
- @Since("1.6.0")
- override def setSeed(value: Long): this.type = set(seed, value)
-
- /** @group setParam */
- @Since("2.0.0")
- def setVarianceCol(value: String): this.type = set(varianceCol, value)
-
- override protected def train(dataset: Dataset[_]): DecisionTreeRegressionModel = {
- val categoricalFeatures: Map[Int, Int] =
- MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
- val oldDataset: RDD[LabeledPoint] = extractLabeledPoints(dataset)
- val strategy = getOldStrategy(categoricalFeatures)
-
- val instr = Instrumentation.create(this, oldDataset)
- instr.logParams(params: _*)
-
- val trees = DecisionForest.run(oldDataset, strategy, numTrees = 1,
- featureSubsetStrategy = "all", seed = $(seed), instr = Some(instr), parentUID = Some(uid))
-
- val m = trees.head.asInstanceOf[DecisionTreeRegressionModel]
- instr.logSuccess(m)
- m
- }
-
- /** (private[ml]) Train a decision tree on an RDD */
- private[ml] def train(
- data: RDD[LabeledPoint],
- oldStrategy: OldStrategy,
- featureSubsetStrategy: String): DecisionTreeRegressionModel = {
- val instr = Instrumentation.create(this, data)
- instr.logParams(params: _*)
-
- val trees = DecisionForest.run(data, oldStrategy, numTrees = 1, featureSubsetStrategy,
- seed = $(seed), instr = Some(instr), parentUID = Some(uid))
-
- val m = trees.head.asInstanceOf[DecisionTreeRegressionModel]
- instr.logSuccess(m)
- m
- }
-
- /** (private[ml]) Train a decision tree on an RDD */
- private[ml] def train4GBDTX(
- labelArrayBc: Broadcast[DoubleArrayList],
- processedInput: RDD[(Int, (IntArrayList, ObjectArrayList[Split]))],
- metadata: DecisionTreeMetadata,
- splits: Array[Array[Split]],
- oldStrategy: OldStrategy,
- featureSubsetStrategy: String,
- input: RDD[TreePoint],
- rawPartInfoBc: Broadcast[Int2ObjectOpenHashMap[IntArrayList]]):
- DecisionTreeRegressionModel = {
- val instr = Instrumentation.create(this, processedInput)
- instr.logParams(params: _*)
-
- val trees = RandomForest4GBDTX.runX(labelArrayBc, processedInput, metadata,
- splits, oldStrategy, numTrees = 1, seed = $(seed), input,
- rawPartInfoBc, parentUID = Some(uid))
-
- val m = trees.head.asInstanceOf[DecisionTreeRegressionModel]
- instr.logSuccess(m)
- m
- }
-
-
- /** (private[ml]) Create a Strategy instance to use with the old API. */
- private[ml] def getOldStrategy(categoricalFeatures: Map[Int, Int]): OldStrategy = {
- super.getOldStrategy(categoricalFeatures, numClasses = 0, OldAlgo.Regression, getOldImpurity,
- subsamplingRate = 1.0)
- }
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): DecisionTreeRegressor = defaultCopy(extra)
-}
-
-@Since("1.4.0")
-object DecisionTreeRegressor extends DefaultParamsReadable[DecisionTreeRegressor] {
- /** Accessor for supported impurities: variance */
- final val supportedImpurities: Array[String] = TreeRegressorParams.supportedImpurities
-
- @Since("2.0.0")
- override def load(path: String): DecisionTreeRegressor = super.load(path)
-}
-
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala
deleted file mode 100644
index ac7c2ba..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/GBTRegressor.scala
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.regression
-
-import com.github.fommil.netlib.BLAS.{getInstance => blas}
-import org.json4s.{DefaultFormats, JObject}
-import org.json4s.JsonDSL._
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.{PredictionModel, Predictor}
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.linalg.Vector
-import org.apache.spark.ml.param.ParamMap
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.GradientBoostedTrees
-import org.apache.spark.ml.util._
-import org.apache.spark.ml.util.DefaultParamsReader.Metadata
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo}
-import org.apache.spark.mllib.tree.model.{GradientBoostedTreesModel => OldGBTModel}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{DataFrame, Dataset}
-import org.apache.spark.sql.functions._
-
-/**
- * Gradient-Boosted Trees (GBTs)
- * learning algorithm for regression.
- * It supports both continuous and categorical features.
- *
- * The implementation is based upon: J.H. Friedman. "Stochastic Gradient Boosting." 1999.
- *
- * Notes on Gradient Boosting vs. TreeBoost:
- * - This implementation is for Stochastic Gradient Boosting, not for TreeBoost.
- * - Both algorithms learn tree ensembles by minimizing loss functions.
- * - TreeBoost (Friedman, 1999) additionally modifies the outputs at tree leaf nodes
- * based on the loss function, whereas the original gradient boosting method does not.
- * - When the loss is SquaredError, these methods give the same result, but they could differ
- * for other loss functions.
- * - We expect to implement TreeBoost in the future:
- * [https://issues.apache.org/jira/browse/SPARK-4240]
- */
-@Since("1.4.0")
-class GBTRegressor @Since("1.4.0") (@Since("1.4.0") override val uid: String)
- extends Predictor[Vector, GBTRegressor, GBTRegressionModel]
- with GBTRegressorParams with DefaultParamsWritable with Logging {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("gbtr"))
-
- // Override parameter setters from parent trait for Java API compatibility.
-
- // Parameters from TreeRegressorParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxDepth(value: Int): this.type = set(maxDepth, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxBins(value: Int): this.type = set(maxBins, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInstancesPerNode(value: Int): this.type = set(minInstancesPerNode, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInfoGain(value: Double): this.type = set(minInfoGain, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setMaxMemoryInMB(value: Int): this.type = set(maxMemoryInMB, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setCacheNodeIds(value: Boolean): this.type = set(cacheNodeIds, value)
-
- /**
- * Specifies how often to checkpoint the cached node IDs.
- * E.g. 10 means that the cache will get checkpointed every 10 iterations.
- * This is only used if cacheNodeIds is true and if the checkpoint directory is set in
- * [[org.apache.spark.SparkContext]].
- * Must be at least 1.
- * (default = 10)
- * @group setParam
- */
- @Since("1.4.0")
- override def setCheckpointInterval(value: Int): this.type = set(checkpointInterval, value)
-
- /**
- * The impurity setting is ignored for GBT models.
- * Individual trees are built using impurity "Variance."
- *
- * @group setParam
- */
- @Since("1.4.0")
- override def setImpurity(value: String): this.type = {
- logWarning("GBTRegressor.setImpurity should NOT be used")
- this
- }
-
- // Parameters from TreeEnsembleParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSubsamplingRate(value: Double): this.type = set(subsamplingRate, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSeed(value: Long): this.type = set(seed, value)
-
- // Parameters from GBTParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxIter(value: Int): this.type = set(maxIter, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setStepSize(value: Double): this.type = set(stepSize, value)
-
- // Parameters from GBTRegressorParams:
-
- /** @group setParam */
- @Since("1.4.0")
- def setLossType(value: String): this.type = set(lossType, value)
-
- /** @group setParam */
- @Since("2.3.0")
- override def setFeatureSubsetStrategy(value: String): this.type =
- set(featureSubsetStrategy, value)
-
- override protected def train(dataset: Dataset[_]): GBTRegressionModel = {
- val categoricalFeatures: Map[Int, Int] =
- MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
- val oldDataset: RDD[LabeledPoint] = extractLabeledPoints(dataset)
- val numFeatures = oldDataset.first().features.size
- val boostingStrategy = super.getOldBoostingStrategy(categoricalFeatures, OldAlgo.Regression)
-
- val instr = Instrumentation.create(this, oldDataset)
- instr.logParams(labelCol, featuresCol, predictionCol, impurity, lossType,
- maxDepth, maxBins, maxIter, maxMemoryInMB, minInfoGain, minInstancesPerNode,
- seed, stepSize, subsamplingRate, cacheNodeIds, checkpointInterval, featureSubsetStrategy)
- instr.logNumFeatures(numFeatures)
-
- val (doUseAcc, setUseAccFlag) = super.getDoUseAcc
- val (baseLearners, learnerWeights) = if (setUseAccFlag) {
- GradientBoostedTrees.run(oldDataset, boostingStrategy,
- $(seed), $(featureSubsetStrategy), doUseAcc)
- } else {
- GradientBoostedTrees.run(oldDataset, boostingStrategy,
- $(seed), $(featureSubsetStrategy))
- }
- val m = new GBTRegressionModel(uid, baseLearners, learnerWeights, numFeatures)
- instr.logSuccess(m)
- m
- }
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): GBTRegressor = defaultCopy(extra)
-}
-
-@Since("1.4.0")
-object GBTRegressor extends DefaultParamsReadable[GBTRegressor] {
-
- /** Accessor for supported loss settings: squared (L2), absolute (L1) */
- @Since("1.4.0")
- final val supportedLossTypes: Array[String] = GBTRegressorParams.supportedLossTypes
-
- @Since("2.0.0")
- override def load(path: String): GBTRegressor = super.load(path)
-}
-
-/**
- * Gradient-Boosted Trees (GBTs)
- * model for regression.
- * It supports both continuous and categorical features.
- * @param _trees Decision trees in the ensemble.
- * @param _treeWeights Weights for the decision trees in the ensemble.
- */
-@Since("1.4.0")
-class GBTRegressionModel private[ml](
- override val uid: String,
- private val _trees: Array[DecisionTreeRegressionModel],
- private val _treeWeights: Array[Double],
- override val numFeatures: Int)
- extends PredictionModel[Vector, GBTRegressionModel]
- with GBTRegressorParams with TreeEnsembleModel[DecisionTreeRegressionModel]
- with MLWritable with Serializable {
-
- require(_trees.nonEmpty, "GBTRegressionModel requires at least 1 tree.")
- require(_trees.length == _treeWeights.length, "GBTRegressionModel given trees, treeWeights of" +
- s" non-matching lengths (${_trees.length}, ${_treeWeights.length}, respectively).")
-
- /**
- * Construct a GBTRegressionModel
- * @param _trees Decision trees in the ensemble.
- * @param _treeWeights Weights for the decision trees in the ensemble.
- */
- @Since("1.4.0")
- def this(uid: String, _trees: Array[DecisionTreeRegressionModel], _treeWeights: Array[Double]) =
- this(uid, _trees, _treeWeights, -1)
-
- @Since("1.4.0")
- override def trees: Array[DecisionTreeRegressionModel] = _trees
-
- /**
- * Number of trees in ensemble
- */
- @Since("2.0.0")
- val getNumTrees: Int = trees.length
-
- @Since("1.4.0")
- override def treeWeights: Array[Double] = _treeWeights
-
- override protected def transformImpl(dataset: Dataset[_]): DataFrame = {
- val bcastModel = dataset.sparkSession.sparkContext.broadcast(this)
- val predictUDF = udf { (features: Any) =>
- bcastModel.value.predict(features.asInstanceOf[Vector])
- }
- dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
- }
-
- override protected def predict(features: Vector): Double = {
- // TODO: When we add a generic Boosting class, handle transform there? SPARK-7129
- // Classifies by thresholding sum of weighted tree predictions
- val treePredictions = _trees.map(_.rootNode.predictImpl(features).prediction)
- blas.ddot(numTrees, treePredictions, 1, _treeWeights, 1)
- }
-
- /** Number of trees in ensemble */
- val numTrees: Int = trees.length
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): GBTRegressionModel = {
- copyValues(new GBTRegressionModel(uid, _trees, _treeWeights, numFeatures),
- extra).setParent(parent)
- }
-
- @Since("1.4.0")
- override def toString: String = {
- s"GBTRegressionModel (uid=$uid) with $numTrees trees"
- }
-
- /**
- * Estimate of the importance of each feature.
- *
- * Each feature's importance is the average of its importance across all trees in the ensemble
- * The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
- * (Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
- * and follows the implementation from scikit-learn.
- *
- * @see `DecisionTreeRegressionModel.featureImportances`
- */
- @Since("2.0.0")
- lazy val featureImportances: Vector = TreeEnsembleModel.featureImportances(trees, numFeatures)
-
- /** (private[ml]) Convert to a model in the old API */
- private[ml] def toOld: OldGBTModel = {
- new OldGBTModel(OldAlgo.Regression, _trees.map(_.toOld), _treeWeights)
- }
-
- @Since("2.0.0")
- override def write: MLWriter = new GBTRegressionModel.GBTRegressionModelWriter(this)
-}
-
-@Since("2.0.0")
-object GBTRegressionModel extends MLReadable[GBTRegressionModel] {
-
- @Since("2.0.0")
- override def read: MLReader[GBTRegressionModel] = new GBTRegressionModelReader
-
- @Since("2.0.0")
- override def load(path: String): GBTRegressionModel = super.load(path)
-
- private[GBTRegressionModel]
- class GBTRegressionModelWriter(instance: GBTRegressionModel) extends MLWriter {
-
- override protected def saveImpl(path: String): Unit = {
- val extraMetadata: JObject = Map(
- "numFeatures" -> instance.numFeatures,
- "numTrees" -> instance.getNumTrees)
- EnsembleModelReadWrite.saveImpl(instance, path, sparkSession, extraMetadata)
- }
- }
-
- private class GBTRegressionModelReader extends MLReader[GBTRegressionModel] {
-
- /** Checked against metadata when loading model */
- private val className = classOf[GBTRegressionModel].getName
- private val treeClassName = classOf[DecisionTreeRegressionModel].getName
-
- override def load(path: String): GBTRegressionModel = {
- implicit val format = DefaultFormats
- val (metadata: Metadata, treesData: Array[(Metadata, Node)], treeWeights: Array[Double]) =
- EnsembleModelReadWrite.loadImpl(path, sparkSession, className, treeClassName)
-
- val numFeatures = (metadata.metadata \ "numFeatures").extract[Int]
- val numTrees = (metadata.metadata \ "numTrees").extract[Int]
-
- val trees: Array[DecisionTreeRegressionModel] = treesData.map {
- case (treeMetadata, root) =>
- val tree =
- new DecisionTreeRegressionModel(treeMetadata.uid, root, numFeatures)
- DefaultParamsReader.getAndSetParams(tree, treeMetadata)
- tree
- }
-
- require(numTrees == trees.length, s"GBTRegressionModel.load expected $numTrees" +
- s" trees based on metadata but found ${trees.length} trees.")
-
- val model = new GBTRegressionModel(metadata.uid, trees, treeWeights, numFeatures)
- DefaultParamsReader.getAndSetParams(model, metadata)
- model
- }
- }
-
- /** Convert a model from the old API */
- private[ml] def fromOld(
- oldModel: OldGBTModel,
- parent: GBTRegressor,
- categoricalFeatures: Map[Int, Int],
- numFeatures: Int = -1): GBTRegressionModel = {
- require(oldModel.algo == OldAlgo.Regression, "Cannot convert GradientBoostedTreesModel" +
- s" with algo=${oldModel.algo} (old API) to GBTRegressionModel (new API).")
- val newTrees = oldModel.trees.map { tree =>
- // parent for each tree is null since there is no good way to set this.
- DecisionTreeRegressionModel.fromOld(tree, null, categoricalFeatures)
- }
- val uid = if (parent != null) parent.uid else Identifiable.randomUID("gbtr")
- new GBTRegressionModel(uid, newTrees, oldModel.treeWeights, numFeatures)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/LinearRegression.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/LinearRegression.scala
deleted file mode 100644
index 0f00bce..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/LinearRegression.scala
+++ /dev/null
@@ -1,565 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.regression
-
-import scala.collection.mutable
-
-import breeze.linalg.{DenseVector => BDV}
-import breeze.optimize.{CachedDiffFunction, LBFGSL, OWLQNL}
-
-import org.apache.spark.SparkException
-import org.apache.spark.annotation.Since
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.StaticUtils
-import org.apache.spark.ml.feature.Instance
-import org.apache.spark.ml.linalg.{Vector, Vectors}
-import org.apache.spark.ml.linalg.BLAS._
-import org.apache.spark.ml.optim.WeightedLeastSquares
-import org.apache.spark.ml.optim.aggregator.{HuberAggregatorX, LeastSquaresAggregatorX}
-import org.apache.spark.ml.optim.loss.{L2Regularization, RDDLossFunctionX}
-import org.apache.spark.ml.param.ParamMap
-import org.apache.spark.ml.util._
-import org.apache.spark.mllib.linalg.VectorImplicits._
-import org.apache.spark.mllib.stat.MultivariateOnlineSummarizer
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{Dataset, Row}
-import org.apache.spark.sql.functions._
-import org.apache.spark.storage.StorageLevel
-
-/**
- * Linear regression.
- *
- * The learning objective is to minimize the specified loss function, with regularization.
- * This supports two kinds of loss:
- * - squaredError (a.k.a squared loss)
- * - huber (a hybrid of squared error for relatively small errors and absolute error for
- * relatively large ones, and we estimate the scale parameter from training data)
- *
- * This supports multiple types of regularization:
- * - none (a.k.a. ordinary least squares)
- * - L2 (ridge regression)
- * - L1 (Lasso)
- * - L2 + L1 (elastic net)
- *
- * The squared error objective function is:
- *
- *
- * $$
- * \begin{align}
- * \min_{w}\frac{1}{2n}{\sum_{i=1}^n(X_{i}w - y_{i})^{2} +
- * \lambda\left[\frac{1-\alpha}{2}{||w||_{2}}^{2} + \alpha{||w||_{1}}\right]}
- * \end{align}
- * $$
- *
- *
- * The huber objective function is:
- *
- *
- * $$
- * \begin{align}
- * \min_{w, \sigma}\frac{1}{2n}{\sum_{i=1}^n\left(\sigma +
- * H_m\left(\frac{X_{i}w - y_{i}}{\sigma}\right)\sigma\right) + \frac{1}{2}\lambda {||w||_2}^2}
- * \end{align}
- * $$
- *
- *
- * where
- *
- *
- * $$
- * \begin{align}
- * H_m(z) = \begin{cases}
- * z^2, & \text {if } |z| < \epsilon, \\
- * 2\epsilon|z| - \epsilon^2, & \text{otherwise}
- * \end{cases}
- * \end{align}
- * $$
- *
- *
- * Note: Fitting with huber loss only supports none and L2 regularization.
- */
-@Since("1.3.0")
-class LinearRegression @Since("1.3.0") (@Since("1.3.0") override val uid: String)
- extends Regressor[Vector, LinearRegression, LinearRegressionModel]
- with LinearRegressionParams with DefaultParamsWritable with Logging {
-
- import LinearRegression._
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("linReg"))
-
- /**
- * Set the regularization parameter.
- * Default is 0.0.
- *
- * @group setParam
- */
- @Since("1.3.0")
- def setRegParam(value: Double): this.type = set(regParam, value)
- setDefault(regParam -> 0.0)
-
- /**
- * Set if we should fit the intercept.
- * Default is true.
- *
- * @group setParam
- */
- @Since("1.5.0")
- def setFitIntercept(value: Boolean): this.type = set(fitIntercept, value)
- setDefault(fitIntercept -> true)
-
- /**
- * Whether to standardize the training features before fitting the model.
- * The coefficients of models will be always returned on the original scale,
- * so it will be transparent for users.
- * Default is true.
- *
- * @note With/without standardization, the models should be always converged
- * to the same solution when no regularization is applied. In R's GLMNET package,
- * the default behavior is true as well.
- *
- * @group setParam
- */
- @Since("1.5.0")
- def setStandardization(value: Boolean): this.type = set(standardization, value)
- setDefault(standardization -> true)
-
- /**
- * Set the ElasticNet mixing parameter.
- * For alpha = 0, the penalty is an L2 penalty.
- * For alpha = 1, it is an L1 penalty.
- * For alpha in (0,1), the penalty is a combination of L1 and L2.
- * Default is 0.0 which is an L2 penalty.
- *
- * Note: Fitting with huber loss only supports None and L2 regularization,
- * so throws exception if this param is non-zero value.
- *
- * @group setParam
- */
- @Since("1.4.0")
- def setElasticNetParam(value: Double): this.type = set(elasticNetParam, value)
- setDefault(elasticNetParam -> 0.0)
-
- /**
- * Set the maximum number of iterations.
- * Default is 100.
- *
- * @group setParam
- */
- @Since("1.3.0")
- def setMaxIter(value: Int): this.type = set(maxIter, value)
- setDefault(maxIter -> 100)
-
- /**
- * Set the convergence tolerance of iterations.
- * Smaller value will lead to higher accuracy with the cost of more iterations.
- * Default is 1E-6.
- *
- * @group setParam
- */
- @Since("1.4.0")
- def setTol(value: Double): this.type = set(tol, value)
- setDefault(tol -> 1E-6)
-
- /**
- * Whether to over-/under-sample training instances according to the given weights in weightCol.
- * If not set or empty, all instances are treated equally (weight 1.0).
- * Default is not set, so all instances have weight one.
- *
- * @group setParam
- */
- @Since("1.6.0")
- def setWeightCol(value: String): this.type = set(weightCol, value)
-
- /**
- * Set the solver algorithm used for optimization.
- * In case of linear regression, this can be "l-bfgs", "normal" and "auto".
- * - "l-bfgs" denotes Limited-memory BFGS which is a limited-memory quasi-Newton
- * optimization method.
- * - "normal" denotes using Normal Equation as an analytical solution to the linear regression
- * problem. This solver is limited to `LinearRegression.MAX_FEATURES_FOR_NORMAL_SOLVER`.
- * - "auto" (default) means that the solver algorithm is selected automatically.
- * The Normal Equations solver will be used when possible, but this will automatically fall
- * back to iterative optimization methods when needed.
- *
- * Note: Fitting with huber loss doesn't support normal solver,
- * so throws exception if this param was set with "normal".
- * @group setParam
- */
- @Since("1.6.0")
- def setSolver(value: String): this.type = set(solver, value)
- setDefault(solver -> Auto)
-
- /**
- * Suggested depth for treeAggregate (greater than or equal to 2).
- * If the dimensions of features or the number of partitions are large,
- * this param could be adjusted to a larger size.
- * Default is 2.
- *
- * @group expertSetParam
- */
- @Since("2.1.0")
- def setAggregationDepth(value: Int): this.type = set(aggregationDepth, value)
- setDefault(aggregationDepth -> 2)
-
- /**
- * Sets the value of param [[loss]].
- * Default is "squaredError".
- *
- * @group setParam
- */
- @Since("2.3.0")
- def setLoss(value: String): this.type = set(loss, value)
- setDefault(loss -> SquaredError)
-
- /**
- * Sets the value of param [[epsilon]].
- * Default is 1.35.
- *
- * @group setExpertParam
- */
- @Since("2.3.0")
- def setEpsilon(value: Double): this.type = set(epsilon, value)
- setDefault(epsilon -> 1.35)
-
- override protected def train(dataset: Dataset[_]): LinearRegressionModel = {
- // Extract the number of features before deciding optimization solver.
- val numFeatures = dataset.select(col($(featuresCol))).first()
- .getAs[Vector](StaticUtils.ZERO_INT).size
- val w = if (!isDefined(weightCol) || $(weightCol).isEmpty) lit(1.0) else col($(weightCol))
-
- val instances: RDD[Instance] = dataset.select(
- col($(labelCol)), w, col($(featuresCol))).rdd.map {
- case Row(label: Double, weight: Double, features: Vector) =>
- Instance(label, weight + StaticUtils.ZERO_DOUBLE, features)
- }
-
- val instr = Instrumentation.create(this, dataset)
- instr.logParams(labelCol, featuresCol, weightCol, predictionCol, solver, tol, elasticNetParam,
- fitIntercept, maxIter, regParam, standardization, aggregationDepth, loss, epsilon)
- instr.logNumFeatures(numFeatures)
-
- if ($(loss) == SquaredError && (($(solver) == Auto &&
- numFeatures <= WeightedLeastSquares.MAX_NUM_FEATURES) || $(solver) == Normal)) {
- // For low dimensional data, WeightedLeastSquares is more efficient since the
- // training algorithm only requires one pass through the data. (SPARK-10668)
-
- val optimizer = new WeightedLeastSquares($(fitIntercept), $(regParam),
- elasticNetParam = $(elasticNetParam), $(standardization), true,
- solverType = WeightedLeastSquares.Auto, maxIter = $(maxIter), tol = $(tol))
- val model = optimizer.fit(instances)
- // When it is trained by WeightedLeastSquares, training summary does not
- // attach returned model.
- val lrModel = copyValues(new LinearRegressionModel(uid, model.coefficients, model.intercept))
- val (summaryModel, predictionColName) = lrModel.findSummaryModelAndPredictionCol()
- val trainingSummary = new LinearRegressionTrainingSummary(
- summaryModel.transform(dataset),
- predictionColName,
- $(labelCol),
- $(featuresCol),
- summaryModel,
- model.diagInvAtWA.toArray,
- model.objectiveHistory)
-
- lrModel.setSummary(Some(trainingSummary))
- instr.logSuccess(lrModel)
- return lrModel
- }
-
- val handlePersistence = dataset.storageLevel == StorageLevel.NONE
- if (handlePersistence) instances.persist(StorageLevel.MEMORY_AND_DISK)
-
- val (featuresSummarizer, ySummarizer) = {
- val seqOp = (c: (MultivariateOnlineSummarizer, MultivariateOnlineSummarizer),
- instance: Instance) =>
- (c._1.add(instance.features, instance.weight),
- c._2.add(Vectors.dense(instance.label), instance.weight))
-
- val combOp = (c1: (MultivariateOnlineSummarizer, MultivariateOnlineSummarizer),
- c2: (MultivariateOnlineSummarizer, MultivariateOnlineSummarizer)) =>
- (c1._1.merge(c2._1), c1._2.merge(c2._2))
-
- instances.treeAggregate(
- (new MultivariateOnlineSummarizer, new MultivariateOnlineSummarizer)
- )(seqOp, combOp, $(aggregationDepth))
- }
-
- val yMean = ySummarizer.mean(0)
- val rawYStd = math.sqrt(ySummarizer.variance(0))
- if (rawYStd == 0.0) {
- if ($(fitIntercept) || yMean == 0.0) {
- // If the rawYStd==0 and fitIntercept==true, then the intercept is yMean with
- // zero coefficient; as a result, training is not needed.
- // Also, if yMean==0 and rawYStd==0, all the coefficients are zero regardless of
- // the fitIntercept.
- if (yMean == 0.0) {
- logWarning(s"Mean and standard deviation of the label are zero, so the coefficients " +
- s"and the intercept will all be zero; as a result, training is not needed.")
- } else {
- logWarning(s"The standard deviation of the label is zero, so the coefficients will be " +
- s"zeros and the intercept will be the mean of the label; as a result, " +
- s"training is not needed.")
- }
- if (handlePersistence) instances.unpersist()
- val coefficients = Vectors.sparse(numFeatures, Seq.empty)
- val intercept = yMean
-
- val model = copyValues(new LinearRegressionModel(uid, coefficients, intercept))
- // Handle possible missing or invalid prediction columns
- val (summaryModel, predictionColName) = model.findSummaryModelAndPredictionCol()
-
- val trainingSummary = new LinearRegressionTrainingSummary(
- summaryModel.transform(dataset),
- predictionColName,
- $(labelCol),
- $(featuresCol),
- model,
- Array(0D),
- Array(0D))
-
- model.setSummary(Some(trainingSummary))
- instr.logSuccess(model)
- return model
- } else {
- require($(regParam) == 0.0, "The standard deviation of the label is zero. " +
- "Model cannot be regularized.")
- logWarning(s"The standard deviation of the label is zero. " +
- "Consider setting fitIntercept=true.")
- }
- }
-
- // if y is constant (rawYStd is zero), then y cannot be scaled. In this case
- // setting yStd=abs(yMean) ensures that y is not scaled anymore in l-bfgs algorithm.
- val yStd = if (rawYStd > 0) rawYStd else math.abs(yMean)
- val featuresMean = featuresSummarizer.mean.toArray
- val featuresStd = featuresSummarizer.variance.toArray.map(math.sqrt)
- val bcFeaturesMean = instances.context.broadcast(featuresMean)
- val bcFeaturesStd = instances.context.broadcast(featuresStd.map(t =>
- if (t != 0d) 1d / t else 0d))
-
- if (!$(fitIntercept) && (0 until numFeatures).exists { i =>
- featuresStd(i) == 0.0 && featuresMean(i) != 0.0 }) {
- logWarning("Fitting LinearRegressionModel without intercept on dataset with " +
- "constant nonzero column, Spark MLlib outputs zero coefficients for constant nonzero " +
- "columns. This behavior is the same as R glmnet but different from LIBSVM.")
- }
-
- // Since we implicitly do the feature scaling when we compute the cost function
- // to improve the convergence, the effective regParam will be changed.
- val effectiveRegParam = $(loss) match {
- case SquaredError => $(regParam) / yStd
- case Huber => $(regParam)
- }
- val effectiveL1RegParam = $(elasticNetParam) * effectiveRegParam
- val effectiveL2RegParam = (1.0 - $(elasticNetParam)) * effectiveRegParam
-
- val getFeaturesStd = (j: Int) => if (j >= 0 && j < numFeatures) featuresStd(j) else 0.0
- val regularization = if (effectiveL2RegParam != 0.0) {
- val shouldApply = (idx: Int) => idx >= 0 && idx < numFeatures
- Some(new L2Regularization(effectiveL2RegParam, shouldApply,
- if ($(standardization)) None else Some(getFeaturesStd)))
- } else {
- None
- }
-
- val costFun = $(loss) match {
- case SquaredError =>
- val getAggregatorFunc = new LeastSquaresAggregatorX(yStd, yMean, $(fitIntercept),
- bcFeaturesStd, bcFeaturesMean)(_)
- new RDDLossFunctionX(instances, getAggregatorFunc, regularization, $(aggregationDepth))
- case Huber =>
- val getAggregatorFunc = new HuberAggregatorX($(fitIntercept), $(epsilon), bcFeaturesStd)(_)
- new RDDLossFunctionX(instances, getAggregatorFunc, regularization, $(aggregationDepth))
- }
-
- val optimizer = $(loss) match {
- case SquaredError =>
- val dim = numFeatures
- if ($(elasticNetParam) == 0.0 || effectiveRegParam == 0.0) {
- new LBFGSL($(maxIter), 10, $(tol))
- } else {
- val standardizationParam = $(standardization)
- val effectiveL1Reg =
- if (standardizationParam) {
- BDV[Double](Array.fill(dim)(effectiveL1RegParam))
- } else {
- // If `standardization` is false, we still standardize the data
- // to improve the rate of convergence; as a result, we have to
- // perform this reverse standardization by penalizing each component
- // differently to get effectively the same objective function when
- // the training dataset is not standardized.
- BDV[Double](featuresStd.map(x => if (x != 0.0) effectiveL1RegParam / x else 0.0))
- }
- new OWLQNL($(maxIter), 10, $(tol), effectiveL1Reg)
- }
- case Huber =>
- val dim = if ($(fitIntercept)) numFeatures + 2 else numFeatures + 1
- val lowerBounds = BDV[Double](Array.fill(dim)(Double.MinValue))
- // Optimize huber loss in space "\sigma > 0"
- lowerBounds(dim - 1) = Double.MinPositiveValue
- val upperBounds = BDV[Double](Array.fill(dim)(Double.MaxValue))
- new LBFGSL(lowerBounds, upperBounds, $(maxIter), 10, $(tol))
- }
-
- val initialValues = $(loss) match {
- case SquaredError =>
- Vectors.zeros(numFeatures)
- case Huber =>
- val dim = if ($(fitIntercept)) numFeatures + 2 else numFeatures + 1
- Vectors.dense(Array.fill(dim)(1.0))
- }
-
- val states = optimizer.iterations(new CachedDiffFunction(costFun),
- initialValues.asBreeze.toDenseVector)
-
- val (coefficients, intercept, scale, objectiveHistory) = {
- /*
- Note that in Linear Regression, the objective history (loss + regularization) returned
- from optimizer is computed in the scaled space given by the following formula.
-
- $$
- L &= 1/2n||\sum_i w_i(x_i - \bar{x_i}) / \hat{x_i} - (y - \bar{y}) / \hat{y}||^2
- + regTerms \\
- $$
-
- */
- val arrayBuilder = mutable.ArrayBuilder.make[Double]
- var state: optimizer.State = null
- while (states.hasNext) {
- state = states.next()
- arrayBuilder += state.adjustedValue
- }
- if (state == null) {
- val msg = s"${optimizer.getClass.getName} failed."
- logError(msg)
- throw new SparkException(msg)
- }
-
- bcFeaturesMean.destroy(blocking = false)
- bcFeaturesStd.destroy(blocking = false)
-
- val parameters = state.x.toArray.clone()
-
- /*
- The coefficients are trained in the scaled space; we're converting them back to
- the original space.
- */
- val rawCoefficients: Array[Double] = $(loss) match {
- case SquaredError => parameters
- case Huber => parameters.slice(0, numFeatures)
- }
-
- var i = 0
- val len = rawCoefficients.length
- val multiplier = $(loss) match {
- case SquaredError => yStd
- case Huber => 1.0
- }
- while (i < len) {
- rawCoefficients(i) *= { if (featuresStd(i) != 0.0) multiplier / featuresStd(i) else 0.0 }
- i += 1
- }
-
- val interceptValue: Double = if ($(fitIntercept)) {
- $(loss) match {
- case SquaredError =>
- /*
- The intercept of squared error in R's GLMNET is computed using closed form
- after the coefficients are converged. See the following discussion for detail.
- http://stats.stackexchange.com/questions/13617/how-is-the-intercept-computed-in-glmnet
- */
- yMean - dot(Vectors.dense(rawCoefficients), Vectors.dense(featuresMean))
- case Huber => parameters(numFeatures)
- }
- } else {
- 0.0
- }
-
- val scaleValue: Double = $(loss) match {
- case SquaredError => 1.0
- case Huber => parameters.last
- }
-
- (Vectors.dense(rawCoefficients).compressed, interceptValue, scaleValue, arrayBuilder.result())
- }
-
- if (handlePersistence) instances.unpersist()
-
- val model = copyValues(new LinearRegressionModel(uid, coefficients, intercept, scale))
- // Handle possible missing or invalid prediction columns
- val (summaryModel, predictionColName) = model.findSummaryModelAndPredictionCol()
-
- val trainingSummary = new LinearRegressionTrainingSummary(
- summaryModel.transform(dataset),
- predictionColName,
- $(labelCol),
- $(featuresCol),
- model,
- Array(0D),
- objectiveHistory)
-
- model.setSummary(Some(trainingSummary))
- instr.logSuccess(model)
- model
- }
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): LinearRegression = defaultCopy(extra)
-}
-
-@Since("1.6.0")
-object LinearRegression extends DefaultParamsReadable[LinearRegression] {
-
- @Since("1.6.0")
- override def load(path: String): LinearRegression = super.load(path)
-
- /**
- * When using `LinearRegression.solver` == "normal", the solver must limit the number of
- * features to at most this number. The entire covariance matrix X^T^X will be collected
- * to the driver. This limit helps prevent memory overflow errors.
- */
- @Since("2.1.0")
- val MAX_FEATURES_FOR_NORMAL_SOLVER: Int = WeightedLeastSquares.MAX_NUM_FEATURES
-
- /** String name for "auto". */
- private[regression] val Auto = "auto"
-
- /** String name for "normal". */
- private[regression] val Normal = "normal"
-
- /** String name for "l-bfgs". */
- private[regression] val LBFGS = "l-bfgs"
-
- /** Set of solvers that LinearRegression supports. */
- private[regression] val supportedSolvers = Array(Auto, Normal, LBFGS)
-
- /** String name for "squaredError". */
- private[regression] val SquaredError = "squaredError"
-
- /** String name for "huber". */
- private[regression] val Huber = "huber"
-
- /** Set of loss function names that LinearRegression supports. */
- private[regression] val supportedLosses = Array(SquaredError, Huber)
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/RandomForestRegressor.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/RandomForestRegressor.scala
deleted file mode 100644
index ada1b5e..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/regression/RandomForestRegressor.scala
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.regression
-
-import org.json4s.{DefaultFormats, JObject}
-import org.json4s.JsonDSL._
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.ml.{PredictionModel, Predictor}
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.linalg.Vector
-import org.apache.spark.ml.param.ParamMap
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.RandomForest
-import org.apache.spark.ml.util._
-import org.apache.spark.ml.util.DefaultParamsReader.Metadata
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo}
-import org.apache.spark.mllib.tree.model.{RandomForestModel => OldRandomForestModel}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.{DataFrame, Dataset}
-import org.apache.spark.sql.functions._
-
-
-/**
- * Random Forest
- * learning algorithm for regression.
- * It supports both continuous and categorical features.
- */
-@Since("1.4.0")
-class RandomForestRegressor @Since("1.4.0") (@Since("1.4.0") override val uid: String)
- extends Predictor[Vector, RandomForestRegressor, RandomForestRegressionModel]
- with RandomForestRegressorParams with DefaultParamsWritable {
-
- @Since("1.4.0")
- def this() = this(Identifiable.randomUID("rfr"))
-
- // Override parameter setters from parent trait for Java API compatibility.
-
- // Parameters from TreeRegressorParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxDepth(value: Int): this.type = set(maxDepth, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMaxBins(value: Int): this.type = set(maxBins, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInstancesPerNode(value: Int): this.type = set(minInstancesPerNode, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setMinInfoGain(value: Double): this.type = set(minInfoGain, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setMaxMemoryInMB(value: Int): this.type = set(maxMemoryInMB, value)
-
- /** @group expertSetParam */
- @Since("1.4.0")
- override def setCacheNodeIds(value: Boolean): this.type = set(cacheNodeIds, value)
-
- /**
- * Specifies how often to checkpoint the cached node IDs.
- * E.g. 10 means that the cache will get checkpointed every 10 iterations.
- * This is only used if cacheNodeIds is true and if the checkpoint directory is set in
- * [[org.apache.spark.SparkContext]].
- * Must be at least 1.
- * (default = 10)
- * @group setParam
- */
- @Since("1.4.0")
- override def setCheckpointInterval(value: Int): this.type = set(checkpointInterval, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setImpurity(value: String): this.type = set(impurity, value)
-
- // Parameters from TreeEnsembleParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSubsamplingRate(value: Double): this.type = set(subsamplingRate, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setSeed(value: Long): this.type = set(seed, value)
-
- // Parameters from RandomForestParams:
-
- /** @group setParam */
- @Since("1.4.0")
- override def setNumTrees(value: Int): this.type = set(numTrees, value)
-
- /** @group setParam */
- @Since("1.4.0")
- override def setFeatureSubsetStrategy(value: String): this.type =
- set(featureSubsetStrategy, value)
-
- override protected def train(dataset: Dataset[_]): RandomForestRegressionModel = {
- val categoricalFeatures: Map[Int, Int] =
- MetadataUtils.getCategoricalFeatures(dataset.schema($(featuresCol)))
- val oldDataset: RDD[LabeledPoint] = extractLabeledPoints(dataset)
- val strategy =
- super.getOldStrategy(categoricalFeatures, numClasses = 0, OldAlgo.Regression, getOldImpurity)
-
- val instr = Instrumentation.create(this, oldDataset)
- instr.logParams(labelCol, featuresCol, predictionCol, impurity, numTrees,
- featureSubsetStrategy, maxDepth, maxBins, maxMemoryInMB, minInfoGain,
- minInstancesPerNode, seed, subsamplingRate, cacheNodeIds, checkpointInterval)
-
- val trees = RandomForest
- .run(oldDataset, strategy, getNumTrees, getFeatureSubsetStrategy, getSeed, Some(instr))
- .map(_.asInstanceOf[DecisionTreeRegressionModel])
-
- val numFeatures = oldDataset.first().features.size
- val m = new RandomForestRegressionModel(uid, trees, numFeatures)
- instr.logSuccess(m)
- m
- }
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): RandomForestRegressor = defaultCopy(extra)
-}
-
-@Since("1.4.0")
-object RandomForestRegressor extends DefaultParamsReadable[RandomForestRegressor]{
- /** Accessor for supported impurity settings: variance */
- @Since("1.4.0")
- final val supportedImpurities: Array[String] = TreeRegressorParams.supportedImpurities
-
- /** Accessor for supported featureSubsetStrategy settings: auto, all, onethird, sqrt, log2 */
- @Since("1.4.0")
- final val supportedFeatureSubsetStrategies: Array[String] =
- TreeEnsembleParams.supportedFeatureSubsetStrategies
-
- @Since("2.0.0")
- override def load(path: String): RandomForestRegressor = super.load(path)
-
-}
-
-/**
- * Random Forest model for regression.
- * It supports both continuous and categorical features.
- *
- * @param _trees Decision trees in the ensemble.
- * @param numFeatures Number of features used by this model
- */
-@Since("1.4.0")
-class RandomForestRegressionModel private[ml] (
- override val uid: String,
- private val _trees: Array[DecisionTreeRegressionModel],
- override val numFeatures: Int)
- extends PredictionModel[Vector, RandomForestRegressionModel]
- with RandomForestRegressorParams with TreeEnsembleModel[DecisionTreeRegressionModel]
- with MLWritable with Serializable {
-
- require(_trees.nonEmpty, "RandomForestRegressionModel requires at least 1 tree.")
-
- /**
- * Construct a random forest regression model, with all trees weighted equally.
- *
- * @param trees Component trees
- */
- private[ml] def this(trees: Array[DecisionTreeRegressionModel], numFeatures: Int) =
- this(Identifiable.randomUID("rfr"), trees, numFeatures)
-
- @Since("1.4.0")
- override def trees: Array[DecisionTreeRegressionModel] = _trees
-
- // Note: We may add support for weights (based on tree performance) later on.
- private lazy val _treeWeights: Array[Double] = Array.fill[Double](_trees.length)(1.0)
-
- @Since("1.4.0")
- override def treeWeights: Array[Double] = _treeWeights
-
- override protected def transformImpl(dataset: Dataset[_]): DataFrame = {
- val bcastModel = dataset.sparkSession.sparkContext.broadcast(this)
- val predictUDF = udf { (features: Any) =>
- bcastModel.value.predict(features.asInstanceOf[Vector])
- }
- dataset.withColumn($(predictionCol), predictUDF(col($(featuresCol))))
- }
-
- override protected def predict(features: Vector): Double = {
- // TODO: When we add a generic Bagging class, handle transform there. SPARK-7128
- // Predict average of tree predictions.
- // Ignore the weights since all are 1.0 for now.
- _trees.map(_.rootNode.predictImpl(features).prediction).sum / getNumTrees
- }
-
- @Since("1.4.0")
- override def copy(extra: ParamMap): RandomForestRegressionModel = {
- copyValues(new RandomForestRegressionModel(uid, _trees, numFeatures), extra).setParent(parent)
- }
-
- @Since("1.4.0")
- override def toString: String = {
- s"RandomForestRegressionModel (uid=$uid) with $getNumTrees trees"
- }
-
- /**
- * Estimate of the importance of each feature.
- *
- * Each feature's importance is the average of its importance across all trees in the ensemble
- * The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
- * (Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
- * and follows the implementation from scikit-learn.
- *
- * @see `DecisionTreeRegressionModel.featureImportances`
- */
- @Since("1.5.0")
- lazy val featureImportances: Vector = TreeEnsembleModel.featureImportances(trees, numFeatures)
-
- /** (private[ml]) Convert to a model in the old API */
- private[ml] def toOld: OldRandomForestModel = {
- new OldRandomForestModel(OldAlgo.Regression, _trees.map(_.toOld))
- }
-
- @Since("2.0.0")
- override def write: MLWriter =
- new RandomForestRegressionModel.RandomForestRegressionModelWriter(this)
-}
-
-@Since("2.0.0")
-object RandomForestRegressionModel extends MLReadable[RandomForestRegressionModel] {
-
- @Since("2.0.0")
- override def read: MLReader[RandomForestRegressionModel] = new RandomForestRegressionModelReader
-
- @Since("2.0.0")
- override def load(path: String): RandomForestRegressionModel = super.load(path)
-
- private[RandomForestRegressionModel]
- class RandomForestRegressionModelWriter(instance: RandomForestRegressionModel)
- extends MLWriter {
-
- override protected def saveImpl(path: String): Unit = {
- val extraMetadata: JObject = Map(
- "numFeatures" -> instance.numFeatures,
- "numTrees" -> instance.getNumTrees)
- EnsembleModelReadWrite.saveImpl(instance, path, sparkSession, extraMetadata)
- }
- }
-
- private class RandomForestRegressionModelReader extends MLReader[RandomForestRegressionModel] {
-
- /** Checked against metadata when loading model */
- private val className = classOf[RandomForestRegressionModel].getName
- private val treeClassName = classOf[DecisionTreeRegressionModel].getName
-
- override def load(path: String): RandomForestRegressionModel = {
- implicit val format = DefaultFormats
- val (metadata: Metadata, treesData: Array[(Metadata, Node)], treeWeights: Array[Double]) =
- EnsembleModelReadWrite.loadImpl(path, sparkSession, className, treeClassName)
- val numFeatures = (metadata.metadata \ "numFeatures").extract[Int]
- val numTrees = (metadata.metadata \ "numTrees").extract[Int]
-
- val trees: Array[DecisionTreeRegressionModel] = treesData.map { case (treeMetadata, root) =>
- val tree =
- new DecisionTreeRegressionModel(treeMetadata.uid, root, numFeatures)
- DefaultParamsReader.getAndSetParams(tree, treeMetadata)
- tree
- }
- require(numTrees == trees.length, s"RandomForestRegressionModel.load expected $numTrees" +
- s" trees based on metadata but found ${trees.length} trees.")
-
- val model = new RandomForestRegressionModel(metadata.uid, trees, numFeatures)
- DefaultParamsReader.getAndSetParams(model, metadata)
- model
- }
- }
-
- /** Convert a model from the old API */
- private[ml] def fromOld(
- oldModel: OldRandomForestModel,
- parent: RandomForestRegressor,
- categoricalFeatures: Map[Int, Int],
- numFeatures: Int = -1): RandomForestRegressionModel = {
- require(oldModel.algo == OldAlgo.Regression, "Cannot convert RandomForestModel" +
- s" with algo=${oldModel.algo} (old API) to RandomForestRegressionModel (new API).")
- val newTrees = oldModel.trees.map { tree =>
- // parent for each tree is null since there is no good way to set this.
- DecisionTreeRegressionModel.fromOld(tree, null, categoricalFeatures)
- }
- val uid = if (parent != null) parent.uid else Identifiable.randomUID("rfr")
- new RandomForestRegressionModel(uid, newTrees, numFeatures)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/stat/Correlation.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/stat/Correlation.scala
deleted file mode 100644
index d84f291..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/stat/Correlation.scala
+++ /dev/null
@@ -1,93 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.stat
-
-import scala.collection.JavaConverters._
-
-import org.apache.spark.annotation.{Experimental, Since}
-import org.apache.spark.ml.linalg.{SQLDataTypes, Vector}
-import org.apache.spark.mllib.linalg.{Vectors => OldVectors}
-import org.apache.spark.mllib.stat.{Statistics => OldStatistics}
-import org.apache.spark.sql.{DataFrame, Dataset, Row}
-import org.apache.spark.sql.types.{StructField, StructType}
-
-/**
- * API for correlation functions in MLlib, compatible with DataFrames and Datasets.
- *
- * The functions in this package generalize the functions in [[org.apache.spark.sql.Dataset#stat]]
- * to spark.ml's Vector types.
- */
-@Since("2.2.0")
-@Experimental
-object Correlation {
-
- /**
- * :: Experimental ::
- * Compute the correlation matrix for the input Dataset of Vectors using the specified method.
- * Methods currently supported: `pearson` (default), `spearman`.
- *
- * @param dataset A dataset or a dataframe
- * @param column The name of the column of vectors for which the correlation coefficient needs
- * to be computed. This must be a column of the dataset, and it must contain
- * Vector objects.
- * @param method String specifying the method to use for computing correlation.
- * Supported: `pearson` (default), `spearman`
- * @return A dataframe that contains the correlation matrix of the column of vectors. This
- * dataframe contains a single row and a single column of name
- * '$METHODNAME($COLUMN)'.
- * @throws IllegalArgumentException if the column is not a valid column in the dataset, or if
- * the content of this column is not of type Vector.
- *
- * Here is how to access the correlation coefficient:
- * {{{
- * val data: Dataset[Vector] = ...
- * val Row(coeff: Matrix) = Correlation.corr(data, "value").head
- * // coeff now contains the Pearson correlation matrix.
- * }}}
- *
- * @note For Spearman, a rank correlation, we need to create an RDD[Double] for each column
- * and sort it in order to retrieve the ranks and then join the columns back into an RDD[Vector],
- * which is fairly costly. Cache the input Dataset before calling corr with `method = "spearman"`
- * to avoid recomputing the common lineage.
- */
- @Since("2.2.0")
- def corr(dataset: Dataset[_], column: String, method: String): DataFrame = {
- val rdd = dataset.select(column).rdd.map {
- case Row(v: Vector) => OldVectors.fromML(v)
- }
- val oldM = OldStatistics.corr(rdd, method)
- val name = s"$method($column)"
- val schema = StructType(Array(StructField(name, SQLDataTypes.MatrixType, nullable = false)))
- dataset.sparkSession.createDataFrame(Seq(Row(oldM.asML)).asJava, schema)
- }
-
- /**
- * Compute the Pearson correlation matrix for the input Dataset of Vectors.
- */
- @Since("2.2.0")
- def corr(dataset: Dataset[_], column: String): DataFrame = {
- corr(dataset, column, "pearson")
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/DecisionForest.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/DecisionForest.scala
deleted file mode 100644
index ebce220..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/DecisionForest.scala
+++ /dev/null
@@ -1,1275 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import java.io.IOException
-
-import scala.collection.mutable
-import scala.util.Random
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.classification.DecisionTreeClassificationModel
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.regression.DecisionTreeRegressionModel
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.RandomForest.NodeIndexInfo
-import org.apache.spark.ml.util.Instrumentation
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo, Strategy => OldStrategy}
-import org.apache.spark.mllib.tree.impurity.ImpurityCalculator
-import org.apache.spark.mllib.tree.model.ImpurityStats
-import org.apache.spark.rdd.RDD
-import org.apache.spark.util.random.{SamplingUtils, XORShiftRandom}
-
-/**
- * ALGORITHM
- *
- * This is a sketch of the algorithm to help new developers.
- *
- * The algorithm partitions data by instances (rows).
- * On each iteration, the algorithm splits a set of nodes. In order to choose the best split
- * for a given node, sufficient statistics are collected from the distributed data.
- * For each node, the statistics are collected to some worker node, and that worker selects
- * the best split.
- *
- * This setup requires discretization of continuous features. This binning is done in the
- * findSplits() method during initialization, after which each continuous feature becomes
- * an ordered discretized feature with at most maxBins possible values.
- *
- * The main loop in the algorithm operates on a queue of nodes (nodeStack). These nodes
- * lie at the periphery of the tree being trained. If multiple trees are being trained at once,
- * then this queue contains nodes from all of them. Each iteration works roughly as follows:
- * On the master node:
- * - Some number of nodes are pulled off of the queue (based on the amount of memory
- * required for their sufficient statistics).
- * - For random forests, if featureSubsetStrategy is not "all," then a subset of candidate
- * features are chosen for each node. See method selectNodesToSplit().
- * On worker nodes, via method findBestSplits():
- * - The worker makes one pass over its subset of instances.
- * - For each (tree, node, feature, split) tuple, the worker collects statistics about
- * splitting. Note that the set of (tree, node) pairs is limited to the nodes selected
- * from the queue for this iteration. The set of features considered can also be limited
- * based on featureSubsetStrategy.
- * - For each node, the statistics for that node are aggregated to a particular worker
- * via reduceByKey(). The designated worker chooses the best (feature, split) pair,
- * or chooses to stop splitting if the stopping criteria are met.
- * On the master node:
- * - The master collects all decisions about splitting nodes and updates the model.
- * - The updated model is passed to the workers on the next iteration.
- * This process continues until the node queue is empty.
- *
- * Most of the methods in this implementation support the statistics aggregation, which is
- * the heaviest part of the computation. In general, this implementation is bound by either
- * the cost of statistics computation on workers or by communicating the sufficient statistics.
- */
-private[spark] object DecisionForest extends Logging {
-
- /**
- * Train a random forest.
- *
- * @param input Training data: RDD of `LabeledPoint`
- * @return an unweighted set of trees
- */
- def run(
- input: RDD[LabeledPoint],
- strategy: OldStrategy,
- numTrees: Int,
- featureSubsetStrategy: String,
- seed: Long,
- instr: Option[Instrumentation[_]],
- parentUID: Option[String] = None): Array[DecisionTreeModel] = {
- val exParams = DTUtils.parseExtraParams(input, strategy)
- runX(input, strategy, numTrees, featureSubsetStrategy, seed, instr, exParams, parentUID)
- }
-
- /**
- * Train a random forest.
- *
- * @param input Training data: RDD of `LabeledPoint`
- * @return an unweighted set of trees
- */
- def runX(
- input: RDD[LabeledPoint],
- strategy: OldStrategy,
- numTrees: Int,
- featureSubsetStrategy: String,
- seed: Long,
- instr: Option[Instrumentation[_]],
- extraParams: DFExtraParams,
- parentUID: Option[String] = None): Array[DecisionTreeModel] = {
-
- DecisionForestInfo.timerResult = ""
- val timer = new TimeTracker()
-
- timer.start("total")
-
- timer.start("init")
-
- val binnedFeaturesType = BinnedFeaturesDataType.withName(extraParams.rfParams.featuresDataType)
- val retaggedInput = input.retag(classOf[LabeledPoint])
- // featureSubsetStrategy: The number of features to consider for splits at each tree node.
- // featureSubsetStrategy: default value is "auto" for random forest.
- // impurity: default value is "gini" for random forest.
- val metadata =
- DecisionTreeMetadata.buildMetadata(retaggedInput, strategy, numTrees, featureSubsetStrategy)
- logWarning(s"decisionTreeMetadata details: ${metadata.numFeatures}," +
- s" ${metadata.numExamples}, ${metadata.numClasses: Int}, ${metadata.maxBins: Int}," +
- s" ${metadata.featureArity}, ${metadata.unorderedFeatures.mkString("[", ";", "]")}," +
- s" ${metadata.impurity}, ${metadata.quantileStrategy}, ${metadata.maxDepth: Int}," +
- s" ${metadata.minInstancesPerNode: Int}, ${metadata.minInfoGain: Double}," +
- s" ${metadata.numTrees: Int}, ${metadata.numFeaturesPerNode: Int},${binnedFeaturesType}")
- instr match {
- case Some(instrumentation) =>
- instrumentation.logNumFeatures(metadata.numFeatures)
- instrumentation.logNumClasses(metadata.numClasses)
- case None =>
- logInfo("numFeatures: " + metadata.numFeatures)
- logInfo("numClasses: " + metadata.numClasses)
- }
-
- // Find the splits and the corresponding bins (interval between the splits) using a sample
- // of the input data.
- timer.start("findSplits")
- val splits = findSplits(retaggedInput, metadata, seed, extraParams.numFeaturesOptFindSplits)
- timer.stop("findSplits")
- logDebug("numBins: feature: number of bins")
- logDebug(Range(0, metadata.numFeatures).map { featureIndex =>
- s"\t$featureIndex\t${metadata.numBins(featureIndex)}"
- }.mkString("\n"))
-
- // Bin feature values (TreePoint representation).
- // Cache input RDD for speedup during multiple passes.
- val treeInput = TreePointY.convertToTreeRDD(retaggedInput, splits, metadata, binnedFeaturesType)
-
- val withReplacement = numTrees > 1
-
- // Default value of subsamplingRate is 1 for random forest.
- val baggedInputOri = BaggedPoint.convertToBaggedRDD(treeInput, strategy.subsamplingRate,
- numTrees, withReplacement, seed)
-
- val baggedInput = DTUtils.transformBaggedRDD(baggedInputOri, extraParams)
-
- // depth of the decision tree
- val maxDepth = strategy.maxDepth
- require(maxDepth <= 30,
- s"DecisionTree currently only supports maxDepth <= 30, but was given maxDepth = $maxDepth.")
-
- // Max memory usage for aggregates
- // TODO: Calculate memory usage more precisely.
- val maxMemoryUsage: Long = strategy.maxMemoryInMB * 1024L * 1024L
- logDebug("max memory usage for aggregates = " + maxMemoryUsage + " bytes.")
-
- /*
- * The main idea here is to perform group-wise training of the decision tree nodes thus
- * reducing the passes over the data from (# nodes) to (# nodes / maxNumberOfNodesPerGroup).
- * Each data sample is handled by a particular node (or it reaches a leaf and is not used
- * in lower levels).
- */
-
- // Create an RDD of node Id cache.
- // At first, all the rows belong to the root nodes (node Id == 1).
- // Default value of useNodeIdCache is false for random forest.
- val nodeIdCache = if (strategy.useNodeIdCache) {
- Some(NodeIdCache.init(
- data = baggedInput,
- numTrees = numTrees,
- checkpointInterval = strategy.checkpointInterval,
- initVal = 1))
- } else {
- None
- }
-
- /*
- Stack of nodes to train: (treeIndex, node)
- The reason this is a stack is that we train many trees at once, but we want to focus on
- completing trees, rather than training all simultaneously. If we are splitting nodes from
- 1 tree, then the new nodes to split will be put at the top of this stack, so we will continue
- training the same tree in the next iteration. This focus allows us to send fewer trees to
- workers on each iteration; see topNodesForGroup below.
- */
- val nodeStack = new mutable.ArrayStack[(Int, LearningNode)]
- val localTrainingStack = new mutable.ListBuffer[LocalTrainingTask]
-
- val rng = new Random()
- rng.setSeed(seed)
-
- // Allocate and queue root nodes.
- val topNodes = Array.fill[LearningNode](numTrees)(LearningNode.emptyNode(nodeIndex = 1))
- Range(0, numTrees).foreach(treeIndex => nodeStack.push((treeIndex, topNodes(treeIndex))))
-
- timer.stop("init")
-
- while (nodeStack.nonEmpty) {
- // Collect some nodes to split, and choose features for each node (if subsampling).
- // Each group of nodes may come from one or multiple trees, and at multiple levels.
- // nodesForGroup: treeIndex --> learningNodes in tree
- // treeToNodeToIndexInfo: treeIndex --> (global) learningNodes index in tree
- // --> (node index in group, feature indices).
- val (nodesForGroup, treeToNodeToIndexInfo) =
- DecisionForest.selectNodesToSplit(nodeStack, maxMemoryUsage, metadata, rng)
- // Sanity check (should never occur):
- assert(nodesForGroup.nonEmpty,
- s"DecisionForest selected empty nodesForGroup. Error for unknown reason.")
-
- // Only send trees to worker if they contain nodes being split this iteration.
- // topNodesForGroup: treeIndex --> top node in tree
- val topNodesForGroup: Map[Int, LearningNode] =
- nodesForGroup.keys.map(treeIdx => treeIdx -> topNodes(treeIdx)).toMap
-
- // Choose node splits, and enqueue new nodes as needed.
- timer.start("findBestSplits")
- DecisionForest.findBestSplits(baggedInput, metadata, topNodesForGroup, nodesForGroup,
- treeToNodeToIndexInfo, splits, (nodeStack, localTrainingStack),
- extraParams, timer, nodeIdCache)
- timer.stop("findBestSplits")
- }
-
- baggedInput.unpersist()
-
- timer.stop("total")
-
- logInfo("Internal timing for DecisionTree:")
- logInfo(s"$timer")
- DecisionForestInfo.timerResult = timer.toString()
-
- // Delete any remaining checkpoints used for node Id cache.
- if (nodeIdCache.nonEmpty) {
- try {
- nodeIdCache.get.deleteAllCheckpoints()
- } catch {
- case e: IOException =>
- logWarning(s"delete all checkpoints failed. Error reason: ${e.getMessage}")
- }
- }
-
- val numFeatures = metadata.numFeatures
-
- parentUID match {
- case Some(uid) =>
- if (strategy.algo == OldAlgo.Classification) {
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(uid, rootNode.toNode, numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map { rootNode =>
- new DecisionTreeRegressionModel(uid, rootNode.toNode, numFeatures)
- }
- }
- case None =>
- if (strategy.algo == OldAlgo.Classification) {
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(rootNode.toNode, numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map { rootNode =>
- new DecisionTreeRegressionModel(rootNode.toNode, numFeatures)
- }
- }
- }
- }
-
- /**
- * Helper for binSeqOp, for data which can contain a mix of ordered and unordered features.
- *
- * For ordered features, a single bin is updated.
- * For unordered features, bins correspond to subsets of categories; either the left or right bin
- * for each subset is updated.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (feature, bin).
- * @param treePoint Data point being aggregated.
- * @param splits possible splits indexed (numFeatures)(numSplits)
- * @param unorderedFeatures Set of indices of unordered features.
- * @param instanceWeight Weight (importance) of instance in dataset.
- */
- private def mixedBinSeqOp(
- agg: DTStatsAggregator,
- treePoint: TreePointY,
- splits: Array[Array[Split]],
- unorderedFeatures: Set[Int],
- instanceWeight: Int,
- featuresForNode: Option[Array[Int]]): Unit = {
- val numFeaturesPerNode = if (featuresForNode.nonEmpty) {
- // Use subsampled features
- featuresForNode.get.length
- } else {
- // Use all features
- agg.metadata.numFeatures
- }
- // Iterate over features.
- var featureIndexIdx = 0
- while (featureIndexIdx < numFeaturesPerNode) {
- val featureIndex = if (featuresForNode.nonEmpty) {
- featuresForNode.get.apply(featureIndexIdx)
- } else {
- featureIndexIdx
- }
- // TODO: we can use AggUpdateUtils to update histogram.
- if (unorderedFeatures.contains(featureIndex)) {
- // Unordered feature
- val featureValue = treePoint.binnedFeatures.get(featureIndex)
- val leftNodeFeatureOffset = agg.getFeatureOffset(featureIndexIdx)
- // Update the left or right bin for each split.
- val numSplits = agg.metadata.numSplits(featureIndex)
- val featureSplits = splits(featureIndex)
- var splitIndex = 0
- while (splitIndex < numSplits) {
- if (featureSplits(splitIndex).shouldGoLeft(featureValue, featureSplits)) {
- agg.featureUpdate(leftNodeFeatureOffset, splitIndex, treePoint.label, instanceWeight)
- }
- splitIndex += 1
- }
- } else {
- // Ordered feature
- val binIndex = treePoint.binnedFeatures.get(featureIndex)
- agg.update(featureIndexIdx, binIndex, treePoint.label, instanceWeight)
- }
- featureIndexIdx += 1
- }
- }
-
- /**
- * Helper for binSeqOp, for regression and for classification with only ordered features.
- *
- * For each feature, the sufficient statistics of one bin are updated.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (feature, bin).
- * @param treePoint Data point being aggregated.
- * @param instanceWeight Weight (importance) of instance in dataset.
- */
- private def orderedBinSeqOp(
- agg: DTStatsAggregator,
- treePoint: TreePointY,
- instanceWeight: Int,
- featuresForNode: Option[Array[Int]]): Unit = {
- val label = treePoint.label
-
- // Iterate over features.
- if (featuresForNode.nonEmpty) {
- // Use subsampled features
- var featureIndexIdx = 0
- while (featureIndexIdx < featuresForNode.get.length) {
- val binIndex = treePoint.binnedFeatures.get(featuresForNode.get.apply(featureIndexIdx))
- agg.update(featureIndexIdx, binIndex, label, instanceWeight)
- featureIndexIdx += 1
- }
- } else {
- // Use all features
- val numFeatures = agg.metadata.numFeatures
- var featureIndex = 0
- while (featureIndex < numFeatures) {
- val binIndex = treePoint.binnedFeatures.get(featureIndex)
- agg.update(featureIndex, binIndex, label, instanceWeight)
- featureIndex += 1
- }
- }
- }
-
- /**
- * Given a group of nodes, this finds the best split for each node.
- *
- * @param input Training data: RDD of [[TreePointX]]
- * @param metadata Learning and dataset metadata
- * @param topNodesForGroup For each tree in group, tree index -> root node.
- * Used for matching instances with nodes.
- * @param nodesForGroup Mapping: treeIndex --> nodes to be split in tree
- * @param treeToNodeToIndexInfo Mapping: treeIndex --> (global) learningNodes index in tree
- * --> (node index in group, feature indices)
- * feature indices: probably parts of full features.
- * Mapping: treeIndex --> nodeIndex --> nodeIndexInfo,
- * where nodeIndexInfo stores the index in the group and the
- * feature subsets (if using feature subsets).
- * @param splits possible splits for all features, indexed (numFeatures)(numSplits)
- * @param stacks Queue of nodes to split, with values (treeIndex, node).
- * Updated with new non-leaf nodes which are created.
- * @param nodeIdCache Node Id cache containing an RDD of Array[Int] where
- * each value in the array is the data point's node Id
- * for a corresponding tree. This is used to prevent the need
- * to pass the entire tree to the executors during
- * the node stat aggregation phase.
- *
- */
- private[tree] def findBestSplits(
- input: RDD[BaggedPoint[TreePointY]],
- metadata: DecisionTreeMetadata,
- topNodesForGroup: Map[Int, LearningNode],
- nodesForGroup: Map[Int, Array[LearningNode]],
- treeToNodeToIndexInfo: Map[Int, Map[Int, NodeIndexInfo]],
- splits: Array[Array[Split]],
- stacks: (mutable.ArrayStack[(Int, LearningNode)], mutable.ListBuffer[LocalTrainingTask]),
- extraParams: DFExtraParams,
- timer: TimeTracker = new TimeTracker,
- nodeIdCache: Option[NodeIdCache] = None): Unit = {
-
- /*
- * The high-level descriptions of the best split optimizations are noted here.
- *
- * *Group-wise training*
- * We perform bin calculations for groups of nodes to reduce the number of
- * passes over the data. Each iteration requires more computation and storage,
- * but saves several iterations over the data.
- *
- * *Bin-wise computation*
- * We use a bin-wise best split computation strategy instead of a straightforward best split
- * computation strategy. Instead of analyzing each sample for contribution to the left/right
- * child node impurity of every split, we first categorize each feature of a sample into a
- * bin. We exploit this structure to calculate aggregates for bins and then use these aggregates
- * to calculate information gain for each split.
- *
- * *Aggregation over partitions*
- * Instead of performing a flatMap/reduceByKey operation, we exploit the fact that we know
- * the number of splits in advance. Thus, we store the aggregates (at the appropriate
- * indices) in a single array for all bins and rely upon the RDD aggregate method to
- * drastically reduce the communication overhead.
- */
-
- val bcVariables = if (null == extraParams.rfParams) false else extraParams.rfParams.bcVariables
- val (nodeStack, _) = stacks
- /** numNodes: Number of nodes in this group */
- val numNodes = nodesForGroup.values.map(_.length).sum
- logDebug("numNodes = " + numNodes)
- logDebug("numFeatures = " + metadata.numFeatures)
- logDebug("numClasses = " + metadata.numClasses)
- logDebug("isMulticlass = " + metadata.isMulticlass)
- logDebug("isMulticlassWithCategoricalFeatures = " +
- metadata.isMulticlassWithCategoricalFeatures)
- logDebug("using nodeIdCache = " + nodeIdCache.nonEmpty.toString)
-
- val groupInfo =
- DTUtils.getGroupInfo(numNodes, treeToNodeToIndexInfo, extraParams, nodesForGroup)
-
- val splitsBc = if (bcVariables) Some(input.sparkContext.broadcast(splits)) else Option.empty
- val splitsOption = if (bcVariables) Option.empty else Some(splits)
-
- /**
- * Performs a sequential aggregation over a partition for a particular tree and node.
- *
- * For each feature, the aggregate sufficient statistics are updated for the relevant
- * bins.
- *
- * @param treeIndex Index of the tree that we want to perform aggregation for.
- * @param nodeInfo The node info for the tree node.
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics
- * for each (node, feature, bin).
- * @param baggedPoint Data point being aggregated.
- */
- def nodeBinSeqOp(
- treeIndex: Int,
- nodeInfo: NodeIndexInfo,
- agg: Array[DTStatsAggregator],
- splitsBcv: Array[Array[Split]],
- baggedPoint: BaggedPoint[TreePointY],
- sampleId: Short = 0): Unit = {
- if (DTUtils.isValidNodeInfo(nodeInfo, agg, groupInfo, baggedPoint, sampleId)) {
- val aggNodeIndex = nodeInfo.nodeIndexInGroup
- val featuresForNode = nodeInfo.featureSubset
- val instanceWeight = baggedPoint.subsampleWeights(treeIndex)
- if (metadata.unorderedFeatures.isEmpty) {
- orderedBinSeqOp(agg(aggNodeIndex), baggedPoint.datum, instanceWeight, featuresForNode)
- } else {
- mixedBinSeqOp(agg(aggNodeIndex), baggedPoint.datum, splitsBcv,
- metadata.unorderedFeatures, instanceWeight, featuresForNode)
- }
- agg(aggNodeIndex).updateParent(baggedPoint.datum.label, instanceWeight)
- }
- }
-
- /**
- * Performs a sequential aggregation over a partition.
- *
- * Each data point contributes to one node. For each feature,
- * the aggregate sufficient statistics are updated for the relevant bins.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (node, feature, bin).
- * @param baggedPoint Data point being aggregated.
- * @return agg
- */
- def binSeqOp(
- agg: Array[DTStatsAggregator],
- baggedPoint: BaggedPoint[TreePointY],
- splitsBcv: Array[Array[Split]],
- sampleId: Short): Array[DTStatsAggregator] = {
- // TODO: treeToNodeToIndexInfo and topNodesForGroup(include sub-nodes) weren't broadcast.
- treeToNodeToIndexInfo.foreach { case (treeIndex, nodeIndexToInfo) =>
- if (DTUtils.isSubSampled(baggedPoint, groupInfo, treeIndex, sampleId)) {
- val nodeIndex =
- topNodesForGroup(treeIndex).predictImpl(baggedPoint.datum.binnedFeatures, splitsBcv)
- nodeBinSeqOp(treeIndex, nodeIndexToInfo.getOrElse(nodeIndex, null),
- agg, splitsBcv, baggedPoint, sampleId)
- }
- }
- agg
- }
-
- /**
- * Do the same thing as binSeqOp, but with nodeIdCache.
- */
- def binSeqOpWithNodeIdCache(
- agg: Array[DTStatsAggregator],
- splitsBcv: Array[Array[Split]],
- dataPoint: (BaggedPoint[TreePointY], Array[Int])): Array[DTStatsAggregator] = {
- treeToNodeToIndexInfo.foreach { case (treeIndex, nodeIndexToInfo) =>
- val baggedPoint = dataPoint._1
- val nodeIdCache = dataPoint._2
- val nodeIndex = nodeIdCache(treeIndex)
- nodeBinSeqOp(treeIndex, nodeIndexToInfo.getOrElse(nodeIndex, null),
- agg, splitsBcv, baggedPoint)
- }
-
- agg
- }
-
- /**
- * Get node index in group --> features indices map,
- * which is a short cut to find feature indices for a node given node index in group.
- */
- def getNodeToFeatures(
- treeToNodeToIndexInfo: Map[Int, Map[Int, NodeIndexInfo]]): Option[Map[Int, Array[Int]]] = {
- if (!metadata.subsamplingFeatures) {
- None
- } else {
- val mutableNodeToFeatures = new mutable.HashMap[Int, Array[Int]]()
- treeToNodeToIndexInfo.values.foreach { nodeIdToNodeInfo =>
- nodeIdToNodeInfo.values.foreach { nodeIndexInfo =>
- assert(nodeIndexInfo.featureSubset.isDefined)
- mutableNodeToFeatures(nodeIndexInfo.nodeIndexInGroup) = nodeIndexInfo.featureSubset.get
- }
- }
- Some(mutableNodeToFeatures.toMap)
- }
- }
-
- /** array of nodes to train indexed by node index in group */
- val nodes = new Array[LearningNode](numNodes)
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- nodes(treeToNodeToIndexInfo(treeIndex)(node.id).nodeIndexInGroup) = node
- }
- }
-
- // Calculate best splits for all nodes in the group
- timer.start("chooseSplits")
-
- // In each partition, iterate all instances and compute aggregate stats for each node,
- // yield a (nodeIndex, nodeAggregateStats) pair for each node.
- // After a `reduceByKey` operation,
- // stats of a node will be shuffled to a particular partition and be combined together,
- // then best splits for nodes are found there.
- // Finally, only best Splits for nodes are collected to driver to construct decision tree.
- // nodeToFeatures: node index in group -> selected feature indexes
- val nodeToFeatures = getNodeToFeatures(treeToNodeToIndexInfo)
- val nodeToFeaturesBc = input.sparkContext.broadcast(nodeToFeatures)
-
- /** partitionAggregates RDD: node index in group --> nodeStats */
- val partitionAggregates: RDD[(Int, DTStatsAggregator)] = if (nodeIdCache.nonEmpty) {
- input.zip(nodeIdCache.get.nodeIdsForInstances).mapPartitions { points =>
- // Construct a nodeStatsAggregators array to hold node aggregate stats,
- // each node will have a nodeStatsAggregator
- val nodeStatsAggregators = Array.tabulate(numNodes) { nodeIndex =>
- val featuresForNode = nodeToFeaturesBc.value.map { nodeToFeatures =>
- nodeToFeatures(nodeIndex)
- }
- new DTStatsAggregator(metadata, featuresForNode)
- }
-
- val splitsBcv = if (bcVariables) splitsBc.get.value else splitsOption.get
- // iterator all instances in current partition and update aggregate stats
- points.foreach(binSeqOpWithNodeIdCache(nodeStatsAggregators, splitsBcv, _))
-
- // transform nodeStatsAggregators array to (nodeIndex, nodeAggregateStats) pairs,
- // which can be combined with other partition using `reduceByKey`
- nodeStatsAggregators.view.zipWithIndex.map(_.swap).iterator
- }
- } else {
- input.mapPartitions { points =>
- val (firstPointOption, nodeStatsAggregators) =
- DTUtils.initNodeStatsAgg(numNodes, nodeToFeaturesBc, metadata, points, groupInfo)
- if (firstPointOption.isEmpty) {
- Iterator.empty
- } else {
- val firstPoint = firstPointOption.get
- val sampleId = firstPoint.sampleId
-
- val splitsBcv = if (bcVariables) splitsBc.get.value else splitsOption.get
- binSeqOp(nodeStatsAggregators, firstPoint, splitsBcv, sampleId)
- // iterator all instances in current partition and update aggregate stats
- points.foreach(binSeqOp(nodeStatsAggregators, _, splitsBcv, sampleId))
-
- // transform nodeStatsAggregators array to (nodeIndex, nodeAggregateStats) pairs,
- // which can be combined with other partition using `reduceByKey`
- nodeStatsAggregators.view.zipWithIndex
- .filter(v => RFUtils.isValidAgg(v._1)).map(_.swap).iterator
- }
- }
- }
-
- val reducedAggregates = if (extraParams.useDFCollPtner) {
- val partitioner = new DFCollectionPartitioner(input.partitions.length,
- DTUtils.maxNumParallelThreads(), metadata.numFeatures)
- partitionAggregates.reduceByKey(partitioner, (a, b) => a.merge(b))
- } else {
- logInfo("DFCollectionPartitioner discarded.")
- partitionAggregates.reduceByKey((a, b) => a.merge(b))
- }
- val nodeToBestSplits = reducedAggregates.map {
- case (nodeIndex, aggStats) =>
- val featuresForNode = nodeToFeaturesBc.value.flatMap { nodeToFeatures =>
- Some(nodeToFeatures(nodeIndex))
- }
-
- val splitsBcv = if (bcVariables) splitsBc.get.value else splitsOption.get
- // find best split for each node
- val (split: Split, stats: ImpurityStats) =
- binsToBestSplit(aggStats, splitsBcv, featuresForNode, nodes(nodeIndex))
- (nodeIndex, (split, stats))
- }.collectAsMap()
-
- timer.stop("chooseSplits")
-
- val nodeIdUpdaters = if (nodeIdCache.nonEmpty) {
- Array.fill[mutable.Map[Int, NodeIndexUpdaterRaw]](
- metadata.numTrees)(mutable.Map[Int, NodeIndexUpdaterRaw]())
- } else {
- null
- }
- // Iterate over all nodes in this group.
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- val nodeIndex = node.id
- val nodeLevel = LearningNode.indexToLevel(nodeIndex)
- val nodeInfo = treeToNodeToIndexInfo(treeIndex)(nodeIndex)
- val aggNodeIndex = nodeInfo.nodeIndexInGroup
- val (split: Split, stats: ImpurityStats) =
- nodeToBestSplits(aggNodeIndex)
- logDebug("best split = " + split)
-
- // Extract info for this node. Create children if not leaf.
- val isLeaf =
- (stats.gain <= 0) || (nodeLevel == metadata.maxDepth)
- node.isLeaf = isLeaf
- node.stats = stats
- logDebug("Node = " + node)
-
- if (!isLeaf) {
- node.split = Some(split)
- val childIsLeaf = (nodeLevel + 1) == metadata.maxDepth
- val leftChildIsLeaf = childIsLeaf || (stats.leftImpurity == 0.0)
- val rightChildIsLeaf = childIsLeaf || (stats.rightImpurity == 0.0)
- node.leftChild = Some(LearningNode(LearningNode.leftChildIndex(nodeIndex),
- leftChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.leftImpurityCalculator)))
- node.rightChild = Some(LearningNode(LearningNode.rightChildIndex(nodeIndex),
- rightChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.rightImpurityCalculator)))
-
- if (nodeIdCache.nonEmpty) {
- val nodeIndexUpdater = NodeIndexUpdaterRaw(
- split = split,
- nodeIndex = nodeIndex)
- nodeIdUpdaters(treeIndex).put(nodeIndex, nodeIndexUpdater)
- }
-
- // enqueue left child and right child if they are not leaves
- if (!leftChildIsLeaf) {
- nodeStack.push((treeIndex, node.leftChild.get))
- }
- if (!rightChildIsLeaf) {
- nodeStack.push((treeIndex, node.rightChild.get))
- }
-
- logDebug("leftChildIndex = " + node.leftChild.get.id +
- ", impurity = " + stats.leftImpurity)
- logDebug("rightChildIndex = " + node.rightChild.get.id +
- ", impurity = " + stats.rightImpurity)
- }
- }
- }
-
- if (nodeIdCache.nonEmpty) {
- // Update the cache if needed.
- nodeIdCache.get.updateNodeIndicesY(input, nodeIdUpdaters, splits)
- }
- }
-
- /**
- * Calculate the impurity statistics for a given (feature, split) based upon left/right
- * aggregates.
- *
- * @param stats the recycle impurity statistics for this feature's all splits,
- * only 'impurity' and 'impurityCalculator' are valid between each iteration
- * @param leftImpurityCalculator left node aggregates for this (feature, split)
- * @param rightImpurityCalculator right node aggregate for this (feature, split)
- * @param metadata learning and dataset metadata for DecisionTree
- * @return Impurity statistics for this (feature, split)
- */
- private def calculateImpurityStats(
- stats: ImpurityStats,
- leftImpurityCalculator: ImpurityCalculator,
- rightImpurityCalculator: ImpurityCalculator,
- metadata: DecisionTreeMetadata): ImpurityStats = {
-
- val parentImpurityCalculator: ImpurityCalculator = if (stats == null) {
- leftImpurityCalculator.copy.add(rightImpurityCalculator)
- } else {
- stats.impurityCalculator
- }
-
- val impurity: Double = if (stats == null) {
- parentImpurityCalculator.calculate()
- } else {
- stats.impurity
- }
-
- val leftCount = leftImpurityCalculator.count
- val rightCount = rightImpurityCalculator.count
-
- val totalCount = leftCount + rightCount
-
- // If left child or right child doesn't satisfy minimum instances per node,
- // then this split is invalid, return invalid information gain stats.
- if ((leftCount < metadata.minInstancesPerNode) ||
- (rightCount < metadata.minInstancesPerNode)) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- val leftImpurity = leftImpurityCalculator.calculate() // Note: This equals 0 if count = 0
- val rightImpurity = rightImpurityCalculator.calculate()
-
- val leftWeight = leftCount / totalCount.toDouble
- val rightWeight = rightCount / totalCount.toDouble
-
- val gain = impurity - leftWeight * leftImpurity - rightWeight * rightImpurity
-
- // if information gain doesn't satisfy minimum information gain,
- // then this split is invalid, return invalid information gain stats.
- if (gain < metadata.minInfoGain) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- new ImpurityStats(gain, impurity, parentImpurityCalculator,
- leftImpurityCalculator, rightImpurityCalculator)
- }
-
- /**
- * Find the best split for a node.
- *
- * @param binAggregates Bin statistics.
- * @return tuple for best split: (Split, information gain, prediction at node)
- */
- private[tree] def binsToBestSplit(
- binAggregates: DTStatsAggregator,
- splits: Array[Array[Split]],
- featuresForNode: Option[Array[Int]],
- node: LearningNode): (Split, ImpurityStats) = {
-
- // Calculate InformationGain and ImpurityStats if current node is top node
- val level = LearningNode.indexToLevel(node.id)
- var gainAndImpurityStats: ImpurityStats = if (level == 0) {
- null
- } else {
- node.stats
- }
-
- val validFeatureSplits =
- Range(0, binAggregates.metadata.numFeaturesPerNode).view.map { featureIndexIdx =>
- featuresForNode.map(features => (featureIndexIdx, features(featureIndexIdx)))
- .getOrElse((featureIndexIdx, featureIndexIdx))
- }.withFilter { case (_, featureIndex) =>
- binAggregates.metadata.numSplits(featureIndex) != 0
- }
-
- // For each (feature, split), calculate the gain, and select the best (feature, split).
- val splitsAndImpurityInfo =
- validFeatureSplits.map { case (featureIndexIdx, featureIndex) =>
- val numSplits = binAggregates.metadata.numSplits(featureIndex)
- if (binAggregates.metadata.isContinuous(featureIndex)) {
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- val nodeFeatureOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- var splitIndex = 0
- while (splitIndex < numSplits) {
- binAggregates.mergeForFeature(nodeFeatureOffset, splitIndex + 1, splitIndex)
- splitIndex += 1
- }
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { case splitIdx =>
- val leftChildStats = binAggregates.getImpurityCalculator(nodeFeatureOffset, splitIdx)
- val rightChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, numSplits)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIdx, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits(featureIndex)(bestFeatureSplitIndex), bestFeatureGainStats)
- } else if (binAggregates.metadata.isUnordered(featureIndex)) {
- // Unordered categorical feature
- val leftChildOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val leftChildStats = binAggregates.getImpurityCalculator(leftChildOffset, splitIndex)
- val rightChildStats = binAggregates.getParentImpurityCalculator()
- .subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits(featureIndex)(bestFeatureSplitIndex), bestFeatureGainStats)
- } else {
- // Ordered categorical feature
- val nodeFeatureOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- val numCategories = binAggregates.metadata.numBins(featureIndex)
-
- /* Each bin is one category (feature value).
- * The bins are ordered based on centroidForCategories, and this ordering determines which
- * splits are considered. (With K categories, we consider K - 1 possible splits.)
- *
- * centroidForCategories is a list: (category, centroid)
- */
- val centroidForCategories = Range(0, numCategories).map { case featureValue =>
- val categoryStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, featureValue)
- val centroid = if (categoryStats.count != 0) {
- if (binAggregates.metadata.isMulticlass) {
- // multiclass classification
- // For categorical variables in multiclass classification,
- // the bins are ordered by the impurity of their corresponding labels.
- categoryStats.calculate()
- } else if (binAggregates.metadata.isClassification) {
- // binary classification
- // For categorical variables in binary classification,
- // the bins are ordered by the count of class 1.
- categoryStats.stats(1)
- } else {
- // regression
- // For categorical variables in regression and binary classification,
- // the bins are ordered by the prediction.
- categoryStats.predict
- }
- } else {
- Double.MaxValue
- }
- (featureValue, centroid)
- }
-
- logDebug("Centroids for categorical variable: " + centroidForCategories.mkString(","))
-
- // bins sorted by centroids
- val categoriesSortedByCentroid = centroidForCategories.toList.sortBy(_._2)
-
- logDebug("Sorted centroids for categorical variable = " +
- categoriesSortedByCentroid.mkString(","))
-
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- var splitIndex = 0
- while (splitIndex < numSplits) {
- val currentCategory = categoriesSortedByCentroid(splitIndex)._1
- val nextCategory = categoriesSortedByCentroid(splitIndex + 1)._1
- binAggregates.mergeForFeature(nodeFeatureOffset, nextCategory, currentCategory)
- splitIndex += 1
- }
- // lastCategory = index of bin with total aggregates for this (node, feature)
- val lastCategory = categoriesSortedByCentroid.last._1
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val featureValue = categoriesSortedByCentroid(splitIndex)._1
- val leftChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, featureValue)
- val rightChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, lastCategory)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- val categoriesForSplit =
- categoriesSortedByCentroid.map(_._1.toDouble).slice(0, bestFeatureSplitIndex + 1)
- val bestFeatureSplit =
- new CategoricalSplit(featureIndex, categoriesForSplit.toArray, numCategories)
- (bestFeatureSplit, bestFeatureGainStats)
- }
- }
-
- val (bestSplit, bestSplitStats) =
- if (splitsAndImpurityInfo.isEmpty) {
- // If no valid splits for features, then this split is invalid,
- // return invalid information gain stats. Take any split and continue.
- // Splits is empty, so arbitrarily choose to split on any threshold
- val dummyFeatureIndex = featuresForNode.map(_.head).getOrElse(0)
- val parentImpurityCalculator = binAggregates.getParentImpurityCalculator()
- if (binAggregates.metadata.isContinuous(dummyFeatureIndex)) {
- (new ContinuousSplit(dummyFeatureIndex, 0),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- } else {
- val numCategories = binAggregates.metadata.featureArity(dummyFeatureIndex)
- (new CategoricalSplit(dummyFeatureIndex, Array(), numCategories),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- }
- } else {
- splitsAndImpurityInfo.maxBy(_._2.gain)
- }
- (bestSplit, bestSplitStats)
- }
-
- /**
- * Returns splits for decision tree calculation.
- * Continuous and categorical features are handled differently.
- *
- * Continuous features:
- * For each feature, there are numBins - 1 possible splits representing the possible binary
- * decisions at each node in the tree.
- * This finds locations (feature values) for splits using a subsample of the data.
- *
- * Categorical features:
- * For each feature, there is 1 bin per split.
- * Splits and bins are handled in 2 ways:
- * (a) "unordered features"
- * For multiclass classification with a low-arity feature
- * (i.e., if isMulticlass && isSpaceSufficientForAllCategoricalSplits),
- * the feature is split based on subsets of categories.
- * (b) "ordered features"
- * For regression and binary classification,
- * and for multiclass classification with a high-arity feature,
- * there is one bin per category.
- *
- * @param input Training data: RDD of [[LabeledPoint]]
- * @param metadata Learning and dataset metadata
- * @param seed random seed
- * @return Splits, an Array of [[Split]]
- * of size (numFeatures, numSplits)
- */
- protected[tree] def findSplits(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- seed: Long,
- numFeaturesOptFindSplits: Int = 8192): Array[Array[Split]] = {
-
- logDebug("isMulticlass = " + metadata.isMulticlass)
-
- val numFeatures = metadata.numFeatures
-
- // Sample the input only if there are continuous features.
- val continuousFeatures = Range(0, numFeatures).filter(metadata.isContinuous)
- val sampledInput = if (continuousFeatures.nonEmpty) {
- // Calculate the number of samples for approximate quantile calculation.
- val requiredSamples = math.max(metadata.maxBins * metadata.maxBins, 10000)
- val fraction = if (requiredSamples < metadata.numExamples) {
- requiredSamples.toDouble / metadata.numExamples
- } else {
- 1.0
- }
- logDebug("fraction of data used for calculating quantiles = " + fraction)
- input.sample(withReplacement = false, fraction, new XORShiftRandom(seed).nextInt())
- } else {
- input.sparkContext.emptyRDD[LabeledPoint]
- }
-
- findSplitsBySorting(sampledInput, metadata, continuousFeatures, numFeaturesOptFindSplits)
- }
-
- private def findSplitsBySorting(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- continuousFeatures: IndexedSeq[Int],
- numFeaturesOptFindSplits: Int = 8192): Array[Array[Split]] = {
-
- val continuousSplits: scala.collection.Map[Int, Array[Split]] = {
- // reduce the parallelism for split computations when there are less
- // continuous features than input partitions. this prevents tasks from
- // being spun up that will definitely do no work.
- val numPartitions = math.min(continuousFeatures.length, input.partitions.length)
-
- if (continuousFeatures.length < numFeaturesOptFindSplits) {
- input
- .flatMap(point => continuousFeatures.map(idx => (idx, point.features(idx))))
- .groupByKey(numPartitions)
- .map { case (idx, samples) =>
- val thresholds = findSplitsForContinuousFeature(samples, metadata, idx)
- val splits: Array[Split] = thresholds.map(thresh => new ContinuousSplit(idx, thresh))
- logDebug(s"featureIndex = $idx, numSplits = ${splits.length}")
- (idx, splits)
- }.collectAsMap()
- } else {
- val numSamples = input.count
- require(numSamples < Int.MaxValue)
- input.mapPartitions { points =>
- val partialRes = points.foldLeft(Array.empty[(Int, Array[Double])]) { case (res, point) =>
- var resNew = res
- continuousFeatures.foreach { idx =>
- val featureValue = point.features(idx)
- if (featureValue != 0.0) {
- resNew = resNew :+ (idx, Array(featureValue))
- }
- }
- resNew
- }
- val restRes = continuousFeatures.indices.diff(partialRes.map(_._1).distinct)
- .toArray.map(idx => (idx, Array.empty[Double]))
- (partialRes ++ restRes).iterator
- }.reduceByKey(_ ++ _).map { case (idx, partialSamples) =>
- val thresholds = findSplitsForContinuousFeature(partialSamples, metadata, idx,
- numSamples.toInt - partialSamples.length)
- val splits: Array[Split] = thresholds.map(thresh => new ContinuousSplit(idx, thresh))
- logDebug(s"featureIndex = $idx, numSplits = ${splits.length}")
- (idx, splits)
- }.collectAsMap()
- }
- }
-
- val numFeatures = metadata.numFeatures
- val splits: Array[Array[Split]] = Array.tabulate(numFeatures) {
- case i if metadata.isContinuous(i) =>
- val split = continuousSplits(i)
- metadata.setNumSplits(i, split.length)
- split
-
- case i if metadata.isCategorical(i) && metadata.isUnordered(i) =>
- // Unordered features
- // 2^(maxFeatureValue - 1) - 1 combinations
- val featureArity = metadata.featureArity(i)
- Array.tabulate[Split](metadata.numSplits(i)) { splitIndex =>
- val categories = extractMultiClassCategories(splitIndex + 1, featureArity)
- new CategoricalSplit(i, categories.toArray, featureArity)
- }
-
- case i if metadata.isCategorical(i) =>
- // Ordered features
- // Splits are constructed as needed during training.
- Array.empty[Split]
- }
- splits
- }
-
- /**
- * Nested method to extract list of eligible categories given an index. It extracts the
- * position of ones in a binary representation of the input. If binary
- * representation of an number is 01101 (13), the output list should (3.0, 2.0,
- * 0.0). The maxFeatureValue depict the number of rightmost digits that will be tested for ones.
- */
- private[tree] def extractMultiClassCategories(
- input: Int,
- maxFeatureValue: Int): List[Double] = {
- var categories = List[Double]()
- var j = 0
- var bitShiftedInput = input
- while (j < maxFeatureValue) {
- if (bitShiftedInput % 2 != 0) {
- // updating the list of categories.
- categories = j.toDouble :: categories
- }
- // Right shift by one
- bitShiftedInput = bitShiftedInput >> 1
- j += 1
- }
- categories
- }
-
- /**
- * Find splits for a continuous feature
- * NOTE: Returned number of splits is set based on `featureSamples` and
- * could be different from the specified `numSplits`.
- * The `numSplits` attribute in the `DecisionTreeMetadata` class will be set accordingly.
- *
- * @param featureSamples feature values of each sample
- * @param metadata decision tree metadata
- * NOTE: `metadata.numbins` will be changed accordingly
- * if there are not enough splits to be found
- * @param featureIndex feature index to find splits
- * @return array of split thresholds
- */
- private[tree] def findSplitsForContinuousFeature(
- featureSamples: Iterable[Double],
- metadata: DecisionTreeMetadata,
- featureIndex: Int,
- numSamplesOfZeroFeature: Int = 0): Array[Double] = {
- require(metadata.isContinuous(featureIndex),
- "findSplitsForContinuousFeature can only be used to find splits for a continuous feature.")
-
- val splits: Array[Double] = if (featureSamples.isEmpty && 0 == numSamplesOfZeroFeature) {
- Array.empty[Double]
- } else {
- val numSplits = metadata.numSplits(featureIndex)
-
- // get count for each distinct value
- val startValueCountPair = if (0 == numSamplesOfZeroFeature) {
- (Map.empty[Double, Int], 0)
- } else {
- (Map(0.0 -> numSamplesOfZeroFeature), numSamplesOfZeroFeature)
- }
- val (valueCountMap, numSamples) = featureSamples.foldLeft(startValueCountPair) {
- case ((m, cnt), x) =>
- (m + ((x, m.getOrElse(x, 0) + 1)), cnt + 1)
- }
- // sort distinct values
- val valueCounts = valueCountMap.toSeq.sortBy(_._1).toArray
-
- val possibleSplits = valueCounts.length - 1
- if (possibleSplits == 0) {
- // constant feature
- Array.empty[Double]
- } else if (possibleSplits <= numSplits) {
- // if possible splits is not enough or just enough, just return all possible splits
- (1 to possibleSplits)
- .map(index => (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0)
- .toArray
- } else {
- // stride between splits
- val stride: Double = numSamples.toDouble / (numSplits + 1)
- logDebug("stride = " + stride)
-
- // iterate `valueCount` to find splits
- val splitsBuilder = mutable.ArrayBuilder.make[Double]
- var index = 1
- // currentCount: sum of counts of values that have been visited
- var currentCount = valueCounts(0)._2
- // targetCount: target value for `currentCount`.
- // If `currentCount` is closest value to `targetCount`,
- // then current value is a split threshold.
- // After finding a split threshold, `targetCount` is added by stride.
- var targetCount = stride
- while (index < valueCounts.length) {
- val previousCount = currentCount
- currentCount += valueCounts(index)._2
- val previousGap = math.abs(previousCount - targetCount)
- val currentGap = math.abs(currentCount - targetCount)
- // If adding count of current value to currentCount
- // makes the gap between currentCount and targetCount smaller,
- // previous value is a split threshold.
- if (previousGap < currentGap) {
- splitsBuilder += (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0
- targetCount += stride
- }
- index += 1
- }
-
- splitsBuilder.result()
- }
- }
- splits
- }
-
- /**
- * Pull nodes off of the queue, and collect a group of nodes to be split on this iteration.
- * This tracks the memory usage for aggregates and stops adding nodes when too much memory
- * will be needed; this allows an adaptive number of nodes since different nodes may require
- * different amounts of memory (if featureSubsetStrategy is not "all").
- *
- * @param nodeStack Queue of nodes to split.
- * @param maxMemoryUsage Bound on size of aggregate statistics.
- * @return (nodesForGroup, treeToNodeToIndexInfo).
- * nodesForGroup holds the nodes to split: treeIndex --> nodes in tree.
- *
- * treeToNodeToIndexInfo holds indices selected features for each node:
- * treeIndex --> (global) node index --> (node index in group, feature indices).
- * The (global) node index is the index in the tree; the node index in group is the
- * index in [0, numNodesInGroup) of the node in this group.
- * The feature indices are None if not subsampling features.
- */
- private[tree] def selectNodesToSplit(
- nodeStack: mutable.ArrayStack[(Int, LearningNode)],
- maxMemoryUsage: Long,
- metadata: DecisionTreeMetadata,
- rng: Random): (Map[Int, Array[LearningNode]], Map[Int, Map[Int, NodeIndexInfo]]) = {
- // Collect some nodes to split:
- // nodesForGroup(treeIndex) = nodes to split
- val mutableNodesForGroup = new mutable.HashMap[Int, mutable.ArrayBuffer[LearningNode]]()
- val mutableTreeToNodeToIndexInfo =
- new mutable.HashMap[Int, mutable.HashMap[Int, NodeIndexInfo]]()
- var memUsage: Long = 0L
- var numNodesInGroup = 0
- // If maxMemoryInMB is set very small, we want to still try to split 1 node,
- // so we allow one iteration if memUsage == 0.
- var groupDone = false
- while (nodeStack.nonEmpty && !groupDone) {
- val (treeIndex, node) = nodeStack.top
- // Choose subset of features for node (if subsampling).
- val featureSubset: Option[Array[Int]] = if (metadata.subsamplingFeatures) {
- Some(SamplingUtils.reservoirSampleAndCount(Range(0,
- metadata.numFeatures).iterator, metadata.numFeaturesPerNode, rng.nextLong())._1)
- } else {
- None
- }
- // Check if enough memory remains to add this node to the group.
- val nodeMemUsage = DecisionForest.aggregateSizeForNode(metadata, featureSubset) * 8L
- if (memUsage + nodeMemUsage <= maxMemoryUsage || memUsage == 0) {
- nodeStack.pop()
- mutableNodesForGroup.getOrElseUpdate(treeIndex, new mutable.ArrayBuffer[LearningNode]()) +=
- node
- mutableTreeToNodeToIndexInfo
- .getOrElseUpdate(treeIndex, new mutable.HashMap[Int, NodeIndexInfo]())(node.id)
- = new NodeIndexInfo(numNodesInGroup, featureSubset)
- numNodesInGroup += 1
- memUsage += nodeMemUsage
- } else {
- groupDone = true
- }
- }
- if (memUsage > maxMemoryUsage) {
- // If maxMemoryUsage is 0, we should still allow splitting 1 node.
- logWarning(s"Tree learning is using approximately $memUsage bytes per iteration, which" +
- s" exceeds requested limit maxMemoryUsage=$maxMemoryUsage. This allows splitting" +
- s" $numNodesInGroup nodes in this iteration.")
- }
- logWarning(f"[this group] actualMemUsage: ${memUsage/(1024d*1024d)}%.2f MB," +
- f" maxMemoryUsage: ${maxMemoryUsage/(1024d*1024d)}%.2f MB.")
- // Convert mutable maps to immutable ones.
- val nodesForGroup: Map[Int, Array[LearningNode]] =
- mutableNodesForGroup.mapValues(_.toArray).toMap
- val treeToNodeToIndexInfo = mutableTreeToNodeToIndexInfo.mapValues(_.toMap).toMap
- (nodesForGroup, treeToNodeToIndexInfo)
- }
-
- /**
- * Get the number of values to be stored for this node in the bin aggregates.
- *
- * @param featureSubset Indices of features which may be split at this node.
- * If None, then use all features.
- */
- private def aggregateSizeForNode(
- metadata: DecisionTreeMetadata,
- featureSubset: Option[Array[Int]]): Long = {
- val totalBins = if (featureSubset.nonEmpty) {
- featureSubset.get.map(featureIndex => metadata.numBins(featureIndex).toLong).sum
- } else {
- metadata.numBins.map(_.toLong).sum
- }
- if (metadata.isClassification) {
- metadata.numClasses * totalBins
- } else {
- 3 * totalBins
- }
- }
-}
-
-object DecisionForestInfo {
- var timerResult: String = ""
-}
-
-case class LocalTrainingTask(node: LearningNode)
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTrees.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTrees.scala
deleted file mode 100644
index ddb6925..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTrees.scala
+++ /dev/null
@@ -1,663 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-
-import org.apache.spark.SparkContext
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.linalg.Vector
-import org.apache.spark.ml.regression.{DecisionTreeRegressionModel, DecisionTreeRegressor}
-import org.apache.spark.ml.tree.Split
-import org.apache.spark.ml.tree.impl.RandomForest4GBDTX.findSplits
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo}
-import org.apache.spark.mllib.tree.configuration.{BoostingStrategy => OldBoostingStrategy}
-import org.apache.spark.mllib.tree.impurity.{Variance => OldVariance}
-import org.apache.spark.mllib.tree.loss.{Loss => OldLoss}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.rdd.util.PeriodicRDDCheckpointer
-import org.apache.spark.storage.StorageLevel
-
-
-private[spark] object GradientBoostedTrees extends Logging {
-
- /**
- * Method to train a gradient boosting model
- * @param input Training dataset: RDD of `LabeledPoint`.
- * @param seed Random seed.
- * @return tuple of ensemble models and weights:
- * (array of decision tree models, array of model weights)
- */
- def run(
- input: RDD[LabeledPoint],
- boostingStrategy: OldBoostingStrategy,
- seed: Long,
- featureSubsetStrategy: String): (Array[DecisionTreeRegressionModel], Array[Double]) = {
- val doUseAcc = getDoUseAccFromSparkConf(input.sparkContext)
- run(input, boostingStrategy, seed, featureSubsetStrategy, doUseAcc)
- }
-
- /** Run with extended parameters */
- def run(
- input: RDD[LabeledPoint],
- boostingStrategy: OldBoostingStrategy,
- seed: Long,
- featureSubsetStrategy: String,
- doUseAcc: Boolean): (Array[DecisionTreeRegressionModel], Array[Double]) = {
- val algo = boostingStrategy.treeStrategy.algo
- algo match {
- case OldAlgo.Regression =>
- if (doUseAcc) {
- GradientBoostedTrees.boostX(input, input, boostingStrategy, validate = false,
- seed, featureSubsetStrategy)
- } else {
- GradientBoostedTrees.boost(input, input, boostingStrategy, validate = false,
- seed, featureSubsetStrategy)
- }
- case OldAlgo.Classification =>
- // Map labels to -1, +1 so binary classification can be treated as regression.
- val remappedInput = input.map(x => new LabeledPoint((x.label * 2) - 1, x.features))
- if (doUseAcc) {
- GradientBoostedTrees.boostX(remappedInput, remappedInput,
- boostingStrategy, validate = false, seed, featureSubsetStrategy)
- } else {
- GradientBoostedTrees.boost(remappedInput, remappedInput,
- boostingStrategy, validate = false, seed, featureSubsetStrategy)
- }
- // algo is enumerate value, this case may be unreachable
- case _ =>
- throw new IllegalArgumentException(s"$algo is not supported by gradient boosting.")
- }
- }
-
- /**
- * Method to validate a gradient boosting model
- * @param input Training dataset: RDD of `LabeledPoint`.
- * @param validationInput Validation dataset.
- * This dataset should be different from the training dataset,
- * but it should follow the same distribution.
- * E.g., these two datasets could be created from an original dataset
- * by using `org.apache.spark.rdd.RDD.randomSplit()`
- * @param seed Random seed.
- * @return tuple of ensemble models and weights:
- * (array of decision tree models, array of model weights)
- */
- def runWithValidation(
- input: RDD[LabeledPoint],
- validationInput: RDD[LabeledPoint],
- boostingStrategy: OldBoostingStrategy,
- seed: Long,
- featureSubsetStrategy: String): (Array[DecisionTreeRegressionModel], Array[Double]) = {
- val doUseAcc = getDoUseAccFromSparkConf(input.sparkContext)
- runWithValidation(input, validationInput, boostingStrategy, seed, featureSubsetStrategy,
- doUseAcc)
- }
-
- /** Run with validation dataset and extended parameters */
- def runWithValidation(
- input: RDD[LabeledPoint],
- validationInput: RDD[LabeledPoint],
- boostingStrategy: OldBoostingStrategy,
- seed: Long,
- featureSubsetStrategy: String,
- doUseAcc: Boolean): (Array[DecisionTreeRegressionModel], Array[Double]) = {
- val algo = boostingStrategy.treeStrategy.algo
- algo match {
- case OldAlgo.Regression =>
- if (doUseAcc) {
- GradientBoostedTrees.boostX(input, validationInput, boostingStrategy,
- validate = true, seed, featureSubsetStrategy)
- } else {
- GradientBoostedTrees.boost(input, validationInput, boostingStrategy,
- validate = true, seed, featureSubsetStrategy)
- }
- case OldAlgo.Classification =>
- // Map labels to -1, +1 so binary classification can be treated as regression.
- val remappedInput = input.map(
- x => new LabeledPoint((x.label * 2) - 1, x.features))
- val remappedValidationInput = validationInput.map(
- x => new LabeledPoint((x.label * 2) - 1, x.features))
- if (doUseAcc) {
- GradientBoostedTrees.boostX(remappedInput, remappedValidationInput, boostingStrategy,
- validate = true, seed, featureSubsetStrategy)
- } else {
- GradientBoostedTrees.boost(remappedInput, remappedValidationInput, boostingStrategy,
- validate = true, seed, featureSubsetStrategy)
- }
-
- // algo is enumerate value, this case may be unreachable
- case _ =>
- throw new IllegalArgumentException(s"$algo is not supported by the gradient boosting.")
- }
- }
-
- private val extraParamKey = "spark.boostkit.ml.gbdt.doUseAcc"
- private val doUseAccDefault = true
-
- private def getDoUseAccFromSparkConf(sc: SparkContext): Boolean = {
- val doUseAcctStr = sc.conf.getOption(extraParamKey)
- if (doUseAcctStr.nonEmpty) {
- try {
- doUseAcctStr.get.toBoolean
- } catch {
- case ex: Exception =>
- throw new IllegalArgumentException(s"Parse boostkit parameter" +
- s"($extraParamKey) failed, Error reason: ${ex.getMessage}")
- }
- } else {
- doUseAccDefault
- }
- }
-
- /**
- * Compute the initial predictions and errors for a dataset for the first
- * iteration of gradient boosting.
- * @param data: training data.
- * @param initTreeWeight: learning rate assigned to the first tree.
- * @param initTree: first DecisionTreeModel.
- * @param loss: evaluation metric.
- * @return an RDD with each element being a zip of the prediction and error
- * corresponding to every sample.
- */
- def computeInitialPredictionAndError(
- data: RDD[LabeledPoint],
- initTreeWeight: Double,
- initTree: DecisionTreeRegressionModel,
- loss: OldLoss): RDD[(Double, Double)] = {
- data.map { lp =>
- val pred = updatePrediction(lp.features, 0.0, initTree, initTreeWeight)
- val error = loss.computeError(pred, lp.label)
- (pred, error)
- }
- }
-
- def computeInitialPredictionAndErrorX(
- data: RDD[TreePoint],
- initTreeWeight: Double,
- initTree: DecisionTreeRegressionModel,
- loss: OldLoss,
- splits: Array[Array[Split]]): RDD[(Double, Double)] = {
- data.map { lp =>
- val pred = updatePredictionX(lp.binnedFeatures, 0.0, initTree, initTreeWeight, splits)
- val error = loss.computeError(pred, lp.label)
- (pred, error)
- }
- }
-
- /**
- * Update a zipped predictionError RDD
- * (as obtained with computeInitialPredictionAndError)
- * @param data: training data.
- * @param predictionAndError: predictionError RDD
- * @param treeWeight: Learning rate.
- * @param tree: Tree using which the prediction and error should be updated.
- * @param loss: evaluation metric.
- * @return an RDD with each element being a zip of the prediction and error
- * corresponding to each sample.
- */
- def updatePredictionError(
- data: RDD[LabeledPoint],
- predictionAndError: RDD[(Double, Double)],
- treeWeight: Double,
- tree: DecisionTreeRegressionModel,
- loss: OldLoss): RDD[(Double, Double)] = {
-
- val newPredError = data.zip(predictionAndError).mapPartitions { iter =>
- iter.map { case (lp, (pred, error)) =>
- val newPred = updatePrediction(lp.features, pred, tree, treeWeight)
- val newError = loss.computeError(newPred, lp.label)
- (newPred, newError)
- }
- }
- newPredError
- }
-
- def updatePredictionErrorX(
- data: RDD[TreePoint],
- predictionAndError: RDD[(Double, Double)],
- treeWeight: Double,
- tree: DecisionTreeRegressionModel,
- loss: OldLoss,
- splits: Array[Array[Split]]): RDD[(Double, Double)] = {
-
- val newPredError = data.zip(predictionAndError).mapPartitions { iter =>
- iter.map { case (lp, (pred, error)) =>
- val newPred = updatePredictionX(lp.binnedFeatures, pred, tree, treeWeight, splits)
- val newError = loss.computeError(newPred, lp.label)
- (newPred, newError)
- }
- }
- newPredError
- }
-
- /**
- * Add prediction from a new boosting iteration to an existing prediction.
- *
- * @param features Vector of features representing a single data point.
- * @param prediction The existing prediction.
- * @param tree New Decision Tree model.
- * @param weight Tree weight.
- * @return Updated prediction.
- */
- def updatePrediction(
- features: Vector,
- prediction: Double,
- tree: DecisionTreeRegressionModel,
- weight: Double): Double = {
- prediction + tree.rootNode.predictImpl(features).prediction * weight
- }
-
- def updatePredictionX(
- features: Array[Int],
- prediction: Double,
- tree: DecisionTreeRegressionModel,
- weight: Double,
- splits: Array[Array[Split]]): Double = {
- prediction + tree.rootNode.predictImplX(features, splits).prediction * weight
- }
-
- /**
- * Method to calculate error of the base learner for the gradient boosting calculation.
- * Note: This method is not used by the gradient boosting algorithm but is useful for debugging
- * purposes.
- * @param data Training dataset: RDD of `LabeledPoint`.
- * @param trees Boosted Decision Tree models
- * @param treeWeights Learning rates at each boosting iteration.
- * @param loss evaluation metric.
- * @return Measure of model error on data
- */
- def computeError(
- data: RDD[LabeledPoint],
- trees: Array[DecisionTreeRegressionModel],
- treeWeights: Array[Double],
- loss: OldLoss): Double = {
- data.map { lp =>
- val predicted = trees.zip(treeWeights).foldLeft(0.0) { case (acc, (model, weight)) =>
- updatePrediction(lp.features, acc, model, weight)
- }
- loss.computeError(predicted, lp.label)
- }.mean()
- }
-
- /**
- * Method to compute error or loss for every iteration of gradient boosting.
- *
- * @param data RDD of `LabeledPoint`
- * @param trees Boosted Decision Tree models
- * @param treeWeights Learning rates at each boosting iteration.
- * @param loss evaluation metric.
- * @param algo algorithm for the ensemble, either Classification or Regression
- * @return an array with index i having the losses or errors for the ensemble
- * containing the first i+1 trees
- */
- def evaluateEachIteration(
- data: RDD[LabeledPoint],
- trees: Array[DecisionTreeRegressionModel],
- treeWeights: Array[Double],
- loss: OldLoss,
- algo: OldAlgo.Value): Array[Double] = {
-
- val sc = data.sparkContext
- val remappedData = algo match {
- case OldAlgo.Classification => data.map(x => new LabeledPoint((x.label * 2) - 1, x.features))
- case _ => data
- }
-
- val broadcastTrees = sc.broadcast(trees)
- val localTreeWeights = treeWeights
- val treesIndices = trees.indices
-
- val dataCount = remappedData.count()
- val evaluation = remappedData.map { point =>
- treesIndices.map { idx =>
- val prediction = broadcastTrees.value(idx)
- .rootNode
- .predictImpl(point.features)
- .prediction
- prediction * localTreeWeights(idx)
- }
- .scanLeft(0.0)(_ + _).drop(1)
- .map(prediction => loss.computeError(prediction, point.label))
- }
- .aggregate(treesIndices.map(_ => 0.0))(
- (aggregated, row) => treesIndices.map(idx => aggregated(idx) + row(idx)),
- (a, b) => treesIndices.map(idx => a(idx) + b(idx)))
- .map(_ / dataCount)
-
- broadcastTrees.destroy(blocking = false)
- evaluation.toArray
- }
-
- /**
- * Internal method for performing regression using trees as base learners.
- * @param input training dataset
- * @param validationInput validation dataset, ignored if validate is set to false.
- * @param boostingStrategy boosting parameters
- * @param validate whether or not to use the validation dataset.
- * @param seed Random seed.
- * @return tuple of ensemble models and weights:
- * (array of decision tree models, array of model weights)
- */
- def boost(
- input: RDD[LabeledPoint],
- validationInput: RDD[LabeledPoint],
- boostingStrategy: OldBoostingStrategy,
- validate: Boolean,
- seed: Long,
- featureSubsetStrategy: String): (Array[DecisionTreeRegressionModel], Array[Double]) = {
- val timer = new TimeTracker()
- timer.start("total")
- timer.start("init")
-
- boostingStrategy.assertValid()
-
- // Initialize gradient boosting parameters
- val numIterations = boostingStrategy.numIterations
- val baseLearners = new Array[DecisionTreeRegressionModel](numIterations)
- val baseLearnerWeights = new Array[Double](numIterations)
- val loss = boostingStrategy.loss
- val learningRate = boostingStrategy.learningRate
-
- // Prepare strategy for individual trees, which use regression with variance impurity.
- val treeStrategy = boostingStrategy.treeStrategy.copy
- val validationTol = boostingStrategy.validationTol
- treeStrategy.algo = OldAlgo.Regression
- treeStrategy.impurity = OldVariance
- treeStrategy.assertValid()
-
- // Cache input
- val persistedInput = if (input.getStorageLevel == StorageLevel.NONE) {
- input.persist(StorageLevel.MEMORY_AND_DISK)
- true
- } else {
- false
- }
-
- // Prepare periodic checkpointers
- val predErrorCheckpointer = new PeriodicRDDCheckpointer[(Double, Double)](
- treeStrategy.getCheckpointInterval, input.sparkContext)
- val validatePredErrorCheckpointer = new PeriodicRDDCheckpointer[(Double, Double)](
- treeStrategy.getCheckpointInterval, input.sparkContext)
-
- timer.stop("init")
-
- logDebug("##########")
- logDebug("Building tree 0")
- logDebug("##########")
-
- // Initialize tree
- timer.start("building tree 0")
- val firstTree = new DecisionTreeRegressor().setSeed(seed)
- val firstTreeModel = firstTree.train(input, treeStrategy, featureSubsetStrategy)
- val firstTreeWeight = 1.0
- baseLearners(0) = firstTreeModel
- baseLearnerWeights(0) = firstTreeWeight
-
- var predError: RDD[(Double, Double)] =
- computeInitialPredictionAndError(input, firstTreeWeight, firstTreeModel, loss)
- predErrorCheckpointer.update(predError)
- logDebug(s"error of gbt = ${predError.values.mean()}")
-
- // Note: A model of type regression is used since we require raw prediction
- timer.stop("building tree 0")
-
- var validatePredError: RDD[(Double, Double)] =
- computeInitialPredictionAndError(validationInput, firstTreeWeight, firstTreeModel, loss)
- if (validate) validatePredErrorCheckpointer.update(validatePredError)
- var bestValidateError = if (validate) validatePredError.values.mean() else 0.0
- var bestM = 1
-
- var m = 1
- var doneLearning = false
- while (m < numIterations && !doneLearning) {
- // Update data with pseudo-residuals
- val data = predError.zip(input).map { case ((pred, _), point) =>
- LabeledPoint(-loss.gradient(pred, point.label), point.features)
- }
-
- timer.start(s"building tree $m")
- logDebug("###################################################")
- logDebug(s"Gradient boosting tree iteration ${m}")
- logDebug("###################################################")
-
- val dt = new DecisionTreeRegressor().setSeed(seed + m)
- val model = dt.train(data, treeStrategy, featureSubsetStrategy)
- timer.stop(s"building tree $m")
- // Update partial model
- baseLearners(m) = model
- // Note: The setting of baseLearnerWeights is incorrect for losses other than SquaredError.
- // Technically, the weight should be optimized for the particular loss.
- // However, the behavior should be reasonable, though not optimal.
- baseLearnerWeights(m) = learningRate
-
- predError = updatePredictionError(
- input, predError, baseLearnerWeights(m), baseLearners(m), loss)
- predErrorCheckpointer.update(predError)
- logDebug(s"error of gbt = ${predError.values.mean()}")
-
- if (validate) {
- // Stop training early if
- // 1. Reduction in error is less than the validationTol or
- // 2. If the error increases, that is if the model is overfit.
- // We want the model returned corresponding to the best validation error.
-
- validatePredError = updatePredictionError(
- validationInput, validatePredError, baseLearnerWeights(m), baseLearners(m), loss)
- validatePredErrorCheckpointer.update(validatePredError)
- val currentValidateError = validatePredError.values.mean()
- if (bestValidateError - currentValidateError < validationTol * Math.max(
- currentValidateError, 0.01)) {
- doneLearning = true
- } else if (currentValidateError < bestValidateError) {
- bestValidateError = currentValidateError
- bestM = m + 1
- }
- }
- m += 1
- }
-
- timer.stop("total")
-
- logInfo("Internal timing for DecisionTree:")
- logInfo(s"$timer")
-
- predErrorCheckpointer.unpersistDataSet()
- predErrorCheckpointer.deleteAllCheckpoints()
- validatePredErrorCheckpointer.unpersistDataSet()
- validatePredErrorCheckpointer.deleteAllCheckpoints()
- if (persistedInput) input.unpersist()
-
- if (validate) {
- (baseLearners.slice(0, bestM), baseLearnerWeights.slice(0, bestM))
- } else {
- (baseLearners, baseLearnerWeights)
- }
- }
-
- /**
- * Internal method for performing regression using trees as base learners.
- * @param input training dataset
- * @param validationInput validation dataset, ignored if validate is set to false.
- * @param boostingStrategy boosting parameters
- * @param validate whether or not to use the validation dataset.
- * @param seed Random seed.
- * @return tuple of ensemble models and weights:
- * (array of decision tree models, array of model weights)
- */
- def boostX(
- input: RDD[LabeledPoint],
- validationInput: RDD[LabeledPoint],
- boostingStrategy: OldBoostingStrategy,
- validate: Boolean,
- seed: Long,
- featureSubsetStrategy: String): (Array[DecisionTreeRegressionModel], Array[Double]) = {
- val timer = new TimeTracker()
- timer.start("total")
- timer.start("init")
-
- boostingStrategy.assertValid()
-
- // Initialize gradient boosting parameters
- val numIterations = boostingStrategy.numIterations
- val baseLearners = new Array[DecisionTreeRegressionModel](numIterations)
- val baseLearnerWeights = new Array[Double](numIterations)
- val loss = boostingStrategy.loss
- val learningRate = boostingStrategy.learningRate
-
- // Prepare strategy for individual trees, which use regression with variance impurity.
- val treeStrategy = boostingStrategy.treeStrategy.copy
- val validationTol = boostingStrategy.validationTol
- treeStrategy.algo = OldAlgo.Regression
- treeStrategy.impurity = OldVariance
- treeStrategy.assertValid()
-
- // Prepare periodic checkpointers
- val predErrorCheckpointer = new PeriodicRDDCheckpointer[(Double, Double)](
- treeStrategy.getCheckpointInterval, input.sparkContext)
- val validatePredErrorCheckpointer = new PeriodicRDDCheckpointer[(Double, Double)](
- treeStrategy.getCheckpointInterval, input.sparkContext)
-
- // X
- val retaggedInput = input.retag(classOf[LabeledPoint])
- val metadata =
- DecisionTreeMetadata.buildMetadata(retaggedInput, treeStrategy, 1, featureSubsetStrategy)
-
- // Find the splits and the corresponding bins (interval between the splits) using a sample
- // of the input data.
- timer.start("findSplits")
- val splits = findSplits(retaggedInput, metadata, seed)
- timer.stop("findSplits")
- logDebug("numBins: feature: number of bins")
- logDebug(Range(0, metadata.numFeatures).map { featureIndex =>
- s"\t$featureIndex\t${metadata.numBins(featureIndex)}"
- }.mkString("\n"))
-
- val (treeInput, processedInput, labelArrayBcTmp, rawPartInfoBcTmp) =
- GradientBoostedTreesUtil.dataProcessX(retaggedInput, splits, treeStrategy, metadata, timer,
- seed)
- var rawPartInfoBc = rawPartInfoBcTmp
- var labelArrayBc = labelArrayBcTmp
-
- // X
- timer.stop("init")
-
- logDebug("##########")
- logDebug("Building tree 0")
- logDebug("##########")
-
- // Initialize tree
- timer.start("building tree 0")
- val firstTree = new DecisionTreeRegressor().setSeed(seed)
- val firstTreeModel = firstTree.train4GBDTX(labelArrayBc, processedInput, metadata, splits,
- treeStrategy, featureSubsetStrategy, treeInput, rawPartInfoBc)
- val firstTreeWeight = 1.0
- baseLearners(0) = firstTreeModel
- baseLearnerWeights(0) = firstTreeWeight
-
- var predError: RDD[(Double, Double)] =
- computeInitialPredictionAndErrorX(treeInput, firstTreeWeight, firstTreeModel, loss, splits)
- predErrorCheckpointer.update(predError)
- logDebug(s"error of gbt = ${predError.values.mean()}")
-
- // Note: A model of type regression is used since we require raw prediction
- timer.stop("building tree 0")
-
- var validatePredError: RDD[(Double, Double)] =
- computeInitialPredictionAndError(validationInput, firstTreeWeight, firstTreeModel, loss)
- if (validate) validatePredErrorCheckpointer.update(validatePredError)
- var bestValidateError = if (validate) validatePredError.values.mean() else 0.0
- var bestM = 1
-
- var m = 1
- var doneLearning = false
- while (m < numIterations && !doneLearning) {
- labelArrayBc = treeInput.sparkContext.broadcast(
- DoubleArrayList.wrap(
- predError.zip(treeInput).map { case ((pred, _), point) =>
- -loss.gradient(pred, point.label)}.collect()
- )
- )
-
- timer.start(s"building tree $m")
- logDebug("###################################################")
- logDebug(s"Gradient boosting tree iteration ${m}")
- logDebug("###################################################")
-
- val dt = new DecisionTreeRegressor().setSeed(seed + m)
- val model = dt.train4GBDTX(labelArrayBc, processedInput, metadata, splits, treeStrategy,
- featureSubsetStrategy, treeInput, rawPartInfoBc)
- timer.stop(s"building tree $m")
- // Update partial model
- baseLearners(m) = model
- // Note: The setting of baseLearnerWeights is incorrect for losses other than SquaredError.
- // Technically, the weight should be optimized for the particular loss.
- // However, the behavior should be reasonable, though not optimal.
- baseLearnerWeights(m) = learningRate
-
- predError = updatePredictionErrorX(
- treeInput, predError, baseLearnerWeights(m), baseLearners(m), loss, splits)
- predErrorCheckpointer.update(predError)
- logDebug(s"error of gbt = ${predError.values.mean()}")
-
- if (validate) {
- // Stop training early if
- // 1. Reduction in error is less than the validationTol or
- // 2. If the error increases, that is if the model is overfit.
- // We want the model returned corresponding to the best validation error.
-
- validatePredError = updatePredictionError(
- validationInput, validatePredError, baseLearnerWeights(m), baseLearners(m), loss)
- validatePredErrorCheckpointer.update(validatePredError)
- val currentValidateError = validatePredError.values.mean()
- if (bestValidateError - currentValidateError < validationTol * Math.max(
- currentValidateError, 0.01)) {
- doneLearning = true
- } else if (currentValidateError < bestValidateError) {
- bestValidateError = currentValidateError
- bestM = m + 1
- }
- }
- m += 1
- }
-
- timer.stop("total")
-
- logInfo("Internal timing for DecisionTree:")
- logInfo(s"$timer")
-
- predErrorCheckpointer.unpersistDataSet()
- predErrorCheckpointer.deleteAllCheckpoints()
- validatePredErrorCheckpointer.unpersistDataSet()
- validatePredErrorCheckpointer.deleteAllCheckpoints()
- treeInput.unpersist()
- processedInput.unpersist()
-
- if (validate) {
- (baseLearners.slice(0, bestM), baseLearnerWeights.slice(0, bestM))
- } else {
- (baseLearners, baseLearnerWeights)
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/NodeIdCache.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/NodeIdCache.scala
deleted file mode 100644
index 7fb606d..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/NodeIdCache.scala
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import java.io.IOException
-
-import scala.collection.mutable
-
-import org.apache.hadoop.fs.Path
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.tree.{LearningNode, Split, SplitBase}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.storage.StorageLevel
-
-/**
- * This is used by the node id cache to find the child id that a data point would belong to.
- * @param split Split information.
- * @param nodeIndex The current node index of a data point that this will update.
- */
-private[tree] case class NodeIndexUpdaterRaw(split: Split, nodeIndex: Int) {
-
- /**
- * Determine a child node index based on the feature value and the split.
- * @param binnedFeature Binned feature value.
- * @param splits Split information to convert the bin indices to approximate feature values.
- * @return Child node index to update to.
- */
- def updateNodeIndex(binnedFeature: Int, splits: Array[Split]): Int = {
- if (split.shouldGoLeft(binnedFeature, splits)) {
- LearningNode.leftChildIndex(nodeIndex)
- } else {
- LearningNode.rightChildIndex(nodeIndex)
- }
- }
-}
-
-/**
- * This is used by the node id cache to find the child id that a data point would belong to.
- * @param split Split information.
- * @param nodeIndex The current node index of a data point that this will update.
- */
-private[tree] case class NodeIndexUpdater(split: SplitBase, nodeIndex: Int) {
-
- /**
- * Determine a child node index based on the feature value and the split.
- * @param binnedFeature Binned feature value.
- * @param splits Split information to convert the bin indices to approximate feature values.
- * @return Child node index to update to.
- */
- def updateNodeIndex(binnedFeature: Char, splits: Array[SplitBase]): Int = {
- if (split.shouldGoLeft(binnedFeature, splits)) {
- LearningNode.leftChildIndex(nodeIndex)
- } else {
- LearningNode.rightChildIndex(nodeIndex)
- }
- }
-}
-
-/**
- * Each TreePoint belongs to a particular node per tree.
- * Each row in the nodeIdsForInstances RDD is an array over trees of the node index
- * in each tree. Initially, values should all be 1 for root node.
- * The nodeIdsForInstances RDD needs to be updated at each iteration.
- * @param nodeIdsForInstances The initial values in the cache
- * (should be an Array of all 1's (meaning the root nodes)).
- * @param checkpointInterval The checkpointing interval
- * (how often should the cache be checkpointed.).
- */
-private[spark] class NodeIdCache(
- var nodeIdsForInstances: RDD[Array[Int]],
- val checkpointInterval: Int) extends Logging {
-
- // Keep a reference to a previous node Ids for instances.
- // Because we will keep on re-persisting updated node Ids,
- // we want to unpersist the previous RDD.
- private var prevNodeIdsForInstances: RDD[Array[Int]] = null
-
- // To keep track of the past checkpointed RDDs.
- private val checkpointQueue = mutable.Queue[RDD[Array[Int]]]()
- private var rddUpdateCount = 0
-
- // Indicates whether we can checkpoint
- private val canCheckpoint = nodeIdsForInstances.sparkContext.getCheckpointDir.nonEmpty
-
- // Hadoop Configuration for deleting checkpoints as needed
- private val hadoopConf = nodeIdsForInstances.sparkContext.hadoopConfiguration
-
- /**
- * Update the node index values in the cache.
- * This updates the RDD and its lineage.
- * TODO: Passing bin information to executors seems unnecessary and costly.
- * @param data The RDD of training rows.
- * @param nodeIdUpdaters A map of node index updaters.
- * The key is the indices of nodes that we want to update.
- * @param splits Split information needed to find child node indices.
- */
- def updateNodeIndices(
- data: RDD[BaggedPoint[TreePointX]],
- nodeIdUpdaters: Array[mutable.Map[Int, NodeIndexUpdater]],
- splits: Array[Array[SplitBase]]): Unit = {
- if (prevNodeIdsForInstances != null) {
- // Unpersist the previous one if one exists.
- prevNodeIdsForInstances.unpersist()
- }
-
- prevNodeIdsForInstances = nodeIdsForInstances
- nodeIdsForInstances = data.zip(nodeIdsForInstances).map { case (point, ids) =>
- var treeId = 0
- while (treeId < nodeIdUpdaters.length) {
- val nodeIdUpdater = nodeIdUpdaters(treeId).getOrElse(ids(treeId), null)
- if (nodeIdUpdater != null) {
- val featureIndex = nodeIdUpdater.split.featureIndex
- val newNodeIndex = nodeIdUpdater.updateNodeIndex(
- binnedFeature = point.datum.binnedFeatures.get(featureIndex),
- splits = splits(featureIndex))
- ids(treeId) = newNodeIndex
- }
- treeId += 1
- }
- ids
- }
-
- // Keep on persisting new ones.
- nodeIdsForInstances.persist(StorageLevel.MEMORY_AND_DISK)
- rddUpdateCount += 1
-
- // Handle checkpointing if the directory is not None.
- if (canCheckpoint && checkpointInterval != -1 && (rddUpdateCount % checkpointInterval) == 0) {
- // Let's see if we can delete previous checkpoints.
- var canDelete = true
- while (checkpointQueue.size > 1 && canDelete) {
- // We can delete the oldest checkpoint iff
- // the next checkpoint actually exists in the file system.
- if (checkpointQueue(1).getCheckpointFile.isDefined) {
- val old = checkpointQueue.dequeue()
- // Since the old checkpoint is not deleted by Spark, we'll manually delete it here.
- try {
- val path = new Path(old.getCheckpointFile.get)
- val fs = path.getFileSystem(hadoopConf)
- fs.delete(path, true)
- } catch {
- case e: IOException =>
- logError("Decision Tree learning using cacheNodeIds failed to remove checkpoint" +
- s" file: ${old.getCheckpointFile.get}")
- }
- } else {
- canDelete = false
- }
- }
-
- nodeIdsForInstances.checkpoint()
- checkpointQueue.enqueue(nodeIdsForInstances)
- }
- }
-
- /**
- * Update the node index values in the cache.
- * This updates the RDD and its lineage.
- * TODO: Passing bin information to executors seems unnecessary and costly.
- * @param data The RDD of training rows.
- * @param nodeIdUpdaters A map of node index updaters.
- * The key is the indices of nodes that we want to update.
- * @param splits Split information needed to find child node indices.
- */
- def updateNodeIndicesRaw(
- data: RDD[BaggedPoint[TreePoint]],
- nodeIdUpdaters: Array[mutable.Map[Int, NodeIndexUpdaterRaw]],
- splits: Array[Array[Split]]): Unit = {
- if (prevNodeIdsForInstances != null) {
- // Unpersist the previous one if one exists.
- prevNodeIdsForInstances.unpersist()
- }
-
- prevNodeIdsForInstances = nodeIdsForInstances
- nodeIdsForInstances = data.zip(nodeIdsForInstances).map { case (point, ids) =>
- var treeId = 0
- while (treeId < nodeIdUpdaters.length) {
- val nodeIdUpdater = nodeIdUpdaters(treeId).getOrElse(ids(treeId), null)
- if (nodeIdUpdater != null) {
- val featureIndex = nodeIdUpdater.split.featureIndex
- val newNodeIndex = nodeIdUpdater.updateNodeIndex(
- binnedFeature = point.datum.binnedFeatures(featureIndex),
- splits = splits(featureIndex))
- ids(treeId) = newNodeIndex
- }
- treeId += 1
- }
- ids
- }
-
- // Keep on persisting new ones.
- nodeIdsForInstances.persist(StorageLevel.MEMORY_AND_DISK)
- rddUpdateCount += 1
-
- // Handle checkpointing if the directory is not None.
- if (canCheckpoint && checkpointInterval != -1 && (rddUpdateCount % checkpointInterval) == 0) {
- // Let's see if we can delete previous checkpoints.
- var canDelete = true
- while (checkpointQueue.size > 1 && canDelete) {
- // We can delete the oldest checkpoint iff
- // the next checkpoint actually exists in the file system.
- if (checkpointQueue(1).getCheckpointFile.isDefined) {
- val old = checkpointQueue.dequeue()
- // Since the old checkpoint is not deleted by Spark, we'll manually delete it here.
- try {
- val path = new Path(old.getCheckpointFile.get)
- val fs = path.getFileSystem(hadoopConf)
- fs.delete(path, true)
- } catch {
- case e: IOException =>
- logError("Decision Tree learning using cacheNodeIds failed to remove checkpoint" +
- s" file: ${old.getCheckpointFile.get}")
- }
- } else {
- canDelete = false
- }
- }
-
- nodeIdsForInstances.checkpoint()
- checkpointQueue.enqueue(nodeIdsForInstances)
- }
- }
-
- /**
- * Update the node index values in the cache.
- * This updates the RDD and its lineage.
- * TODO: Passing bin information to executors seems unnecessary and costly.
- * @param data The RDD of training rows.
- * @param nodeIdUpdaters A map of node index updaters.
- * The key is the indices of nodes that we want to update.
- * @param splits Split information needed to find child node indices.
- */
- def updateNodeIndicesY(
- data: RDD[BaggedPoint[TreePointY]],
- nodeIdUpdaters: Array[mutable.Map[Int, NodeIndexUpdaterRaw]],
- splits: Array[Array[Split]]): Unit = {
- if (prevNodeIdsForInstances != null) {
- // Unpersist the previous one if one exists.
- prevNodeIdsForInstances.unpersist()
- }
-
- prevNodeIdsForInstances = nodeIdsForInstances
- nodeIdsForInstances = data.zip(nodeIdsForInstances).map { case (point, ids) =>
- var treeId = 0
- while (treeId < nodeIdUpdaters.length) {
- val nodeIdUpdater = nodeIdUpdaters(treeId).getOrElse(ids(treeId), null)
- if (nodeIdUpdater != null) {
- val featureIndex = nodeIdUpdater.split.featureIndex
- val newNodeIndex = nodeIdUpdater.updateNodeIndex(
- binnedFeature = point.datum.binnedFeatures.get(featureIndex),
- splits = splits(featureIndex))
- ids(treeId) = newNodeIndex
- }
- treeId += 1
- }
- ids
- }
-
- // Keep on persisting new ones.
- nodeIdsForInstances.persist(StorageLevel.MEMORY_AND_DISK)
- rddUpdateCount += 1
-
- // Handle checkpointing if the directory is not None.
- if (canCheckpoint && checkpointInterval != -1 && (rddUpdateCount % checkpointInterval) == 0) {
- // Let's see if we can delete previous checkpoints.
- var canDelete = true
- while (checkpointQueue.size > 1 && canDelete) {
- // We can delete the oldest checkpoint iff
- // the next checkpoint actually exists in the file system.
- if (checkpointQueue(1).getCheckpointFile.isDefined) {
- val old = checkpointQueue.dequeue()
- // Since the old checkpoint is not deleted by Spark, we'll manually delete it here.
- try {
- val path = new Path(old.getCheckpointFile.get)
- val fs = path.getFileSystem(hadoopConf)
- fs.delete(path, true)
- } catch {
- case e: IOException =>
- logError("Decision Tree learning using cacheNodeIds failed to remove checkpoint" +
- s" file: ${old.getCheckpointFile.get}")
- }
- } else {
- canDelete = false
- }
- }
-
- nodeIdsForInstances.checkpoint()
- checkpointQueue.enqueue(nodeIdsForInstances)
- }
- }
-
-
- /**
- * Call this after training is finished to delete any remaining checkpoints.
- */
- def deleteAllCheckpoints(): Unit = {
- while (checkpointQueue.nonEmpty) {
- val old = checkpointQueue.dequeue()
- if (old.getCheckpointFile.isDefined) {
- try {
- val path = new Path(old.getCheckpointFile.get)
- val fs = path.getFileSystem(hadoopConf)
- fs.delete(path, true)
- } catch {
- case e: IOException =>
- logError("Decision Tree learning using cacheNodeIds failed to remove checkpoint" +
- s" file: ${old.getCheckpointFile.get}")
- }
- }
- }
- if (prevNodeIdsForInstances != null) {
- // Unpersist the previous one if one exists.
- prevNodeIdsForInstances.unpersist()
- }
- }
-}
-
-private[spark] object NodeIdCache {
- /**
- * Initialize the node Id cache with initial node Id values.
- * @param data The RDD of training rows.
- * @param numTrees The number of trees that we want to create cache for.
- * @param checkpointInterval The checkpointing interval
- * (how often should the cache be checkpointed.).
- * @param initVal The initial values in the cache.
- * @return A node Id cache containing an RDD of initial root node Indices.
- */
- def init[T](
- data: RDD[T],
- numTrees: Int,
- checkpointInterval: Int,
- initVal: Int = 1): NodeIdCache = {
- new NodeIdCache(
- data.map(_ => Array.fill[Int](numTrees)(initVal)),
- checkpointInterval)
- }
-}
-
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest.scala
deleted file mode 100644
index 17c8775..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest.scala
+++ /dev/null
@@ -1,1231 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import java.io.IOException
-
-import scala.collection.mutable
-import scala.util.Random
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.classification.DecisionTreeClassificationModel
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.regression.DecisionTreeRegressionModel
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.util.Instrumentation
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo, Strategy => OldStrategy}
-import org.apache.spark.mllib.tree.impurity.ImpurityCalculator
-import org.apache.spark.mllib.tree.model.ImpurityStats
-import org.apache.spark.rdd.RDD
-import org.apache.spark.util.random.{SamplingUtils, XORShiftRandom}
-
-
-/**
- * ALGORITHM
- *
- * This is a sketch of the algorithm to help new developers.
- *
- * The algorithm partitions data by instances (rows).
- * On each iteration, the algorithm splits a set of nodes. In order to choose the best split
- * for a given node, sufficient statistics are collected from the distributed data.
- * For each node, the statistics are collected to some worker node, and that worker selects
- * the best split.
- *
- * This setup requires discretization of continuous features. This binning is done in the
- * findSplits() method during initialization, after which each continuous feature becomes
- * an ordered discretized feature with at most maxBins possible values.
- *
- * The main loop in the algorithm operates on a queue of nodes (nodeStack). These nodes
- * lie at the periphery of the tree being trained. If multiple trees are being trained at once,
- * then this queue contains nodes from all of them. Each iteration works roughly as follows:
- * On the master node:
- * - Some number of nodes are pulled off of the queue (based on the amount of memory
- * required for their sufficient statistics).
- * - For random forests, if featureSubsetStrategy is not "all," then a subset of candidate
- * features are chosen for each node. See method selectNodesToSplit().
- * On worker nodes, via method findBestSplits():
- * - The worker makes one pass over its subset of instances.
- * - For each (tree, node, feature, split) tuple, the worker collects statistics about
- * splitting. Note that the set of (tree, node) pairs is limited to the nodes selected
- * from the queue for this iteration. The set of features considered can also be limited
- * based on featureSubsetStrategy.
- * - For each node, the statistics for that node are aggregated to a particular worker
- * via reduceByKey(). The designated worker chooses the best (feature, split) pair,
- * or chooses to stop splitting if the stopping criteria are met.
- * On the master node:
- * - The master collects all decisions about splitting nodes and updates the model.
- * - The updated model is passed to the workers on the next iteration.
- * This process continues until the node queue is empty.
- *
- * Most of the methods in this implementation support the statistics aggregation, which is
- * the heaviest part of the computation. In general, this implementation is bound by either
- * the cost of statistics computation on workers or by communicating the sufficient statistics.
- */
-private[spark] object RandomForest extends Logging {
-
- /**
- * Train a random forest.
- *
- * @param input Training data: RDD of `LabeledPoint`
- * @return an unweighted set of trees
- */
- def run(
- input: RDD[LabeledPoint],
- strategy: OldStrategy,
- numTrees: Int,
- featureSubsetStrategy: String,
- seed: Long,
- instr: Option[Instrumentation[_]],
- parentUID: Option[String] = None): Array[DecisionTreeModel] = {
- val exParams = RFUtils.parseExtraParams(input, strategy)
- runX(input, strategy, numTrees, featureSubsetStrategy, seed, instr, exParams, parentUID)
- }
-
- /**
- * Train a random forest.
- *
- * @param input Training data: RDD of `LabeledPoint`
- * @return an unweighted set of trees
- */
- def runX(
- input: RDD[LabeledPoint],
- strategy: OldStrategy,
- numTrees: Int,
- featureSubsetStrategy: String,
- seed: Long,
- instr: Option[Instrumentation[_]],
- extraParams: RFExtraParams,
- parentUID: Option[String] = None): Array[DecisionTreeModel] = {
-
- RandomForestInfo.timerResult = ""
- val timer = new TimeTracker()
-
- timer.start("total")
-
- timer.start("init")
-
- val binnedFeaturesType = BinnedFeaturesDataType.withName(extraParams.featuresDataType)
- val retaggedInput = input.retag(classOf[LabeledPoint])
- // featureSubsetStrategy: The number of features to consider for splits at each tree node.
- // featureSubsetStrategy: default value is "auto" for random forest.
- // impurity: default value is "gini" for random forest.
- val metadata =
- DecisionTreeMetadata.buildMetadata(retaggedInput, strategy, numTrees, featureSubsetStrategy)
- logWarning(s"decisionTreeMetadata details: ${metadata.numFeatures}," +
- s" ${metadata.numExamples}, ${metadata.numClasses: Int}, ${metadata.maxBins: Int}," +
- s" ${metadata.featureArity}, ${metadata.unorderedFeatures.mkString("[", ";", "]")}," +
- s" ${metadata.impurity}, ${metadata.quantileStrategy}, ${metadata.maxDepth: Int}," +
- s" ${metadata.minInstancesPerNode: Int}, ${metadata.minInfoGain: Double}," +
- s" ${metadata.numTrees: Int}, ${metadata.numFeaturesPerNode: Int}, ${binnedFeaturesType}")
- instr match {
- case Some(instrumentation) =>
- instrumentation.logNumFeatures(metadata.numFeatures)
- instrumentation.logNumClasses(metadata.numClasses)
- case None =>
- logInfo(s"numFeatures: ${metadata.numFeatures}")
- logInfo(s"numClasses: ${metadata.numClasses}")
- }
-
- // Find the splits and the corresponding bins (interval between the splits) using a sample
- // of the input data.
- timer.start("findSplits")
- val splits = findSplits(retaggedInput, metadata, seed)
- val baseSplits =
- splits.map(v => v.zipWithIndex.map{case (split, binIdx) => Split.toBase(split, binIdx)})
- timer.stop("findSplits")
- logDebug("numBins: feature: number of bins")
- logDebug(Range(0, metadata.numFeatures).map { featureIndex =>
- s"\t$featureIndex\t${metadata.numBins(featureIndex)}"
- }.mkString("\n"))
-
- // Bin feature values (TreePoint representation).
- // Cache input RDD for speedup during multiple passes.
- val treeInput = TreePointX.convertToTreeRDD(retaggedInput, splits, metadata, binnedFeaturesType)
-
- val withReplacement = numTrees > 1
-
- // Default value of subsamplingRate is 1 for random forest.
- val baggedInputOri = BaggedPoint.convertToBaggedRDD(treeInput, strategy.subsamplingRate,
- numTrees, withReplacement, seed)
-
- val baggedInput = RFUtils.transformBaggedRDD(baggedInputOri, extraParams)
-
- // depth of the decision tree
- val maxDepth = strategy.maxDepth
- require(maxDepth <= 30,
- s"DecisionTree currently only supports maxDepth <= 30, but was given maxDepth = $maxDepth.")
-
- // Max memory usage for aggregates
- // TODO: Calculate memory usage more precisely.
- val maxMemoryUsage: Long = strategy.maxMemoryInMB * 1024L * 1024L
- logDebug(s"max memory usage for aggregates = ${maxMemoryUsage} bytes.")
-
- /*
- * The main idea here is to perform group-wise training of the decision tree nodes thus
- * reducing the passes over the data from (# nodes) to (# nodes / maxNumberOfNodesPerGroup).
- * Each data sample is handled by a particular node (or it reaches a leaf and is not used
- * in lower levels).
- */
-
- // Create an RDD of node Id cache.
- // At first, all the rows belong to the root nodes (node Id == 1).
- // Default value of useNodeIdCache is false for random forest.
- val nodeIdCache = if (strategy.useNodeIdCache) {
- Some(NodeIdCache.init(
- data = baggedInput,
- numTrees = numTrees,
- checkpointInterval = strategy.checkpointInterval,
- initVal = 1))
- } else {
- None
- }
-
- /*
- Stack of nodes to train: (treeIndex, node)
- The reason this is a stack is that we train many trees at once, but we want to focus on
- completing trees, rather than training all simultaneously. If we are splitting nodes from
- 1 tree, then the new nodes to split will be put at the top of this stack, so we will continue
- training the same tree in the next iteration. This focus allows us to send fewer trees to
- workers on each iteration; see topNodesForGroup below.
- */
- val nodeStack = new mutable.ArrayStack[(Int, LearningNodeX)]
-
- val rng = new Random()
- rng.setSeed(seed)
-
- // Allocate and queue root nodes.
- val topNodes = Array.fill[LearningNodeX](numTrees)(LearningNodeX.emptyNode(nodeIndex = 1))
- Range(0, numTrees).foreach(treeIndex => nodeStack.push((treeIndex, topNodes(treeIndex))))
-
- timer.stop("init")
-
- while (nodeStack.nonEmpty) {
- // Collect some nodes to split, and choose features for each node (if subsampling).
- // Each group of nodes may come from one or multiple trees, and at multiple levels.
- // nodesForGroup: treeIndex --> learningNodes in tree
- // treeToNodeToIndexInfo: treeIndex --> (global) learningNodes index in tree
- // --> (node index in group, feature indices).
- val (nodesForGroup, treeToNodeToIndexInfo) =
- RandomForest.selectNodesToSplit(nodeStack, maxMemoryUsage, metadata, rng)
- // Sanity check (should never occur):
- assert(nodesForGroup.nonEmpty,
- s"RandomForest selected empty nodesForGroup. Error for unknown reason.")
-
- // Only send trees to worker if they contain nodes being split this iteration.
- // topNodesForGroup: treeIndex --> top node in tree
- val topNodesForGroup: Map[Int, LearningNodeX] =
- nodesForGroup.keys.map(treeIdx => treeIdx -> topNodes(treeIdx)).toMap
-
- // Choose node splits, and enqueue new nodes as needed.
- timer.start("findBestSplits")
- RandomForest.findBestSplits(baggedInput, metadata, topNodesForGroup, nodesForGroup,
- treeToNodeToIndexInfo, baseSplits, nodeStack, timer, nodeIdCache, Some(extraParams))
- timer.stop("findBestSplits")
- }
-
- baggedInput.unpersist()
-
- timer.stop("total")
-
- logInfo("Internal timing for DecisionTree:")
- logInfo(s"$timer")
- RandomForestInfo.timerResult = timer.toString()
-
- // Delete any remaining checkpoints used for node Id cache.
- if (nodeIdCache.nonEmpty) {
- try {
- nodeIdCache.get.deleteAllCheckpoints()
- } catch {
- case e: IOException =>
- logWarning(s"delete all checkpoints failed. Error reason: ${e.getMessage}")
- }
- }
-
- val numFeatures = metadata.numFeatures
-
- parentUID match {
- case Some(uid) =>
- if (strategy.algo == OldAlgo.Classification) {
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(uid, rootNode.toNode(splits), numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map { rootNode =>
- new DecisionTreeRegressionModel(uid, rootNode.toNode(splits), numFeatures)
- }
- }
- case None =>
- if (strategy.algo == OldAlgo.Classification) {
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(rootNode.toNode(splits), numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map(rootNode =>
- new DecisionTreeRegressionModel(rootNode.toNode(splits), numFeatures))
- }
- }
- }
-
- /**
- * Helper for binSeqOp, for data which can contain a mix of ordered and unordered features.
- *
- * For ordered features, a single bin is updated.
- * For unordered features, bins correspond to subsets of categories; either the left or right bin
- * for each subset is updated.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (feature, bin).
- * @param treePoint Data point being aggregated.
- * @param splits possible splits indexed (numFeatures)(numSplits)
- * @param unorderedFeatures Set of indices of unordered features.
- * @param instanceWeight Weight (importance) of instance in dataset.
- */
- private def mixedBinSeqOp(
- agg: DTStatsAggregator,
- treePoint: TreePointX,
- splits: Array[Array[SplitBase]],
- unorderedFeatures: Set[Int],
- instanceWeight: Int,
- featuresForNode: Option[Array[Int]]): Unit = {
- val numFeaturesPerNode = if (featuresForNode.nonEmpty) {
- // Use subsampled features
- featuresForNode.get.length
- } else {
- // Use all features
- agg.metadata.numFeatures
- }
- // Iterate over features.
- var featureIndexIdx = 0
- while (featureIndexIdx < numFeaturesPerNode) {
- val featureIndex = if (featuresForNode.nonEmpty) {
- featuresForNode.get.apply(featureIndexIdx)
- } else {
- featureIndexIdx
- }
- if (unorderedFeatures.contains(featureIndex)) {
- // Unordered feature
- val featureValue = treePoint.binnedFeatures.get(featureIndex)
- val leftNodeFeatureOffset = agg.getFeatureOffset(featureIndexIdx)
- // Update the left or right bin for each split.
- val numSplits = agg.metadata.numSplits(featureIndex)
- val featureSplits = splits(featureIndex)
- var splitIndex = 0
- while (splitIndex < numSplits) {
- if (featureSplits(splitIndex).shouldGoLeft(featureValue, featureSplits)) {
- agg.featureUpdate(leftNodeFeatureOffset, splitIndex, treePoint.label, instanceWeight)
- }
- splitIndex += 1
- }
- } else {
- // Ordered feature
- val binIndex = treePoint.binnedFeatures.get(featureIndex)
- agg.update(featureIndexIdx, binIndex, treePoint.label, instanceWeight)
- }
- featureIndexIdx += 1
- }
- }
-
- /**
- * Helper for binSeqOp, for regression and for classification with only ordered features.
- *
- * For each feature, the sufficient statistics of one bin are updated.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (feature, bin).
- * @param treePoint Data point being aggregated.
- * @param instanceWeight Weight (importance) of instance in dataset.
- */
- private def orderedBinSeqOp(
- agg: DTStatsAggregator,
- treePoint: TreePointX,
- instanceWeight: Int,
- featuresForNode: Option[Array[Int]]): Unit = {
- val label = treePoint.label
-
- // Iterate over features.
- if (featuresForNode.nonEmpty) {
- // Use subsampled features
- var featureIndexIdx = 0
- while (featureIndexIdx < featuresForNode.get.length) {
- val binIndex = treePoint.binnedFeatures.get(featuresForNode.get.apply(featureIndexIdx))
- agg.update(featureIndexIdx, binIndex, label, instanceWeight)
- featureIndexIdx += 1
- }
- } else {
- // Use all features
- val numFeatures = agg.metadata.numFeatures
- var featureIndex = 0
- while (featureIndex < numFeatures) {
- val binIndex = treePoint.binnedFeatures.get(featureIndex)
- agg.update(featureIndex, binIndex, label, instanceWeight)
- featureIndex += 1
- }
- }
- }
-
- /**
- * Given a group of nodes, this finds the best split for each node.
- *
- * @param input Training data: RDD of [[TreePointX]]
- * @param metadata Learning and dataset metadata
- * @param topNodesForGroup For each tree in group, tree index -> root node.
- * Used for matching instances with nodes.
- * @param nodesForGroup Mapping: treeIndex --> nodes to be split in tree
- * @param treeToNodeToIndexInfo Mapping: treeIndex --> (global) learningNodes index in tree
- * --> (node index in group, feature indices)
- * feature indices: probably parts of full features.
- * Mapping: treeIndex --> nodeIndex --> nodeIndexInfo,
- * where nodeIndexInfo stores the index in the group and the
- * feature subsets (if using feature subsets).
- * @param splits possible splits for all features, indexed (numFeatures)(numSplits)
- * @param nodeStack Queue of nodes to split, with values (treeIndex, node).
- * Updated with new non-leaf nodes which are created.
- * @param nodeIdCache Node Id cache containing an RDD of Array[Int] where
- * each value in the array is the data point's node Id
- * for a corresponding tree. This is used to prevent the need
- * to pass the entire tree to the executors during
- * the node stat aggregation phase.
- */
- private[tree] def findBestSplits(
- input: RDD[BaggedPoint[TreePointX]],
- metadata: DecisionTreeMetadata,
- topNodesForGroup: Map[Int, LearningNodeX],
- nodesForGroup: Map[Int, Array[LearningNodeX]],
- treeToNodeToIndexInfo: Map[Int, Map[Int, NodeIndexInfo]],
- splits: Array[Array[SplitBase]],
- nodeStack: mutable.ArrayStack[(Int, LearningNodeX)],
- timer: TimeTracker = new TimeTracker,
- nodeIdCache: Option[NodeIdCache] = None,
- extraParams: Option[RFExtraParams] = None): Unit = {
-
- /*
- * The high-level descriptions of the best split optimizations are noted here.
- *
- * *Group-wise training*
- * We perform bin calculations for groups of nodes to reduce the number of
- * passes over the data. Each iteration requires more computation and storage,
- * but saves several iterations over the data.
- *
- * *Bin-wise computation*
- * We use a bin-wise best split computation strategy instead of a straightforward best split
- * computation strategy. Instead of analyzing each sample for contribution to the left/right
- * child node impurity of every split, we first categorize each feature of a sample into a
- * bin. We exploit this structure to calculate aggregates for bins and then use these aggregates
- * to calculate information gain for each split.
- *
- * *Aggregation over partitions*
- * Instead of performing a flatMap/reduceByKey operation, we exploit the fact that we know
- * the number of splits in advance. Thus, we store the aggregates (at the appropriate
- * indices) in a single array for all bins and rely upon the RDD aggregate method to
- * drastically reduce the communication overhead.
- */
-
- val bcVariables = if (extraParams.isEmpty) false else extraParams.get.bcVariables
- /** numNodes: Number of nodes in this group */
- val numNodes = nodesForGroup.values.map(_.length).sum
- logDebug(s"numNodes = ${numNodes}")
- logDebug(s"numFeatures = ${metadata.numFeatures}")
- logDebug(s"numClasses = ${metadata.numClasses}")
- logDebug(s"isMulticlass = ${metadata.isMulticlass}")
- logDebug(s"isMulticlassWithCategoricalFeatures = " +
- s"${metadata.isMulticlassWithCategoricalFeatures}")
- logDebug(s"using nodeIdCache = ${ nodeIdCache.nonEmpty.toString}")
-
- val groupInfo = RFUtils.getGroupInfo(numNodes, treeToNodeToIndexInfo, extraParams)
-
- val splitsBc = if (bcVariables) Some(input.sparkContext.broadcast(splits)) else Option.empty
- val splitsOption = if (bcVariables) Option.empty else Some(splits)
-
-
- /**
- * Performs a sequential aggregation over a partition for a particular tree and node.
- *
- * For each feature, the aggregate sufficient statistics are updated for the relevant
- * bins.
- *
- * @param treeIndex Index of the tree that we want to perform aggregation for.
- * @param nodeInfo The node info for the tree node.
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics
- * for each (node, feature, bin).
- * @param baggedPoint Data point being aggregated.
- */
- def nodeBinSeqOp(
- treeIndex: Int,
- nodeInfo: NodeIndexInfo,
- agg: Array[DTStatsAggregator],
- splitsBcv: Array[Array[SplitBase]],
- baggedPoint: BaggedPoint[TreePointX]): Unit = {
- if (RFUtils.isValidNodeInfo(nodeInfo, agg)) {
- val aggNodeIndex = nodeInfo.nodeIndexInGroup
- val featuresForNode = nodeInfo.featureSubset
- val instanceWeight = baggedPoint.subsampleWeights(treeIndex)
- if (metadata.unorderedFeatures.isEmpty) {
- orderedBinSeqOp(agg(aggNodeIndex), baggedPoint.datum, instanceWeight, featuresForNode)
- } else {
- mixedBinSeqOp(agg(aggNodeIndex), baggedPoint.datum, splitsBcv,
- metadata.unorderedFeatures, instanceWeight, featuresForNode)
- }
- agg(aggNodeIndex).updateParent(baggedPoint.datum.label, instanceWeight)
- }
- }
-
- /**
- * Performs a sequential aggregation over a partition.
- *
- * Each data point contributes to one node. For each feature,
- * the aggregate sufficient statistics are updated for the relevant bins.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (node, feature, bin).
- * @param baggedPoint Data point being aggregated.
- * @return agg
- */
- def binSeqOp(
- agg: Array[DTStatsAggregator],
- baggedPoint: BaggedPoint[TreePointX],
- splitsBcv: Array[Array[SplitBase]],
- sampleId: Short): Array[DTStatsAggregator] = {
- // TODO: treeToNodeToIndexInfo and topNodesForGroup(include sub-nodes) weren't broadcast.
- treeToNodeToIndexInfo.foreach { case (treeIndex, nodeIndexToInfo) =>
- if (RFUtils.isSubSampled(baggedPoint, groupInfo, treeIndex, sampleId)) {
- val nodeIndex =
- topNodesForGroup(treeIndex).predictImpl(baggedPoint.datum.binnedFeatures, splitsBcv)
- nodeBinSeqOp(treeIndex, nodeIndexToInfo.getOrElse(nodeIndex, null),
- agg, splitsBcv, baggedPoint)
- }
- }
- agg
- }
-
- /**
- * Do the same thing as binSeqOp, but with nodeIdCache.
- */
- def binSeqOpWithNodeIdCache(
- agg: Array[DTStatsAggregator],
- splitsBcv: Array[Array[SplitBase]],
- dataPoint: (BaggedPoint[TreePointX], Array[Int])): Array[DTStatsAggregator] = {
- treeToNodeToIndexInfo.foreach { case (treeIndex, nodeIndexToInfo) =>
- val baggedPoint = dataPoint._1
- val nodeIdCache = dataPoint._2
- val nodeIndex = nodeIdCache(treeIndex)
- nodeBinSeqOp(treeIndex, nodeIndexToInfo.getOrElse(nodeIndex, null),
- agg, splitsBcv, baggedPoint)
- }
-
- agg
- }
-
- /**
- * Get node index in group --> features indices map,
- * which is a short cut to find feature indices for a node given node index in group.
- */
- def getNodeToFeatures(
- treeToNodeToIndexInfo: Map[Int, Map[Int, NodeIndexInfo]]): Option[Map[Int, Array[Int]]] = {
- if (!metadata.subsamplingFeatures) {
- None
- } else {
- val mutableNodeToFeatures = new mutable.HashMap[Int, Array[Int]]()
- treeToNodeToIndexInfo.values.foreach { nodeIdToNodeInfo =>
- nodeIdToNodeInfo.values.foreach { nodeIndexInfo =>
- assert(nodeIndexInfo.featureSubset.isDefined)
- mutableNodeToFeatures(nodeIndexInfo.nodeIndexInGroup) = nodeIndexInfo.featureSubset.get
- }
- }
- Some(mutableNodeToFeatures.toMap)
- }
- }
-
- // array of nodes to train indexed by node index in group
- val nodes = new Array[LearningNodeX](numNodes)
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- nodes(treeToNodeToIndexInfo(treeIndex)(node.id).nodeIndexInGroup) = node
- }
- }
-
- // Calculate best splits for all nodes in the group
- timer.start("chooseSplits")
-
- // In each partition, iterate all instances and compute aggregate stats for each node,
- // yield a (nodeIndex, nodeAggregateStats) pair for each node.
- // After a `reduceByKey` operation,
- // stats of a node will be shuffled to a particular partition and be combined together,
- // then best splits for nodes are found there.
- // Finally, only best Splits for nodes are collected to driver to construct decision tree.
- // nodeToFeatures: node index in group -> selected feature indexes
- val nodeToFeatures = getNodeToFeatures(treeToNodeToIndexInfo)
- val nodeToFeaturesBc = input.sparkContext.broadcast(nodeToFeatures)
-
- /** partitionAggregates RDD: node index in group --> nodeStats */
- val partitionAggregates: RDD[(Int, DTStatsAggregator)] = if (nodeIdCache.nonEmpty) {
- input.zip(nodeIdCache.get.nodeIdsForInstances).mapPartitions { points =>
- // Construct a nodeStatsAggregators array to hold node aggregate stats,
- // each node will have a nodeStatsAggregator
- val nodeStatsAggregators = Array.tabulate(numNodes) { nodeIndex =>
- val featuresForNode = nodeToFeaturesBc.value.map { nodeToFeatures =>
- nodeToFeatures(nodeIndex)
- }
- new DTStatsAggregator(metadata, featuresForNode)
- }
-
- val splitsBcv = if (bcVariables) splitsBc.get.value else splitsOption.get
- // iterator all instances in current partition and update aggregate stats
- points.foreach(binSeqOpWithNodeIdCache(nodeStatsAggregators, splitsBcv, _))
-
- // transform nodeStatsAggregators array to (nodeIndex, nodeAggregateStats) pairs,
- // which can be combined with other partition using `reduceByKey`
- nodeStatsAggregators.view.zipWithIndex.map(_.swap).iterator
- }
- } else {
- input.mapPartitions { points =>
- val (firstPointOption, nodeStatsAggregators) =
- RFUtils.initNodeStatsAgg(numNodes, nodeToFeaturesBc, metadata, points, groupInfo)
- if (firstPointOption.isEmpty) {
- Iterator.empty
- } else {
- val firstPoint = firstPointOption.get
- val sampleId = firstPoint.sampleId
-
- val splitsBcv = if (bcVariables) splitsBc.get.value else splitsOption.get
- binSeqOp(nodeStatsAggregators, firstPoint, splitsBcv, sampleId)
-
-
- // iterator all instances in current partition and update aggregate stats
- points.foreach(binSeqOp(nodeStatsAggregators, _, splitsBcv, sampleId))
-
- // transform nodeStatsAggregators array to (nodeIndex, nodeAggregateStats) pairs,
- // which can be combined with other partition using `reduceByKey`
- nodeStatsAggregators.view.zipWithIndex
- .filter(v => RFUtils.isValidAgg(v._1)).map(_.swap).iterator
- }
- }
- }
-
- val nodeToBestSplits = partitionAggregates.reduceByKey((a, b) => a.merge(b)).map {
- case (nodeIndex, aggStats) =>
- val featuresForNode = nodeToFeaturesBc.value.flatMap { nodeToFeatures =>
- Some(nodeToFeatures(nodeIndex))
- }
-
- val splitsBcv = if (bcVariables) splitsBc.get.value else splitsOption.get
- // find best split for each node
- val (split: SplitBase, stats: ImpurityStats) =
- binsToBestSplit(aggStats, splitsBcv, featuresForNode, nodes(nodeIndex))
- (nodeIndex, (split, stats))
- }.collectAsMap()
-
- timer.stop("chooseSplits")
-
- val nodeIdUpdaters = if (nodeIdCache.nonEmpty) {
- Array.fill[mutable.Map[Int, NodeIndexUpdater]](
- metadata.numTrees)(mutable.Map[Int, NodeIndexUpdater]())
- } else {
- null
- }
- // Iterate over all nodes in this group.
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- val nodeIndex = node.id
- val nodeInfo = treeToNodeToIndexInfo(treeIndex)(nodeIndex)
- val aggNodeIndex = nodeInfo.nodeIndexInGroup
- val (split: SplitBase, stats: ImpurityStats) =
- nodeToBestSplits(aggNodeIndex)
- logDebug(s"best split = ${split}")
-
- // Extract info for this node. Create children if not leaf.
- val isLeaf =
- (stats.gain <= 0) || (LearningNodeX.indexToLevel(nodeIndex) == metadata.maxDepth)
- node.isLeaf = isLeaf
- node.stats = stats
- logDebug(s"Node = ${node}")
-
- if (!isLeaf) {
- node.split = Some(split)
- val childIsLeaf = (LearningNodeX.indexToLevel(nodeIndex) + 1) == metadata.maxDepth
- val leftChildIsLeaf = childIsLeaf || (stats.leftImpurity == 0.0)
- val rightChildIsLeaf = childIsLeaf || (stats.rightImpurity == 0.0)
- node.leftChild = Some(LearningNodeX(LearningNodeX.leftChildIndex(nodeIndex),
- leftChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.leftImpurityCalculator)))
- node.rightChild = Some(LearningNodeX(LearningNodeX.rightChildIndex(nodeIndex),
- rightChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.rightImpurityCalculator)))
-
- if (nodeIdCache.nonEmpty) {
- val nodeIndexUpdater = NodeIndexUpdater(
- split = split,
- nodeIndex = nodeIndex)
- nodeIdUpdaters(treeIndex).put(nodeIndex, nodeIndexUpdater)
- }
-
- // enqueue left child and right child if they are not leaves
- if (!leftChildIsLeaf) {
- nodeStack.push((treeIndex, node.leftChild.get))
- }
- if (!rightChildIsLeaf) {
- nodeStack.push((treeIndex, node.rightChild.get))
- }
-
- logDebug(s"leftChildIndex = ${node.leftChild.get.id}" +
- s", impurity = ${stats.leftImpurity}")
- logDebug(s"rightChildIndex = ${node.rightChild.get.id}" +
- s", impurity = ${stats.rightImpurity}")
- }
- }
- }
-
- if (nodeIdCache.nonEmpty) {
- // Update the cache if needed.
- nodeIdCache.get.updateNodeIndices(input, nodeIdUpdaters, splits)
- }
- }
-
- /**
- * Calculate the impurity statistics for a given (feature, split) based upon left/right
- * aggregates.
- *
- * @param stats the recycle impurity statistics for this feature's all splits,
- * only 'impurity' and 'impurityCalculator' are valid between each iteration
- * @param leftImpurityCalculator left node aggregates for this (feature, split)
- * @param rightImpurityCalculator right node aggregate for this (feature, split)
- * @param metadata learning and dataset metadata for DecisionTree
- * @return Impurity statistics for this (feature, split)
- */
- private def calculateImpurityStats(
- stats: ImpurityStats,
- leftImpurityCalculator: ImpurityCalculator,
- rightImpurityCalculator: ImpurityCalculator,
- metadata: DecisionTreeMetadata): ImpurityStats = {
-
- val parentImpurityCalculator: ImpurityCalculator = if (stats == null) {
- leftImpurityCalculator.copy.add(rightImpurityCalculator)
- } else {
- stats.impurityCalculator
- }
-
- val impurity: Double = if (stats == null) {
- parentImpurityCalculator.calculate()
- } else {
- stats.impurity
- }
-
- val leftCount = leftImpurityCalculator.count
- val rightCount = rightImpurityCalculator.count
-
- val totalCount = leftCount + rightCount
-
- // If left child or right child doesn't satisfy minimum instances per node,
- // then this split is invalid, return invalid information gain stats.
- if ((leftCount < metadata.minInstancesPerNode) ||
- (rightCount < metadata.minInstancesPerNode)) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- val leftImpurity = leftImpurityCalculator.calculate() // Note: This equals 0 if count = 0
- val rightImpurity = rightImpurityCalculator.calculate()
-
- val leftWeight = leftCount / totalCount.toDouble
- val rightWeight = rightCount / totalCount.toDouble
-
- val gain = impurity - leftWeight * leftImpurity - rightWeight * rightImpurity
-
- // if information gain doesn't satisfy minimum information gain,
- // then this split is invalid, return invalid information gain stats.
- if (gain < metadata.minInfoGain) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- new ImpurityStats(gain, impurity, parentImpurityCalculator,
- leftImpurityCalculator, rightImpurityCalculator)
- }
-
- /**
- * Find the best split for a node.
- *
- * @param binAggregates Bin statistics.
- * @return tuple for best split: (Split, information gain, prediction at node)
- */
- private[tree] def binsToBestSplit(
- binAggregates: DTStatsAggregator,
- splits: Array[Array[SplitBase]],
- featuresForNode: Option[Array[Int]],
- node: LearningNodeX): (SplitBase, ImpurityStats) = {
-
- // Calculate InformationGain and ImpurityStats if current node is top node
- val level = LearningNodeX.indexToLevel(node.id)
- var gainAndImpurityStats: ImpurityStats = if (level == 0) {
- null
- } else {
- node.stats
- }
-
- val validFeatureSplits =
- Range(0, binAggregates.metadata.numFeaturesPerNode).view.map { featureIndexIdx =>
- featuresForNode.map(features => (featureIndexIdx, features(featureIndexIdx)))
- .getOrElse((featureIndexIdx, featureIndexIdx))
- }.withFilter { case (_, featureIndex) =>
- binAggregates.metadata.numSplits(featureIndex) != 0
- }
-
- // For each (feature, split), calculate the gain, and select the best (feature, split).
- val splitsAndImpurityInfo =
- validFeatureSplits.map { case (featureIndexIdx, featureIndex) =>
- val numSplits = binAggregates.metadata.numSplits(featureIndex)
- if (binAggregates.metadata.isContinuous(featureIndex)) {
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- val nodeFeatureOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- var splitIndex = 0
- while (splitIndex < numSplits) {
- binAggregates.mergeForFeature(nodeFeatureOffset, splitIndex + 1, splitIndex)
- splitIndex += 1
- }
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { case splitIdx =>
- val leftChildStats = binAggregates.getImpurityCalculator(nodeFeatureOffset, splitIdx)
- val rightChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, numSplits)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIdx, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits(featureIndex)(bestFeatureSplitIndex), bestFeatureGainStats)
- } else if (binAggregates.metadata.isUnordered(featureIndex)) {
- // Unordered categorical feature
- val leftChildOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val leftChildStats = binAggregates.getImpurityCalculator(leftChildOffset, splitIndex)
- val rightChildStats = binAggregates.getParentImpurityCalculator()
- .subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits(featureIndex)(bestFeatureSplitIndex), bestFeatureGainStats)
- } else {
- // Ordered categorical feature
- val nodeFeatureOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- val numCategories = binAggregates.metadata.numBins(featureIndex)
-
- /* Each bin is one category (feature value).
- * The bins are ordered based on centroidForCategories, and this ordering determines which
- * splits are considered. (With K categories, we consider K - 1 possible splits.)
- *
- * centroidForCategories is a list: (category, centroid)
- */
- val centroidForCategories = Range(0, numCategories).map { case featureValue =>
- val categoryStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, featureValue)
- val centroid = if (categoryStats.count != 0) {
- if (binAggregates.metadata.isMulticlass) {
- // multiclass classification
- // For categorical variables in multiclass classification,
- // the bins are ordered by the impurity of their corresponding labels.
- categoryStats.calculate()
- } else if (binAggregates.metadata.isClassification) {
- // binary classification
- // For categorical variables in binary classification,
- // the bins are ordered by the count of class 1.
- categoryStats.stats(1)
- } else {
- // regression
- // For categorical variables in regression and binary classification,
- // the bins are ordered by the prediction.
- categoryStats.predict
- }
- } else {
- Double.MaxValue
- }
- (featureValue, centroid)
- }
-
- logDebug(s"Centroids for categorical variable: ${centroidForCategories.mkString(",")}")
-
- // bins sorted by centroids
- val categoriesSortedByCentroid = centroidForCategories.toList.sortBy(_._2)
-
- logDebug("Sorted centroids for categorical variable = " +
- categoriesSortedByCentroid.mkString(","))
-
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- var splitIndex = 0
- while (splitIndex < numSplits) {
- val currentCategory = categoriesSortedByCentroid(splitIndex)._1
- val nextCategory = categoriesSortedByCentroid(splitIndex + 1)._1
- binAggregates.mergeForFeature(nodeFeatureOffset, nextCategory, currentCategory)
- splitIndex += 1
- }
- // lastCategory = index of bin with total aggregates for this (node, feature)
- val lastCategory = categoriesSortedByCentroid.last._1
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val featureValue = categoriesSortedByCentroid(splitIndex)._1
- val leftChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, featureValue)
- val rightChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, lastCategory)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- val categoriesForSplit =
- categoriesSortedByCentroid.map(_._1.toDouble).slice(0, bestFeatureSplitIndex + 1)
- val bestFeatureSplit =
- new CategoricalSplit(featureIndex, categoriesForSplit.toArray, numCategories)
- (bestFeatureSplit, bestFeatureGainStats)
- }
- }
-
- val (bestSplit, bestSplitStats) =
- if (splitsAndImpurityInfo.isEmpty) {
- // If no valid splits for features, then this split is invalid,
- // return invalid information gain stats. Take any split and continue.
- // Splits is empty, so arbitrarily choose to split on any threshold
- val dummyFeatureIndex = featuresForNode.map(_.head).getOrElse(0)
- val parentImpurityCalculator = binAggregates.getParentImpurityCalculator()
- if (binAggregates.metadata.isContinuous(dummyFeatureIndex)) {
- (new ContinuousSplit(dummyFeatureIndex, 0),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- } else {
- val numCategories = binAggregates.metadata.featureArity(dummyFeatureIndex)
- (new CategoricalSplit(dummyFeatureIndex, Array(), numCategories),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- }
- } else {
- splitsAndImpurityInfo.maxBy(_._2.gain)
- }
- (bestSplit, bestSplitStats)
- }
-
- /**
- * Returns splits for decision tree calculation.
- * Continuous and categorical features are handled differently.
- *
- * Continuous features:
- * For each feature, there are numBins - 1 possible splits representing the possible binary
- * decisions at each node in the tree.
- * This finds locations (feature values) for splits using a subsample of the data.
- *
- * Categorical features:
- * For each feature, there is 1 bin per split.
- * Splits and bins are handled in 2 ways:
- * (a) "unordered features"
- * For multiclass classification with a low-arity feature
- * (i.e., if isMulticlass && isSpaceSufficientForAllCategoricalSplits),
- * the feature is split based on subsets of categories.
- * (b) "ordered features"
- * For regression and binary classification,
- * and for multiclass classification with a high-arity feature,
- * there is one bin per category.
- *
- * @param input Training data: RDD of [[LabeledPoint]]
- * @param metadata Learning and dataset metadata
- * @param seed random seed
- * @return Splits, an Array of [[Split]]
- * of size (numFeatures, numSplits)
- */
- protected[tree] def findSplits(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- seed: Long): Array[Array[Split]] = {
-
- logDebug(s"isMulticlass = ${metadata.isMulticlass}")
-
- val numFeatures = metadata.numFeatures
-
- // Sample the input only if there are continuous features.
- val continuousFeatures = Range(0, numFeatures).filter(metadata.isContinuous)
- val sampledInput = if (continuousFeatures.nonEmpty) {
- // Calculate the number of samples for approximate quantile calculation.
- val requiredSamples = math.max(metadata.maxBins * metadata.maxBins, 10000)
- val fraction = if (requiredSamples < metadata.numExamples) {
- requiredSamples.toDouble / metadata.numExamples
- } else {
- 1.0
- }
- logDebug(s"fraction of data used for calculating quantiles = ${fraction}")
- input.sample(withReplacement = false, fraction, new XORShiftRandom(seed).nextInt())
- } else {
- input.sparkContext.emptyRDD[LabeledPoint]
- }
-
- findSplitsBySorting(sampledInput, metadata, continuousFeatures)
- }
-
- private def findSplitsBySorting(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- continuousFeatures: IndexedSeq[Int]): Array[Array[Split]] = {
-
- val continuousSplits: scala.collection.Map[Int, Array[Split]] = {
- // reduce the parallelism for split computations when there are less
- // continuous features than input partitions. this prevents tasks from
- // being spun up that will definitely do no work.
- val numPartitions = math.min(continuousFeatures.length, input.partitions.length)
-
- input
- .flatMap(point => continuousFeatures.map(idx => (idx, point.features(idx))))
- .groupByKey(numPartitions)
- .map { case (idx, samples) =>
- val thresholds = findSplitsForContinuousFeature(samples, metadata, idx)
- val splits: Array[Split] = thresholds.map(thresh => new ContinuousSplit(idx, thresh))
- logDebug(s"featureIndex = $idx, numSplits = ${splits.length}")
- (idx, splits)
- }.collectAsMap()
- }
-
- val numFeatures = metadata.numFeatures
- val splits: Array[Array[Split]] = Array.tabulate(numFeatures) {
- case i if metadata.isContinuous(i) =>
- val split = continuousSplits(i)
- metadata.setNumSplits(i, split.length)
- split
-
- case i if metadata.isCategorical(i) && metadata.isUnordered(i) =>
- // Unordered features
- // 2^(maxFeatureValue - 1) - 1 combinations
- val featureArity = metadata.featureArity(i)
- Array.tabulate[Split](metadata.numSplits(i)) { splitIndex =>
- val categories = extractMultiClassCategories(splitIndex + 1, featureArity)
- new CategoricalSplit(i, categories.toArray, featureArity)
- }
-
- case i if metadata.isCategorical(i) =>
- // Ordered features
- // Splits are constructed as needed during training.
- Array.empty[Split]
- }
- splits
- }
-
- /**
- * Nested method to extract list of eligible categories given an index. It extracts the
- * position of ones in a binary representation of the input. If binary
- * representation of an number is 01101 (13), the output list should (3.0, 2.0,
- * 0.0). The maxFeatureValue depict the number of rightmost digits that will be tested for ones.
- */
- private[tree] def extractMultiClassCategories(
- input: Int,
- maxFeatureValue: Int): List[Double] = {
- var categories = List[Double]()
- var j = 0
- var bitShiftedInput = input
- while (j < maxFeatureValue) {
- if (bitShiftedInput % 2 != 0) {
- // updating the list of categories.
- categories = j.toDouble :: categories
- }
- // Right shift by one
- bitShiftedInput = bitShiftedInput >> 1
- j += 1
- }
- categories
- }
-
- /**
- * Find splits for a continuous feature
- * NOTE: Returned number of splits is set based on `featureSamples` and
- * could be different from the specified `numSplits`.
- * The `numSplits` attribute in the `DecisionTreeMetadata` class will be set accordingly.
- *
- * @param featureSamples feature values of each sample
- * @param metadata decision tree metadata
- * NOTE: `metadata.numbins` will be changed accordingly
- * if there are not enough splits to be found
- * @param featureIndex feature index to find splits
- * @return array of split thresholds
- */
- private[tree] def findSplitsForContinuousFeature(
- featureSamples: Iterable[Double],
- metadata: DecisionTreeMetadata,
- featureIndex: Int): Array[Double] = {
- require(metadata.isContinuous(featureIndex),
- "findSplitsForContinuousFeature can only be used to find splits for a continuous feature.")
-
- val splits: Array[Double] = if (featureSamples.isEmpty) {
- Array.empty[Double]
- } else {
- val numSplits = metadata.numSplits(featureIndex)
-
- // get count for each distinct value
- val (valueCountMap, numSamples) = featureSamples.foldLeft((Map.empty[Double, Int], 0)) {
- case ((m, cnt), x) =>
- (m + ((x, m.getOrElse(x, 0) + 1)), cnt + 1)
- }
- // sort distinct values
- val valueCounts = valueCountMap.toSeq.sortBy(_._1).toArray
-
- val possibleSplits = valueCounts.length - 1
- if (possibleSplits == 0) {
- // constant feature
- Array.empty[Double]
- } else if (possibleSplits <= numSplits) {
- // if possible splits is not enough or just enough, just return all possible splits
- (1 to possibleSplits)
- .map(index => (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0)
- .toArray
- } else {
- // stride between splits
- val stride: Double = numSamples.toDouble / (numSplits + 1)
- logDebug(s"stride = ${stride}")
-
- // iterate `valueCount` to find splits
- val splitsBuilder = mutable.ArrayBuilder.make[Double]
- var index = 1
- // currentCount: sum of counts of values that have been visited
- var currentCount = valueCounts(0)._2
- // targetCount: target value for `currentCount`.
- // If `currentCount` is closest value to `targetCount`,
- // then current value is a split threshold.
- // After finding a split threshold, `targetCount` is added by stride.
- var targetCount = stride
- while (index < valueCounts.length) {
- val previousCount = currentCount
- currentCount += valueCounts(index)._2
- val previousGap = math.abs(previousCount - targetCount)
- val currentGap = math.abs(currentCount - targetCount)
- // If adding count of current value to currentCount
- // makes the gap between currentCount and targetCount smaller,
- // previous value is a split threshold.
- if (previousGap < currentGap) {
- splitsBuilder += (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0
- targetCount += stride
- }
- index += 1
- }
-
- splitsBuilder.result()
- }
- }
- splits
- }
-
- private[tree] class NodeIndexInfo(
- val nodeIndexInGroup: Int,
- val featureSubset: Option[Array[Int]]) extends Serializable
-
- /**
- * Pull nodes off of the queue, and collect a group of nodes to be split on this iteration.
- * This tracks the memory usage for aggregates and stops adding nodes when too much memory
- * will be needed; this allows an adaptive number of nodes since different nodes may require
- * different amounts of memory (if featureSubsetStrategy is not "all").
- *
- * @param nodeStack Queue of nodes to split.
- * @param maxMemoryUsage Bound on size of aggregate statistics.
- * @return (nodesForGroup, treeToNodeToIndexInfo).
- * nodesForGroup holds the nodes to split: treeIndex --> nodes in tree.
- *
- * treeToNodeToIndexInfo holds indices selected features for each node:
- * treeIndex --> (global) node index --> (node index in group, feature indices).
- * The (global) node index is the index in the tree; the node index in group is the
- * index in [0, numNodesInGroup) of the node in this group.
- * The feature indices are None if not subsampling features.
- */
- private[tree] def selectNodesToSplit(
- nodeStack: mutable.ArrayStack[(Int, LearningNodeX)],
- maxMemoryUsage: Long,
- metadata: DecisionTreeMetadata,
- rng: Random): (Map[Int, Array[LearningNodeX]], Map[Int, Map[Int, NodeIndexInfo]]) = {
- // Collect some nodes to split:
- // nodesForGroup(treeIndex) = nodes to split
- val mutableNodesForGroup = new mutable.HashMap[Int, mutable.ArrayBuffer[LearningNodeX]]()
- val mutableTreeToNodeToIndexInfo =
- new mutable.HashMap[Int, mutable.HashMap[Int, NodeIndexInfo]]()
- var memUsage: Long = 0L
- var numNodesInGroup = 0
- // If maxMemoryInMB is set very small, we want to still try to split 1 node,
- // so we allow one iteration if memUsage == 0.
- var groupDone = false
- while (nodeStack.nonEmpty && !groupDone) {
- val (treeIndex, node) = nodeStack.top
- // Choose subset of features for node (if subsampling).
- val featureSubset: Option[Array[Int]] = if (metadata.subsamplingFeatures) {
- Some(SamplingUtils.reservoirSampleAndCount(Range(0,
- metadata.numFeatures).iterator, metadata.numFeaturesPerNode, rng.nextLong())._1)
- } else {
- None
- }
- // Check if enough memory remains to add this node to the group.
- val nodeMemUsage = RandomForest.aggregateSizeForNode(metadata, featureSubset) * 8L
- if (memUsage + nodeMemUsage <= maxMemoryUsage || memUsage == 0) {
- nodeStack.pop()
- mutableNodesForGroup.getOrElseUpdate(treeIndex, new mutable.ArrayBuffer[LearningNodeX]()) +=
- node
- mutableTreeToNodeToIndexInfo
- .getOrElseUpdate(treeIndex, new mutable.HashMap[Int, NodeIndexInfo]())(node.id)
- = new NodeIndexInfo(numNodesInGroup, featureSubset)
- numNodesInGroup += 1
- memUsage += nodeMemUsage
- } else {
- groupDone = true
- }
- }
- if (memUsage > maxMemoryUsage) {
- // If maxMemoryUsage is 0, we should still allow splitting 1 node.
- logWarning(s"Tree learning is using approximately $memUsage bytes per iteration, which" +
- s" exceeds requested limit maxMemoryUsage=$maxMemoryUsage. This allows splitting" +
- s" $numNodesInGroup nodes in this iteration.")
- }
- logWarning(f"[this group] actualMemUsage: ${memUsage/(1024d*1024d)}%.2f MB," +
- f" maxMemoryUsage: ${maxMemoryUsage/(1024d*1024d)}%.2f MB.")
- // Convert mutable maps to immutable ones.
- val nodesForGroup: Map[Int, Array[LearningNodeX]] =
- mutableNodesForGroup.mapValues(_.toArray).toMap
- val treeToNodeToIndexInfo = mutableTreeToNodeToIndexInfo.mapValues(_.toMap).toMap
- (nodesForGroup, treeToNodeToIndexInfo)
- }
-
- /**
- * Get the number of values to be stored for this node in the bin aggregates.
- *
- * @param featureSubset Indices of features which may be split at this node.
- * If None, then use all features.
- */
- private def aggregateSizeForNode(
- metadata: DecisionTreeMetadata,
- featureSubset: Option[Array[Int]]): Long = {
- val totalBins = if (featureSubset.nonEmpty) {
- featureSubset.get.map(featureIndex => metadata.numBins(featureIndex).toLong).sum
- } else {
- metadata.numBins.map(_.toLong).sum
- }
- if (metadata.isClassification) {
- metadata.numClasses * totalBins
- } else {
- 3 * totalBins
- }
- }
-}
-
-object RandomForestInfo {
- var timerResult: String = ""
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest4GBDTX.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest4GBDTX.scala
deleted file mode 100644
index 101adf1..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForest4GBDTX.scala
+++ /dev/null
@@ -1,621 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-import it.unimi.dsi.fastutil.ints.{Int2ObjectOpenHashMap, IntArrayList}
-import it.unimi.dsi.fastutil.objects.ObjectArrayList
-import scala.collection.mutable
-import scala.util.Random
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.classification.DecisionTreeClassificationModel
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.regression.DecisionTreeRegressionModel
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.tree.impl.GradientBoostedTreesCore.NodeIndexInfo
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo, Strategy => OldStrategy}
-import org.apache.spark.mllib.tree.model.ImpurityStats
-import org.apache.spark.rdd.RDD
-import org.apache.spark.util.random.{SamplingUtils, XORShiftRandom}
-
-
-/**
- * ALGORITHM
- *
- * This is a sketch of the algorithm to help new developers.
- *
- * The algorithm partitions data by instances (rows).
- * On each iteration, the algorithm splits a set of nodes. In order to choose the best split
- * for a given node, sufficient statistics are collected from the distributed data.
- * For each node, the statistics are collected to some worker node, and that worker selects
- * the best split.
- *
- * This setup requires discretization of continuous features. This binning is done in the
- * findSplits() method during initialization, after which each continuous feature becomes
- * an ordered discretized feature with at most maxBins possible values.
- *
- * The main loop in the algorithm operates on a queue of nodes (nodeStack). These nodes
- * lie at the periphery of the tree being trained. If multiple trees are being trained at once,
- * then this queue contains nodes from all of them. Each iteration works roughly as follows:
- * On the master node:
- * - Some number of nodes are pulled off of the queue (based on the amount of memory
- * required for their sufficient statistics).
- * - For random forests, if featureSubsetStrategy is not "all," then a subset of candidate
- * features are chosen for each node. See method selectNodesToSplit().
- * On worker nodes, via method findBestSplits():
- * - The worker makes one pass over its subset of instances.
- * - For each (tree, node, feature, split) tuple, the worker collects statistics about
- * splitting. Note that the set of (tree, node) pairs is limited to the nodes selected
- * from the queue for this iteration. The set of features considered can also be limited
- * based on featureSubsetStrategy.
- * - For each node, the statistics for that node are aggregated to a particular worker
- * via reduceByKey(). The designated worker chooses the best (feature, split) pair,
- * or chooses to stop splitting if the stopping criteria are met.
- * On the master node:
- * - The master collects all decisions about splitting nodes and updates the model.
- * - The updated model is passed to the workers on the next iteration.
- * This process continues until the node queue is empty.
- *
- * Most of the methods in this implementation support the statistics aggregation, which is
- * the heaviest part of the computation. In general, this implementation is bound by either
- * the cost of statistics computation on workers or by communicating the sufficient statistics.
- */
-private[spark] object RandomForest4GBDTX extends Logging {
-
- /**
- * Train a random forest.
- *
- * @param input Training data: RDD of `LabeledPoint`
- * @return an unweighted set of trees
- */
- def runX(
- labelArrayBc: Broadcast[DoubleArrayList],
- processedInput: RDD[(Int, (IntArrayList, ObjectArrayList[Split]))],
- metadata: DecisionTreeMetadata,
- splits: Array[Array[Split]],
- strategy: OldStrategy,
- numTrees: Int,
- seed: Long,
- input: RDD[TreePoint],
- rawPartInfoBc: Broadcast[Int2ObjectOpenHashMap[IntArrayList]],
- parentUID: Option[String] = None): Array[DecisionTreeModel] = {
-
- val timer = new TimeTracker()
-
- timer.start("total")
-
- timer.start("init")
-
- // depth of the decision tree
- val maxDepth = strategy.maxDepth
- require(maxDepth <= 30,
- s"DecisionTree currently only supports maxDepth <= 30, but was given maxDepth = $maxDepth.")
-
- // Max memory usage for aggregates
- // TODO: Calculate memory usage more precisely.
- val maxMemoryUsage: Long = strategy.maxMemoryInMB * 1024L * 1024L
- logDebug(s"max memory usage for aggregates = ${maxMemoryUsage} bytes.")
-
- /*
- Stack of nodes to train: (treeIndex, node)
- The reason this is a stack is that we train many trees at once, but we want to focus on
- completing trees, rather than training all simultaneously. If we are splitting nodes from
- 1 tree, then the new nodes to split will be put at the top of this stack, so we will continue
- training the same tree in the next iteration. This focus allows us to send fewer trees to
- workers on each iteration; see topNodesForGroup below.
- */
- val nodeStack = new mutable.ArrayStack[(Int, LearningNode)]
-
- val rng = new Random()
- rng.setSeed(seed)
-
- // Allocate and queue root nodes.
- val topNodes = Array.fill[LearningNode](numTrees)(LearningNode.emptyNode(nodeIndex = 1))
- Range(0, numTrees).foreach(treeIndex => nodeStack.push((treeIndex, topNodes(treeIndex))))
-
- val nodeIdCacheX = GradientBoostedTreesUtil.nodeIdCacheXConstruction(topNodes, rawPartInfoBc)
- timer.stop("init")
-
- while (nodeStack.nonEmpty) {
- // Collect some nodes to split, and choose features for each node (if subsampling).
- // Each group of nodes may come from one or multiple trees, and at multiple levels.
- val (nodesForGroup, treeToNodeToIndexInfo) =
- RandomForest4GBDTX.selectNodesToSplitX(nodeStack, maxMemoryUsage, metadata, rng)
- // Sanity check (should never occur):
- assert(nodesForGroup.nonEmpty,
- s"RandomForest selected empty nodesForGroup. Error for unknown reason.")
-
- // Only send trees to worker if they contain nodes being split this iteration.
- val topNodesForGroup: Map[Int, LearningNode] =
- nodesForGroup.keys.map(treeIdx => treeIdx -> topNodes(treeIdx)).toMap
-
- // Choose node splits, and enqueue new nodes as needed.
- timer.start("findBestSplits")
- RandomForest4GBDTX.findBestSplitsX(labelArrayBc, processedInput, metadata,
- (nodesForGroup, treeToNodeToIndexInfo), splits, nodeStack, nodeIdCacheX, input,
- rawPartInfoBc, timer)
- timer.stop("findBestSplits")
- }
-
- timer.stop("total")
-
- logInfo("Internal timing for DecisionTree:")
- logInfo(s"$timer")
-
- val numFeatures = metadata.numFeatures
-
- parentUID match {
- case Some(uid) =>
- if (strategy.algo == OldAlgo.Classification) {
- // unreachable for GBDT
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(uid, rootNode.toNode, numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map { rootNode =>
- new DecisionTreeRegressionModel(uid, rootNode.toNode, numFeatures)
- }
- }
- // unreachable for GBDT
- case None =>
- if (strategy.algo == OldAlgo.Classification) {
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(rootNode.toNode, numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map(rootNode => new DecisionTreeRegressionModel(rootNode.toNode, numFeatures))
- }
- }
- }
-
- /**
- * Given a group of nodes, this finds the best split for each node.
- *
- * @param input Training data: RDD of [[TreePoint]]
- * @param metadata Learning and dataset metadata
- * @param splits possible splits for all features, indexed (numFeatures)(numSplits)
- * @param nodeStack Queue of nodes to split, with values (treeIndex, node).
- * Updated with new non-leaf nodes which are created.
- * @param nodeIdCache Node Id cache containing an RDD of Array[Int] where
- * each value in the array is the data point's node Id
- * for a corresponding tree. This is used to prevent the need
- * to pass the entire tree to the executors during
- * the node stat aggregation phase.
- */
- private[tree] def findBestSplitsX(
- labelArrayBc: Broadcast[DoubleArrayList],
- processedInput: RDD[(Int, (IntArrayList, ObjectArrayList[Split]))],
- metadata: DecisionTreeMetadata,
- packagedNodeInfo: (Map[Int, Array[LearningNode]], Map[Int, Map[Int, NodeIndexInfo]]),
- splits: Array[Array[Split]],
- nodeStack: mutable.ArrayStack[(Int, LearningNode)],
- nodeIdCache: Int2ObjectOpenHashMap[Int2ObjectOpenHashMap[IntArrayList]],
- input: RDD[TreePoint],
- rawPartInfoBc: Broadcast[Int2ObjectOpenHashMap[IntArrayList]],
- timer: TimeTracker = new TimeTracker) : Unit = {
-
- /*
- * The high-level descriptions of the best split optimizations are noted here.
- *
- * *Group-wise training*
- * We perform bin calculations for groups of nodes to reduce the number of
- * passes over the data. Each iteration requires more computation and storage,
- * but saves several iterations over the data.
- *
- * *Bin-wise computation*
- * We use a bin-wise best split computation strategy instead of a straightforward best split
- * computation strategy. Instead of analyzing each sample for contribution to the left/right
- * child node impurity of every split, we first categorize each feature of a sample into a
- * bin. We exploit this structure to calculate aggregates for bins and then use these aggregates
- * to calculate information gain for each split.
- *
- * *Aggregation over partitions*
- * Instead of performing a flatMap/reduceByKey operation, we exploit the fact that we know
- * the number of splits in advance. Thus, we store the aggregates (at the appropriate
- * indices) in a single array for all bins and rely upon the RDD aggregate method to
- * drastically reduce the communication overhead.
- */
-
- // Un-package node info
- val (nodesForGroup, treeToNodeToIndexInfo) = packagedNodeInfo
- // numNodes: Number of nodes in this group
- val numNodes = nodesForGroup.values.map(_.length).sum
- logDebug(s"numNodes = ${numNodes}")
- logDebug(s"numFeatures = ${metadata.numFeatures}")
- logDebug(s"numClasses = ${metadata.numClasses}")
- logDebug(s"isMulticlass = ${metadata.isMulticlass}")
- logDebug(s"isMulticlassWithCategoricalFeatures =" +
- s"${metadata.isMulticlassWithCategoricalFeatures}")
-
- // array of nodes to train indexed by node index in group
- val nodes = new Array[LearningNode](numNodes)
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- nodes(treeToNodeToIndexInfo(treeIndex)(node.id).nodeIndexInGroup) = node
- }
- }
-
- timer.start("broadcast")
- val nodeIdCacheBc = processedInput.sparkContext.broadcast(nodeIdCache)
- timer.stop("broadcast")
-
- // Calculate best splits for all nodes in the group
- timer.start("chooseSplits")
-
- val nodeToBestSplits = GradientBoostedTreesUtil.chooseBestSplits(processedInput,
- treeToNodeToIndexInfo, metadata, nodeIdCacheBc, labelArrayBc, nodes)
-
- timer.stop("chooseSplits")
-
- // Iterate over all nodes in this group.
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- val nodeIndex = node.id
- val nodeInfo = treeToNodeToIndexInfo(treeIndex)(nodeIndex)
- val aggNodeIndex = nodeInfo.nodeIndexInGroup
- val (split: Split, stats: ImpurityStats) =
- nodeToBestSplits(nodeIndex)
- logDebug(s"best split = ${split}")
-
- // Extract info for this node. Create children if not leaf.
- val isLeaf =
- (stats.gain <= 0) || (LearningNode.indexToLevel(nodeIndex) == metadata.maxDepth)
- node.isLeaf = isLeaf
- node.stats = stats
- logDebug(s"Node = ${node}")
-
- if (!isLeaf) {
- node.split = Some(split)
- val childIsLeaf = (LearningNode.indexToLevel(nodeIndex) + 1) == metadata.maxDepth
- val leftChildIsLeaf = childIsLeaf || (stats.leftImpurity == 0.0)
- val rightChildIsLeaf = childIsLeaf || (stats.rightImpurity == 0.0)
- node.leftChild = Some(LearningNode(LearningNode.leftChildIndex(nodeIndex),
- leftChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.leftImpurityCalculator)))
- node.rightChild = Some(LearningNode(LearningNode.rightChildIndex(nodeIndex),
- rightChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.rightImpurityCalculator)))
-
- // enqueue left child and right child if they are not leaves
- if (!leftChildIsLeaf) {
- nodeStack.push((treeIndex, node.leftChild.get))
- }
- if (!rightChildIsLeaf) {
- nodeStack.push((treeIndex, node.rightChild.get))
- }
-
- logDebug(s"leftChildIndex = ${node.leftChild.get.id}" +
- s", impurity = ${stats.leftImpurity}")
- logDebug(s"rightChildIndex = ${node.rightChild.get.id}" +
- s", impurity = ${stats.rightImpurity}")
- }
- }
- }
-
- GradientBoostedTreesUtil.updateNodeIdCache(nodeIdCache, nodeIdCacheBc, input, nodesForGroup,
- treeToNodeToIndexInfo, splits, rawPartInfoBc, metadata, timer)
- }
-
- /**
- * Returns splits for decision tree calculation.
- * Continuous and categorical features are handled differently.
- *
- * Continuous features:
- * For each feature, there are numBins - 1 possible splits representing the possible binary
- * decisions at each node in the tree.
- * This finds locations (feature values) for splits using a subsample of the data.
- *
- * Categorical features:
- * For each feature, there is 1 bin per split.
- * Splits and bins are handled in 2 ways:
- * (a) "unordered features"
- * For multiclass classification with a low-arity feature
- * (i.e., if isMulticlass && isSpaceSufficientForAllCategoricalSplits),
- * the feature is split based on subsets of categories.
- * (b) "ordered features"
- * For regression and binary classification,
- * and for multiclass classification with a high-arity feature,
- * there is one bin per category.
- *
- * @param input Training data: RDD of [[LabeledPoint]]
- * @param metadata Learning and dataset metadata
- * @param seed random seed
- * @return Splits, an Array of [[Split]]
- * of size (numFeatures, numSplits)
- */
- protected[tree] def findSplits(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- seed: Long): Array[Array[Split]] = {
-
- logDebug(s"isMulticlass = ${metadata.isMulticlass}")
-
- val numFeatures = metadata.numFeatures
-
- // Sample the input only if there are continuous features.
- val continuousFeatures = Range(0, numFeatures).filter(metadata.isContinuous)
- val sampledInput = if (continuousFeatures.nonEmpty) {
- // Calculate the number of samples for approximate quantile calculation.
- val requiredSamples = math.max(metadata.maxBins * metadata.maxBins, 10000)
- val fraction = if (requiredSamples < metadata.numExamples) {
- requiredSamples.toDouble / metadata.numExamples
- } else {
- 1.0
- }
- logDebug(s"fraction of data used for calculating quantiles = ${fraction}")
- input.sample(withReplacement = false, fraction, new XORShiftRandom(seed).nextInt())
- } else {
- input.sparkContext.emptyRDD[LabeledPoint]
- }
-
- findSplitsBySorting(sampledInput, metadata, continuousFeatures)
- }
-
- private def findSplitsBySorting(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- continuousFeatures: IndexedSeq[Int]): Array[Array[Split]] = {
-
- val continuousSplits: scala.collection.Map[Int, Array[Split]] = {
- // reduce the parallelism for split computations when there are less
- // continuous features than input partitions. this prevents tasks from
- // being spun up that will definitely do no work.
- val numPartitions = math.min(continuousFeatures.length, input.partitions.length)
-
- input
- .flatMap(point => continuousFeatures.map(idx => (idx, point.features(idx))))
- .groupByKey(numPartitions)
- .map { case (idx, samples) =>
- val thresholds = findSplitsForContinuousFeature(samples, metadata, idx)
- val splits: Array[Split] = thresholds.map(thresh => new ContinuousSplit(idx, thresh))
- logDebug(s"featureIndex = $idx, numSplits = ${splits.length}")
- (idx, splits)
- }.collectAsMap()
- }
-
- val numFeatures = metadata.numFeatures
- val splits: Array[Array[Split]] = Array.tabulate(numFeatures) {
- case i if metadata.isContinuous(i) =>
- val split = continuousSplits(i)
- metadata.setNumSplits(i, split.length)
- split
-
- // unreachable for GBDT
- case i if metadata.isCategorical(i) && metadata.isUnordered(i) =>
- // Unordered features
- // 2^(maxFeatureValue - 1) - 1 combinations
- val featureArity = metadata.featureArity(i)
- Array.tabulate[Split](metadata.numSplits(i)) { splitIndex =>
- val categories = extractMultiClassCategories(splitIndex + 1, featureArity)
- new CategoricalSplit(i, categories.toArray, featureArity)
- }
-
- case i if metadata.isCategorical(i) =>
- // Ordered features
- // Splits are constructed as needed during training.
- Array.empty[Split]
- }
- splits
- }
-
- /**
- * Nested method to extract list of eligible categories given an index. It extracts the
- * position of ones in a binary representation of the input. If binary
- * representation of an number is 01101 (13), the output list should (3.0, 2.0,
- * 0.0). The maxFeatureValue depict the number of rightmost digits that will be tested for ones.
- */
- private[tree] def extractMultiClassCategories(
- input: Int,
- maxFeatureValue: Int): List[Double] = {
- var categories = List[Double]()
- var j = 0
- var bitShiftedInput = input
- while (j < maxFeatureValue) {
- if (bitShiftedInput % 2 != 0) {
- // updating the list of categories.
- categories = j.toDouble :: categories
- }
- // Right shift by one
- bitShiftedInput = bitShiftedInput >> 1
- j += 1
- }
- categories
- }
-
- /**
- * Find splits for a continuous feature
- * NOTE: Returned number of splits is set based on `featureSamples` and
- * could be different from the specified `numSplits`.
- * The `numSplits` attribute in the `DecisionTreeMetadata` class will be set accordingly.
- *
- * @param featureSamples feature values of each sample
- * @param metadata decision tree metadata
- * NOTE: `metadata.numbins` will be changed accordingly
- * if there are not enough splits to be found
- * @param featureIndex feature index to find splits
- * @return array of split thresholds
- */
- private[tree] def findSplitsForContinuousFeature(
- featureSamples: Iterable[Double],
- metadata: DecisionTreeMetadata,
- featureIndex: Int): Array[Double] = {
- require(metadata.isContinuous(featureIndex),
- "findSplitsForContinuousFeature can only be used to find splits for a continuous feature.")
-
- val splits: Array[Double] = if (featureSamples.isEmpty) {
- Array.empty[Double]
- } else {
- val numSplits = metadata.numSplits(featureIndex)
-
- // get count for each distinct value
- val (valueCountMap, numSamples) = featureSamples.foldLeft((Map.empty[Double, Int], 0)) {
- case ((m, cnt), x) =>
- (m + ((x, m.getOrElse(x, 0) + 1)), cnt + 1)
- }
- // sort distinct values
- val valueCounts = valueCountMap.toSeq.sortBy(_._1).toArray
-
- val possibleSplits = valueCounts.length - 1
- if (possibleSplits == 0) {
- // constant feature
- Array.empty[Double]
- } else if (possibleSplits <= numSplits) {
- // if possible splits is not enough or just enough, just return all possible splits
- (1 to possibleSplits)
- .map(index => (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0)
- .toArray
- } else {
- // stride between splits
- val stride: Double = numSamples.toDouble / (numSplits + 1)
- logDebug(s"stride = ${stride}")
-
- // iterate `valueCount` to find splits
- val splitsBuilder = mutable.ArrayBuilder.make[Double]
- var index = 1
- // currentCount: sum of counts of values that have been visited
- var currentCount = valueCounts(0)._2
- // targetCount: target value for `currentCount`.
- // If `currentCount` is closest value to `targetCount`,
- // then current value is a split threshold.
- // After finding a split threshold, `targetCount` is added by stride.
- var targetCount = stride
- while (index < valueCounts.length) {
- val previousCount = currentCount
- currentCount += valueCounts(index)._2
- val previousGap = math.abs(previousCount - targetCount)
- val currentGap = math.abs(currentCount - targetCount)
- // If adding count of current value to currentCount
- // makes the gap between currentCount and targetCount smaller,
- // previous value is a split threshold.
- if (previousGap < currentGap) {
- splitsBuilder += (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0
- targetCount += stride
- }
- index += 1
- }
-
- splitsBuilder.result()
- }
- }
- splits
- }
-
- /**
- * Pull nodes off of the queue, and collect a group of nodes to be split on this iteration.
- * This tracks the memory usage for aggregates and stops adding nodes when too much memory
- * will be needed; this allows an adaptive number of nodes since different nodes may require
- * different amounts of memory (if featureSubsetStrategy is not "all").
- *
- * @param nodeStack Queue of nodes to split.
- * @param maxMemoryUsage Bound on size of aggregate statistics.
- * @return (nodesForGroup, treeToNodeToIndexInfo).
- * nodesForGroup holds the nodes to split: treeIndex --> nodes in tree.
- *
- * treeToNodeToIndexInfo holds indices selected features for each node:
- * treeIndex --> (global) node index --> (node index in group, feature indices).
- * The (global) node index is the index in the tree; the node index in group is the
- * index in [0, numNodesInGroup) of the node in this group.
- * The feature indices are None if not subsampling features.
- */
- private[tree] def selectNodesToSplitX(
- nodeStack: mutable.ArrayStack[(Int, LearningNode)],
- maxMemoryUsage: Long,
- metadata: DecisionTreeMetadata,
- rng: Random): (Map[Int, Array[LearningNode]], Map[Int, Map[Int, NodeIndexInfo]]) = {
- // Collect some nodes to split:
- // nodesForGroup(treeIndex) = nodes to split
- val mutableNodesForGroup = new mutable.HashMap[Int, mutable.ArrayBuffer[LearningNode]]()
- val mutableTreeToNodeToIndexInfo =
- new mutable.HashMap[Int, mutable.HashMap[Int, NodeIndexInfo]]()
- var memUsage: Long = 0L
- var numNodesInGroup = 0
- // If maxMemoryInMB is set very small, we want to still try to split 1 node,
- // so we allow one iteration if memUsage == 0.
- var groupDone = false
- while (nodeStack.nonEmpty && !groupDone) {
- val (treeIndex, node) = nodeStack.top
- // Choose subset of features for node (if subsampling).
- val featureSubset: Option[Array[Int]] = if (metadata.subsamplingFeatures) {
- Some(SamplingUtils.reservoirSampleAndCount(Range(0,
- metadata.numFeatures).iterator, metadata.numFeaturesPerNode, rng.nextLong())._1)
- } else {
- None
- }
- val featureSubsetHashSetX: Option[mutable.HashSet[Int]] = if (metadata.subsamplingFeatures) {
- Some(scala.collection.mutable.HashSet(featureSubset.get: _*))
- } else {
- None
- }
- // Check if enough memory remains to add this node to the group.
- val nodeMemUsage = RandomForest4GBDTX.aggregateSizeForNode(metadata, featureSubset) * 8L
- if (memUsage + nodeMemUsage <= maxMemoryUsage || memUsage == 0) {
- nodeStack.pop()
- mutableNodesForGroup.getOrElseUpdate(treeIndex, new mutable.ArrayBuffer[LearningNode]()) +=
- node
- mutableTreeToNodeToIndexInfo
- .getOrElseUpdate(treeIndex, new mutable.HashMap[Int, NodeIndexInfo]())(node.id)
- = new NodeIndexInfo(numNodesInGroup, featureSubset, featureSubsetHashSetX)
- numNodesInGroup += 1
- memUsage += nodeMemUsage
- } else {
- groupDone = true
- }
- }
- if (memUsage > maxMemoryUsage) {
- // If maxMemoryUsage is 0, we should still allow splitting 1 node.
- logWarning(s"Tree learning is using approximately $memUsage bytes per iteration, which" +
- s" exceeds requested limit maxMemoryUsage=$maxMemoryUsage. This allows splitting" +
- s" $numNodesInGroup nodes in this iteration.")
- }
- // Convert mutable maps to immutable ones.
- val nodesForGroup: Map[Int, Array[LearningNode]] =
- mutableNodesForGroup.mapValues(_.toArray).toMap
- val treeToNodeToIndexInfo = mutableTreeToNodeToIndexInfo.mapValues(_.toMap).toMap
- (nodesForGroup, treeToNodeToIndexInfo)
- }
-
- /**
- * Get the number of values to be stored for this node in the bin aggregates.
- *
- * @param featureSubset Indices of features which may be split at this node.
- * If None, then use all features.
- */
- private def aggregateSizeForNode(
- metadata: DecisionTreeMetadata,
- featureSubset: Option[Array[Int]]): Long = {
- val totalBins = if (featureSubset.nonEmpty) {
- featureSubset.get.map(featureIndex => metadata.numBins(featureIndex).toLong).sum
- } else {
- metadata.numBins.map(_.toLong).sum
- }
- if (metadata.isClassification) {
- // unreachable for GBDT
- metadata.numClasses * totalBins
- } else {
- 3 * totalBins
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForestRaw.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForestRaw.scala
deleted file mode 100644
index 25dfd36..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/impl/RandomForestRaw.scala
+++ /dev/null
@@ -1,1157 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import java.io.IOException
-
-import scala.collection.mutable
-import scala.util.Random
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.classification.DecisionTreeClassificationModel
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.regression.DecisionTreeRegressionModel
-import org.apache.spark.ml.tree._
-import org.apache.spark.ml.util.Instrumentation
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo, Strategy => OldStrategy}
-import org.apache.spark.mllib.tree.impurity.ImpurityCalculator
-import org.apache.spark.mllib.tree.model.ImpurityStats
-import org.apache.spark.rdd.RDD
-import org.apache.spark.storage.StorageLevel
-import org.apache.spark.util.random.{SamplingUtils, XORShiftRandom}
-
-
-/**
- * ALGORITHM
- *
- * This is a sketch of the algorithm to help new developers.
- *
- * The algorithm partitions data by instances (rows).
- * On each iteration, the algorithm splits a set of nodes. In order to choose the best split
- * for a given node, sufficient statistics are collected from the distributed data.
- * For each node, the statistics are collected to some worker node, and that worker selects
- * the best split.
- *
- * This setup requires discretization of continuous features. This binning is done in the
- * findSplits() method during initialization, after which each continuous feature becomes
- * an ordered discretized feature with at most maxBins possible values.
- *
- * The main loop in the algorithm operates on a queue of nodes (nodeStack). These nodes
- * lie at the periphery of the tree being trained. If multiple trees are being trained at once,
- * then this queue contains nodes from all of them. Each iteration works roughly as follows:
- * On the master node:
- * - Some number of nodes are pulled off of the queue (based on the amount of memory
- * required for their sufficient statistics).
- * - For random forests, if featureSubsetStrategy is not "all," then a subset of candidate
- * features are chosen for each node. See method selectNodesToSplit().
- * On worker nodes, via method findBestSplits():
- * - The worker makes one pass over its subset of instances.
- * - For each (tree, node, feature, split) tuple, the worker collects statistics about
- * splitting. Note that the set of (tree, node) pairs is limited to the nodes selected
- * from the queue for this iteration. The set of features considered can also be limited
- * based on featureSubsetStrategy.
- * - For each node, the statistics for that node are aggregated to a particular worker
- * via reduceByKey(). The designated worker chooses the best (feature, split) pair,
- * or chooses to stop splitting if the stopping criteria are met.
- * On the master node:
- * - The master collects all decisions about splitting nodes and updates the model.
- * - The updated model is passed to the workers on the next iteration.
- * This process continues until the node queue is empty.
- *
- * Most of the methods in this implementation support the statistics aggregation, which is
- * the heaviest part of the computation. In general, this implementation is bound by either
- * the cost of statistics computation on workers or by communicating the sufficient statistics.
- */
-private[spark] object RandomForestRaw extends Logging {
-
- /**
- * Train a random forest.
- *
- * @param input Training data: RDD of `LabeledPoint`
- * @return an unweighted set of trees
- */
- def run(
- input: RDD[LabeledPoint],
- strategy: OldStrategy,
- numTrees: Int,
- featureSubsetStrategy: String,
- seed: Long,
- instr: Option[Instrumentation[_]],
- parentUID: Option[String] = None): Array[DecisionTreeModel] = {
-
- val timer = new TimeTracker()
-
- timer.start("total")
-
- timer.start("init")
-
- val retaggedInput = input.retag(classOf[LabeledPoint])
- val metadata =
- DecisionTreeMetadata.buildMetadata(retaggedInput, strategy, numTrees, featureSubsetStrategy)
- instr match {
- case Some(instrumentation) =>
- instrumentation.logNumFeatures(metadata.numFeatures)
- instrumentation.logNumClasses(metadata.numClasses)
- case None =>
- logInfo(s"numFeatures: ${metadata.numFeatures}")
- logInfo(s"numClasses: ${metadata.numClasses}")
- }
-
- // Find the splits and the corresponding bins (interval between the splits) using a sample
- // of the input data.
- timer.start("findSplits")
- val splits = findSplits(retaggedInput, metadata, seed)
- timer.stop("findSplits")
- logDebug("numBins: feature: number of bins")
- logDebug(Range(0, metadata.numFeatures).map { featureIndex =>
- s"\t$featureIndex\t${metadata.numBins(featureIndex)}"
- }.mkString("\n"))
-
- // Bin feature values (TreePoint representation).
- // Cache input RDD for speedup during multiple passes.
- val treeInput = TreePoint.convertToTreeRDD(retaggedInput, splits, metadata)
-
- val withReplacement = numTrees > 1
-
- val baggedInput = BaggedPoint
- .convertToBaggedRDD(treeInput, strategy.subsamplingRate, numTrees, withReplacement, seed)
- .persist(StorageLevel.MEMORY_AND_DISK)
-
- // depth of the decision tree
- val maxDepth = strategy.maxDepth
- require(maxDepth <= 30,
- s"DecisionTree currently only supports maxDepth <= 30, but was given maxDepth = $maxDepth.")
-
- // Max memory usage for aggregates
- // TODO: Calculate memory usage more precisely.
- val maxMemoryUsage: Long = strategy.maxMemoryInMB * 1024L * 1024L
- logDebug(s"max memory usage for aggregates = ${maxMemoryUsage} bytes.")
-
- /*
- * The main idea here is to perform group-wise training of the decision tree nodes thus
- * reducing the passes over the data from (# nodes) to (# nodes / maxNumberOfNodesPerGroup).
- * Each data sample is handled by a particular node (or it reaches a leaf and is not used
- * in lower levels).
- */
-
- // Create an RDD of node Id cache.
- // At first, all the rows belong to the root nodes (node Id == 1).
- val nodeIdCache = if (strategy.useNodeIdCache) {
- Some(NodeIdCache.init(
- data = baggedInput,
- numTrees = numTrees,
- checkpointInterval = strategy.checkpointInterval,
- initVal = 1))
- } else {
- None
- }
-
- /*
- Stack of nodes to train: (treeIndex, node)
- The reason this is a stack is that we train many trees at once, but we want to focus on
- completing trees, rather than training all simultaneously. If we are splitting nodes from
- 1 tree, then the new nodes to split will be put at the top of this stack, so we will continue
- training the same tree in the next iteration. This focus allows us to send fewer trees to
- workers on each iteration; see topNodesForGroup below.
- */
- val nodeStack = new mutable.ArrayStack[(Int, LearningNode)]
-
- val rng = new Random()
- rng.setSeed(seed)
-
- // Allocate and queue root nodes.
- val topNodes = Array.fill[LearningNode](numTrees)(LearningNode.emptyNode(nodeIndex = 1))
- Range(0, numTrees).foreach(treeIndex => nodeStack.push((treeIndex, topNodes(treeIndex))))
-
- timer.stop("init")
-
- while (nodeStack.nonEmpty) {
- // Collect some nodes to split, and choose features for each node (if subsampling).
- // Each group of nodes may come from one or multiple trees, and at multiple levels.
- val (nodesForGroup, treeToNodeToIndexInfo) =
- RandomForestRaw.selectNodesToSplit(nodeStack, maxMemoryUsage, metadata, rng)
- // Sanity check (should never occur):
- assert(nodesForGroup.nonEmpty,
- s"RandomForest selected empty nodesForGroup. Error for unknown reason.")
-
- // Only send trees to worker if they contain nodes being split this iteration.
- val topNodesForGroup: Map[Int, LearningNode] =
- nodesForGroup.keys.map(treeIdx => treeIdx -> topNodes(treeIdx)).toMap
-
- // Choose node splits, and enqueue new nodes as needed.
- timer.start("findBestSplits")
- RandomForestRaw.findBestSplits(baggedInput, metadata, topNodesForGroup, nodesForGroup,
- treeToNodeToIndexInfo, splits, nodeStack, timer, nodeIdCache)
- timer.stop("findBestSplits")
- }
-
- baggedInput.unpersist()
-
- timer.stop("total")
-
- logInfo("Internal timing for DecisionTree:")
- logInfo(s"$timer")
-
- // Delete any remaining checkpoints used for node Id cache.
- if (nodeIdCache.nonEmpty) {
- try {
- nodeIdCache.get.deleteAllCheckpoints()
- } catch {
- case e: IOException =>
- logWarning(s"delete all checkpoints failed. Error reason: ${e.getMessage}")
- }
- }
-
- val numFeatures = metadata.numFeatures
-
- parentUID match {
- case Some(uid) =>
- if (strategy.algo == OldAlgo.Classification) {
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(uid, rootNode.toNode, numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map { rootNode =>
- new DecisionTreeRegressionModel(uid, rootNode.toNode, numFeatures)
- }
- }
- case None =>
- if (strategy.algo == OldAlgo.Classification) {
- topNodes.map { rootNode =>
- new DecisionTreeClassificationModel(rootNode.toNode, numFeatures,
- strategy.getNumClasses)
- }
- } else {
- topNodes.map(rootNode => new DecisionTreeRegressionModel(rootNode.toNode, numFeatures))
- }
- }
- }
-
- /**
- * Helper for binSeqOp, for data which can contain a mix of ordered and unordered features.
- *
- * For ordered features, a single bin is updated.
- * For unordered features, bins correspond to subsets of categories; either the left or right bin
- * for each subset is updated.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (feature, bin).
- * @param treePoint Data point being aggregated.
- * @param splits possible splits indexed (numFeatures)(numSplits)
- * @param unorderedFeatures Set of indices of unordered features.
- * @param instanceWeight Weight (importance) of instance in dataset.
- */
- private def mixedBinSeqOp(
- agg: DTStatsAggregator,
- treePoint: TreePoint,
- splits: Array[Array[Split]],
- unorderedFeatures: Set[Int],
- instanceWeight: Double,
- featuresForNode: Option[Array[Int]]): Unit = {
- val numFeaturesPerNode = if (featuresForNode.nonEmpty) {
- // Use subsampled features
- featuresForNode.get.length
- } else {
- // Use all features
- agg.metadata.numFeatures
- }
- // Iterate over features.
- var featureIndexIdx = 0
- while (featureIndexIdx < numFeaturesPerNode) {
- val featureIndex = if (featuresForNode.nonEmpty) {
- featuresForNode.get.apply(featureIndexIdx)
- } else {
- featureIndexIdx
- }
- if (unorderedFeatures.contains(featureIndex)) {
- // Unordered feature
- val featureValue = treePoint.binnedFeatures(featureIndex)
- val leftNodeFeatureOffset = agg.getFeatureOffset(featureIndexIdx)
- // Update the left or right bin for each split.
- val numSplits = agg.metadata.numSplits(featureIndex)
- val featureSplits = splits(featureIndex)
- var splitIndex = 0
- while (splitIndex < numSplits) {
- if (featureSplits(splitIndex).shouldGoLeft(featureValue, featureSplits)) {
- agg.featureUpdate(leftNodeFeatureOffset, splitIndex,
- treePoint.label, instanceWeight.toInt)
- }
- splitIndex += 1
- }
- } else {
- // Ordered feature
- val binIndex = treePoint.binnedFeatures(featureIndex)
- agg.update(featureIndexIdx, binIndex, treePoint.label, instanceWeight.toInt)
- }
- featureIndexIdx += 1
- }
- }
-
- /**
- * Helper for binSeqOp, for regression and for classification with only ordered features.
- *
- * For each feature, the sufficient statistics of one bin are updated.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (feature, bin).
- * @param treePoint Data point being aggregated.
- * @param instanceWeight Weight (importance) of instance in dataset.
- */
- private def orderedBinSeqOp(
- agg: DTStatsAggregator,
- treePoint: TreePoint,
- instanceWeight: Double,
- featuresForNode: Option[Array[Int]]): Unit = {
- val label = treePoint.label
-
- // Iterate over features.
- if (featuresForNode.nonEmpty) {
- // Use subsampled features
- var featureIndexIdx = 0
- while (featureIndexIdx < featuresForNode.get.length) {
- val binIndex = treePoint.binnedFeatures(featuresForNode.get.apply(featureIndexIdx))
- agg.update(featureIndexIdx, binIndex, label, instanceWeight.toInt)
- featureIndexIdx += 1
- }
- } else {
- // Use all features
- val numFeatures = agg.metadata.numFeatures
- var featureIndex = 0
- while (featureIndex < numFeatures) {
- val binIndex = treePoint.binnedFeatures(featureIndex)
- agg.update(featureIndex, binIndex, label, instanceWeight.toInt)
- featureIndex += 1
- }
- }
- }
-
- /**
- * Given a group of nodes, this finds the best split for each node.
- *
- * @param input Training data: RDD of [[TreePoint]]
- * @param metadata Learning and dataset metadata
- * @param topNodesForGroup For each tree in group, tree index -> root node.
- * Used for matching instances with nodes.
- * @param nodesForGroup Mapping: treeIndex --> nodes to be split in tree
- * @param treeToNodeToIndexInfo Mapping: treeIndex --> nodeIndex --> nodeIndexInfo,
- * where nodeIndexInfo stores the index in the group and the
- * feature subsets (if using feature subsets).
- * @param splits possible splits for all features, indexed (numFeatures)(numSplits)
- * @param nodeStack Queue of nodes to split, with values (treeIndex, node).
- * Updated with new non-leaf nodes which are created.
- * @param nodeIdCache Node Id cache containing an RDD of Array[Int] where
- * each value in the array is the data point's node Id
- * for a corresponding tree. This is used to prevent the need
- * to pass the entire tree to the executors during
- * the node stat aggregation phase.
- */
- private[tree] def findBestSplits(
- input: RDD[BaggedPoint[TreePoint]],
- metadata: DecisionTreeMetadata,
- topNodesForGroup: Map[Int, LearningNode],
- nodesForGroup: Map[Int, Array[LearningNode]],
- treeToNodeToIndexInfo: Map[Int, Map[Int, NodeIndexInfo]],
- splits: Array[Array[Split]],
- nodeStack: mutable.ArrayStack[(Int, LearningNode)],
- timer: TimeTracker = new TimeTracker,
- nodeIdCache: Option[NodeIdCache] = None): Unit = {
-
- /*
- * The high-level descriptions of the best split optimizations are noted here.
- *
- * *Group-wise training*
- * We perform bin calculations for groups of nodes to reduce the number of
- * passes over the data. Each iteration requires more computation and storage,
- * but saves several iterations over the data.
- *
- * *Bin-wise computation*
- * We use a bin-wise best split computation strategy instead of a straightforward best split
- * computation strategy. Instead of analyzing each sample for contribution to the left/right
- * child node impurity of every split, we first categorize each feature of a sample into a
- * bin. We exploit this structure to calculate aggregates for bins and then use these aggregates
- * to calculate information gain for each split.
- *
- * *Aggregation over partitions*
- * Instead of performing a flatMap/reduceByKey operation, we exploit the fact that we know
- * the number of splits in advance. Thus, we store the aggregates (at the appropriate
- * indices) in a single array for all bins and rely upon the RDD aggregate method to
- * drastically reduce the communication overhead.
- */
-
- // numNodes: Number of nodes in this group
- val numNodes = nodesForGroup.values.map(_.length).sum
- logDebug(s"numNodes = ${numNodes}")
- logDebug(s"numFeatures = ${metadata.numFeatures}")
- logDebug(s"numClasses = ${metadata.numClasses}")
- logDebug(s"isMulticlass = ${metadata.isMulticlass}")
- logDebug("isMulticlassWithCategoricalFeatures = " +
- s"${metadata.isMulticlassWithCategoricalFeatures}")
- logDebug(s"using nodeIdCache = ${nodeIdCache.nonEmpty.toString}")
-
- /**
- * Performs a sequential aggregation over a partition for a particular tree and node.
- *
- * For each feature, the aggregate sufficient statistics are updated for the relevant
- * bins.
- *
- * @param treeIndex Index of the tree that we want to perform aggregation for.
- * @param nodeInfo The node info for the tree node.
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics
- * for each (node, feature, bin).
- * @param baggedPoint Data point being aggregated.
- */
- def nodeBinSeqOp(
- treeIndex: Int,
- nodeInfo: NodeIndexInfo,
- agg: Array[DTStatsAggregator],
- baggedPoint: BaggedPoint[TreePoint]): Unit = {
- if (nodeInfo != null) {
- val aggNodeIndex = nodeInfo.nodeIndexInGroup
- val featuresForNode = nodeInfo.featureSubset
- val instanceWeight = baggedPoint.subsampleWeights(treeIndex)
- if (metadata.unorderedFeatures.isEmpty) {
- orderedBinSeqOp(agg(aggNodeIndex), baggedPoint.datum, instanceWeight, featuresForNode)
- } else {
- mixedBinSeqOp(agg(aggNodeIndex), baggedPoint.datum, splits,
- metadata.unorderedFeatures, instanceWeight, featuresForNode)
- }
- agg(aggNodeIndex).updateParent(baggedPoint.datum.label, instanceWeight)
- }
- }
-
- /**
- * Performs a sequential aggregation over a partition.
- *
- * Each data point contributes to one node. For each feature,
- * the aggregate sufficient statistics are updated for the relevant bins.
- *
- * @param agg Array storing aggregate calculation, with a set of sufficient statistics for
- * each (node, feature, bin).
- * @param baggedPoint Data point being aggregated.
- * @return agg
- */
- def binSeqOp(
- agg: Array[DTStatsAggregator],
- baggedPoint: BaggedPoint[TreePoint]): Array[DTStatsAggregator] = {
- treeToNodeToIndexInfo.foreach { case (treeIndex, nodeIndexToInfo) =>
- val nodeIndex =
- topNodesForGroup(treeIndex).predictImpl(baggedPoint.datum.binnedFeatures, splits)
- nodeBinSeqOp(treeIndex, nodeIndexToInfo.getOrElse(nodeIndex, null), agg, baggedPoint)
- }
- agg
- }
-
- /**
- * Do the same thing as binSeqOp, but with nodeIdCache.
- */
- def binSeqOpWithNodeIdCache(
- agg: Array[DTStatsAggregator],
- dataPoint: (BaggedPoint[TreePoint], Array[Int])): Array[DTStatsAggregator] = {
- treeToNodeToIndexInfo.foreach { case (treeIndex, nodeIndexToInfo) =>
- val baggedPoint = dataPoint._1
- val nodeIdCache = dataPoint._2
- val nodeIndex = nodeIdCache(treeIndex)
- nodeBinSeqOp(treeIndex, nodeIndexToInfo.getOrElse(nodeIndex, null), agg, baggedPoint)
- }
-
- agg
- }
-
- /**
- * Get node index in group --> features indices map,
- * which is a short cut to find feature indices for a node given node index in group.
- */
- def getNodeToFeatures(
- treeToNodeToIndexInfo: Map[Int, Map[Int, NodeIndexInfo]]): Option[Map[Int, Array[Int]]] = {
- if (!metadata.subsamplingFeatures) {
- None
- } else {
- val mutableNodeToFeatures = new mutable.HashMap[Int, Array[Int]]()
- treeToNodeToIndexInfo.values.foreach { nodeIdToNodeInfo =>
- nodeIdToNodeInfo.values.foreach { nodeIndexInfo =>
- assert(nodeIndexInfo.featureSubset.isDefined)
- mutableNodeToFeatures(nodeIndexInfo.nodeIndexInGroup) = nodeIndexInfo.featureSubset.get
- }
- }
- Some(mutableNodeToFeatures.toMap)
- }
- }
-
- // array of nodes to train indexed by node index in group
- val nodes = new Array[LearningNode](numNodes)
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- nodes(treeToNodeToIndexInfo(treeIndex)(node.id).nodeIndexInGroup) = node
- }
- }
-
- // Calculate best splits for all nodes in the group
- timer.start("chooseSplits")
-
- // In each partition, iterate all instances and compute aggregate stats for each node,
- // yield a (nodeIndex, nodeAggregateStats) pair for each node.
- // After a `reduceByKey` operation,
- // stats of a node will be shuffled to a particular partition and be combined together,
- // then best splits for nodes are found there.
- // Finally, only best Splits for nodes are collected to driver to construct decision tree.
- val nodeToFeatures = getNodeToFeatures(treeToNodeToIndexInfo)
- val nodeToFeaturesBc = input.sparkContext.broadcast(nodeToFeatures)
-
- val partitionAggregates: RDD[(Int, DTStatsAggregator)] = if (nodeIdCache.nonEmpty) {
- input.zip(nodeIdCache.get.nodeIdsForInstances).mapPartitions { points =>
- // Construct a nodeStatsAggregators array to hold node aggregate stats,
- // each node will have a nodeStatsAggregator
- val nodeStatsAggregators = Array.tabulate(numNodes) { nodeIndex =>
- val featuresForNode = nodeToFeaturesBc.value.map { nodeToFeatures =>
- nodeToFeatures(nodeIndex)
- }
- new DTStatsAggregator(metadata, featuresForNode)
- }
-
- // iterator all instances in current partition and update aggregate stats
- points.foreach(binSeqOpWithNodeIdCache(nodeStatsAggregators, _))
-
- // transform nodeStatsAggregators array to (nodeIndex, nodeAggregateStats) pairs,
- // which can be combined with other partition using `reduceByKey`
- nodeStatsAggregators.view.zipWithIndex.map(_.swap).iterator
- }
- } else {
- input.mapPartitions { points =>
- // Construct a nodeStatsAggregators array to hold node aggregate stats,
- // each node will have a nodeStatsAggregator
- val nodeStatsAggregators = Array.tabulate(numNodes) { nodeIndex =>
- val featuresForNode = nodeToFeaturesBc.value.flatMap { nodeToFeatures =>
- Some(nodeToFeatures(nodeIndex))
- }
- new DTStatsAggregator(metadata, featuresForNode)
- }
-
- // iterator all instances in current partition and update aggregate stats
- points.foreach(binSeqOp(nodeStatsAggregators, _))
-
- // transform nodeStatsAggregators array to (nodeIndex, nodeAggregateStats) pairs,
- // which can be combined with other partition using `reduceByKey`
- nodeStatsAggregators.view.zipWithIndex.map(_.swap).iterator
- }
- }
-
- val nodeToBestSplits = partitionAggregates.reduceByKey((a, b) => a.merge(b)).map {
- case (nodeIndex, aggStats) =>
- val featuresForNode = nodeToFeaturesBc.value.flatMap { nodeToFeatures =>
- Some(nodeToFeatures(nodeIndex))
- }
-
- // find best split for each node
- val (split: Split, stats: ImpurityStats) =
- binsToBestSplit(aggStats, splits, featuresForNode, nodes(nodeIndex))
- (nodeIndex, (split, stats))
- }.collectAsMap()
-
- timer.stop("chooseSplits")
-
- val nodeIdUpdaters = if (nodeIdCache.nonEmpty) {
- Array.fill[mutable.Map[Int, NodeIndexUpdaterRaw]](
- metadata.numTrees)(mutable.Map[Int, NodeIndexUpdaterRaw]())
- } else {
- null
- }
- // Iterate over all nodes in this group.
- nodesForGroup.foreach { case (treeIndex, nodesForTree) =>
- nodesForTree.foreach { node =>
- val nodeIndex = node.id
- val nodeInfo = treeToNodeToIndexInfo(treeIndex)(nodeIndex)
- val aggNodeIndex = nodeInfo.nodeIndexInGroup
- val (split: Split, stats: ImpurityStats) =
- nodeToBestSplits(aggNodeIndex)
- logDebug(s"best split = ${split}")
-
- // Extract info for this node. Create children if not leaf.
- val isLeaf =
- (stats.gain <= 0) || (LearningNode.indexToLevel(nodeIndex) == metadata.maxDepth)
- node.isLeaf = isLeaf
- node.stats = stats
- logDebug(s"Node = ${node}")
-
- if (!isLeaf) {
- node.split = Some(split)
- val childIsLeaf = (LearningNode.indexToLevel(nodeIndex) + 1) == metadata.maxDepth
- val leftChildIsLeaf = childIsLeaf || (stats.leftImpurity == 0.0)
- val rightChildIsLeaf = childIsLeaf || (stats.rightImpurity == 0.0)
- node.leftChild = Some(LearningNode(LearningNode.leftChildIndex(nodeIndex),
- leftChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.leftImpurityCalculator)))
- node.rightChild = Some(LearningNode(LearningNode.rightChildIndex(nodeIndex),
- rightChildIsLeaf, ImpurityStats.getEmptyImpurityStats(stats.rightImpurityCalculator)))
-
- if (nodeIdCache.nonEmpty) {
- val nodeIndexUpdater = NodeIndexUpdaterRaw(
- split = split,
- nodeIndex = nodeIndex)
- nodeIdUpdaters(treeIndex).put(nodeIndex, nodeIndexUpdater)
- }
-
- // enqueue left child and right child if they are not leaves
- if (!leftChildIsLeaf) {
- nodeStack.push((treeIndex, node.leftChild.get))
- }
- if (!rightChildIsLeaf) {
- nodeStack.push((treeIndex, node.rightChild.get))
- }
-
- logDebug(s"leftChildIndex = ${node.leftChild.get.id}" +
- s", impurity = ${stats.leftImpurity}")
- logDebug(s"rightChildIndex = ${node.rightChild.get.id}" +
- s", impurity = ${stats.rightImpurity}")
- }
- }
- }
-
- if (nodeIdCache.nonEmpty) {
- // Update the cache if needed.
- nodeIdCache.get.updateNodeIndicesRaw(input, nodeIdUpdaters, splits)
- }
- }
-
- /**
- * Calculate the impurity statistics for a given (feature, split) based upon left/right
- * aggregates.
- *
- * @param stats the recycle impurity statistics for this feature's all splits,
- * only 'impurity' and 'impurityCalculator' are valid between each iteration
- * @param leftImpurityCalculator left node aggregates for this (feature, split)
- * @param rightImpurityCalculator right node aggregate for this (feature, split)
- * @param metadata learning and dataset metadata for DecisionTree
- * @return Impurity statistics for this (feature, split)
- */
- private def calculateImpurityStats(
- stats: ImpurityStats,
- leftImpurityCalculator: ImpurityCalculator,
- rightImpurityCalculator: ImpurityCalculator,
- metadata: DecisionTreeMetadata): ImpurityStats = {
-
- val parentImpurityCalculator: ImpurityCalculator = if (stats == null) {
- leftImpurityCalculator.copy.add(rightImpurityCalculator)
- } else {
- stats.impurityCalculator
- }
-
- val impurity: Double = if (stats == null) {
- parentImpurityCalculator.calculate()
- } else {
- stats.impurity
- }
-
- val leftCount = leftImpurityCalculator.count
- val rightCount = rightImpurityCalculator.count
-
- val totalCount = leftCount + rightCount
-
- // If left child or right child doesn't satisfy minimum instances per node,
- // then this split is invalid, return invalid information gain stats.
- if ((leftCount < metadata.minInstancesPerNode) ||
- (rightCount < metadata.minInstancesPerNode)) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- val leftImpurity = leftImpurityCalculator.calculate() // Note: This equals 0 if count = 0
- val rightImpurity = rightImpurityCalculator.calculate()
-
- val leftWeight = leftCount / totalCount.toDouble
- val rightWeight = rightCount / totalCount.toDouble
-
- val gain = impurity - leftWeight * leftImpurity - rightWeight * rightImpurity
-
- // if information gain doesn't satisfy minimum information gain,
- // then this split is invalid, return invalid information gain stats.
- if (gain < metadata.minInfoGain) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- new ImpurityStats(gain, impurity, parentImpurityCalculator,
- leftImpurityCalculator, rightImpurityCalculator)
- }
-
- /**
- * Find the best split for a node.
- *
- * @param binAggregates Bin statistics.
- * @return tuple for best split: (Split, information gain, prediction at node)
- */
- private[tree] def binsToBestSplit(
- binAggregates: DTStatsAggregator,
- splits: Array[Array[Split]],
- featuresForNode: Option[Array[Int]],
- node: LearningNode): (Split, ImpurityStats) = {
-
- // Calculate InformationGain and ImpurityStats if current node is top node
- val level = LearningNode.indexToLevel(node.id)
- var gainAndImpurityStats: ImpurityStats = if (level == 0) {
- null
- } else {
- node.stats
- }
-
- val validFeatureSplits =
- Range(0, binAggregates.metadata.numFeaturesPerNode).view.map { featureIndexIdx =>
- featuresForNode.map(features => (featureIndexIdx, features(featureIndexIdx)))
- .getOrElse((featureIndexIdx, featureIndexIdx))
- }.withFilter { case (_, featureIndex) =>
- binAggregates.metadata.numSplits(featureIndex) != 0
- }
-
- // For each (feature, split), calculate the gain, and select the best (feature, split).
- val splitsAndImpurityInfo =
- validFeatureSplits.map { case (featureIndexIdx, featureIndex) =>
- val numSplits = binAggregates.metadata.numSplits(featureIndex)
- if (binAggregates.metadata.isContinuous(featureIndex)) {
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- val nodeFeatureOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- var splitIndex = 0
- while (splitIndex < numSplits) {
- binAggregates.mergeForFeature(nodeFeatureOffset, splitIndex + 1, splitIndex)
- splitIndex += 1
- }
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { case splitIdx =>
- val leftChildStats = binAggregates.getImpurityCalculator(nodeFeatureOffset, splitIdx)
- val rightChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, numSplits)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIdx, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits(featureIndex)(bestFeatureSplitIndex), bestFeatureGainStats)
- } else if (binAggregates.metadata.isUnordered(featureIndex)) {
- // Unordered categorical feature
- val leftChildOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val leftChildStats = binAggregates.getImpurityCalculator(leftChildOffset, splitIndex)
- val rightChildStats = binAggregates.getParentImpurityCalculator()
- .subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits(featureIndex)(bestFeatureSplitIndex), bestFeatureGainStats)
- } else {
- // Ordered categorical feature
- val nodeFeatureOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- val numCategories = binAggregates.metadata.numBins(featureIndex)
-
- /* Each bin is one category (feature value).
- * The bins are ordered based on centroidForCategories, and this ordering determines which
- * splits are considered. (With K categories, we consider K - 1 possible splits.)
- *
- * centroidForCategories is a list: (category, centroid)
- */
- val centroidForCategories = Range(0, numCategories).map { case featureValue =>
- val categoryStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, featureValue)
- val centroid = if (categoryStats.count != 0) {
- if (binAggregates.metadata.isMulticlass) {
- // multiclass classification
- // For categorical variables in multiclass classification,
- // the bins are ordered by the impurity of their corresponding labels.
- categoryStats.calculate()
- } else if (binAggregates.metadata.isClassification) {
- // binary classification
- // For categorical variables in binary classification,
- // the bins are ordered by the count of class 1.
- categoryStats.stats(1)
- } else {
- // regression
- // For categorical variables in regression and binary classification,
- // the bins are ordered by the prediction.
- categoryStats.predict
- }
- } else {
- Double.MaxValue
- }
- (featureValue, centroid)
- }
-
- logDebug(s"Centroids for categorical variable: ${ centroidForCategories.mkString(",")}")
-
- // bins sorted by centroids
- val categoriesSortedByCentroid = centroidForCategories.toList.sortBy(_._2)
-
- logDebug("Sorted centroids for categorical variable = " +
- categoriesSortedByCentroid.mkString(","))
-
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- var splitIndex = 0
- while (splitIndex < numSplits) {
- val currentCategory = categoriesSortedByCentroid(splitIndex)._1
- val nextCategory = categoriesSortedByCentroid(splitIndex + 1)._1
- binAggregates.mergeForFeature(nodeFeatureOffset, nextCategory, currentCategory)
- splitIndex += 1
- }
- // lastCategory = index of bin with total aggregates for this (node, feature)
- val lastCategory = categoriesSortedByCentroid.last._1
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val featureValue = categoriesSortedByCentroid(splitIndex)._1
- val leftChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, featureValue)
- val rightChildStats =
- binAggregates.getImpurityCalculator(nodeFeatureOffset, lastCategory)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- val categoriesForSplit =
- categoriesSortedByCentroid.map(_._1.toDouble).slice(0, bestFeatureSplitIndex + 1)
- val bestFeatureSplit =
- new CategoricalSplit(featureIndex, categoriesForSplit.toArray, numCategories)
- (bestFeatureSplit, bestFeatureGainStats)
- }
- }
-
- val (bestSplit, bestSplitStats) =
- if (splitsAndImpurityInfo.isEmpty) {
- // If no valid splits for features, then this split is invalid,
- // return invalid information gain stats. Take any split and continue.
- // Splits is empty, so arbitrarily choose to split on any threshold
- val dummyFeatureIndex = featuresForNode.map(_.head).getOrElse(0)
- val parentImpurityCalculator = binAggregates.getParentImpurityCalculator()
- if (binAggregates.metadata.isContinuous(dummyFeatureIndex)) {
- (new ContinuousSplit(dummyFeatureIndex, 0),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- } else {
- val numCategories = binAggregates.metadata.featureArity(dummyFeatureIndex)
- (new CategoricalSplit(dummyFeatureIndex, Array(), numCategories),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- }
- } else {
- splitsAndImpurityInfo.maxBy(_._2.gain)
- }
- (bestSplit, bestSplitStats)
- }
-
- /**
- * Returns splits for decision tree calculation.
- * Continuous and categorical features are handled differently.
- *
- * Continuous features:
- * For each feature, there are numBins - 1 possible splits representing the possible binary
- * decisions at each node in the tree.
- * This finds locations (feature values) for splits using a subsample of the data.
- *
- * Categorical features:
- * For each feature, there is 1 bin per split.
- * Splits and bins are handled in 2 ways:
- * (a) "unordered features"
- * For multiclass classification with a low-arity feature
- * (i.e., if isMulticlass && isSpaceSufficientForAllCategoricalSplits),
- * the feature is split based on subsets of categories.
- * (b) "ordered features"
- * For regression and binary classification,
- * and for multiclass classification with a high-arity feature,
- * there is one bin per category.
- *
- * @param input Training data: RDD of [[LabeledPoint]]
- * @param metadata Learning and dataset metadata
- * @param seed random seed
- * @return Splits, an Array of [[Split]]
- * of size (numFeatures, numSplits)
- */
- protected[tree] def findSplits(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- seed: Long): Array[Array[Split]] = {
-
- logDebug(s"isMulticlass = ${metadata.isMulticlass}")
-
- val numFeatures = metadata.numFeatures
-
- // Sample the input only if there are continuous features.
- val continuousFeatures = Range(0, numFeatures).filter(metadata.isContinuous)
- val sampledInput = if (continuousFeatures.nonEmpty) {
- // Calculate the number of samples for approximate quantile calculation.
- val requiredSamples = math.max(metadata.maxBins * metadata.maxBins, 10000)
- val fraction = if (requiredSamples < metadata.numExamples) {
- requiredSamples.toDouble / metadata.numExamples
- } else {
- 1.0
- }
- logDebug(s"fraction of data used for calculating quantiles = ${fraction}")
- input.sample(withReplacement = false, fraction, new XORShiftRandom(seed).nextInt())
- } else {
- input.sparkContext.emptyRDD[LabeledPoint]
- }
-
- findSplitsBySorting(sampledInput, metadata, continuousFeatures)
- }
-
- private def findSplitsBySorting(
- input: RDD[LabeledPoint],
- metadata: DecisionTreeMetadata,
- continuousFeatures: IndexedSeq[Int]): Array[Array[Split]] = {
-
- val continuousSplits: scala.collection.Map[Int, Array[Split]] = {
- // reduce the parallelism for split computations when there are less
- // continuous features than input partitions. this prevents tasks from
- // being spun up that will definitely do no work.
- val numPartitions = math.min(continuousFeatures.length, input.partitions.length)
-
- input
- .flatMap(point => continuousFeatures.map(idx => (idx, point.features(idx))))
- .groupByKey(numPartitions)
- .map { case (idx, samples) =>
- val thresholds = findSplitsForContinuousFeature(samples, metadata, idx)
- val splits: Array[Split] = thresholds.map(thresh => new ContinuousSplit(idx, thresh))
- logDebug(s"featureIndex = $idx, numSplits = ${splits.length}")
- (idx, splits)
- }.collectAsMap()
- }
-
- val numFeatures = metadata.numFeatures
- val splits: Array[Array[Split]] = Array.tabulate(numFeatures) {
- case i if metadata.isContinuous(i) =>
- val split = continuousSplits(i)
- metadata.setNumSplits(i, split.length)
- split
-
- case i if metadata.isCategorical(i) && metadata.isUnordered(i) =>
- // Unordered features
- // 2^(maxFeatureValue - 1) - 1 combinations
- val featureArity = metadata.featureArity(i)
- Array.tabulate[Split](metadata.numSplits(i)) { splitIndex =>
- val categories = extractMultiClassCategories(splitIndex + 1, featureArity)
- new CategoricalSplit(i, categories.toArray, featureArity)
- }
-
- case i if metadata.isCategorical(i) =>
- // Ordered features
- // Splits are constructed as needed during training.
- Array.empty[Split]
- }
- splits
- }
-
- /**
- * Nested method to extract list of eligible categories given an index. It extracts the
- * position of ones in a binary representation of the input. If binary
- * representation of an number is 01101 (13), the output list should (3.0, 2.0,
- * 0.0). The maxFeatureValue depict the number of rightmost digits that will be tested for ones.
- */
- private[tree] def extractMultiClassCategories(
- input: Int,
- maxFeatureValue: Int): List[Double] = {
- var categories = List[Double]()
- var j = 0
- var bitShiftedInput = input
- while (j < maxFeatureValue) {
- if (bitShiftedInput % 2 != 0) {
- // updating the list of categories.
- categories = j.toDouble :: categories
- }
- // Right shift by one
- bitShiftedInput = bitShiftedInput >> 1
- j += 1
- }
- categories
- }
-
- /**
- * Find splits for a continuous feature
- * NOTE: Returned number of splits is set based on `featureSamples` and
- * could be different from the specified `numSplits`.
- * The `numSplits` attribute in the `DecisionTreeMetadata` class will be set accordingly.
- *
- * @param featureSamples feature values of each sample
- * @param metadata decision tree metadata
- * NOTE: `metadata.numbins` will be changed accordingly
- * if there are not enough splits to be found
- * @param featureIndex feature index to find splits
- * @return array of split thresholds
- */
- private[tree] def findSplitsForContinuousFeature(
- featureSamples: Iterable[Double],
- metadata: DecisionTreeMetadata,
- featureIndex: Int): Array[Double] = {
- require(metadata.isContinuous(featureIndex),
- "findSplitsForContinuousFeature can only be used to find splits for a continuous feature.")
-
- val splits: Array[Double] = if (featureSamples.isEmpty) {
- Array.empty[Double]
- } else {
- val numSplits = metadata.numSplits(featureIndex)
-
- // get count for each distinct value
- val (valueCountMap, numSamples) = featureSamples.foldLeft((Map.empty[Double, Int], 0)) {
- case ((m, cnt), x) =>
- (m + ((x, m.getOrElse(x, 0) + 1)), cnt + 1)
- }
- // sort distinct values
- val valueCounts = valueCountMap.toSeq.sortBy(_._1).toArray
-
- val possibleSplits = valueCounts.length - 1
- if (possibleSplits == 0) {
- // constant feature
- Array.empty[Double]
- } else if (possibleSplits <= numSplits) {
- // if possible splits is not enough or just enough, just return all possible splits
- (1 to possibleSplits)
- .map(index => (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0)
- .toArray
- } else {
- // stride between splits
- val stride: Double = numSamples.toDouble / (numSplits + 1)
- logDebug(s"stride = ${stride}")
-
- // iterate `valueCount` to find splits
- val splitsBuilder = mutable.ArrayBuilder.make[Double]
- var index = 1
- // currentCount: sum of counts of values that have been visited
- var currentCount = valueCounts(0)._2
- // targetCount: target value for `currentCount`.
- // If `currentCount` is closest value to `targetCount`,
- // then current value is a split threshold.
- // After finding a split threshold, `targetCount` is added by stride.
- var targetCount = stride
- while (index < valueCounts.length) {
- val previousCount = currentCount
- currentCount += valueCounts(index)._2
- val previousGap = math.abs(previousCount - targetCount)
- val currentGap = math.abs(currentCount - targetCount)
- // If adding count of current value to currentCount
- // makes the gap between currentCount and targetCount smaller,
- // previous value is a split threshold.
- if (previousGap < currentGap) {
- splitsBuilder += (valueCounts(index - 1)._1 + valueCounts(index)._1) / 2.0
- targetCount += stride
- }
- index += 1
- }
-
- splitsBuilder.result()
- }
- }
- splits
- }
-
- private[tree] class NodeIndexInfo(
- val nodeIndexInGroup: Int,
- val featureSubset: Option[Array[Int]]) extends Serializable
-
- /**
- * Pull nodes off of the queue, and collect a group of nodes to be split on this iteration.
- * This tracks the memory usage for aggregates and stops adding nodes when too much memory
- * will be needed; this allows an adaptive number of nodes since different nodes may require
- * different amounts of memory (if featureSubsetStrategy is not "all").
- *
- * @param nodeStack Queue of nodes to split.
- * @param maxMemoryUsage Bound on size of aggregate statistics.
- * @return (nodesForGroup, treeToNodeToIndexInfo).
- * nodesForGroup holds the nodes to split: treeIndex --> nodes in tree.
- *
- * treeToNodeToIndexInfo holds indices selected features for each node:
- * treeIndex --> (global) node index --> (node index in group, feature indices).
- * The (global) node index is the index in the tree; the node index in group is the
- * index in [0, numNodesInGroup) of the node in this group.
- * The feature indices are None if not subsampling features.
- */
- private[tree] def selectNodesToSplit(
- nodeStack: mutable.ArrayStack[(Int, LearningNode)],
- maxMemoryUsage: Long,
- metadata: DecisionTreeMetadata,
- rng: Random): (Map[Int, Array[LearningNode]], Map[Int, Map[Int, NodeIndexInfo]]) = {
- // Collect some nodes to split:
- // nodesForGroup(treeIndex) = nodes to split
- val mutableNodesForGroup = new mutable.HashMap[Int, mutable.ArrayBuffer[LearningNode]]()
- val mutableTreeToNodeToIndexInfo =
- new mutable.HashMap[Int, mutable.HashMap[Int, NodeIndexInfo]]()
- var memUsage: Long = 0L
- var numNodesInGroup = 0
- // If maxMemoryInMB is set very small, we want to still try to split 1 node,
- // so we allow one iteration if memUsage == 0.
- var groupDone = false
- while (nodeStack.nonEmpty && !groupDone) {
- val (treeIndex, node) = nodeStack.top
- // Choose subset of features for node (if subsampling).
- val featureSubset: Option[Array[Int]] = if (metadata.subsamplingFeatures) {
- Some(SamplingUtils.reservoirSampleAndCount(Range(0,
- metadata.numFeatures).iterator, metadata.numFeaturesPerNode, rng.nextLong())._1)
- } else {
- None
- }
- // Check if enough memory remains to add this node to the group.
- val nodeMemUsage = RandomForestRaw.aggregateSizeForNode(metadata, featureSubset) * 8L
- if (memUsage + nodeMemUsage <= maxMemoryUsage || memUsage == 0) {
- nodeStack.pop()
- mutableNodesForGroup.getOrElseUpdate(treeIndex, new mutable.ArrayBuffer[LearningNode]()) +=
- node
- mutableTreeToNodeToIndexInfo
- .getOrElseUpdate(treeIndex, new mutable.HashMap[Int, NodeIndexInfo]())(node.id)
- = new NodeIndexInfo(numNodesInGroup, featureSubset)
- numNodesInGroup += 1
- memUsage += nodeMemUsage
- } else {
- groupDone = true
- }
- }
- if (memUsage > maxMemoryUsage) {
- // If maxMemoryUsage is 0, we should still allow splitting 1 node.
- logWarning(s"Tree learning is using approximately $memUsage bytes per iteration, which" +
- s" exceeds requested limit maxMemoryUsage=$maxMemoryUsage. This allows splitting" +
- s" $numNodesInGroup nodes in this iteration.")
- }
- // Convert mutable maps to immutable ones.
- val nodesForGroup: Map[Int, Array[LearningNode]] =
- mutableNodesForGroup.mapValues(_.toArray).toMap
- val treeToNodeToIndexInfo = mutableTreeToNodeToIndexInfo.mapValues(_.toMap).toMap
- (nodesForGroup, treeToNodeToIndexInfo)
- }
-
- /**
- * Get the number of values to be stored for this node in the bin aggregates.
- *
- * @param featureSubset Indices of features which may be split at this node.
- * If None, then use all features.
- */
- private def aggregateSizeForNode(
- metadata: DecisionTreeMetadata,
- featureSubset: Option[Array[Int]]): Long = {
- val totalBins = if (featureSubset.nonEmpty) {
- featureSubset.get.map(featureIndex => metadata.numBins(featureIndex).toLong).sum
- } else {
- metadata.numBins.map(_.toLong).sum
- }
- if (metadata.isClassification) {
- metadata.numClasses * totalBins
- } else {
- 3 * totalBins
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/treeParams.scala b/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/treeParams.scala
deleted file mode 100644
index 38b79ec..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/ml/tree/treeParams.scala
+++ /dev/null
@@ -1,611 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree
-
-import java.util.Locale
-
-import scala.util.Try
-
-import org.apache.spark.ml.PredictorParams
-import org.apache.spark.ml.param._
-import org.apache.spark.ml.param.shared._
-import org.apache.spark.ml.util.SchemaUtils
-import org.apache.spark.mllib.tree.configuration.{Algo => OldAlgo, BoostingStrategy => OldBoostingStrategy, Strategy => OldStrategy}
-import org.apache.spark.mllib.tree.impurity.{Entropy => OldEntropy, Gini => OldGini, Impurity => OldImpurity, Variance => OldVariance}
-import org.apache.spark.mllib.tree.loss.{AbsoluteError => OldAbsoluteError, ClassificationLoss => OldClassificationLoss, LogLoss => OldLogLoss, Loss => OldLoss, SquaredError => OldSquaredError}
-import org.apache.spark.sql.types.{DataType, DoubleType, StructType}
-
-/**
- * Parameters for Decision Tree-based algorithms.
- *
- * Note: Marked as private and DeveloperApi since this may be made public in the future.
- */
-private[ml] trait DecisionTreeParams extends PredictorParams
- with HasCheckpointInterval with HasSeed {
-
- /**
- * Maximum depth of the tree (>= 0).
- * E.g., depth 0 means 1 leaf node; depth 1 means 1 internal node + 2 leaf nodes.
- * (default = 5)
- * @group param
- */
- final val maxDepth: IntParam =
- new IntParam(this, "maxDepth", "Maximum depth of the tree. (>= 0)" +
- " E.g., depth 0 means 1 leaf node; depth 1 means 1 internal node + 2 leaf nodes.",
- ParamValidators.gtEq(0))
-
- /**
- * Maximum number of bins used for discretizing continuous features and for choosing how to split
- * on features at each node. More bins give higher granularity.
- * Must be >= 2 and >= number of categories in any categorical feature.
- * (default = 32)
- * @group param
- */
- final val maxBins: IntParam = new IntParam(this, "maxBins", "Max number of bins for" +
- " discretizing continuous features. Must be >=2 and >= number of categories for any" +
- " categorical feature.", ParamValidators.gtEq(2))
-
- /**
- * Minimum number of instances each child must have after split.
- * If a split causes the left or right child to have fewer than minInstancesPerNode,
- * the split will be discarded as invalid.
- * Should be >= 1.
- * (default = 1)
- * @group param
- */
- final val minInstancesPerNode: IntParam = new IntParam(this, "minInstancesPerNode", "Minimum" +
- " number of instances each child must have after split. If a split causes the left or right" +
- " child to have fewer than minInstancesPerNode, the split will be discarded as invalid." +
- " Should be >= 1.", ParamValidators.gtEq(1))
-
- /**
- * Minimum information gain for a split to be considered at a tree node.
- * Should be >= 0.0.
- * (default = 0.0)
- * @group param
- */
- final val minInfoGain: DoubleParam = new DoubleParam(this, "minInfoGain",
- "Minimum information gain for a split to be considered at a tree node.",
- ParamValidators.gtEq(0.0))
-
- /**
- * Maximum memory in MB allocated to histogram aggregation. If too small, then 1 node will be
- * split per iteration, and its aggregates may exceed this size.
- * (default = 256 MB)
- * @group expertParam
- */
- final val maxMemoryInMB: IntParam = new IntParam(this, "maxMemoryInMB",
- "Maximum memory in MB allocated to histogram aggregation.",
- ParamValidators.gtEq(0))
-
- /**
- * If false, the algorithm will pass trees to executors to match instances with nodes.
- * If true, the algorithm will cache node IDs for each instance.
- * Caching can speed up training of deeper trees. Users can set how often should the
- * cache be checkpointed or disable it by setting checkpointInterval.
- * (default = false)
- * @group expertParam
- */
- final val cacheNodeIds: BooleanParam = new BooleanParam(this, "cacheNodeIds", "If false, the" +
- " algorithm will pass trees to executors to match instances with nodes. If true, the" +
- " algorithm will cache node IDs for each instance. Caching can speed up training of deeper" +
- " trees.")
-
- setDefault(maxDepth -> 5, maxBins -> 32, minInstancesPerNode -> 1, minInfoGain -> 0.0,
- maxMemoryInMB -> 256, cacheNodeIds -> false, checkpointInterval -> 10)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setMaxDepth(value: Int): this.type = set(maxDepth, value)
-
- /** @group getParam */
- final def getMaxDepth: Int = $(maxDepth)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setMaxBins(value: Int): this.type = set(maxBins, value)
-
- /** @group getParam */
- final def getMaxBins: Int = $(maxBins)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setMinInstancesPerNode(value: Int): this.type = set(minInstancesPerNode, value)
-
- /** @group getParam */
- final def getMinInstancesPerNode: Int = $(minInstancesPerNode)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setMinInfoGain(value: Double): this.type = set(minInfoGain, value)
-
- /** @group getParam */
- final def getMinInfoGain: Double = $(minInfoGain)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setSeed(value: Long): this.type = set(seed, value)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group expertSetParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setMaxMemoryInMB(value: Int): this.type = set(maxMemoryInMB, value)
-
- /** @group expertGetParam */
- final def getMaxMemoryInMB: Int = $(maxMemoryInMB)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group expertSetParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setCacheNodeIds(value: Boolean): this.type = set(cacheNodeIds, value)
-
- /** @group expertGetParam */
- final def getCacheNodeIds: Boolean = $(cacheNodeIds)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setCheckpointInterval(value: Int): this.type = set(checkpointInterval, value)
-
- /** (private[ml]) Create a Strategy instance to use with the old API. */
- private[ml] def getOldStrategy(
- categoricalFeatures: Map[Int, Int],
- numClasses: Int,
- oldAlgo: OldAlgo.Algo,
- oldImpurity: OldImpurity,
- subsamplingRate: Double): OldStrategy = {
- val strategy = OldStrategy.defaultStrategy(oldAlgo)
- strategy.impurity = oldImpurity
- strategy.checkpointInterval = getCheckpointInterval
- strategy.maxBins = getMaxBins
- strategy.maxDepth = getMaxDepth
- strategy.maxMemoryInMB = getMaxMemoryInMB
- strategy.minInfoGain = getMinInfoGain
- strategy.minInstancesPerNode = getMinInstancesPerNode
- strategy.useNodeIdCache = getCacheNodeIds
- strategy.numClasses = numClasses
- strategy.categoricalFeaturesInfo = categoricalFeatures
- strategy.subsamplingRate = subsamplingRate
- strategy
- }
-}
-
-/**
- * Parameters for Decision Tree-based classification algorithms.
- */
-private[ml] trait TreeClassifierParams extends Params {
-
- /**
- * Criterion used for information gain calculation (case-insensitive).
- * Supported: "entropy" and "gini".
- * (default = gini)
- * @group param
- */
- final val impurity: Param[String] = new Param[String](this, "impurity", "Criterion used for" +
- " information gain calculation (case-insensitive). Supported options:" +
- s" ${TreeClassifierParams.supportedImpurities.mkString(", ")}",
- (value: String) =>
- TreeClassifierParams.supportedImpurities.contains(value.toLowerCase(Locale.ROOT)))
-
- setDefault(impurity -> "gini")
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setImpurity(value: String): this.type = set(impurity, value)
-
- /** @group getParam */
- final def getImpurity: String = $(impurity).toLowerCase(Locale.ROOT)
-
- /** Convert new impurity to old impurity. */
- private[ml] def getOldImpurity: OldImpurity = {
- getImpurity match {
- case "entropy" => OldEntropy
- case "gini" => OldGini
- case _ =>
- // Should never happen because of check in setter method.
- throw new RuntimeException(
- s"TreeClassifierParams was given unrecognized impurity: $impurity.")
- }
- }
-}
-
-private[ml] object TreeClassifierParams {
- // These options should be lowercase.
- final val supportedImpurities: Array[String] =
- Array("entropy", "gini").map(_.toLowerCase(Locale.ROOT))
-}
-
-private[ml] trait DecisionTreeClassifierParams
- extends DecisionTreeParams with TreeClassifierParams
-
-/**
- * Parameters for Decision Tree-based regression algorithms.
- */
-private[ml] trait TreeRegressorParams extends Params {
-
- /**
- * Criterion used for information gain calculation (case-insensitive).
- * Supported: "variance".
- * (default = variance)
- * @group param
- */
- final val impurity: Param[String] = new Param[String](this, "impurity", "Criterion used for" +
- " information gain calculation (case-insensitive). Supported options:" +
- s" ${TreeRegressorParams.supportedImpurities.mkString(", ")}",
- (value: String) =>
- TreeRegressorParams.supportedImpurities.contains(value.toLowerCase(Locale.ROOT)))
-
- setDefault(impurity -> "variance")
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setImpurity(value: String): this.type = set(impurity, value)
-
- /** @group getParam */
- final def getImpurity: String = $(impurity).toLowerCase(Locale.ROOT)
-
- /** Convert new impurity to old impurity. */
- private[ml] def getOldImpurity: OldImpurity = {
- getImpurity match {
- case "variance" => OldVariance
- case _ =>
- // Should never happen because of check in setter method.
- throw new RuntimeException(
- s"TreeRegressorParams was given unrecognized impurity: $impurity")
- }
- }
-}
-
-private[ml] object TreeRegressorParams {
- // These options should be lowercase.
- final val supportedImpurities: Array[String] =
- Array("variance").map(_.toLowerCase(Locale.ROOT))
-}
-
-private[ml] trait DecisionTreeRegressorParams extends DecisionTreeParams
- with TreeRegressorParams with HasVarianceCol {
-
- override protected def validateAndTransformSchema(
- schema: StructType,
- fitting: Boolean,
- featuresDataType: DataType): StructType = {
- val newSchema = super.validateAndTransformSchema(schema, fitting, featuresDataType)
- if (isDefined(varianceCol) && $(varianceCol).nonEmpty) {
- SchemaUtils.appendColumn(newSchema, $(varianceCol), DoubleType)
- } else {
- newSchema
- }
- }
-}
-
-private[spark] object TreeEnsembleParams {
- // These options should be lowercase.
- final val supportedFeatureSubsetStrategies: Array[String] =
- Array("auto", "all", "onethird", "sqrt", "log2").map(_.toLowerCase(Locale.ROOT))
-}
-
-/**
- * Parameters for Decision Tree-based ensemble algorithms.
- *
- * Note: Marked as private and DeveloperApi since this may be made public in the future.
- */
-private[ml] trait TreeEnsembleParams extends DecisionTreeParams {
-
- /**
- * Fraction of the training data used for learning each decision tree, in range (0, 1].
- * (default = 1.0)
- * @group param
- */
- final val subsamplingRate: DoubleParam = new DoubleParam(this, "subsamplingRate",
- "Fraction of the training data used for learning each decision tree, in range (0, 1].",
- ParamValidators.inRange(0, 1, lowerInclusive = false, upperInclusive = true))
-
- setDefault(subsamplingRate -> 1.0)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setSubsamplingRate(value: Double): this.type = set(subsamplingRate, value)
-
- /** @group getParam */
- final def getSubsamplingRate: Double = $(subsamplingRate)
-
- /**
- * Create a Strategy instance to use with the old API.
- * NOTE: The caller should set impurity and seed.
- */
- private[ml] def getOldStrategy(
- categoricalFeatures: Map[Int, Int],
- numClasses: Int,
- oldAlgo: OldAlgo.Algo,
- oldImpurity: OldImpurity): OldStrategy = {
- super.getOldStrategy(categoricalFeatures, numClasses, oldAlgo, oldImpurity, getSubsamplingRate)
- }
-
- /**
- * The number of features to consider for splits at each tree node.
- * Supported options:
- * - "auto": Choose automatically for task:
- * If numTrees == 1, set to "all."
- * If numTrees > 1 (forest), set to "sqrt" for classification and
- * to "onethird" for regression.
- * - "all": use all features
- * - "onethird": use 1/3 of the features
- * - "sqrt": use sqrt(number of features)
- * - "log2": use log2(number of features)
- * - "n": when n is in the range (0, 1.0], use n * number of features. When n
- * is in the range (1, number of features), use n features.
- * (default = "auto")
- *
- * These various settings are based on the following references:
- * - log2: tested in Breiman (2001)
- * - sqrt: recommended by Breiman manual for random forests
- * - The defaults of sqrt (classification) and onethird (regression) match the R randomForest
- * package.
- * @see Breiman (2001)
- * @see
- * Breiman manual for random forests
- *
- * @group param
- */
- final val featureSubsetStrategy: Param[String] = new Param[String](this, "featureSubsetStrategy",
- "The number of features to consider for splits at each tree node." +
- s" Supported options: ${TreeEnsembleParams.supportedFeatureSubsetStrategies.mkString(", ")}" +
- s", (0.0-1.0], [1-n].",
- (value: String) =>
- TreeEnsembleParams.supportedFeatureSubsetStrategies.contains(
- value.toLowerCase(Locale.ROOT))
- || Try(value.toInt).filter(_ > 0).isSuccess
- || Try(value.toDouble).filter(_ > 0).filter(_ <= 1.0).isSuccess)
-
- setDefault(featureSubsetStrategy -> "auto")
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setFeatureSubsetStrategy(value: String): this.type = set(featureSubsetStrategy, value)
-
- /** @group getParam */
- final def getFeatureSubsetStrategy: String = $(featureSubsetStrategy).toLowerCase(Locale.ROOT)
-}
-
-
-
-/**
- * Parameters for Random Forest algorithms.
- */
-private[ml] trait RandomForestParams extends TreeEnsembleParams {
-
- /**
- * Number of trees to train (>= 1).
- * If 1, then no bootstrapping is used. If > 1, then bootstrapping is done.
- * TODO: Change to always do bootstrapping (simpler). SPARK-7130
- * (default = 20)
- *
- * Note: The reason that we cannot add this to both GBT and RF (i.e. in TreeEnsembleParams)
- * is the param `maxIter` controls how many trees a GBT has. The semantics in the algorithms
- * are a bit different.
- * @group param
- */
- final val numTrees: IntParam = new IntParam(this, "numTrees", "Number of trees to train (>= 1)",
- ParamValidators.gtEq(1))
-
- setDefault(numTrees -> 20)
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setNumTrees(value: Int): this.type = set(numTrees, value)
-
- /** @group getParam */
- final def getNumTrees: Int = $(numTrees)
-}
-
-private[ml] trait RandomForestClassifierParams
- extends RandomForestParams with TreeClassifierParams
-
-private[ml] trait RandomForestRegressorParams
- extends RandomForestParams with TreeRegressorParams
-
-/**
- * Parameters for Gradient-Boosted Tree algorithms.
- *
- * Note: Marked as private and DeveloperApi since this may be made public in the future.
- */
-private[ml] trait GBTParams extends TreeEnsembleParams with HasMaxIter with HasStepSize {
-
- /* TODO: Add this doc when we add this param. SPARK-7132
- * Threshold for stopping early when runWithValidation is used.
- * If the error rate on the validation input changes by less than the validationTol,
- * then learning will stop early (before [[numIterations]]).
- * This parameter is ignored when run is used.
- * (default = 1e-5)
- * @group param
- */
- // final val validationTol: DoubleParam = new DoubleParam(this, "validationTol", "")
- // validationTol -> 1e-5
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setMaxIter(value: Int): this.type = set(maxIter, value)
-
- /**
- * Param for Step size (a.k.a. learning rate) in interval (0, 1] for shrinking
- * the contribution of each estimator.
- * (default = 0.1)
- * @group param
- */
- final override val stepSize: DoubleParam = new DoubleParam(this, "stepSize", "Step size " +
- "(a.k.a. learning rate) in interval (0, 1] for shrinking the contribution of each estimator.",
- ParamValidators.inRange(0, 1, lowerInclusive = false, upperInclusive = true))
-
- /**
- * @deprecated This method is deprecated and will be removed in 3.0.0.
- * @group setParam
- */
- @deprecated("This method is deprecated and will be removed in 3.0.0.", "2.1.0")
- def setStepSize(value: Double): this.type = set(stepSize, value)
-
- setDefault(maxIter -> 20, stepSize -> 0.1)
-
- setDefault(featureSubsetStrategy -> "all")
-
- /** (private[ml]) Create a BoostingStrategy instance to use with the old API. */
- private[ml] def getOldBoostingStrategy(
- categoricalFeatures: Map[Int, Int],
- oldAlgo: OldAlgo.Algo): OldBoostingStrategy = {
- val strategy = super.getOldStrategy(categoricalFeatures, numClasses = 2, oldAlgo, OldVariance)
- // NOTE: The old API does not support "seed" so we ignore it.
- new OldBoostingStrategy(strategy, getOldLossType, getMaxIter, getStepSize)
- }
-
- /** Get old Gradient Boosting Loss type */
- private[ml] def getOldLossType: OldLoss
-
- final val doUseAcc: BooleanParam = new BooleanParam(this, "doUseAcc",
- "If true, use the optimized algorithm; otherwise, use the raw version")
-
- var setUseAccFlag = false
-
- /** Set algorithm to the raw version. */
- def setDoUseAcc(value: Boolean): this.type = {
- setUseAccFlag = true
- set(doUseAcc, value)
- }
- setDefault(doUseAcc -> true)
-
- /** Get algorithm type. */
- def getDoUseAcc: (Boolean, Boolean) = ($(doUseAcc), setUseAccFlag)
-}
-
-private[ml] object GBTClassifierParams {
- // The losses below should be lowercase.
- /** Accessor for supported loss settings: logistic */
- final val supportedLossTypes: Array[String] =
- Array("logistic").map(_.toLowerCase(Locale.ROOT))
-}
-
-private[ml] trait GBTClassifierParams extends GBTParams with TreeClassifierParams {
-
- /**
- * Loss function which GBT tries to minimize. (case-insensitive)
- * Supported: "logistic"
- * (default = logistic)
- * @group param
- */
- val lossType: Param[String] = new Param[String](this, "lossType", "Loss function which GBT" +
- " tries to minimize (case-insensitive). Supported options:" +
- s" ${GBTClassifierParams.supportedLossTypes.mkString(", ")}",
- (value: String) =>
- GBTClassifierParams.supportedLossTypes.contains(value.toLowerCase(Locale.ROOT)))
-
- setDefault(lossType -> "logistic")
-
- /** @group getParam */
- def getLossType: String = $(lossType).toLowerCase(Locale.ROOT)
-
- /** (private[ml]) Convert new loss to old loss. */
- override private[ml] def getOldLossType: OldClassificationLoss = {
- getLossType match {
- case "logistic" => OldLogLoss
- case _ =>
- // Should never happen because of check in setter method.
- throw new RuntimeException(s"GBTClassifier was given bad loss type: $getLossType")
- }
- }
-}
-
-private[ml] object GBTRegressorParams {
- // The losses below should be lowercase.
- /** Accessor for supported loss settings: squared (L2), absolute (L1) */
- final val supportedLossTypes: Array[String] =
- Array("squared", "absolute").map(_.toLowerCase(Locale.ROOT))
-}
-
-private[ml] trait GBTRegressorParams extends GBTParams with TreeRegressorParams {
-
- /**
- * Loss function which GBT tries to minimize. (case-insensitive)
- * Supported: "squared" (L2) and "absolute" (L1)
- * (default = squared)
- * @group param
- */
- val lossType: Param[String] = new Param[String](this, "lossType", "Loss function which GBT" +
- " tries to minimize (case-insensitive). Supported options:" +
- s" ${GBTRegressorParams.supportedLossTypes.mkString(", ")}",
- (value: String) =>
- GBTRegressorParams.supportedLossTypes.contains(value.toLowerCase(Locale.ROOT)))
-
- setDefault(lossType -> "squared")
-
- /** @group getParam */
- def getLossType: String = $(lossType).toLowerCase(Locale.ROOT)
-
- /** (private[ml]) Convert new loss to old loss. */
- override private[ml] def getOldLossType: OldLoss = {
- getLossType match {
- case "squared" => OldSquaredError
- case "absolute" => OldAbsoluteError
- case _ =>
- // Should never happen because of check in setter method.
- throw new RuntimeException(s"GBTRegressorParams was given bad loss type: $getLossType")
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/KMACCm.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/KMACCm.scala
deleted file mode 100644
index 2f9094c..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/KMACCm.scala
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.clustering
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.mllib.linalg.BLAS.{axpy, scal}
-import org.apache.spark.mllib.linalg.Vectors
-import org.apache.spark.rdd.RDD
-import org.apache.spark.sql.SparkSession
-
-object KMACCm {
- val DEFAULT_SAMPLE_RATE = 0.05
-
- def generateNewCenters(
- data: RDD[VectorWithNorm],
- bcs: Broadcast[Array[Double]],
- bcCenters: Broadcast[Array[VectorWithNorm]]): Map[Int, VectorWithNorm] = {
- val newCenters = data
- .mapPartitions { points =>
- val thisS = bcs.value
- val thisCenters = bcCenters.value
- val dims = thisCenters.head.vector.size
- val sums = Array.fill(thisCenters.length)(Vectors.zeros(dims))
- val counts = Array.fill(thisCenters.length)(0L)
-
- points.foreach { point =>
- val (bestCenter, cost) = KmeansUtil.findClosest(thisCenters, point, thisS)
- val sum = sums(bestCenter)
- axpy(1.0, point.vector, sum)
- counts(bestCenter) += 1
- }
- counts.indices.filter(counts(_) > 0).map(j => (j, (sums(j), counts(j)))).iterator
- }.reduceByKey { case ((sum1, count1), (sum2, count2)) =>
- axpy(1.0, sum2, sum1)
- (sum1, count1 + count2)
- }.mapValues { case (sum, count) =>
- scal(1.0 / count, sum)
- new VectorWithNorm(sum)
- }.collectAsMap()
- newCenters.toMap
- }
-
- def compute(
- data: RDD[VectorWithNorm],
- centers: Array[VectorWithNorm],
- maxIterations: Int,
- epsilon: Double,
- enableMiniBatch: Boolean): Unit = {
- var converged = false
- var iteration = 0
- val cl = centers.length
- val p = Array.fill(cl)(0.0)
- val sc = data.sparkContext
-
- var sampleRate = DEFAULT_SAMPLE_RATE
- try {
- sampleRate = sc.getConf.getDouble("spark.boostkit.Kmeans.sampleRate",
- DEFAULT_SAMPLE_RATE)
- if (sampleRate < 0.0) {
- throw new Exception
- }
- }
- catch {
- case x: Exception =>
- throw new Exception("'spark.boostkit.Kmeans.sampleRate' value is invalid")
- }
-
- val DEFAULT_PAR_LEVEL = 100
- var customParLevel = DEFAULT_PAR_LEVEL
- try{
- customParLevel = SparkSession.builder().getOrCreate()
- .sparkContext.getConf.getInt("spark.boostkit.Kmeans.parLevel",
- DEFAULT_PAR_LEVEL)
- if (customParLevel < 1) {
- throw new Exception
- }
- }
- catch {
- case x: Exception =>
- throw new Exception("'spark.boostkit.Kmeans.parLevel' value is invalid")
- }
-
- while (iteration < maxIterations && !converged) {
- val s = KmeansUtil.generateDisMatrix(centers, customParLevel)
- val bcCenters = sc.broadcast(centers)
- val bcs = sc.broadcast(s)
-
- // Find the new centers
- val newCenters = if (!enableMiniBatch) generateNewCenters(data, bcs, bcCenters)
- else generateNewCenters(data.sample(false, sampleRate), bcs, bcCenters)
- converged = true
- newCenters.foreach { case (j, newCenter) =>
- p(j) = KmeansUtil.fastDistance(newCenter, centers(j))
- if (converged && p(j) > epsilon) {
- converged = false
- }
- centers(j) = newCenter
- }
- bcCenters.destroy(blocking = false)
- bcs.destroy(blocking = false)
- iteration += 1
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/KMeans.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/KMeans.scala
deleted file mode 100644
index 4ecbcc3..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/KMeans.scala
+++ /dev/null
@@ -1,616 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.clustering
-
-import scala.collection.mutable.ArrayBuffer
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.clustering.{KMeans => NewKMeans}
-import org.apache.spark.ml.util.Instrumentation
-import org.apache.spark.mllib.linalg.{Vector, Vectors}
-import org.apache.spark.mllib.linalg.BLAS.{axpy, scal}
-import org.apache.spark.mllib.util.MLUtils
-import org.apache.spark.rdd.RDD
-import org.apache.spark.storage.StorageLevel
-import org.apache.spark.util.Utils
-import org.apache.spark.util.random.XORShiftRandom
-
-/**
- * K-means clustering with a k-means++ like initialization mode
- * (the k-means|| algorithm by Bahmani et al).
- *
- * This is an iterative algorithm that will make multiple passes over the data, so any RDDs given
- * to it should be cached by the user.
- */
-@Since("0.8.0")
-class KMeans private(
- private var k: Int,
- private var maxIterations: Int,
- private var initializationMode: String,
- private var initializationSteps: Int,
- private var epsilon: Double,
- private var seed: Long) extends Serializable with Logging {
-
- /**
- * Constructs a KMeans instance with default parameters: {k: 2, maxIterations: 20,
- * initializationMode: "k-means||", initializationSteps: 2, epsilon: 1e-4, seed: random}.
- */
- @Since("0.8.0")
- def this() = this(2, 20, KMeans.K_MEANS_PARALLEL, 2, 1e-4, Utils.random.nextLong())
-
- /**
- * Number of clusters to create (k).
- *
- * @note It is possible for fewer than k clusters to
- * be returned, for example, if there are fewer than k distinct points to cluster.
- */
- @Since("1.4.0")
- def getK: Int = k
-
- /**
- * Set the number of clusters to create (k).
- *
- * @note It is possible for fewer than k clusters to
- * be returned, for example, if there are fewer than k distinct points to cluster. Default: 2.
- */
- @Since("0.8.0")
- def setK(k: Int): this.type = {
- require(k > 0 && k < Math.sqrt(Int.MaxValue),
- s"Number of clusters must be positive and less than sqrt of Int.MaxValue, but got ${k}")
- this.k = k
- this
- }
-
- /**
- * Maximum number of iterations allowed.
- */
- @Since("1.4.0")
- def getMaxIterations: Int = maxIterations
-
- /**
- * Set maximum number of iterations allowed. Default: 20.
- */
- @Since("0.8.0")
- def setMaxIterations(maxIterations: Int): this.type = {
- require(maxIterations >= 0,
- s"Maximum of iterations must be nonnegative but got ${maxIterations}")
- this.maxIterations = maxIterations
- this
- }
-
- /**
- * The initialization algorithm. This can be either "random" or "k-means||".
- */
- @Since("1.4.0")
- def getInitializationMode: String = initializationMode
-
- /**
- * Set the initialization algorithm. This can be either "random" to choose random points as
- * initial cluster centers, or "k-means||" to use a parallel variant of k-means++
- * (Bahmani et al., Scalable K-Means++, VLDB 2012). Default: k-means||.
- */
- @Since("0.8.0")
- def setInitializationMode(initializationMode: String): this.type = {
- KMeans.validateInitMode(initializationMode)
- this.initializationMode = initializationMode
- this
- }
-
- /**
- * This function has no effect since Spark 2.0.0.
- */
- @Since("1.4.0")
- @deprecated("This has no effect and always returns 1", "2.1.0")
- def getRuns: Int = {
- logWarning("Getting number of runs has no effect since Spark 2.0.0.")
- 1
- }
-
- /**
- * This function has no effect since Spark 2.0.0.
- */
- @Since("0.8.0")
- @deprecated("This has no effect", "2.1.0")
- def setRuns(runs: Int): this.type = {
- logWarning("Setting number of runs has no effect since Spark 2.0.0.")
- this
- }
-
- /**
- * Number of steps for the k-means|| initialization mode
- */
- @Since("1.4.0")
- def getInitializationSteps: Int = initializationSteps
-
- /**
- * Set the number of steps for the k-means|| initialization mode. This is an advanced
- * setting -- the default of 2 is almost always enough. Default: 2.
- */
- @Since("0.8.0")
- def setInitializationSteps(initializationSteps: Int): this.type = {
- require(initializationSteps > 0,
- s"Number of initialization steps must be positive but got ${initializationSteps}")
- this.initializationSteps = initializationSteps
- this
- }
-
- /**
- * The distance threshold within which we've consider centers to have converged.
- */
- @Since("1.4.0")
- def getEpsilon: Double = epsilon
-
- /**
- * Set the distance threshold within which we've consider centers to have converged.
- * If all centers move less than this Euclidean distance, we stop iterating one run.
- */
- @Since("0.8.0")
- def setEpsilon(epsilon: Double): this.type = {
- require(epsilon >= 0,
- s"Distance threshold must be nonnegative but got ${epsilon}")
- this.epsilon = epsilon
- this
- }
-
- /**
- * The random seed for cluster initialization.
- */
- @Since("1.4.0")
- def getSeed: Long = seed
-
- /**
- * Set the random seed for cluster initialization.
- */
- @Since("1.4.0")
- def setSeed(seed: Long): this.type = {
- this.seed = seed
- this
- }
-
- // Initial cluster centers can be provided as a KMeansModel object rather than using the
- // random or k-means|| initializationMode
- private var initialModel: Option[KMeansModel] = None
-
- /**
- * Set the initial starting point, bypassing the random initialization or k-means||
- * The condition model.k == this.k must be met, failure results
- * in an IllegalArgumentException.
- */
- @Since("1.4.0")
- def setInitialModel(model: KMeansModel): this.type = {
- require(model.k == k, "mismatched cluster count")
- initialModel = Some(model)
- this
- }
-
- /**
- * Train a K-means model on the given set of points; `data` should be cached for high
- * performance, because this is an iterative algorithm.
- */
- @Since("0.8.0")
- def run(data: RDD[Vector]): KMeansModel = {
- run(data, None)
- }
-
- private[spark] def run(
- data: RDD[Vector],
- instr: Option[Instrumentation[NewKMeans]]): KMeansModel = {
-
- if (data.getStorageLevel == StorageLevel.NONE) {
- logWarning("The input data is not directly cached, which may hurt performance if its"
- + " parent RDDs are also uncached.")
- }
-
- // Compute squared norms and cache them.
- val norms = data.map(Vectors.norm(_, 2.0))
- norms.persist()
- val zippedData = data.zip(norms).map { case (v, norm) =>
- new VectorWithNorm(v, norm)
- }
- val model = runAlgorithm(zippedData, instr)
- norms.unpersist()
-
- // Warn at the end of the run as well, for increased visibility.
- if (data.getStorageLevel == StorageLevel.NONE) {
- logWarning("The input data was not directly cached, which may hurt performance if its"
- + " parent RDDs are also uncached.")
- }
- model
- }
-
- /**
- * Implementation of K-Means algorithm.
- */
- private def runAlgorithm(
- data: RDD[VectorWithNorm],
- instr: Option[Instrumentation[NewKMeans]]): KMeansModel = {
-
- val sc = data.sparkContext
- val initStartTime = System.nanoTime()
- val centers = initialModel match {
- case Some(kMeansCenters) =>
- kMeansCenters.clusterCenters.map(new VectorWithNorm(_))
- case None =>
- if (initializationMode == KMeans.RANDOM) {
- initRandom(data)
- } else {
- initKMeansParallel(data)
- }
- }
- val centersR = centers.clone()
- val cl = centers.length
- val initTimeInSeconds = (System.nanoTime() - initStartTime) / 1e9
- logInfo(f"Initialization with $initializationMode took $initTimeInSeconds%.3f seconds.")
- var converged = false
- var cost = 0.0
- var iteration = 0
- val iterationStartTime = System.nanoTime()
- instr.foreach(_.logNumFeatures(centers.head.vector.size))
-
- // Execute iterations of Lloyd's algorithm until converged
- if (cl > 1) {
- val methodEnum = Array("default", "allData")
- val method = sc.getConf.get("spark.boostkit.Kmeans.optMethod", "default")
- if (!methodEnum.contains(method)) {
- throw new Exception("'spark.boostkit.Kmeans.optMethod' value is invalid")
- }
- if (method == "allData") {
- KMACCm.compute(data, centers, maxIterations, epsilon, false)
- } else {
- KMACCm.compute(data, centers, maxIterations, epsilon, true)
- }
- } else {
- iteration = 0
- converged = false
- cost = 0.0
- while (iteration < maxIterations && !converged) {
- val costAccum = sc.doubleAccumulator
- val bcCenters = sc.broadcast(centersR)
-
- // Find the new centers
- val newCenters = data.mapPartitions { points =>
- val thisCenters = bcCenters.value
- val dims = thisCenters.head.vector.size
- val sums = Array.fill(thisCenters.length)(Vectors.zeros(dims))
- val counts = Array.fill(thisCenters.length)(0L)
- points.foreach { point =>
- val (bestCenter, cost) = KMeans.findClosest(thisCenters, point)
- costAccum.add(cost)
- val sum = sums(bestCenter)
- axpy(1.0, point.vector, sum)
- counts(bestCenter) += 1
- }
- counts.indices.filter(counts(_) > 0).map(j => (j, (sums(j), counts(j)))).iterator
- }.reduceByKey { case ((sum1, count1), (sum2, count2)) =>
- axpy(1.0, sum2, sum1)
- (sum1, count1 + count2)
- }.mapValues { case (sum, count) =>
- scal(1.0 / count, sum)
- new VectorWithNorm(sum)
- }.collectAsMap()
- bcCenters.destroy(blocking = false)
-
- // Update the cluster centers and costs
- converged = true
- newCenters.foreach { case (j, newCenter) =>
- if (converged && KMeans.fastSquaredDistance(newCenter, centersR(j)) > epsilon * epsilon) {
- converged = false
- }
- centersR(j) = newCenter
- }
- cost = costAccum.value
- iteration += 1
- }
- }
-
- val iterationTimeInSeconds = (System.nanoTime() - iterationStartTime) / 1e9
- logInfo(f"Iterations took $iterationTimeInSeconds%.3f seconds.")
- if (iteration == maxIterations) {
- logInfo(s"KMeansX reached the max number of iterations: $maxIterations.")
- } else {
- logInfo(s"KMeansX converged in $iteration iterations.")
- }
- if (cl > 1) {
- new KMeansModel(centers.map(_.vector))
- }
- else {
- new KMeansModel(centersR.map(_.vector))
- }
- }
-
- /**
- * Initialize a set of cluster centers at random.
- */
- private def initRandom(data: RDD[VectorWithNorm]): Array[VectorWithNorm] = {
- // Select without replacement; may still produce duplicates if the data has < k distinct
- // points, so deduplicate the centroids to match the behavior of k-means|| in the same situation
- data.takeSample(false, k, new XORShiftRandom(this.seed).nextInt())
- .map(_.vector).distinct.map(new VectorWithNorm(_))
- }
-
-
- /**
- * Initialize a set of cluster centers using the k-means|| algorithm by Bahmani et al.
- * (Bahmani et al., Scalable K-Means++, VLDB 2012). This is a variant of k-means++ that tries
- * to find dissimilar cluster centers by starting with a random center and then doing
- * passes where more centers are chosen with probability proportional to their squared distance
- * to the current cluster set. It results in a provable approximation to an optimal clustering.
- *
- * The original paper can be found at http://theory.stanford.edu/~sergei/papers/vldb12-kmpar.pdf.
- */
- private[clustering] def initKMeansParallel(data: RDD[VectorWithNorm]): Array[VectorWithNorm] = {
- // Initialize empty centers and point costs.
- var costs = data.map(_ => Double.PositiveInfinity)
-
- // Initialize the first center to a random point.
- val seed = new XORShiftRandom(this.seed).nextInt()
- val sample = data.takeSample(false, 1, seed)
- // Could be empty if data is empty; fail with a better message early:
- require(sample.nonEmpty, s"No samples available from $data")
-
- val centers = ArrayBuffer[VectorWithNorm]()
- var newCenters = Seq(sample.head.toDense)
- centers ++= newCenters
-
- // On each step, sample 2 * k points on average with probability proportional
- // to their squared distance from the centers. Note that only distances between points
- // and new centers are computed in each iteration.
- var step = 0
- val bcNewCentersList = ArrayBuffer[Broadcast[_]]()
- while (step < initializationSteps) {
- val bcNewCenters = data.context.broadcast(newCenters)
- bcNewCentersList += bcNewCenters
- val preCosts = costs
- costs = data.zip(preCosts).map { case (point, cost) =>
- math.min(KMeans.pointCost(bcNewCenters.value, point), cost)
- }.persist(StorageLevel.MEMORY_AND_DISK)
- val sumCosts = costs.sum()
-
- bcNewCenters.unpersist(blocking = false)
- preCosts.unpersist(blocking = false)
-
- val chosen = data.zip(costs).mapPartitionsWithIndex { (index, pointCosts) =>
- val rand = new XORShiftRandom(seed ^ (step << 16) ^ index)
- pointCosts.filter { case (_, c) => rand.nextDouble() < 2.0 * c * k / sumCosts }.map(_._1)
- }.collect()
- newCenters = chosen.map(_.toDense)
- centers ++= newCenters
- step += 1
- }
-
- costs.unpersist(blocking = false)
- bcNewCentersList.foreach(_.destroy(false))
-
- val distinctCenters = centers.map(_.vector).distinct.map(new VectorWithNorm(_))
-
- if (distinctCenters.size <= k) {
- distinctCenters.toArray
- } else {
- // Finally, we might have a set of more than k distinct candidate centers; weight each
- // candidate by the number of points in the dataset mapping to it and run a local k-means++
- // on the weighted centers to pick k of them
- val bcCenters = data.context.broadcast(distinctCenters)
- val countMap = data.map(KMeans.findClosest(bcCenters.value, _)._1).countByValue()
-
- bcCenters.destroy(blocking = false)
-
- val myWeights = distinctCenters.indices.map(countMap.getOrElse(_, 0L).toDouble).toArray
- LocalKMeansX.kMeansPlusPlus(0, distinctCenters.toArray, myWeights, k, 30)
- }
- }
-}
-
-
-/**
- * Top-level methods for calling K-means clustering.
- */
-@Since("0.8.0")
-object KMeans {
-
- // Initialization mode names
- @Since("0.8.0")
- val RANDOM = "random"
- @Since("0.8.0")
- val K_MEANS_PARALLEL = "k-means||"
-
- /**
- * Trains a k-means model using the given set of parameters.
- *
- * @param data Training points as an `RDD` of `Vector` types.
- * @param k Number of clusters to create.
- * @param maxIterations Maximum number of iterations allowed.
- * @param initializationMode The initialization algorithm. This can either be "random" or
- * "k-means||". (default: "k-means||")
- * @param seed Random seed for cluster initialization. Default is to generate seed based
- * on system time.
- */
- @Since("2.1.0")
- def train(
- data: RDD[Vector],
- k: Int,
- maxIterations: Int,
- initializationMode: String,
- seed: Long): KMeansModel = {
- new KMeans().setK(k)
- .setMaxIterations(maxIterations)
- .setInitializationMode(initializationMode)
- .setSeed(seed)
- .run(data)
- }
-
- /**
- * Trains a k-means model using the given set of parameters.
- *
- * @param data Training points as an `RDD` of `Vector` types.
- * @param k Number of clusters to create.
- * @param maxIterations Maximum number of iterations allowed.
- * @param initializationMode The initialization algorithm. This can either be "random" or
- * "k-means||". (default: "k-means||")
- */
- @Since("2.1.0")
- def train(
- data: RDD[Vector],
- k: Int,
- maxIterations: Int,
- initializationMode: String): KMeansModel = {
- new KMeans().setK(k)
- .setMaxIterations(maxIterations)
- .setInitializationMode(initializationMode)
- .run(data)
- }
-
- /**
- * Trains a k-means model using the given set of parameters.
- *
- * @param data Training points as an `RDD` of `Vector` types.
- * @param k Number of clusters to create.
- * @param maxIterations Maximum number of iterations allowed.
- * @param runs This param has no effect since Spark 2.0.0.
- * @param initializationMode The initialization algorithm. This can either be "random" or
- * "k-means||". (default: "k-means||")
- * @param seed Random seed for cluster initialization. Default is to generate seed based
- * on system time.
- */
- @Since("1.3.0")
- @deprecated("Use train method without 'runs'", "2.1.0")
- def train(
- data: RDD[Vector],
- k: Int,
- maxIterations: Int,
- runs: Int,
- initializationMode: String,
- seed: Long): KMeansModel = {
- new KMeans().setK(k)
- .setMaxIterations(maxIterations)
- .setInitializationMode(initializationMode)
- .setSeed(seed)
- .run(data)
- }
-
- /**
- * Trains a k-means model using the given set of parameters.
- *
- * @param data Training points as an `RDD` of `Vector` types.
- * @param k Number of clusters to create.
- * @param maxIterations Maximum number of iterations allowed.
- * @param runs This param has no effect since Spark 2.0.0.
- * @param initializationMode The initialization algorithm. This can either be "random" or
- * "k-means||". (default: "k-means||")
- */
- @Since("0.8.0")
- @deprecated("Use train method without 'runs'", "2.1.0")
- def train(
- data: RDD[Vector],
- k: Int,
- maxIterations: Int,
- runs: Int,
- initializationMode: String): KMeansModel = {
- new KMeans().setK(k)
- .setMaxIterations(maxIterations)
- .setInitializationMode(initializationMode)
- .run(data)
- }
-
- /**
- * Trains a k-means model using specified parameters and the default values for unspecified.
- */
- @Since("0.8.0")
- def train(
- data: RDD[Vector],
- k: Int,
- maxIterations: Int): KMeansModel = {
- new KMeans().setK(k)
- .setMaxIterations(maxIterations)
- .run(data)
- }
-
- /**
- * Trains a k-means model using specified parameters and the default values for unspecified.
- */
- @Since("0.8.0")
- @deprecated("Use train method without 'runs'", "2.1.0")
- def train(
- data: RDD[Vector],
- k: Int,
- maxIterations: Int,
- runs: Int): KMeansModel = {
- new KMeans().setK(k)
- .setMaxIterations(maxIterations)
- .run(data)
- }
-
- /**
- * Returns the index of the closest center to the given point, as well as the squared distance.
- */
- private[mllib] def findClosest(
- centers: TraversableOnce[VectorWithNorm],
- point: VectorWithNorm): (Int, Double) = {
- var bestDistance = Double.PositiveInfinity
- var bestIndex = 0
- var i = 0
- centers.foreach { center =>
- // Since `\|a - b\| \geq |\|a\| - \|b\||`, we can use this lower bound to avoid unnecessary
- // distance computation.
- var lowerBoundOfSqDist = center.norm - point.norm
- lowerBoundOfSqDist = lowerBoundOfSqDist * lowerBoundOfSqDist
- if (lowerBoundOfSqDist < bestDistance) {
- val distance: Double = fastSquaredDistance(center, point)
- if (distance < bestDistance) {
- bestDistance = distance
- bestIndex = i
- }
- }
- i += 1
- }
- (bestIndex, bestDistance)
- }
-
- /**
- * Returns the K-means cost of a given point against the given cluster centers.
- */
- private[mllib] def pointCost(
- centers: TraversableOnce[VectorWithNorm],
- point: VectorWithNorm): Double =
- findClosest(centers, point)._2
-
- /**
- * Returns the squared Euclidean distance between two vectors computed by
- * [[org.apache.spark.mllib.util.MLUtils#fastSquaredDistance]].
- */
- private[clustering] def fastSquaredDistance(
- v1: VectorWithNorm,
- v2: VectorWithNorm): Double = {
- MLUtils.fastSquaredDistance(v1.vector, v1.norm, v2.vector, v2.norm)
- }
-
- private[spark] def validateInitMode(initMode: String): Boolean = {
- initMode match {
- case KMeans.RANDOM => true
- case KMeans.K_MEANS_PARALLEL => true
- case _ => false
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDA.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDA.scala
index 35f087f..ea40a85 100644
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDA.scala
+++ b/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDA.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -27,7 +21,7 @@ import java.util.Locale
import breeze.linalg.{DenseVector => BDV}
-import org.apache.spark.annotation.{DeveloperApi, Since}
+import org.apache.spark.annotation.Since
import org.apache.spark.api.java.JavaPairRDD
import org.apache.spark.graphx._
import org.apache.spark.internal.Logging
@@ -288,21 +282,15 @@ class LDA private (
/**
- * :: DeveloperApi ::
- *
* LDAOptimizer used to perform the actual calculation
*/
@Since("1.4.0")
- @DeveloperApi
def getOptimizer: LDAOptimizer = ldaOptimizer
/**
- * :: DeveloperApi ::
- *
* LDAOptimizer used to perform the actual calculation (default = EMLDAOptimizer)
*/
@Since("1.4.0")
- @DeveloperApi
def setOptimizer(optimizer: LDAOptimizer): this.type = {
this.ldaOptimizer = optimizer
this
@@ -341,7 +329,7 @@ class LDA private (
val state = ldaOptimizer.initialize(documents, this)
timer.stop("initialize")
var iter = 0
- val iterationTimes = Array.fill[Double](maxIterations)(0)
+ val iterationTimes = Array.ofDim[Double](maxIterations)
timer.start("train")
LDAUtilsXOpt.init(documents.sparkContext)
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDAOptimizer.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDAOptimizer.scala
index 64edba0..42fd9de 100644
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDAOptimizer.scala
+++ b/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LDAOptimizer.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -29,20 +23,18 @@ import breeze.linalg.{all, sum, DenseMatrix => BDM, DenseVector => BDV}
import breeze.numerics.{abs, exp, trigamma}
import breeze.stats.distributions.{Gamma, RandBasis}
-import org.apache.spark.annotation.{DeveloperApi, Since}
+import org.apache.spark.annotation.Since
import org.apache.spark.internal.Logging
import org.apache.spark.ml.tree.impl.TimeTracker
import org.apache.spark.mllib.linalg.{DenseVector, Matrices, SparseVector, Vector, Vectors}
import org.apache.spark.rdd.RDD
+import org.apache.spark.storage.StorageLevel
/**
- * :: DeveloperApi ::
- *
* An LDAOptimizer specifies which optimization/learning/inference algorithm to use, and it can
* hold optimizer-specific parameters for users to set.
*/
@Since("1.4.0")
-@DeveloperApi
trait LDAOptimizer {
/*
@@ -67,8 +59,6 @@ trait LDAOptimizer {
}
/**
- * :: DeveloperApi ::
- *
* An online optimizer for LDA. The Optimizer implements the Online variational Bayes LDA
* algorithm, which processes a subset of the corpus on each iteration, and updates the term-topic
* distribution adaptively.
@@ -77,7 +67,6 @@ trait LDAOptimizer {
* Hoffman, Blei and Bach, "Online Learning for Latent Dirichlet Allocation." NIPS, 2010.
*/
@Since("1.4.0")
-@DeveloperApi
final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
// LDA common parameters
@@ -254,6 +243,10 @@ final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
this.randomGenerator = new Random(lda.getSeed)
this.docs = docs
+ if (this.docs.getStorageLevel == StorageLevel.NONE) {
+ logWarning("The input data is not directly cached, which may hurt performance if its"
+ + " parent RDDs are also uncached.")
+ }
// Initialize the variational distribution q(beta|lambda)
this.lambda = getGammaMatrix(k, vocabSize)
@@ -296,9 +289,10 @@ final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
val alpha = this.alpha.asBreeze
val gammaShape = this.gammaShape
val optimizeDocConcentration = this.optimizeDocConcentration
+ val seed = randomGenerator.nextLong()
// If and only if optimizeDocConcentration is set true,
// we calculate logphat in the same pass as other statistics.
- // No calculation of loghat happens otherwise.
+ // No calculation of logphat happens otherwise.
val logphatPartOptionBase = () => if (optimizeDocConcentration) {
Some(BDV.zeros[Double](k))
} else {
@@ -309,9 +303,10 @@ final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
val stats: RDD[(BDM[Double], Option[BDV[Double]], Long)] =
if (LDAUtilsXOpt.useOptimizedCalc()) {
LDAUtilsXOpt.optimizedCalcStats(batch, expElogbetaBc, k, vocabSize, logphatPartOptionBase,
- alpha, gammaShape)
+ alpha, gammaShape, seed)
} else {
- batch.mapPartitions { docs =>
+ batch.mapPartitionsWithIndex {
+ (index, docs) =>
val nonEmptyDocs = docs.filter(_._2.numNonzeros > 0)
val stat = BDM.zeros[Double](k, vocabSize)
@@ -321,7 +316,7 @@ final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
nonEmptyDocs.foreach { case (_, termCounts: Vector) =>
nonEmptyDocCount += 1
val (gammad, sstats, ids) = OnlineLDAOptimizerXObj.variationalTopicInference(
- termCounts, expElogbetaBcValue, alpha, gammaShape, k)
+ termCounts, expElogbetaBcValue, alpha, gammaShape, k, seed + index)
stat(::, ids) := stat(::, ids) + sstats
logphatPartOption.foreach(_ += LDAUtilsX.dirichletExpectation(gammad))
}
@@ -357,6 +352,7 @@ final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
if (nonEmptyDocsN == 0) {
logWarning("No non-empty documents were submitted in the batch.")
+ timer.stop("update-lambda")
// Therefore, there is no need to update any of the model parameters
return this
}
@@ -439,7 +435,8 @@ final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
}
override private[clustering] def getLDAModel(iterationTimes: Array[Double]): LDAModel = {
- new LocalLDAModel(Matrices.fromBreeze(lambda).transpose, alpha, eta, gammaShape)
+ new LocalLDAModel(Matrices.fromBreeze(lambda).transpose, alpha, eta)
+ .setSeed(randomGenerator.nextLong())
}
}
@@ -448,7 +445,7 @@ final class OnlineLDAOptimizer extends LDAOptimizer with Logging {
* Serializable companion object containing helper methods and shared code for
* [[OnlineLDAOptimizer]] and [[LocalLDAModel]].
*/
-private[clustering] object OnlineLDAOptimizer {
+private[spark] object OnlineLDAOptimizer {
/**
* Uses variational inference to infer the topic distribution `gammad` given the term counts
* for a document. `termCounts` must contain at least one non-zero entry, otherwise Breeze will
@@ -461,25 +458,24 @@ private[clustering] object OnlineLDAOptimizer {
* @return Returns a tuple of `gammad` - estimate of gamma, the topic distribution, `sstatsd` -
* statistics for updating lambda and `ids` - list of termCounts vector indices.
*/
- private[clustering] def variationalTopicInference(
- termCounts: Vector,
+ private[spark] def variationalTopicInference(
+ indices: List[Int],
+ values: Array[Double],
expElogbeta: BDM[Double],
alpha: breeze.linalg.Vector[Double],
gammaShape: Double,
- k: Int): (BDV[Double], BDM[Double], List[Int]) = {
- val (ids: List[Int], cts: Array[Double]) = termCounts match {
- case v: DenseVector => ((0 until v.size).toList, v.values)
- case v: SparseVector => (v.indices.toList, v.values)
- }
+ k: Int,
+ seed: Long): (BDV[Double], BDM[Double], List[Int]) = {
// Initialize the variational distribution q(theta|gamma) for the mini-batch
+ val randBasis = new RandBasis(new org.apache.commons.math3.random.MersenneTwister(seed))
val gammad: BDV[Double] =
- new Gamma(gammaShape, 1.0 / gammaShape).samplesVector(k) // K
+ new Gamma(gammaShape, 1.0 / gammaShape)(randBasis).samplesVector(k) // K
val expElogthetad: BDV[Double] = exp(LDAUtils.dirichletExpectation(gammad)) // K
- val expElogbetad = expElogbeta(ids, ::).toDenseMatrix // ids * K
+ val expElogbetad = expElogbeta(indices, ::).toDenseMatrix // ids * K
val phiNorm: BDV[Double] = expElogbetad * expElogthetad +:+ 1e-100 // ids
var meanGammaChange = 1D
- val ctsVector = new BDV[Double](cts) // ids
+ val ctsVector = new BDV[Double](values) // ids
// Iterate between gamma and phi until convergence
while (meanGammaChange > 1e-3) {
@@ -493,6 +489,20 @@ private[clustering] object OnlineLDAOptimizer {
}
val sstatsd = expElogthetad.asDenseMatrix.t * (ctsVector /:/ phiNorm).asDenseMatrix
- (gammad, sstatsd, ids)
+ (gammad, sstatsd, indices)
+ }
+
+ private[clustering] def variationalTopicInference(
+ termCounts: Vector,
+ expElogbeta: BDM[Double],
+ alpha: breeze.linalg.Vector[Double],
+ gammaShape: Double,
+ k: Int,
+ seed: Long): (BDV[Double], BDM[Double], List[Int]) = {
+ val (ids: List[Int], cts: Array[Double]) = termCounts match {
+ case v: DenseVector => (List.range(0, v.size), v.values)
+ case v: SparseVector => (v.indices.toList, v.values)
+ }
+ variationalTopicInference(ids, cts, expElogbeta, alpha, gammaShape, k, seed)
}
}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LocalKMeansX.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LocalKMeansX.scala
deleted file mode 100644
index 4d7c18a..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/clustering/LocalKMeansX.scala
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * 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.clustering
-
-import scala.util.Random
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.mllib.linalg.BLAS.{axpy, scal}
-import org.apache.spark.mllib.linalg.Vectors
-import org.apache.spark.sql.SparkSession
-
-/**
- * An utility object to run K-means locally. This is private to the ML package because it's used
- * in the initialization of KMeans but not meant to be publicly exposed.
- */
-private[mllib] object LocalKMeansX extends Logging {
-
- /**
- * Run K-means++ on the weighted point set `points`. This first does the K-means++
- * initialization procedure and then rounds of Lloyd's algorithm.
- */
- def kMeansPlusPlus(
- seed: Int,
- points: Array[VectorWithNorm],
- weights: Array[Double],
- k: Int,
- maxIterations: Int
- ): Array[VectorWithNorm] = {
- val DEFAULT_PAR_LEVEL = 100
- val rand = new Random(seed)
- val dimensions = points(0).vector.size
- val centers = new Array[VectorWithNorm](k)
-
- // Initialize centers by sampling using the k-means++ procedure.
- centers(0) = pickWeighted(rand, points, weights).toDense
- var costArray = points.map(KMeans.fastSquaredDistance(_, centers(0)))
-
- var customParLevel = DEFAULT_PAR_LEVEL
- try{
- customParLevel = SparkSession.builder().getOrCreate()
- .sparkContext.getConf.getInt("spark.boostkit.Kmeans.parLevel",
- DEFAULT_PAR_LEVEL)
- if (customParLevel < 1) {
- throw new Exception
- }
- }
- catch {
- case x: Exception =>
- throw new Exception("'spark.boostkit.Kmeans.parLevel' value is invalid")
- }
- val customForkJoinPool = new scala.concurrent.forkjoin.ForkJoinPool(customParLevel)
- val customTaskSupport = new scala.collection.parallel.ForkJoinTaskSupport(customForkJoinPool)
-
- for (i <- 1 until k) {
- val sum = costArray.zip(weights).map(p => p._1 * p._2).sum
- val r = rand.nextDouble() * sum
- var cumulativeScore = 0.0
- var j = 0
- while (j < points.length && cumulativeScore < r) {
- cumulativeScore += weights(j) * costArray(j)
- j += 1
- }
- if (j == 0) {
- logWarning("kMeansPlusPlus initialization ran out of distinct points for centers." +
- s" Using duplicate point for center k = $i.")
- centers(i) = points(0).toDense
- } else {
- centers(i) = points(j - 1).toDense
- }
-
- val costArrayPar = points.zipWithIndex.par
- costArrayPar.tasksupport = customTaskSupport
- costArray = costArrayPar.map{
- t =>
- math.min(KMeans.fastSquaredDistance(points(t._2), centers(i)), costArray(t._2))
- }.toArray
- }
-
- // Run up to maxIterations iterations of Lloyd's algorithm
- val oldClosest = Array.fill(points.length)(-1)
- var iteration = 0
- var moved = true
- while (moved && iteration < maxIterations) {
- moved = false
- val counts = Array.fill(k)(0.0)
- val sums = Array.fill(k)(Vectors.zeros(dimensions))
-
- val assignPar = points.par
- assignPar.tasksupport = customTaskSupport
- val assign = assignPar.map{
- case point =>
- val index = KMeans.findClosest(centers, point)._1
- (point, index)
- }.toArray
-
- var idx = 0
- while(idx < assign.size) {
- val index = assign(idx)._2
- if (index != oldClosest(idx)) {
- moved = true
- oldClosest(idx) = index
- }
- axpy(weights(idx), assign(idx)._1.vector, sums(index))
- counts(index) += weights(idx)
- idx += 1
- }
-
- // Update centers
- var j = 0
- while (j < k) {
- if (counts(j) == 0.0) {
- // Assign center to a random point
- centers(j) = points(rand.nextInt(points.length)).toDense
- } else {
- scal(1.0 / counts(j), sums(j))
- centers(j) = new VectorWithNorm(sums(j))
- }
- j += 1
- }
- iteration += 1
- }
-
- if (iteration == maxIterations) {
- logInfo(s"Local KMeans++ reached the max number of iterations: $maxIterations.")
- } else {
- logInfo(s"Local KMeans++ converged in $iteration iterations.")
- }
- centers
- }
-
- private def pickWeighted[T](rand: Random, data: Array[T], weights: Array[Double]): T = {
- val r = rand.nextDouble() * weights.sum
- var i = 0
- var curWeight = 0.0
- while (i < data.length && curWeight < r) {
- curWeight += weights(i)
- i += 1
- }
- data(i - 1)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/feature/IDF.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/feature/IDF.scala
deleted file mode 100644
index f633c1b..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/feature/IDF.scala
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * 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.feature
-
-import breeze.linalg.{DenseVector => BDV}
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.api.java.JavaRDD
-import org.apache.spark.mllib.linalg.{DenseVector, SparseVector, Vector, Vectors}
-import org.apache.spark.rdd.RDD
-
-/**
- * Inverse document frequency (IDF).
- * The standard formulation is used: `idf = log((m + 1) / (d(t) + 1))`, where `m` is the total
- * number of documents and `d(t)` is the number of documents that contain term `t`.
- *
- * This implementation supports filtering out terms which do not appear in a minimum number
- * of documents (controlled by the variable `minDocFreq`). For terms that are not in
- * at least `minDocFreq` documents, the IDF is found as 0, resulting in TF-IDFs of 0.
- *
- * @param minDocFreq minimum of documents in which a term
- * should appear for filtering
- */
-@Since("1.1.0")
-class IDF @Since("1.2.0") (@Since("1.2.0") val minDocFreq: Int) {
-
- @Since("1.1.0")
- def this() = this(0)
-
- // TODO: Allow different IDF formulations.
-
- /**
- * Computes the inverse document frequency.
- * @param dataset an RDD of term frequency vectors
- */
- @Since("1.1.0")
- def fit(dataset: RDD[Vector]): IDFModel = {
- val (idf, docFreq, numDocs) = IDFUtils.train(dataset, minDocFreq)
- new IDFModel(idf)
- }
-
- /**
- * Computes the inverse document frequency.
- * @param dataset a JavaRDD of term frequency vectors
- */
- @Since("1.1.0")
- def fit(dataset: JavaRDD[Vector]): IDFModel = {
- fit(dataset.rdd)
- }
-}
-
-private object IDF {
-
- /** Document frequency aggregator. */
- class DocumentFrequencyAggregator(val minDocFreq: Int) extends Serializable {
-
- /** number of documents */
- private var m = 0L
- /** document frequency vector */
- private var df: BDV[Long] = _
-
-
- def this() = this(0)
-
- /** Adds a new document. */
- def add(doc: Vector): this.type = {
- if (isEmpty) {
- df = BDV.zeros(doc.size)
- }
- doc match {
- case SparseVector(size, indices, values) =>
- val nnz = indices.length
- var k = 0
- while (k < nnz) {
- if (values(k) > 0) {
- df(indices(k)) += 1L
- }
- k += 1
- }
- case DenseVector(values) =>
- val n = values.length
- var j = 0
- while (j < n) {
- if (values(j) > 0.0) {
- df(j) += 1L
- }
- j += 1
- }
- case other =>
- throw new UnsupportedOperationException(
- s"Only sparse and dense vectors are supported but got ${other.getClass}.")
- }
- m += 1L
- this
- }
-
- /** Merges another. */
- def merge(other: DocumentFrequencyAggregator): this.type = {
- if (!other.isEmpty) {
- m += other.m
- if (df == null) {
- df = other.df.copy
- } else {
- df += other.df
- }
- }
- this
- }
-
- private def isEmpty: Boolean = m == 0L
-
- /** Returns the current IDF vector. */
- def idf(): Vector = {
- if (isEmpty) {
- throw new IllegalStateException("Haven't seen any document yet.")
- }
- val n = df.length
- val inv = new Array[Double](n)
- var j = 0
- while (j < n) {
- /*
- * If the term is not present in the minimum
- * number of documents, set IDF to 0. This
- * will cause multiplication in IDFModel to
- * set TF-IDF to 0.
- *
- * Since arrays are initialized to 0 by default,
- * we just omit changing those entries.
- */
- if (df(j) >= minDocFreq) {
- inv(j) = math.log((m + 1.0) / (df(j) + 1.0))
- }
- j += 1
- }
- Vectors.dense(inv)
- }
- }
-}
-
-/**
- * Represents an IDF model that can transform term frequency vectors.
- */
-@Since("1.1.0")
-class IDFModel private[spark] (@Since("1.1.0") val idf: Vector) extends Serializable {
-
- /**
- * Transforms term frequency (TF) vectors to TF-IDF vectors.
- *
- * If `minDocFreq` was set for the IDF calculation,
- * the terms which occur in fewer than `minDocFreq`
- * documents will have an entry of 0.
- *
- * @param dataset an RDD of term frequency vectors
- * @return an RDD of TF-IDF vectors
- */
- @Since("1.1.0")
- def transform(dataset: RDD[Vector]): RDD[Vector] = {
- val bcIdf = dataset.context.broadcast(idf)
- dataset.mapPartitions(iter => iter.map(v => IDFModel.transform(bcIdf.value, v)))
- }
-
- /**
- * Transforms a term frequency (TF) vector to a TF-IDF vector
- *
- * @param v a term frequency vector
- * @return a TF-IDF vector
- */
- @Since("1.3.0")
- def transform(v: Vector): Vector = IDFModel.transform(idf, v)
-
- /**
- * Transforms term frequency (TF) vectors to TF-IDF vectors (Java version).
- * @param dataset a JavaRDD of term frequency vectors
- * @return a JavaRDD of TF-IDF vectors
- */
- @Since("1.1.0")
- def transform(dataset: JavaRDD[Vector]): JavaRDD[Vector] = {
- transform(dataset.rdd).toJavaRDD()
- }
-}
-
-private object IDFModel {
-
- /**
- * Transforms a term frequency (TF) vector to a TF-IDF vector with a IDF vector
- *
- * @param idf an IDF vector
- * @param v a term frequency vector
- * @return a TF-IDF vector
- */
- def transform(idf: Vector, v: Vector): Vector = {
- val n = v.size
- v match {
- case SparseVector(size, indices, values) =>
- val nnz = indices.length
- val newValues = new Array[Double](nnz)
- var k = 0
- while (k < nnz) {
- newValues(k) = values(k) * idf(indices(k))
- k += 1
- }
- Vectors.sparse(n, indices, newValues)
- case DenseVector(values) =>
- val newValues = new Array[Double](n)
- var j = 0
- while (j < n) {
- newValues(j) = values(j) * idf(j)
- j += 1
- }
- Vectors.dense(newValues)
- case other =>
- throw new UnsupportedOperationException(
- s"Only sparse and dense vectors are supported but got ${other.getClass}.")
- }
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpan.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpan.scala
index 0a30a2e..23fabc6 100644
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpan.scala
+++ b/ml-accelerator/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpan.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -40,12 +34,11 @@ import org.apache.spark.storage.StorageLevel
* A parallel PrefixSpan algorithm to mine frequent sequential patterns.
* The PrefixSpan algorithm is described in J. Pei, et al., PrefixSpan: Mining Sequential Patterns
* Efficiently by Prefix-Projected Pattern Growth
- * (see here ).
+ * (see here ).
*
* @param minSupport the minimal support level of the sequential pattern, any pattern that appears
* more than (minSupport * size-of-the-dataset) times will be output
- * @param maxPatternLength the maximal length of the sequential pattern, any pattern that appears
- * less than maxPatternLength will be output
+ * @param maxPatternLength the maximal length of the sequential pattern
* @param maxLocalProjDBSize The maximum number of items (including delimiters used in the internal
* storage format) allowed in a projected database before local
* processing. If a projected database exceeds this size, another
@@ -170,6 +163,13 @@ class PrefixSpan private (
val freqSequences = results.map { case (seq: Array[Int], count: Long) =>
new FreqSequence(toPublicRepr(seq), count)
}
+ // Cache the final RDD to the same storage level as input
+ if (data.getStorageLevel != StorageLevel.NONE) {
+ freqSequences.persist(data.getStorageLevel)
+ freqSequences.count()
+ }
+ dataInternalRepr.unpersist()
+
new PrefixSpanModel(freqSequences)
}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/linalg/EigenValueDecomposition.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/linalg/EigenValueDecomposition.scala
deleted file mode 100644
index d121ad1..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/linalg/EigenValueDecomposition.scala
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.linalg
-
-import breeze.linalg.{DenseMatrix => BDM, DenseMatrixUtil, DenseVector => BDV}
-import breeze.linalg.blas.Dgemv
-import com.github.fommil.netlib.ARPACK
-import org.netlib.util.{doubleW, intW}
-
-/**
- * Compute eigen-decomposition.
- */
-private[mllib] object EigenValueDecomposition {
-
- private val DEFAULT_THREAD_NUM = 35
-
- /**
- * Compute the leading k eigenvalues and eigenvectors on a symmetric square matrix using ARPACK.
- * The caller needs to ensure that the input matrix is real symmetric. This function requires
- * memory for `n*(4*k+4)` doubles.
- *
- * @param mul a function that multiplies the symmetric matrix with a DenseVector.
- * @param n dimension of the square matrix (maximum Int.MaxValue).
- * @param k number of leading eigenvalues required, where k must be positive and less than n.
- * @param tol tolerance of the eigs computation.
- * @param maxIterations the maximum number of Arnoldi update iterations.
- * @return a dense vector of eigenvalues in descending order and a dense matrix of eigenvectors
- * (columns of the matrix).
- * @note The number of computed eigenvalues might be smaller than k when some Ritz values do not
- * satisfy the convergence criterion specified by tol (see ARPACK Users Guide, Chapter 4.6
- * for more details). The maximum number of Arnoldi update iterations is set to 300 in this
- * function.
- */
- def symmetricEigs(
- mul: BDV[Double] => BDV[Double],
- n: Int,
- k: Int,
- tol: Double,
- maxIterations: Int): (BDV[Double], BDM[Double]) = {
- // TODO: remove this function and use eigs in breeze when switching breeze version
- require(n > k, s"Number of required eigenvalues $k must be smaller than matrix dimension $n")
-
- val arpack = ARPACK.getInstance()
-
- // tolerance used in stopping criterion
- val tolW = new doubleW(tol)
- // number of desired eigenvalues, 0 < nev < n
- val nev = new intW(k)
- // nev Lanczos vectors are generated in the first iteration
- // ncv-nev Lanczos vectors are generated in each subsequent iteration
- // ncv must be smaller than n
- val ncv = math.min(2 * k, n)
-
- // "I" for standard eigenvalue problem, "G" for generalized eigenvalue problem
- val bmat = "I"
- // "LM" : compute the NEV largest (in magnitude) eigenvalues
- val which = "LM"
-
- var iparam = new Array[Int](11)
- // use exact shift in each iteration
- iparam(0) = 1
- // maximum number of Arnoldi update iterations, or the actual number of iterations on output
- iparam(2) = maxIterations
- // Mode 1: A*x = lambda*x, A symmetric
- iparam(6) = 1
-
- require(n * ncv.toLong <= Integer.MAX_VALUE && ncv * (ncv.toLong + 8) <= Integer.MAX_VALUE,
- s"k = $k and/or n = $n are too large to compute an eigendecomposition")
-
- val ido = new intW(0)
- val info = new intW(0)
- val resid = new Array[Double](n)
- val v = new Array[Double](n * ncv)
- val workd = new Array[Double](n * 3)
- val workl = new Array[Double](ncv * (ncv + 8))
- val ipntr = new Array[Int](11)
-
- // call ARPACK's reverse communication, first iteration with ido = 0
- arpack.dsaupd(ido, bmat, n, which, nev.`val`, tolW, resid, ncv, v, n, iparam, ipntr, workd,
- workl, workl.length, info)
-
- val w = BDV(workd)
-
- // ido = 99 : done flag in reverse communication
- while (ido.`val` != 99) {
- if (ido.`val` != -1 && ido.`val` != 1) {
- throw new IllegalStateException("ARPACK returns ido = " + ido.`val` +
- " This flag is not compatible with Mode 1: A*x = lambda*x, A symmetric.")
- }
- // multiply working vector with the matrix
- val inputOffset = ipntr(0) - 1
- val outputOffset = ipntr(1) - 1
- val x = w.slice(inputOffset, inputOffset + n)
- val y = w.slice(outputOffset, outputOffset + n)
- y := mul(x)
- // call ARPACK's reverse communication
- arpack.dsaupd(ido, bmat, n, which, nev.`val`, tolW, resid, ncv, v, n, iparam, ipntr,
- workd, workl, workl.length, info)
- }
-
- if (info.`val` != 0) {
- info.`val` match {
- case 1 => throw new IllegalStateException("ARPACK returns non-zero info = " + info.`val` +
- " Maximum number of iterations taken. (Refer ARPACK user guide for details)")
- case 3 => throw new IllegalStateException("ARPACK returns non-zero info = " + info.`val` +
- " No shifts could be applied. Try to increase NCV. " +
- "(Refer ARPACK user guide for details)")
- case _ => throw new IllegalStateException("ARPACK returns non-zero info = " + info.`val` +
- " Please refer ARPACK user guide for error message.")
- }
- }
-
- val d = new Array[Double](nev.`val`)
- val select = new Array[Boolean](ncv)
- // copy the Ritz vectors
- val z = java.util.Arrays.copyOfRange(v, 0, nev.`val` * n)
-
- // call ARPACK's post-processing for eigenvectors
- arpack.dseupd(true, "A", select, d, z, n, 0.0, bmat, n, which, nev, tol, resid, ncv, v, n,
- iparam, ipntr, workd, workl, workl.length, info)
-
- // number of computed eigenvalues, might be smaller than k
- val computed = iparam(4)
-
- val eigenPairs = java.util.Arrays.copyOfRange(d, 0, computed).zipWithIndex.map { r =>
- (r._1, java.util.Arrays.copyOfRange(z, r._2 * n, r._2 * n + n))
- }
-
- // sort the eigen-pairs in descending order
- val sortedEigenPairs = eigenPairs.sortBy(- _._1)
-
- // copy eigenvectors in descending order of eigenvalues
- val sortedU = BDM.zeros[Double](n, computed)
- sortedEigenPairs.zipWithIndex.foreach { r =>
- val b = r._2 * n
- var i = 0
- while (i < n) {
- sortedU.data(b + i) = r._1._2(i)
- i += 1
- }
- }
-
- (BDV[Double](sortedEigenPairs.map(_._1)), sortedU)
- }
-
- def symmetricEigsLocal(
- matrix: BDM[Double],
- n: Int,
- k: Int,
- tol: Double,
- maxIterations: Int,
- driverCores: Int): (BDV[Double], BDM[Double]) = {
- // TODO: remove this function and use eigs in breeze when switching breeze version
- require(n > k, s"Number of required eigenvalues $k must be smaller than matrix dimension $n")
-
- val threadNum = math.min(
- if (driverCores < 2) DEFAULT_THREAD_NUM else driverCores, matrix.rows)
- val blocks = DenseMatrixUtil.blockByRow(matrix, threadNum)
-
- val arpack = ARPACK.getInstance()
-
- // tolerance used in stopping criterion
- val tolW = new doubleW(tol)
- // number of desired eigenvalues, 0 < nev < n
- val nev = new intW(k)
- // nev Lanczos vectors are generated in the first iteration
- // ncv-nev Lanczos vectors are generated in each subsequent iteration
- // ncv must be smaller than n
- val ncv = math.min(2 * k, n)
-
- // "I" for standard eigenvalue problem, "G" for generalized eigenvalue problem
- val bmat = "I"
- // "LM" : compute the NEV largest (in magnitude) eigenvalues
- val which = "LM"
-
- var iparam = new Array[Int](11)
- // use exact shift in each iteration
- iparam(0) = 1
- // maximum number of Arnoldi update iterations, or the actual number of iterations on output
- iparam(2) = maxIterations
- // Mode 1: A*x = lambda*x, A symmetric
- iparam(6) = 1
-
- require(n * ncv.toLong <= Integer.MAX_VALUE && ncv * (ncv.toLong + 8) <= Integer.MAX_VALUE,
- s"k = $k and/or n = $n are too large to compute an eigendecomposition")
-
- val ido = new intW(0)
- val info = new intW(0)
- val resid = new Array[Double](n)
- val v = new Array[Double](n * ncv)
- val workd = new Array[Double](n * 3)
- val workl = new Array[Double](ncv * (ncv + 8))
- val ipntr = new Array[Int](11)
-
- // call ARPACK's reverse communication, first iteration with ido = 0
- arpack.dsaupd(ido, bmat, n, which, nev.`val`, tolW, resid, ncv, v, n, iparam, ipntr, workd,
- workl, workl.length, info)
-
- val w = BDV(workd)
-
- // ido = 99 : done flag in reverse communication
- while (ido.`val` != 99) {
- if (ido.`val` != -1 && ido.`val` != 1) {
- throw new IllegalStateException("ARPACK returns ido = " + ido.`val` +
- " This flag is not compatible with Mode 1: A*x = lambda*x, A symmetric.")
- }
-
- // multiply working vector with the matrix
- val inputOffset = ipntr(0) - 1
- val outputOffset = ipntr(1) - 1
- val input = w.slice(inputOffset, inputOffset + n)
- val output = Dgemv.compute(blocks, input)
- System.arraycopy(output.data, 0, workd, outputOffset, n)
-
- // call ARPACK's reverse communication
- arpack.dsaupd(ido, bmat, n, which, nev.`val`, tolW, resid, ncv, v, n, iparam, ipntr,
- workd, workl, workl.length, info)
- }
-
- if (info.`val` != 0) {
- info.`val` match {
- case 1 => throw new IllegalStateException("ARPACK returns non-zero info = " + info.`val` +
- " Maximum number of iterations taken. (Refer ARPACK user guide for details)")
- case 3 => throw new IllegalStateException("ARPACK returns non-zero info = " + info.`val` +
- " No shifts could be applied. Try to increase NCV. " +
- "(Refer ARPACK user guide for details)")
- case _ => throw new IllegalStateException("ARPACK returns non-zero info = " + info.`val` +
- " Please refer ARPACK user guide for error message.")
- }
- }
-
- val d = new Array[Double](nev.`val`)
- val select = new Array[Boolean](ncv)
- // copy the Ritz vectors
- val z = java.util.Arrays.copyOfRange(v, 0, nev.`val` * n)
-
- // call ARPACK's post-processing for eigenvectors
- arpack.dseupd(true, "A", select, d, z, n, 0.0, bmat, n, which, nev, tol, resid, ncv, v, n,
- iparam, ipntr, workd, workl, workl.length, info)
-
- // number of computed eigenvalues, might be smaller than k
- val computed = iparam(4)
-
- val eigenPairs = java.util.Arrays.copyOfRange(d, 0, computed).zipWithIndex.map { r =>
- (r._1, java.util.Arrays.copyOfRange(z, r._2 * n, r._2 * n + n))
- }
-
- // sort the eigen-pairs in descending order
- val sortedEigenPairs = eigenPairs.sortBy(- _._1)
-
- // copy eigenvectors in descending order of eigenvalues
- val sortedU = BDM.zeros[Double](n, computed)
- sortedEigenPairs.zipWithIndex.foreach { r =>
- val b = r._2 * n
- var i = 0
- while (i < n) {
- sortedU.data(b + i) = r._1._2(i)
- i += 1
- }
- }
-
- (BDV[Double](sortedEigenPairs.map(_._1)), sortedU)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/linalg/distributed/RowMatrix.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/linalg/distributed/RowMatrix.scala
deleted file mode 100644
index 0d62720..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/linalg/distributed/RowMatrix.scala
+++ /dev/null
@@ -1,910 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.linalg.distributed
-
-
-import java.util.Arrays
-
-import scala.collection.mutable.ListBuffer
-
-import breeze.linalg.{axpy => brzAxpy, inv, DenseMatrix => BDM, DenseVector => BDV, MatrixSingularException, SparseVector => BSV}
-import breeze.linalg.blas.Gramian
-import breeze.linalg.lapack.EigenDecomposition
-import breeze.linalg.lapack.EigenDecomposition.Eigen
-import breeze.numerics.{sqrt => brzSqrt}
-import com.github.fommil.netlib.BLAS.{getInstance => blas}
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.StaticUtils
-import org.apache.spark.mllib.feature.SPCA
-import org.apache.spark.mllib.linalg._
-import org.apache.spark.mllib.stat.{MultivariateOnlineSummarizer, MultivariateStatisticalSummary, Statistics}
-import org.apache.spark.rdd.RDD
-import org.apache.spark.storage.StorageLevel
-import org.apache.spark.util.random.XORShiftRandom
-
-
-
-/**
- * Represents a row-oriented distributed Matrix with no meaningful row indices.
- *
- * @param rows rows stored as an RDD[Vector]
- * @param nRows number of rows. A non-positive value means unknown, and then the number of rows will
- * be determined by the number of records in the RDD `rows`.
- * @param nCols number of columns. A non-positive value means unknown, and then the number of
- * columns will be determined by the size of the first row.
- */
-@Since("1.0.0")
-class RowMatrix @Since("1.0.0")(
- @Since("1.0.0") val rows: RDD[Vector],
- private var nRows: Long,
- private var nCols: Int) extends DistributedMatrix with Logging {
-
- /** Alternative constructor leaving matrix dimensions to be determined automatically. */
- @Since("1.0.0")
- def this(rows: RDD[Vector]) = this(rows, 0L, 0)
-
- /** Gets or computes the number of columns. */
- @Since("1.0.0")
- override def numCols(): Long = {
- if (nCols <= 0) {
- try {
- // Calling `first` will throw an exception if `rows` is empty.
- nCols = rows.first().size
- } catch {
- case err: UnsupportedOperationException =>
- sys.error("Cannot determine the number of cols because it is not specified in the " +
- "constructor and the rows RDD is empty.")
- }
- }
- nCols
- }
-
- /** Gets or computes the number of rows. */
- @Since("1.0.0")
- override def numRows(): Long = {
- if (nRows <= 0L) {
- nRows = rows.count()
- if (nRows == 0L) {
- sys.error("Cannot determine the number of rows because it is not specified in the " +
- "constructor and the rows RDD is empty.")
- }
- }
- nRows
- }
-
- /**
- * Multiplies the Gramian matrix `A^T A` by a dense vector on the right without computing `A^T A`.
- *
- * @param v a dense vector whose length must match the number of columns of this matrix
- * @return a dense vector representing the product
- */
- private[mllib] def multiplyGramianMatrixBy(v: BDV[Double]): BDV[Double] = {
- val n = numCols().toInt
- val vbr = rows.context.broadcast(v)
- rows.treeAggregate(BDV.zeros[Double](n))(
- seqOp = (U, r) => {
- val rBrz = r.asBreeze
- val a = rBrz.dot(vbr.value)
- rBrz match {
- // use specialized axpy for better performance
- case _: BDV[_] => brzAxpy(a, rBrz.asInstanceOf[BDV[Double]], U)
- case _: BSV[_] => brzAxpy(a, rBrz.asInstanceOf[BSV[Double]], U)
- case _ => throw new UnsupportedOperationException(
- s"Do not support vector operation from type ${rBrz.getClass.getName}.")
- }
- U
- }, combOp = (U1, U2) => U1 += U2)
- }
-
- /**
- * Computes the Gramian matrix `A^T A`.
- *
- * @note This cannot be computed on matrices with more than 65535 columns.
- */
- @Since("1.0.0")
- def computeGramianMatrix(): Matrix = {
- if (rows.map(_.isInstanceOf[SparseVector]).reduce((x, y) => x && y)) {
- RowMatrixUtil.computeGramMatrixAsDenseMatrix(
- rows.map(_.asInstanceOf[SparseVector]), numCols().toInt)
- } else {
- computeDenseGramianMatrix()
- }
- }
-
-
- /**
- * Compute the leading k eigenvalues and eigenvectors on a symmetric square sparse matrix.
- *
- * @param n dimension of the square matrix (maximum Int.MaxValue).
- * @param k number of leading eigenvalues required, where k must be positive and less than n.
- * @param tol tolerance of the eigs computation.
- * @param maxIter the maximum number of Arnoldi update iterations.
- * @return a dense vector of eigenvalues in descending order and a dense matrix of eigenvectors
- * (columns of the matrix).
- * @note The number of computed eigenvalues might be smaller than k when some Ritz values do not
- * satisfy the convergence criterion specified by tol (see ARPACK Users Guide, Chapter 4.6
- * for more details). The maximum number of Arnoldi update iterations is set to 300 in this
- * function.
- */
- def eigenValueDecompositionOnSparseMatrix(
- n: Int,
- k: Int,
- tol: Double,
- maxIter: Int): (BDV[Double], BDM[Double]) = {
- val result = RowMatrixUtil.computeGramMatrix(
- rows.map(_.asInstanceOf[SparseVector]), n)
- EigenValueDecomposition.symmetricEigs(
- RowMatrixUtil.multiplySparseGramMatrixBy(result),
- n, k, tol, maxIter)
- }
-
- /**
- * Compute the leading k eigenvalues and eigenvectors on a symmetric square dense matrix.
- *
- * @param n dimension of the square matrix (maximum Int.MaxValue).
- * @param k number of leading eigenvalues required, where k must be positive and less than n.
- * @param tol tolerance of the eigs computation.
- * @param maxIter the maximum number of Arnoldi update iterations.
- * @return a dense vector of eigenvalues in descending order and a dense matrix of eigenvectors
- * (columns of the matrix).
- */
- def eigenValueDecompositionOnDenseMatrix(
- n: Int,
- k: Int,
- tol: Double,
- maxIter: Int): (BDV[Double], BDM[Double]) = {
- val result = RowMatrixUtil.computeGramMatrix(
- rows.map(_.asInstanceOf[SparseVector]), n)
- val resultDenseMatrix = result._3.map{case ((i, j), sp) =>
- ((i, j), new BDM[Double](sp.numRows, sp.numCols, sp.toArray))}
- val newResult = (result._1, result._2, resultDenseMatrix)
- EigenValueDecomposition.symmetricEigs(
- RowMatrixUtil.multiplyDenseGramMatrixBy(newResult),
- n, k, tol, maxIter)
- }
-
- /**
- * Computes the Gramian matrix `A^T A` of dense matrix.
- * @return Gramian matrix
- */
- def computeDenseGramianMatrix(): Matrix = {
- val n = numCols().toInt
- checkNumColumns(n)
-
- // compute the upper triangular matrix
- val gramianLen = n * (n + 1) / 2
- val gramian = rows.mapPartitions(iter => {
- val subMatrixValues = iter.map(_.toArray).toArray
- val subMatrixRow = subMatrixValues.length
- val localCovariance = new Array[Double](gramianLen)
- Gramian.compute(subMatrixValues.flatten, localCovariance, subMatrixRow, n)
- Array(localCovariance).iterator
- }).treeReduce((cov1, cov2) => {
- blas.daxpy(cov1.length, 1.0, cov2, 1, cov1, 1)
- cov1
- }, depth = 4)
-
- // full fill the gramian matrix
- val fullGramian = new Array[Double](n * n)
- for(i <- 0 until n) {
- val srcOffset = (2 * n - i + 1) * i / 2
- fullGramian(i * n + i) = gramian(srcOffset)
- for(j <- i until n) {
- val v = gramian(srcOffset + j - i)
- fullGramian(i * n + j) = v
- fullGramian(j * n + i) = v
- }
- }
-
- new DenseMatrix(n, n, fullGramian)
- }
-
-
- private def checkNumColumns(cols: Int): Unit = {
- if (cols > 65535) {
- throw new IllegalArgumentException(s"Argument with more than 65535 cols: $cols")
- }
- if (cols > 10000) {
- val memMB = (cols.toLong * cols) / 125000
- logWarning(s"$cols columns will require at least $memMB megabytes of memory!")
- }
- }
-
- /**
- * Computes singular value decomposition of this matrix. Denote this matrix by A (m x n). This
- * will compute matrices U, S, V such that A ~= U * S * V', where S contains the leading k
- * singular values, U and V contain the corresponding singular vectors.
- *
- * At most k largest non-zero singular values and associated vectors are returned. If there are k
- * such values, then the dimensions of the return will be:
- * - U is a RowMatrix of size m x k that satisfies U' * U = eye(k),
- * - s is a Vector of size k, holding the singular values in descending order,
- * - V is a Matrix of size n x k that satisfies V' * V = eye(k).
- *
- * We assume n is smaller than m, though this is not strictly required.
- * The singular values and the right singular vectors are derived
- * from the eigenvalues and the eigenvectors of the Gramian matrix A' * A. U, the matrix
- * storing the right singular vectors, is computed via matrix multiplication as
- * U = A * (V * S^-1^), if requested by user. The actual method to use is determined
- * automatically based on the cost:
- * - If n is small (n < 100) or k is large compared with n (k > n / 2), we compute
- * the Gramian matrix first and then compute its top eigenvalues and eigenvectors locally
- * on the driver. This requires a single pass with O(n^2^) storage on each executor and
- * on the driver, and O(n^2^ k) time on the driver.
- * - Otherwise, we compute (A' * A) * v in a distributive way and send it to ARPACK's DSAUPD to
- * compute (A' * A)'s top eigenvalues and eigenvectors on the driver node. This requires O(k)
- * passes, O(n) storage on each executor, and O(n k) storage on the driver.
- *
- * Several internal parameters are set to default values. The reciprocal condition number rCond
- * is set to 1e-9. All singular values smaller than rCond * sigma(0) are treated as zeros, where
- * sigma(0) is the largest singular value. The maximum number of Arnoldi update iterations for
- * ARPACK is set to 300 or k * 3, whichever is larger. The numerical tolerance for ARPACK's
- * eigen-decomposition is set to 1e-10.
- *
- * @param k number of leading singular values to keep (0 < k <= n).
- * It might return less than k if
- * there are numerically zero singular values or there are not enough Ritz values
- * converged before the maximum number of Arnoldi update iterations is reached (in case
- * that matrix A is ill-conditioned).
- * @param computeU whether to compute U
- * @param rCond the reciprocal condition number. All singular values smaller than rCond * sigma(0)
- * are treated as zero, where sigma(0) is the largest singular value.
- * @return SingularValueDecomposition(U, s, V). U = null if computeU = false.
- * @note The conditions that decide which method to use internally and the default parameters are
- * subject to change.
- */
- @Since("1.0.0")
- def computeSVD(
- k: Int,
- computeU: Boolean = false,
- rCond: Double = 1e-9): SingularValueDecomposition[RowMatrix, Matrix] = {
- // maximum number of Arnoldi update iterations for invoking ARPACK
- val maxIter = math.max(300, k * 3)
- // numerical tolerance for invoking ARPACK
- val tol = 1e-10
- computeSVD(k, computeU, rCond, maxIter, tol, "auto")
- }
-
- /**
- * The actual SVD implementation, visible for testing.
- *
- * @param k number of leading singular values to keep (0 < k <= n)
- * @param computeU whether to compute U
- * @param rCond the reciprocal condition number
- * @param maxIter max number of iterations (if ARPACK is used)
- * @param tol termination tolerance (if ARPACK is used)
- * @param mode computation mode (auto: determine automatically which mode to use,
- * local-svd: compute gram matrix and computes its full SVD locally,
- * local-eigs: compute gram matrix and computes its top eigenvalues locally,
- * dist-eigs: compute the top eigenvalues of the gram matrix distributively)
- * @return SingularValueDecomposition(U, s, V). U = null if computeU = false.
- */
- private[mllib] def computeSVD(
- k: Int,
- computeU: Boolean,
- rCond: Double,
- maxIter: Int,
- tol: Double,
- mode: String): SingularValueDecomposition[RowMatrix, Matrix] = {
- val n = numCols().toInt
- require(k > 0 && k <= n, s"Requested k singular values but got k=$k and numCols=$n.")
-
- object SVDMode extends Enumeration {
- val LocalARPACK, LocalLAPACK, DistARPACK = Value
- }
-
- val modeStr = if (mode == "auto") RowMatrixUtil.selectSVDBranch(n, k) else mode
- val computeMode = modeStr match {
- case "local-svd" => SVDMode.LocalLAPACK
- case "local-eigs" => SVDMode.LocalARPACK
- case "dist-eigs" => SVDMode.DistARPACK
- case _ => throw new IllegalArgumentException(s"Do not support mode $mode.")
- }
-
- val isSparse: Boolean = rows.map(_.isInstanceOf[SparseVector]).reduce((x, y) => x && y)
-
- // Compute the eigen-decomposition of A' * A.
- val (sigmaSquares: BDV[Double], u: BDM[Double]) = computeMode match {
- case SVDMode.LocalARPACK =>
- require(k < n, s"k must be smaller than n in local-eigs mode but got k=$k and n=$n.")
- if (isSparse) {
- eigenValueDecompositionOnDenseMatrix(n, k, tol, maxIter)
- } else {
- val G = computeDenseGramianMatrix().asBreeze.asInstanceOf[BDM[Double]]
- val driverCores = RowMatrixUtil.parseExtraParams(rows.sparkContext, -1)
- EigenValueDecomposition.symmetricEigsLocal(G, n, k, tol, maxIter, driverCores)
- }
- case SVDMode.LocalLAPACK =>
- // svd latent constraint, 2 * n * n + 6 * n + 1 < Int.MaxValue
- require(n < 32767, s"$n exceeds the breeze svd capability")
- val G = computeGramianMatrix().asBreeze.asInstanceOf[BDM[Double]]
- val Eigen(uFull, sigmaSquaresFull) = EigenDecomposition.symmetricEigenDecomposition(G)
- (sigmaSquaresFull, uFull)
- case SVDMode.DistARPACK =>
- if (rows.getStorageLevel == StorageLevel.NONE) {
- logWarning("The input data is not directly cached, which may hurt performance if its"
- + " parent RDDs are also uncached.")
- }
- require(k < n, s"k must be smaller than n in dist-eigs mode but got k=$k and n=$n.")
- if (isSparse) {
- eigenValueDecompositionOnSparseMatrix(n, k, tol, maxIter)
- } else {
- EigenValueDecomposition.symmetricEigs(multiplyGramianMatrixBy, n, k, tol, maxIter)
- }
- }
-
- val sigmas: BDV[Double] = brzSqrt(sigmaSquares)
-
- // Determine the effective rank.
- val sigma0 = sigmas(0)
- val threshold = rCond * sigma0
- var i = 0
- // sigmas might have a length smaller than k, if some Ritz values do not satisfy the convergence
- // criterion specified by tol after max number of iterations.
- // Thus use i < min(k, sigmas.length) instead of i < k.
- if (sigmas.length < k) {
- logWarning(s"Requested $k singular values but only found ${sigmas.length} converged.")
- }
- while (i < math.min(k, sigmas.length) && sigmas(i) >= threshold) {
- i += 1
- }
- val sk = i
-
- if (sk < k) {
- logWarning(s"Requested $k singular values but only found $sk nonzeros.")
- }
-
- // Warn at the end of the run as well, for increased visibility.
- if (computeMode == SVDMode.DistARPACK && rows.getStorageLevel == StorageLevel.NONE) {
- logWarning("The input data was not directly cached, which may hurt performance if its"
- + " parent RDDs are also uncached.")
- }
-
- val s = Vectors.dense(Arrays.copyOfRange(sigmas.data, 0, sk))
- val V = Matrices.dense(n, sk, Arrays.copyOfRange(u.data, 0, n * sk))
-
- if (computeU) {
- // N = Vk * Sk^{-1}
- val N = new BDM[Double](n, sk, Arrays.copyOfRange(u.data, 0, n * sk))
- var i = 0
- var j = 0
- while (j < sk) {
- i = 0
- val sigma = sigmas(j)
- while (i < n) {
- N(i, j) /= sigma
- i += 1
- }
- j += 1
- }
- val U = this.multiply(Matrices.fromBreeze(N))
- SingularValueDecomposition(U, s, V)
- } else {
- SingularValueDecomposition(null, s, V)
- }
- }
-
- /**
- * Distributed algorithm of computing covariance matrix for a dense matrix with dimension (m,n).
- * @param mean Mean value vector of size n
- * @param n Column number
- * @param m Row number
- * @return Covariance matrix
- */
- private def computeDenseVectorCovariance(mean: Vector, n: Int, m: Long): Matrix = {
- val meanBroadcast = rows.context.broadcast(mean)
-
- // centralize matrix
- val centralizedRows = rows.map(row => {
- val mean = meanBroadcast.value
- val centralizedRow = new Array[Double](n)
- for (idx <- 0 until n)
- centralizedRow(idx) = row(idx) - mean(idx)
- Vectors.dense(centralizedRow)
- })
-
- // compute the upper triangular matrix
- val covarianceLen = n * (n + 1) / 2
- val covariance = centralizedRows.mapPartitions(iter => {
- val subMatrixValues = iter.map(_.toArray).toArray
- val subMatrixRow = subMatrixValues.length
- val localCovariance = new Array[Double](covarianceLen)
- Gramian.compute(subMatrixValues.flatten, localCovariance, subMatrixRow, n)
- Array(localCovariance).iterator
- }).treeReduce((cov1, cov2) => {
- blas.daxpy(cov1.length, 1.0, cov2, 1, cov1, 1)
- cov1
- }, depth = 4)
-
- // full fill the covariance matrix
- val fullCovariance = new Array[Double](n * n)
- val m1 = m - 1.0
- for(i <- StaticUtils.ZERO_INT until n) {
- val srcOffset = (2 * n - i + 1) * i / 2
- fullCovariance(i * n + i) = covariance(srcOffset) / m1
- for(j <- i + 1 until n) {
- val v = covariance(srcOffset + j - i) / m1
- fullCovariance(i * n + j) = v
- fullCovariance(j * n + i) = v
- }
- }
-
- new DenseMatrix(n, n, fullCovariance)
- }
-
- /**
- * Distributed algorithm of computing covariance matrix for a sparse matrix with dimension (m,n).
- * @param mean Mean value vector of size n
- * @param n Column number
- * @param m Row number
- * @return Covariance matrix
- */
- def computeSparseVectorCovariance(mean: Vector, n: Int, m: Long): Matrix = {
- val G = RowMatrixUtil.computeGramMatrixAsDenseMatrix(
- rows.map(_.asInstanceOf[SparseVector]), n)
- var i = 0
- var j = 0
- val m1 = m - 1.0
- var alpha = 0.0
- while (i < n) {
- alpha = m / m1 * mean(i)
- j = i
- while (j < n) {
- val Gij = G(i, j) / m1 - alpha * mean(j)
- G(i, j) = Gij
- G(j, i) = Gij
- j += 1
- }
- i += 1
- }
- G
- }
-
- /**
- * Compute covariance matrix with formula Cov(X, Y) = E[(X-E(X))(Y-E(Y))]
- * @return Covariance matrix
- */
- def computeCovariance(): Matrix = {
- val isSparse = rows.map(_.isInstanceOf[SparseVector]).reduce((x, y) => x && y)
-
- val n = numCols().toInt
- checkNumColumns(n)
- val summary = computeColumnSummaryStatistics()
- val m = summary.count
- require(m > 1, s"RowMatrix.computeCovariance called on matrix with only $m rows." +
- " Cannot compute the covariance of a RowMatrix with <= 1 row.")
- val mean = summary.mean
-
- if (isSparse) {
- computeSparseVectorCovariance(mean, n, m)
- } else {
- computeDenseVectorCovariance(mean, n, m)
- }
- }
-
- /**
- * Computes the top k principal components and a vector of proportions of
- * variance explained by each principal component.
- * Rows correspond to observations and columns correspond to variables.
- * The principal components are stored a local matrix of size n-by-k.
- * Each column corresponds for one principal component,
- * and the columns are in descending order of component variance.
- * The row data do not need to be "centered" first; it is not necessary for
- * the mean of each column to be 0.
- *
- * @param k number of top principal components.
- * @param mode number of top principal components.
- * @return a matrix of size n-by-k, whose columns are principal components, and
- * a vector of values which indicate how much variance each principal component
- * explains
- */
- @Since("1.6.0")
- def computePrincipalComponentsAndExplainedVarianceBody(
- k: Int,
- mode: String = "auto"): (Matrix, Vector) = {
- val n = numCols().toInt
- require(k > 0 && k <= n, s"k = $k out of range (0, n = $n]")
-
- object PCAMode extends Enumeration {
- val Correlation, SVD, SparseSVD = Value
- }
- val checkSparseBranch = if (rows.map(_.isInstanceOf[SparseVector])
- .reduce((x, y) => x && y)) {
- PCAMode.SparseSVD
- } else {
- PCAMode.SVD
- }
- val computeMode = mode match {
- case "Correlation" => PCAMode.Correlation
- case "SVD" => checkSparseBranch
- case _ =>
- if (n == k || n < 1500) {
- PCAMode.Correlation
- } else {
- checkSparseBranch
- }
- }
- computeMode match {
- case PCAMode.Correlation =>
- val cov = computeCovariance().asBreeze.asInstanceOf[BDM[Double]]
- val Eigen(u, s) = EigenDecomposition.symmetricEigenDecomposition(cov)
-
- val eigenSum = s.data.sum
- val explainedVariance = s.data.map(_ / eigenSum)
- if (k == n) {
- (Matrices.dense(n, k, u.data), Vectors.dense(explainedVariance))
- } else {
- (Matrices.dense(n, k, Arrays.copyOfRange(u.data, 0, n * k)),
- Vectors.dense(Arrays.copyOfRange(explainedVariance, 0, k)))
- }
- case PCAMode.SVD =>
- val stas = Statistics.colStats(rows)
- val meanVector = stas.mean.asBreeze
- val centredMatrix = new RowMatrix(rows.map { rowVector =>
- Vectors.fromBreeze(rowVector.asBreeze - meanVector)
- })
- val svd = centredMatrix.computeSVD(k)
- val s = svd.s.toArray.map(eigValue => eigValue * eigValue / (numRows().toInt - 1))
- val eigenSum = stas.variance.toArray.sum
- val explainedVariance = s.map(_ / eigenSum)
- (svd.V, Vectors.dense(explainedVariance))
- case PCAMode.SparseSVD =>
- val model = new SPCA(k).fit(rows)
- (model.pc.asInstanceOf[Matrix], model.explainedVariance.asInstanceOf[Vector])
- }
- }
-
- /**
- * Computes the top k principal components and a vector of proportions of
- * variance explained by each principal component.
- *
- * @param k number of top principal components.
- * @return a matrix of size n-by-k, whose columns are principal components, and
- * a vector of values which indicate how much variance each principal component
- * explains
- */
- def computePrincipalComponentsAndExplainedVariance(k: Int): (Matrix, Vector) = {
- computePrincipalComponentsAndExplainedVarianceBody(k)
- }
-
- /**
- * Computes the top k principal components only.
- *
- * @param k number of top principal components.
- * @return a matrix of size n-by-k, whose columns are principal components
- * @see computePrincipalComponentsAndExplainedVariance
- */
- @Since("1.0.0")
- def computePrincipalComponents(k: Int): Matrix = {
- computePrincipalComponentsAndExplainedVariance(k)._1
- }
-
- /**
- * Computes column-wise summary statistics.
- */
- @Since("1.0.0")
- def computeColumnSummaryStatistics(): MultivariateStatisticalSummary = {
- val summary = rows.treeAggregate(new MultivariateOnlineSummarizer)(
- (aggregator, data) => aggregator.add(data),
- (aggregator1, aggregator2) => aggregator1.merge(aggregator2))
- updateNumRows(summary.count)
- summary
- }
-
- /**
- * Multiply this matrix by a local matrix on the right.
- *
- * @param B a local matrix whose number of rows must match the number of columns of this matrix
- * @return a [[org.apache.spark.mllib.linalg.distributed.RowMatrix]] representing the product,
- * which preserves partitioning
- */
- @Since("1.0.0")
- def multiply(B: Matrix): RowMatrix = {
- val n = numCols().toInt
- val k = B.numCols
- require(n == B.numRows, s"Dimension mismatch: $n vs ${B.numRows}")
-
- require(B.isInstanceOf[DenseMatrix],
- s"Only support dense matrix at this time but found ${B.getClass.getName}.")
-
- val Bb = rows.context.broadcast(B.asBreeze.asInstanceOf[BDM[Double]].toDenseVector.toArray)
- val AB = rows.mapPartitions { iter =>
- val Bi = Bb.value
- iter.map { row =>
- val v = BDV.zeros[Double](k)
- var i = 0
- while (i < k) {
- v(i) = row.asBreeze.dot(new BDV(Bi, i * n, 1, n))
- i += 1
- }
- Vectors.fromBreeze(v)
- }
- }
-
- new RowMatrix(AB, nRows, B.numCols)
- }
-
- /**
- * Compute all cosine similarities between columns of this matrix using the brute-force
- * approach of computing normalized dot products.
- *
- * @return An n x n sparse upper-triangular matrix of cosine similarities between
- * columns of this matrix.
- */
- @Since("1.2.0")
- def columnSimilarities(): CoordinateMatrix = {
- columnSimilarities(0.0)
- }
-
- /**
- * Compute similarities between columns of this matrix using a sampling approach.
- *
- * The threshold parameter is a trade-off knob between estimate quality and computational cost.
- *
- * Setting a threshold of 0 guarantees deterministic correct results, but comes at exactly
- * the same cost as the brute-force approach. Setting the threshold to positive values
- * incurs strictly less computational cost than the brute-force approach, however the
- * similarities computed will be estimates.
- *
- * The sampling guarantees relative-error correctness for those pairs of columns that have
- * similarity greater than the given similarity threshold.
- *
- * To describe the guarantee, we set some notation:
- * Let A be the smallest in magnitude non-zero element of this matrix.
- * Let B be the largest in magnitude non-zero element of this matrix.
- * Let L be the maximum number of non-zeros per row.
- *
- * For example, for {0,1} matrices: A=B=1.
- * Another example, for the Netflix matrix: A=1, B=5
- *
- * For those column pairs that are above the threshold,
- * the computed similarity is correct to within 20% relative error with probability
- * at least 1 - (0.981)^10/B^
- *
- * The shuffle size is bounded by the *smaller* of the following two expressions:
- *
- * O(n log(n) L / (threshold * A))
- * O(m L^2^)
- *
- * The latter is the cost of the brute-force approach, so for non-zero thresholds,
- * the cost is always cheaper than the brute-force approach.
- *
- * @param threshold Set to 0 for deterministic guaranteed correctness.
- * Similarities above this threshold are estimated
- * with the cost vs estimate quality trade-off described above.
- * @return An n x n sparse upper-triangular matrix of cosine similarities
- * between columns of this matrix.
- */
- @Since("1.2.0")
- def columnSimilarities(threshold: Double): CoordinateMatrix = {
- require(threshold >= 0, s"Threshold cannot be negative: $threshold")
-
- if (threshold > 1) {
- logWarning(s"Threshold is greater than 1: $threshold " +
- "Computation will be more efficient with promoted sparsity, " +
- " however there is no correctness guarantee.")
- }
-
- val gamma = if (threshold < 1e-6) {
- Double.PositiveInfinity
- } else {
- 10 * math.log(numCols()) / threshold
- }
-
- columnSimilaritiesDIMSUM(computeColumnSummaryStatistics().normL2.toArray, gamma)
- }
-
- /**
- * Compute QR decomposition for [[RowMatrix]]. The implementation is designed to optimize the QR
- * decomposition (factorization) for the [[RowMatrix]] of a tall and skinny shape.
- * Reference:
- * Paul G. Constantine, David F. Gleich. "Tall and skinny QR factorizations in MapReduce
- * architectures" (see here )
- *
- * @param computeQ whether to computeQ
- * @return QRDecomposition(Q, R), Q = null if computeQ = false.
- */
- @Since("1.5.0")
- def tallSkinnyQR(computeQ: Boolean = false): QRDecomposition[RowMatrix, Matrix] = {
- val col = numCols().toInt
- // split rows horizontally into smaller matrices, and compute QR for each of them
- val blockQRs = rows.retag(classOf[Vector]).glom().filter(_.length != 0).map { partRows =>
- val bdm = BDM.zeros[Double](partRows.length, col)
- var i = 0
- partRows.foreach { row =>
- bdm(i, ::) := row.asBreeze.t
- i += 1
- }
- breeze.linalg.qr.reduced(bdm).r
- }
-
- // combine the R part from previous results vertically into a tall matrix
- val combinedR = blockQRs.treeReduce { (r1, r2) =>
- val stackedR = BDM.vertcat(r1, r2)
- breeze.linalg.qr.reduced(stackedR).r
- }
-
- val finalR = Matrices.fromBreeze(combinedR.toDenseMatrix)
- val finalQ = if (computeQ) {
- try {
- val invR = inv(combinedR)
- this.multiply(Matrices.fromBreeze(invR))
- } catch {
- case err: MatrixSingularException =>
- logWarning("R is not invertible and return Q as null")
- null
- }
- } else {
- null
- }
- QRDecomposition(finalQ, finalR)
- }
-
- /**
- * Find all similar columns using the DIMSUM sampling algorithm, described in two papers
- *
- * http://arxiv.org/abs/1206.2082
- * http://arxiv.org/abs/1304.1467
- *
- * @param colMags A vector of column magnitudes
- * @param gamma The oversampling parameter. For provable results, set to 10 * log(n) / s,
- * where s is the smallest similarity score to be estimated,
- * and n is the number of columns
- * @return An n x n sparse upper-triangular matrix of cosine similarities
- * between columns of this matrix.
- */
- private[mllib] def columnSimilaritiesDIMSUM(
- colMags: Array[Double],
- gamma: Double): CoordinateMatrix = {
- require(gamma > 1.0, s"Oversampling should be greater than 1: $gamma")
- require(colMags.size == this.numCols(), "Number of magnitudes didn't match column dimension")
- val sg = math.sqrt(gamma) // sqrt(gamma) used many times
-
- // Don't divide by zero for those columns with zero magnitude
- val colMagsCorrected = colMags.map(x => if (x == 0) 1.0 else x)
-
- val sc = rows.context
- val pBV = sc.broadcast(colMagsCorrected.map(c => sg / c))
- val qBV = sc.broadcast(colMagsCorrected.map(c => math.min(sg, c)))
-
- val sims = rows.mapPartitionsWithIndex { (indx, iter) =>
- val p = pBV.value
- val q = qBV.value
-
- val rand = new XORShiftRandom(indx)
- val scaled = new Array[Double](p.size)
- iter.flatMap { row =>
- row match {
- case SparseVector(size, indices, values) =>
- val nnz = indices.size
- var k = 0
- while (k < nnz) {
- scaled(k) = values(k) / q(indices(k))
- k += 1
- }
-
- Iterator.tabulate(nnz) { k =>
- val buf = new ListBuffer[((Int, Int), Double)]()
- val i = indices(k)
- val iVal = scaled(k)
- if (iVal != 0 && rand.nextDouble() < p(i)) {
- var l = k + 1
- while (l < nnz) {
- val j = indices(l)
- val jVal = scaled(l)
- if (jVal != 0 && rand.nextDouble() < p(j)) {
- buf += (((i, j), iVal * jVal))
- }
- l += 1
- }
- }
- buf
- }.flatten
- case DenseVector(values) =>
- val n = values.size
- var i = 0
- while (i < n) {
- scaled(i) = values(i) / q(i)
- i += 1
- }
- Iterator.tabulate(n) { i =>
- val buf = new ListBuffer[((Int, Int), Double)]()
- val iVal = scaled(i)
- if (iVal != 0 && rand.nextDouble() < p(i)) {
- var j = i + 1
- while (j < n) {
- val jVal = scaled(j)
- if (jVal != 0 && rand.nextDouble() < p(j)) {
- buf += (((i, j), iVal * jVal))
- }
- j += 1
- }
- }
- buf
- }.flatten
- }
- }
- }.reduceByKey(_ + _).map { case ((i, j), sim) =>
- MatrixEntry(i.toLong, j.toLong, sim)
- }
- new CoordinateMatrix(sims, numCols(), numCols())
- }
-
- private[mllib] override def toBreeze(): BDM[Double] = {
- val m = numRows().toInt
- val n = numCols().toInt
- val mat = BDM.zeros[Double](m, n)
- var i = 0
- rows.collect().foreach { vector =>
- vector.foreachActive { case (j, v) =>
- mat(i, j) = v
- }
- i += 1
- }
- mat
- }
-
- /** Updates or verifies the number of rows. */
- private def updateNumRows(m: Long) {
- if (nRows <= 0) {
- nRows = m
- } else {
- require(nRows == m,
- s"The number of rows $m is different from what specified or previously computed: ${nRows}.")
- }
- }
-}
-
-@Since("1.0.0")
-object RowMatrix {
-
- /**
- * Fills a full square matrix from its upper triangular part.
- */
- private def triuToFull(n: Int, U: Array[Double]): Matrix = {
- val G = new BDM[Double](n, n)
-
- var row = 0
- var col = 0
- var idx = 0
- var value = 0.0
- while (col < n) {
- row = 0
- while (row < col) {
- value = U(idx)
- G(row, col) = value
- G(col, row) = value
- idx += 1
- row += 1
- }
- G(col, col) = U(idx)
- idx += 1
- col += 1
- }
-
- Matrices.dense(n, n, G.data)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/Correlation.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/Correlation.scala
deleted file mode 100644
index 5d58eed..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/Correlation.scala
+++ /dev/null
@@ -1,103 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.stat.correlation
-
-import org.apache.spark.mllib.linalg.{DenseVector, Matrix, Vector}
-import org.apache.spark.rdd.RDD
-
-/**
- * Trait for correlation algorithms.
- */
-private[stat] trait Correlation {
-
- /**
- * Compute correlation for two datasets.
- */
- def computeCorrelation(x: RDD[Double], y: RDD[Double]): Double
-
- /**
- * Compute the correlation matrix S, for the input matrix, where S(i, j) is the correlation
- * between column i and j. S(i, j) can be NaN if the correlation is undefined for column i and j.
- */
- def computeCorrelationMatrix(X: RDD[Vector]): Matrix
-
- /**
- * Combine the two input RDD[Double]s into an RDD[Vector] and compute the correlation using the
- * correlation implementation for RDD[Vector]. Can be NaN if correlation is undefined for the
- * input vectors.
- */
- def computeCorrelationWithMatrixImpl(x: RDD[Double], y: RDD[Double]): Double = {
- val mat: RDD[Vector] = x.zip(y).map { case (xi, yi) => new DenseVector(Array(xi, yi)) }
- computeCorrelationMatrix(mat)(0, 1)
- }
-
-}
-
-/**
- * Delegates computation to the specific correlation object based on the input method name.
- */
-private[stat] object Correlations {
-
- def corr(x: RDD[Double],
- y: RDD[Double],
- method: String = CorrelationNames.defaultCorrName): Double = {
- val correlation = getCorrelationFromName(method)
- correlation.computeCorrelation(x, y)
- }
-
- def corrMatrix(X: RDD[Vector],
- method: String = CorrelationNames.defaultCorrName): Matrix = {
- val correlation = getCorrelationFromName(method)
- correlation.computeCorrelationMatrix(X)
- }
-
- // Match input correlation name with a known name via simple string matching.
- def getCorrelationFromName(method: String): Correlation = {
- try {
- CorrelationNames.nameToObjectMap(method)
- } catch {
- case nse: NoSuchElementException =>
- throw new IllegalArgumentException("Unrecognized method name. Supported correlations: "
- + CorrelationNames.nameToObjectMap.keys.mkString(", "))
- }
- }
-}
-
-/**
- * Maintains supported and default correlation names.
- *
- * Currently supported correlations: `pearson`, `spearman`.
- * Current default correlation: `pearson`.
- *
- * After new correlation algorithms are added, please update the documentation here and in
- * Statistics.scala for the correlation APIs.
- */
-private[mllib] object CorrelationNames {
-
- // Note: after new types of correlations are implemented, please update this map.
- val nameToObjectMap = Map(("pearson", PearsonCorrelation), ("spearman", SpearmanCorrelation))
- val defaultCorrName: String = "pearson"
-
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/PearsonCorrelation.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/PearsonCorrelation.scala
deleted file mode 100644
index 5bee973..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/PearsonCorrelation.scala
+++ /dev/null
@@ -1,119 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.stat.correlation
-
-import breeze.linalg.{DenseMatrix => BDM}
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.mllib.linalg.{DenseVector, Matrices, Matrix, SparseVector, Vector}
-import org.apache.spark.mllib.linalg.distributed.RowMatrix
-import org.apache.spark.rdd.RDD
-
-/**
- * Compute Pearson correlation for two RDDs of the type RDD[Double] or the correlation matrix
- * for an RDD of the type RDD[Vector].
- *
- * Definition of Pearson correlation can be found at
- * http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient
- */
-private[stat] object PearsonCorrelation extends Correlation with Logging {
-
- /**
- * Compute the Pearson correlation for two datasets. NaN if either vector has 0 variance.
- */
- override def computeCorrelation(x: RDD[Double], y: RDD[Double]): Double = {
- computeCorrelationWithMatrixImpl(x, y)
- }
-
- /**
- * Compute the Pearson correlation matrix S, for the input matrix, where S(i, j) is the
- * correlation between column i and j. 0 covariance results in a correlation value of Double.NaN.
- */
- override def computeCorrelationMatrix(X: RDD[Vector]): Matrix = {
- val isSparse: Boolean = X.map(_.isInstanceOf[SparseVector]).treeReduce((x, y) => x && y)
- if (isSparse) {
- val rowMatrix = new RowMatrix(X)
- val cov = rowMatrix.computeCovariance()
- computeCorrelationMatrixFromCovariance(cov)
- } else {
- PearsonCorrelationUtil.computeDenseVectorCorrelation(X.map(_.asInstanceOf[DenseVector]))
- }
- }
-
- /**
- * Compute the Pearson correlation matrix from the covariance matrix.
- * 0 variance results in a correlation value of Double.NaN.
- */
- def computeCorrelationMatrixFromCovariance(covarianceMatrix: Matrix): Matrix = {
- val cov = covarianceMatrix.asBreeze.asInstanceOf[BDM[Double]]
- val n = cov.cols
-
- // Compute the standard deviation on the diagonals first
- var i = 0
- while (i < n) {
- // TODO remove once covariance numerical issue resolved.
- cov(i, i) = if (closeToZero(cov(i, i))) 0.0 else math.sqrt(cov(i, i))
- i +=1
- }
-
- // Loop through columns since cov is column major
- var j = 0
- var sigma = 0.0
- var containNaN = false
- while (j < n) {
- sigma = cov(j, j)
- i = 0
- while (i < j) {
- val corr = if (sigma == 0.0 || cov(i, i) == 0.0) {
- containNaN = true
- Double.NaN
- } else {
- cov(i, j) / (sigma * cov(i, i))
- }
- cov(i, j) = corr
- cov(j, i) = corr
- i += 1
- }
- j += 1
- }
-
- // put 1.0 on the diagonals
- i = 0
- while (i < n) {
- cov(i, i) = 1.0
- i +=1
- }
-
- if (containNaN) {
- logWarning("Pearson correlation matrix contains NaN values.")
- }
-
- Matrices.fromBreeze(cov)
- }
-
- private def closeToZero(value: Double, threshold: Double = 1e-12): Boolean = {
- math.abs(value) <= threshold
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/SpearmanCorrelation.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/SpearmanCorrelation.scala
deleted file mode 100644
index eaf0afc..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/stat/correlation/SpearmanCorrelation.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.stat.correlation
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.mllib.linalg.{Matrix, Vector}
-import org.apache.spark.mllib.linalg.distributed.RowMatrix
-import org.apache.spark.rdd.RDD
-import org.apache.spark.storage.StorageLevel
-
-/**
- * Compute Spearman's correlation for two RDDs of the type RDD[Double] or the correlation matrix
- * for an RDD of the type RDD[Vector].
- *
- * Definition of Spearman's correlation can be found at
- * http://en.wikipedia.org/wiki/Spearman's_rank_correlation_coefficient
- */
-private[stat] object SpearmanCorrelation extends Correlation with Logging {
-
- /**
- * Compute Spearman's correlation for two datasets.
- */
- override def computeCorrelation(x: RDD[Double], y: RDD[Double]): Double = {
- computeCorrelationWithMatrixImpl(x, y)
- }
-
- /**
- * Compute Spearman's correlation matrix S, for the input matrix, where S(i, j) is the
- * correlation between column i and j.
- */
- override def computeCorrelationMatrix(X: RDD[Vector]): Matrix = {
- val groupedRanks = SpearmanCorrelationUtil.getRanks(X)
- .persist(StorageLevel.MEMORY_AND_DISK)
- .setName("groupedRanks")
- groupedRanks.foreach(_ => {})
- X.sparkContext.getPersistentRDDs.foreach{case (_, rdd) =>
- if (!rdd.name.contains("groupedRanks")) rdd.unpersist()
- }
- val rowMatrix = new RowMatrix(groupedRanks)
- val cov = rowMatrix.computeCovariance()
- PearsonCorrelation.computeCorrelationMatrixFromCovariance(cov)
- }
-}
diff --git a/ml-accelerator/src/main/scala/org/apache/spark/mllib/tree/DecisionTree.scala b/ml-accelerator/src/main/scala/org/apache/spark/mllib/tree/DecisionTree.scala
deleted file mode 100644
index bf402c3..0000000
--- a/ml-accelerator/src/main/scala/org/apache/spark/mllib/tree/DecisionTree.scala
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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
-
-import scala.collection.JavaConverters._
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.api.java.JavaRDD
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.tree.impl.{DecisionForest, DTUtils}
-import org.apache.spark.mllib.regression.LabeledPoint
-import org.apache.spark.mllib.tree.configuration.Algo._
-import org.apache.spark.mllib.tree.configuration.QuantileStrategy._
-import org.apache.spark.mllib.tree.configuration.Strategy
-import org.apache.spark.mllib.tree.impurity._
-import org.apache.spark.mllib.tree.model._
-import org.apache.spark.rdd.RDD
-
-
-/**
- * A class which implements a decision tree learning algorithm for classification and regression.
- * It supports both continuous and categorical features.
- *
- * @param strategy The configuration parameters for the tree algorithm which specify the type
- * of decision tree (classification or regression), feature type (continuous,
- * categorical), depth of the tree, quantile calculation strategy, etc.
- * @param seed Random seed.
- */
-@Since("1.0.0")
-class DecisionTree private[spark] (private val strategy: Strategy, private val seed: Int)
- extends Serializable with Logging {
-
- /**
- * @param strategy The configuration parameters for the tree algorithm which specify the type
- * of decision tree (classification or regression), feature type (continuous,
- * categorical), depth of the tree, quantile calculation strategy, etc.
- */
- @Since("1.0.0")
- def this(strategy: Strategy) = this(strategy, seed = 0)
-
- strategy.assertValid()
-
- /**
- * Method to train a decision tree model over an RDD
- *
- * @param input Training data: RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
- * @return DecisionTreeModel that can be used for prediction.
- */
- @Since("1.2.0")
- def run(input: RDD[LabeledPoint]): DecisionTreeModel = {
- val trees = DecisionForest.run(input.map(_.asML), strategy, numTrees = 1,
- featureSubsetStrategy = "all", seed = seed.toLong, None)
- val rfModel = new RandomForestModel(strategy.algo, trees.map(_.toOld))
- rfModel.trees(0)
- }
-}
-
-@Since("1.0.0")
-object DecisionTree extends Serializable with Logging {
-
- /**
- * Method to train a decision tree model.
- * The method supports binary and multiclass classification and regression.
- *
- * @param input Training dataset: RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
- * For classification, labels should take values {0, 1, ..., numClasses-1}.
- * For regression, labels are real numbers.
- * @param strategy The configuration parameters for the tree algorithm which specify the type
- * of decision tree (classification or regression), feature type (continuous,
- * categorical), depth of the tree, quantile calculation strategy, etc.
- * @return DecisionTreeModel that can be used for prediction.
- *
- * @note Using `org.apache.spark.mllib.tree.DecisionTree.trainClassifier`
- * and `org.apache.spark.mllib.tree.DecisionTree.trainRegressor`
- * is recommended to clearly separate classification and regression.
- */
- @Since("1.0.0")
- def train(input: RDD[LabeledPoint], strategy: Strategy): DecisionTreeModel = {
- new DecisionTree(strategy).run(input)
- }
-
- /**
- * Method to train a decision tree model.
- * The method supports binary and multiclass classification and regression.
- *
- * @param input Training dataset: RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
- * For classification, labels should take values {0, 1, ..., numClasses-1}.
- * For regression, labels are real numbers.
- * @param algo Type of decision tree, either classification or regression.
- * @param impurity Criterion used for information gain calculation.
- * @param maxDepth Maximum depth of the tree (e.g. depth 0 means 1 leaf node, depth 1 means
- * 1 internal node + 2 leaf nodes).
- * @return DecisionTreeModel that can be used for prediction.
- *
- * @note Using `org.apache.spark.mllib.tree.DecisionTree.trainClassifier`
- * and `org.apache.spark.mllib.tree.DecisionTree.trainRegressor`
- * is recommended to clearly separate classification and regression.
- */
- @Since("1.0.0")
- def train(
- input: RDD[LabeledPoint],
- algo: Algo,
- impurity: Impurity,
- maxDepth: Int): DecisionTreeModel = {
- val (_, maxMemInMB) = DTUtils.getInvisibleParamsForMLLib(input)
- val strategy =
- new Strategy(algo, impurity, maxDepth, maxMemoryInMB = maxMemInMB)
- new DecisionTree(strategy).run(input)
- }
-
- /**
- * Method to train a decision tree model.
- * The method supports binary and multiclass classification and regression.
- *
- * @param input Training dataset: RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
- * For classification, labels should take values {0, 1, ..., numClasses-1}.
- * For regression, labels are real numbers.
- * @param algo Type of decision tree, either classification or regression.
- * @param impurity Criterion used for information gain calculation.
- * @param maxDepth Maximum depth of the tree (e.g. depth 0 means 1 leaf node, depth 1 means
- * 1 internal node + 2 leaf nodes).
- * @param numClasses Number of classes for classification. Default value of 2.
- * @return DecisionTreeModel that can be used for prediction.
- *
- * @note Using `org.apache.spark.mllib.tree.DecisionTree.trainClassifier`
- * and `org.apache.spark.mllib.tree.DecisionTree.trainRegressor`
- * is recommended to clearly separate classification and regression.
- */
- @Since("1.2.0")
- def train(
- input: RDD[LabeledPoint],
- algo: Algo,
- impurity: Impurity,
- maxDepth: Int,
- numClasses: Int): DecisionTreeModel = {
- val (_, maxMemInMB) = DTUtils.getInvisibleParamsForMLLib(input)
- val strategy = new Strategy(algo, impurity, maxDepth, numClasses,
- maxMemoryInMB = maxMemInMB)
- new DecisionTree(strategy).run(input)
- }
-
- /**
- * Method to train a decision tree model.
- * The method supports binary and multiclass classification and regression.
- *
- * @param input Training dataset: RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
- * For classification, labels should take values {0, 1, ..., numClasses-1}.
- * For regression, labels are real numbers.
- * @param algo Type of decision tree, either classification or regression.
- * @param impurity Criterion used for information gain calculation.
- * @param maxDepth Maximum depth of the tree (e.g. depth 0 means 1 leaf node, depth 1 means
- * 1 internal node + 2 leaf nodes).
- * @param numClasses Number of classes for classification. Default value of 2.
- * @param maxBins Maximum number of bins used for splitting features.
- * @param quantileCalculationStrategy Algorithm for calculating quantiles.
- * @param categoricalFeaturesInfo Map storing arity of categorical features. An entry (n to k)
- * indicates that feature n is categorical with k categories
- * indexed from 0: {0, 1, ..., k-1}.
- * @return DecisionTreeModel that can be used for prediction.
- *
- * @note Using `org.apache.spark.mllib.tree.DecisionTree.trainClassifier`
- * and `org.apache.spark.mllib.tree.DecisionTree.trainRegressor`
- * is recommended to clearly separate classification and regression.
- */
- @Since("1.0.0")
- def train(
- input: RDD[LabeledPoint],
- algo: Algo,
- impurity: Impurity,
- maxDepth: Int,
- numClasses: Int,
- maxBins: Int,
- quantileCalculationStrategy: QuantileStrategy,
- categoricalFeaturesInfo: Map[Int, Int]): DecisionTreeModel = {
- val (_, maxMemInMB) = DTUtils.getInvisibleParamsForMLLib(input)
- val strategy = new Strategy(algo, impurity, maxDepth, numClasses, maxBins,
- quantileCalculationStrategy, categoricalFeaturesInfo, maxMemoryInMB = maxMemInMB)
- new DecisionTree(strategy).run(input)
- }
-
- /**
- * Method to train a decision tree model for binary or multiclass classification.
- *
- * @param input Training dataset: RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
- * Labels should take values {0, 1, ..., numClasses-1}.
- * @param numClasses Number of classes for classification.
- * @param categoricalFeaturesInfo Map storing arity of categorical features. An entry (n to k)
- * indicates that feature n is categorical with k categories
- * indexed from 0: {0, 1, ..., k-1}.
- * @param impurity Criterion used for information gain calculation.
- * Supported values: "gini" (recommended) or "entropy".
- * @param maxDepth Maximum depth of the tree (e.g. depth 0 means 1 leaf node, depth 1 means
- * 1 internal node + 2 leaf nodes).
- * (suggested value: 5)
- * @param maxBins Maximum number of bins used for splitting features.
- * (suggested value: 32)
- * @return DecisionTreeModel that can be used for prediction.
- */
- @Since("1.1.0")
- def trainClassifier(
- input: RDD[LabeledPoint],
- numClasses: Int,
- categoricalFeaturesInfo: Map[Int, Int],
- impurity: String,
- maxDepth: Int,
- maxBins: Int): DecisionTreeModel = {
- val impurityType = Impurities.fromString(impurity)
- train(input, Classification, impurityType, maxDepth, numClasses, maxBins, Sort,
- categoricalFeaturesInfo)
- }
-
- /**
- * Java-friendly API for `org.apache.spark.mllib.tree.DecisionTree.trainClassifier`
- */
- @Since("1.1.0")
- def trainClassifier(
- input: JavaRDD[LabeledPoint],
- numClasses: Int,
- categoricalFeaturesInfo: java.util.Map[java.lang.Integer, java.lang.Integer],
- impurity: String,
- maxDepth: Int,
- maxBins: Int): DecisionTreeModel = {
- trainClassifier(input.rdd, numClasses,
- categoricalFeaturesInfo.asInstanceOf[java.util.Map[Int, Int]].asScala.toMap,
- impurity, maxDepth, maxBins)
- }
-
- /**
- * Method to train a decision tree model for regression.
- *
- * @param input Training dataset: RDD of [[org.apache.spark.mllib.regression.LabeledPoint]].
- * Labels are real numbers.
- * @param categoricalFeaturesInfo Map storing arity of categorical features. An entry (n to k)
- * indicates that feature n is categorical with k categories
- * indexed from 0: {0, 1, ..., k-1}.
- * @param impurity Criterion used for information gain calculation.
- * The only supported value for regression is "variance".
- * @param maxDepth Maximum depth of the tree (e.g. depth 0 means 1 leaf node, depth 1 means
- * 1 internal node + 2 leaf nodes).
- * (suggested value: 5)
- * @param maxBins Maximum number of bins used for splitting features.
- * (suggested value: 32)
- * @return DecisionTreeModel that can be used for prediction.
- */
- @Since("1.1.0")
- def trainRegressor(
- input: RDD[LabeledPoint],
- categoricalFeaturesInfo: Map[Int, Int],
- impurity: String,
- maxDepth: Int,
- maxBins: Int): DecisionTreeModel = {
- val impurityType = Impurities.fromString(impurity)
- train(input, Regression, impurityType, maxDepth, 0, maxBins, Sort, categoricalFeaturesInfo)
- }
-
- /**
- * Java-friendly API for `org.apache.spark.mllib.tree.DecisionTree.trainRegressor`
- */
- @Since("1.1.0")
- def trainRegressor(
- input: JavaRDD[LabeledPoint],
- categoricalFeaturesInfo: java.util.Map[java.lang.Integer, java.lang.Integer],
- impurity: String,
- maxDepth: Int,
- maxBins: Int): DecisionTreeModel = {
- trainRegressor(input.rdd,
- categoricalFeaturesInfo.asInstanceOf[java.util.Map[Int, Int]].asScala.toMap,
- impurity, maxDepth, maxBins)
- }
-}
diff --git a/ml-core/pom.xml b/ml-core/pom.xml
index 6aad5f9..443d9b3 100644
--- a/ml-core/pom.xml
+++ b/ml-core/pom.xml
@@ -6,7 +6,7 @@
4.0.0
- boostkit-ml-core_2.11
+ boostkit-ml-core_2.12
2.1.0
${project.artifactId}
Spark ml core
@@ -14,7 +14,7 @@
org.apache.spark
- boostkit-ml-kernel-client-core_2.11
+ boostkit-ml-kernel-client-core_2.12
2.1.0
${spark.version}
compile
diff --git a/ml-core/src/main/scala/breeze/numerics/DigammaX.scala b/ml-core/src/main/scala/breeze/numerics/DigammaX.scala
index 4fd0f02..7dce00d 100644
--- a/ml-core/src/main/scala/breeze/numerics/DigammaX.scala
+++ b/ml-core/src/main/scala/breeze/numerics/DigammaX.scala
@@ -1,10 +1,4 @@
// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
Copyright 2012 David Hall
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/Node.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/Node.scala
deleted file mode 100644
index bbaaff8..0000000
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/Node.scala
+++ /dev/null
@@ -1,635 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree
-
-import org.apache.spark.ml.linalg.Vector
-import org.apache.spark.ml.tree.impl.BinnedFeature
-import org.apache.spark.mllib.tree.impurity.ImpurityCalculator
-import org.apache.spark.mllib.tree.model.{ImpurityStats,
- InformationGainStats => OldInformationGainStats, Node => OldNode, Predict => OldPredict}
-
-/**
- * Decision tree node interface.
- */
-sealed abstract class Node extends Serializable {
-
- // TODO: Add aggregate stats (once available). This will happen after we move the DecisionTree
- // code into the new API and deprecate the old API. SPARK-3727
-
- /** Prediction a leaf node makes, or which an internal node would make if it were a leaf node */
- def prediction: Double
-
- /** Impurity measure at this node (for training data) */
- def impurity: Double
-
- /**
- * Statistics aggregated from training data at this node, used to compute prediction, impurity,
- * and probabilities.
- * For classification, the array of class counts must be normalized to a probability distribution.
- */
- private[ml] def impurityStats: ImpurityCalculator
-
- /** Recursive prediction helper method */
- private[ml] def predictImpl(features: Vector): LeafNode
-
- private[ml] def predictImplX(binnedFeatures: Array[Int], splits: Array[Array[Split]]): LeafNode
-
- /**
- * Get the number of nodes in tree below this node, including leaf nodes.
- * E.g., if this is a leaf, returns 0. If both children are leaves, returns 2.
- */
- private[tree] def numDescendants: Int
-
- /**
- * Recursive print function.
- * @param indentFactor The number of spaces to add to each level of indentation.
- */
- private[tree] def subtreeToString(indentFactor: Int = 0): String
-
- /**
- * Get depth of tree from this node.
- * E.g.: Depth 0 means this is a leaf node. Depth 1 means 1 internal and 2 leaf nodes.
- */
- private[tree] def subtreeDepth: Int
-
- /**
- * Create a copy of this node in the old Node format, recursively creating child nodes as needed.
- * @param id Node ID using old format IDs
- */
- private[ml] def toOld(id: Int): OldNode
-
- /**
- * Trace down the tree, and return the largest feature index used in any split.
- * @return Max feature index used in a split, or -1 if there are no splits (single leaf node).
- */
- private[ml] def maxSplitFeatureIndex(): Int
-
- /** Returns a deep copy of the subtree rooted at this node. */
- private[tree] def deepCopy(): Node
-}
-
-private[ml] object Node {
-
- /**
- * Create a new Node from the old Node format, recursively creating child nodes as needed.
- */
- def fromOld(oldNode: OldNode, categoricalFeatures: Map[Int, Int]): Node = {
- if (oldNode.isLeaf) {
- // TODO: Once the implementation has been moved to this API, then include sufficient
- // statistics here.
- new LeafNode(prediction = oldNode.predict.predict,
- impurity = oldNode.impurity, impurityStats = null)
- } else {
- val gain = if (oldNode.stats.nonEmpty) {
- oldNode.stats.get.gain
- } else {
- 0.0
- }
- new InternalNode(prediction = oldNode.predict.predict, impurity = oldNode.impurity,
- gain = gain, leftChild = fromOld(oldNode.leftNode.get, categoricalFeatures),
- rightChild = fromOld(oldNode.rightNode.get, categoricalFeatures),
- split = Split.fromOld(oldNode.split.get, categoricalFeatures), impurityStats = null)
- }
- }
-}
-
-/**
- * Decision tree leaf node.
- * @param prediction Prediction this node makes
- * @param impurity Impurity measure at this node (for training data)
- */
-class LeafNode private[ml] (
- override val prediction: Double,
- override val impurity: Double,
- override private[ml] val impurityStats: ImpurityCalculator) extends Node {
-
- override def toString: String =
- s"LeafNode(prediction = $prediction, impurity = $impurity)"
-
- override private[ml] def predictImpl(features: Vector): LeafNode = this
-
- override private[ml] def predictImplX(binnedFeatures: Array[Int], splits: Array[Array[Split]]
- ): LeafNode = this
-
- override private[tree] def numDescendants: Int = 0
-
- override private[tree] def subtreeToString(indentFactor: Int = 0): String = {
- val prefix: String = " " * indentFactor
- s"$prefix" + s"Predict: $prediction\n"
- }
-
- override private[tree] def subtreeDepth: Int = 0
-
- override private[ml] def toOld(id: Int): OldNode = {
- new OldNode(id, new OldPredict(prediction, prob = impurityStats.prob(prediction)),
- impurity, isLeaf = true, None, None, None, None)
- }
-
- override private[ml] def maxSplitFeatureIndex(): Int = -1
-
- override private[tree] def deepCopy(): Node = {
- new LeafNode(prediction, impurity, impurityStats)
- }
-}
-
-/**
- * Internal Decision Tree node.
- * @param prediction Prediction this node would make if it were a leaf node
- * @param impurity Impurity measure at this node (for training data)
- * @param gain Information gain value. Values less than 0 indicate missing values;
- * this quirk will be removed with future updates.
- * @param leftChild Left-hand child node
- * @param rightChild Right-hand child node
- * @param split Information about the test used to split to the left or right child.
- */
-class InternalNode private[ml] (
- override val prediction: Double,
- override val impurity: Double,
- val gain: Double,
- val leftChild: Node,
- val rightChild: Node,
- val split: Split,
- override private[ml] val impurityStats: ImpurityCalculator) extends Node {
-
- // Note to developers: The constructor argument impurityStats should be reconsidered before we
- // make the constructor public. We may be able to improve the representation.
-
- override def toString: String = {
- s"InternalNode(prediction = $prediction, impurity = $impurity, split = $split)"
- }
-
- override private[ml] def predictImpl(features: Vector): LeafNode = {
- if (split.shouldGoLeft(features)) {
- leftChild.predictImpl(features)
- } else {
- rightChild.predictImpl(features)
- }
- }
-
- private[ml] def predictImplX(binnedFeatures: Array[Int], splits: Array[Array[Split]]
- ): LeafNode = {
- if (split.shouldGoLeft(binnedFeatures(split.featureIndex).toChar, splits(split.featureIndex))) {
- leftChild.predictImplX(binnedFeatures, splits)
- } else {
- rightChild.predictImplX(binnedFeatures, splits)
- }
- }
-
- override private[tree] def numDescendants: Int = {
- 2 + leftChild.numDescendants + rightChild.numDescendants
- }
-
- override private[tree] def subtreeToString(indentFactor: Int = 0): String = {
- val prefix: String = " " * indentFactor
- s"$prefix If (${InternalNode.splitToString(split, left = true)})\n" +
- leftChild.subtreeToString(indentFactor + 1) +
- s"$prefix Else (${InternalNode.splitToString(split, left = false)})\n" +
- rightChild.subtreeToString(indentFactor + 1)
- }
-
- override private[tree] def subtreeDepth: Int = {
- 1 + math.max(leftChild.subtreeDepth, rightChild.subtreeDepth)
- }
-
- override private[ml] def toOld(id: Int): OldNode = {
- assert(id.toLong * 2 < Int.MaxValue, "Decision Tree could not be converted from new to old API"
- + " since the old API does not support deep trees.")
- new OldNode(id, new OldPredict(prediction, prob = impurityStats.prob(prediction)), impurity,
- isLeaf = false, Some(split.toOld), Some(leftChild.toOld(OldNode.leftChildIndex(id))),
- Some(rightChild.toOld(OldNode.rightChildIndex(id))),
- Some(new OldInformationGainStats(gain, impurity, leftChild.impurity, rightChild.impurity,
- new OldPredict(leftChild.prediction, prob = 0.0),
- new OldPredict(rightChild.prediction, prob = 0.0))))
- }
-
- override private[ml] def maxSplitFeatureIndex(): Int = {
- math.max(split.featureIndex,
- math.max(leftChild.maxSplitFeatureIndex(), rightChild.maxSplitFeatureIndex()))
- }
-
- override private[tree] def deepCopy(): Node = {
- new InternalNode(prediction, impurity, gain, leftChild.deepCopy(), rightChild.deepCopy(),
- split, impurityStats)
- }
-}
-
-private object InternalNode {
-
- /**
- * Helper method for [[Node.subtreeToString()]].
- * @param split Split to print
- * @param left Indicates whether this is the part of the split going to the left,
- * or that going to the right.
- */
- private def splitToString(split: Split, left: Boolean): String = {
- val featureStr = s"feature ${split.featureIndex}"
- split match {
- case contSplit: ContinuousSplit =>
- if (left) {
- s"$featureStr <= ${contSplit.threshold}"
- } else {
- s"$featureStr > ${contSplit.threshold}"
- }
- case catSplit: CategoricalSplit =>
- val categoriesStr = catSplit.leftCategories.mkString("{", ",", "}")
- if (left) {
- s"$featureStr in $categoriesStr"
- } else {
- s"$featureStr not in $categoriesStr"
- }
- }
- }
-}
-
-/**
- * Version of a node used in learning. This uses vars so that we can modify nodes as we split the
- * tree by adding children, etc.
- *
- * For now, we use node IDs. These will be kept internal since we hope to remove node IDs
- * in the future, or at least change the indexing (so that we can support much deeper trees).
- *
- * This node can either be:
- * - a leaf node, with leftChild, rightChild, split set to null, or
- * - an internal node, with all values set
- *
- * @param id We currently use the same indexing as the old implementation in
- * [[org.apache.spark.mllib.tree.model.Node]], but this will change later.
- * @param isLeaf Indicates whether this node will definitely be a leaf in the learned tree,
- * so that we do not need to consider splitting it further.
- * @param stats Impurity statistics for this node.
- */
-private[tree] class LearningNodeX(
- var id: Int,
- var leftChild: Option[LearningNodeX],
- var rightChild: Option[LearningNodeX],
- var split: Option[SplitBase],
- var isLeaf: Boolean,
- var stats: ImpurityStats) extends Serializable {
-
- /**
- * Convert this [[LearningNodeX]] to a regular [[Node]], and recurse on any children.
- */
- def toNode(splits: Array[Array[Split]]): Node = {
- if (leftChild.nonEmpty) {
- assert(rightChild.nonEmpty && split.nonEmpty && stats != null,
- "Unknown error during Decision Tree learning. Could not convert LearningNodeX to Node.")
- val normalSplit = Split.fromBase(split.get, splits)
- new InternalNode(stats.impurityCalculator.predict, stats.impurity, stats.gain,
- leftChild.get.toNode(splits), rightChild.get.toNode(splits),
- normalSplit, stats.impurityCalculator)
- } else {
- if (stats.valid) {
- new LeafNode(stats.impurityCalculator.predict, stats.impurity,
- stats.impurityCalculator)
- } else {
- // Here we want to keep same behavior with the old mllib.DecisionTreeModel
- new LeafNode(stats.impurityCalculator.predict, -1.0, stats.impurityCalculator)
- }
-
- }
- }
-
- /**
- * Get the node index corresponding to this data point.
- * This function mimics prediction, passing an example from the root node down to a leaf
- * or unsplit node; that node's index is returned.
- *
- * @param binnedFeatures Binned feature vector for data point.
- * @param splits possible splits for all features, indexed (numFeatures)(numSplits)
- * @return Leaf index if the data point reaches a leaf.
- * Otherwise, last node reachable in tree matching this example.
- * Note: This is the global node index, i.e., the index used in the tree.
- * This index is different from the index used during training a particular
- * group of nodes on one call to
- * [[org.apache.spark.ml.tree.impl.RandomForest.findBestSplits()]].
- */
- def predictImpl(binnedFeatures: BinnedFeature, splits: Array[Array[SplitBase]]): Int = {
- if (this.isLeaf || this.split.isEmpty) {
- this.id
- } else {
- val split = this.split.get
- val featureIndex = split.featureIndex
- val splitLeft = split.shouldGoLeft(binnedFeatures.get(featureIndex), splits(featureIndex))
- if (this.leftChild.isEmpty) {
- // Not yet split. Return next layer of nodes to train
- if (splitLeft) {
- LearningNodeX.leftChildIndex(this.id)
- } else {
- LearningNodeX.rightChildIndex(this.id)
- }
- } else {
- if (splitLeft) {
- this.leftChild.get.predictImpl(binnedFeatures, splits)
- } else {
- this.rightChild.get.predictImpl(binnedFeatures, splits)
- }
- }
- }
- }
-
-}
-
-private[tree] object LearningNodeX {
-
- /** Create a node with some of its fields set. */
- def apply(
- id: Int,
- isLeaf: Boolean,
- stats: ImpurityStats): LearningNodeX = {
- // todo: this is a bug at spark 2.3.2 (isLeaf are always assigned false)
- new LearningNodeX(id, None, None, None, isLeaf, stats)
- }
-
- /** Create an empty node with the given node index. Values must be set later on. */
- def emptyNode(nodeIndex: Int): LearningNodeX = {
- new LearningNodeX(nodeIndex, None, None, None, false, null)
- }
-
- // The below indexing methods were copied from spark.mllib.tree.model.Node
-
- /**
- * Return the index of the left child of this node.
- */
- def leftChildIndex(nodeIndex: Int): Int = nodeIndex << 1
-
- /**
- * Return the index of the right child of this node.
- */
- def rightChildIndex(nodeIndex: Int): Int = (nodeIndex << 1) + 1
-
- /**
- * Get the parent index of the given node, or 0 if it is the root.
- */
- def parentIndex(nodeIndex: Int): Int = nodeIndex >> 1
-
- /**
- * Return the level of a tree which the given node is in.
- */
- def indexToLevel(nodeIndex: Int): Int = if (nodeIndex == 0) {
- throw new IllegalArgumentException(s"0 is not a valid node index.")
- } else {
- java.lang.Integer.numberOfTrailingZeros(java.lang.Integer.highestOneBit(nodeIndex))
- }
-
- /**
- * Returns true if this is a left child.
- * Note: Returns false for the root.
- */
- def isLeftChild(nodeIndex: Int): Boolean = nodeIndex > 1 && nodeIndex % 2 == 0
-
- /**
- * Return the maximum number of nodes which can be in the given level of the tree.
- * @param level Level of tree (0 = root).
- */
- def maxNodesInLevel(level: Int): Int = 1 << level
-
- /**
- * Return the index of the first node in the given level.
- * @param level Level of tree (0 = root).
- */
- def startIndexInLevel(level: Int): Int = 1 << level
-
- /**
- * Traces down from a root node to get the node with the given node index.
- * This assumes the node exists.
- */
- def getNode(nodeIndex: Int, rootNode: LearningNodeX): LearningNodeX = {
- var tmpNode: LearningNodeX = rootNode
- var levelsToGo = indexToLevel(nodeIndex)
- while (levelsToGo > 0) {
- if ((nodeIndex & (1 << levelsToGo - 1)) == 0) {
- tmpNode = tmpNode.leftChild.get
- } else {
- tmpNode = tmpNode.rightChild.get
- }
- levelsToGo -= 1
- }
- tmpNode
- }
-
-}
-
-/**
- * Version of a node used in learning. This uses vars so that we can modify nodes as we split the
- * tree by adding children, etc.
- *
- * For now, we use node IDs. These will be kept internal since we hope to remove node IDs
- * in the future, or at least change the indexing (so that we can support much deeper trees).
- *
- * This node can either be:
- * - a leaf node, with leftChild, rightChild, split set to null, or
- * - an internal node, with all values set
- *
- * @param id We currently use the same indexing as the old implementation in
- * [[org.apache.spark.mllib.tree.model.Node]], but this will change later.
- * @param isLeaf Indicates whether this node will definitely be a leaf in the learned tree,
- * so that we do not need to consider splitting it further.
- * @param stats Impurity statistics for this node.
- */
-private[tree] class LearningNode(
- var id: Int,
- var leftChild: Option[LearningNode],
- var rightChild: Option[LearningNode],
- var split: Option[Split],
- var isLeaf: Boolean,
- var stats: ImpurityStats) extends Serializable {
-
- /**
- * Convert this [[LearningNode]] to a regular [[Node]], and recurse on any children.
- */
- def toNode: Node = {
- if (leftChild.nonEmpty) {
- assert(rightChild.nonEmpty && split.nonEmpty && stats != null,
- "Unknown error during Decision Tree learning. Could not convert LearningNode to Node.")
- new InternalNode(stats.impurityCalculator.predict, stats.impurity, stats.gain,
- leftChild.get.toNode, rightChild.get.toNode, split.get, stats.impurityCalculator)
- } else {
- if (stats.valid) {
- new LeafNode(stats.impurityCalculator.predict, stats.impurity,
- stats.impurityCalculator)
- } else {
- // Here we want to keep same behavior with the old mllib.DecisionTreeModel
- new LeafNode(stats.impurityCalculator.predict, -1.0, stats.impurityCalculator)
- }
-
- }
- }
-
- /**
- * Get the node index corresponding to this data point.
- * This function mimics prediction, passing an example from the root node down to a leaf
- * or unsplit node; that node's index is returned.
- *
- * @param binnedFeatures Binned feature vector for data point.
- * @param splits possible splits for all features, indexed (numFeatures)(numSplits)
- * @return Leaf index if the data point reaches a leaf.
- * Otherwise, last node reachable in tree matching this example.
- * Note: This is the global node index, i.e., the index used in the tree.
- * This index is different from the index used during training a particular
- * group of nodes on one call to
- * [[org.apache.spark.ml.tree.impl.RandomForest.findBestSplits()]].
- */
- def predictImpl(binnedFeatures: Array[Int], splits: Array[Array[Split]]): Int = {
- if (this.isLeaf || this.split.isEmpty) {
- this.id
- } else {
- val split = this.split.get
- val featureIndex = split.featureIndex
- val splitLeft = split.shouldGoLeft(binnedFeatures(featureIndex), splits(featureIndex))
- if (this.leftChild.isEmpty) {
- // Not yet split. Return next layer of nodes to train
- if (splitLeft) {
- LearningNode.leftChildIndex(this.id)
- } else {
- LearningNode.rightChildIndex(this.id)
- }
- } else {
- if (splitLeft) {
- this.leftChild.get.predictImpl(binnedFeatures, splits)
- } else {
- this.rightChild.get.predictImpl(binnedFeatures, splits)
- }
- }
- }
- }
-
- /**
- * Get the node index corresponding to this data point.
- * This function mimics prediction, passing an example from the root node down to a leaf
- * or unsplit node; that node's index is returned.
- *
- * @param binnedFeatures Binned feature vector for data point.
- * @param splits possible splits for all features, indexed (numFeatures)(numSplits)
- * @return Leaf index if the data point reaches a leaf.
- * Otherwise, last node reachable in tree matching this example.
- * Note: This is the global node index, i.e., the index used in the tree.
- * This index is different from the index used during training a particular
- * group of nodes on one call to
- * [[org.apache.spark.ml.tree.impl.RandomForest.findBestSplits()]].
- */
- def predictImpl(binnedFeatures: BinnedFeature, splits: Array[Array[Split]]): Int = {
- if (this.isLeaf || this.split.isEmpty) {
- this.id
- } else {
- val split = this.split.get
- val featureIndex = split.featureIndex
- val splitLeft = split.shouldGoLeft(binnedFeatures.get(featureIndex), splits(featureIndex))
- if (this.leftChild.isEmpty) {
- // Not yet split. Return next layer of nodes to train
- if (splitLeft) {
- LearningNode.leftChildIndex(this.id)
- } else {
- LearningNode.rightChildIndex(this.id)
- }
- } else {
- if (splitLeft) {
- this.leftChild.get.predictImpl(binnedFeatures, splits)
- } else {
- this.rightChild.get.predictImpl(binnedFeatures, splits)
- }
- }
- }
- }
-
-}
-
-
-private[tree] object LearningNode {
-
- /** Create a node with some of its fields set. */
- def apply(
- id: Int,
- isLeaf: Boolean,
- stats: ImpurityStats): LearningNode = {
- // todo: this is a bug at spark 2.3.2 (isLeaf are always assigned false)
- new LearningNode(id, None, None, None, isLeaf, stats)
- }
-
- /** Create an empty node with the given node index. Values must be set later on. */
- def emptyNode(nodeIndex: Int): LearningNode = {
- new LearningNode(nodeIndex, None, None, None, false, null)
- }
-
- // The below indexing methods were copied from spark.mllib.tree.model.Node
-
- /**
- * Return the index of the left child of this node.
- */
- def leftChildIndex(nodeIndex: Int): Int = nodeIndex << 1
-
- /**
- * Return the index of the right child of this node.
- */
- def rightChildIndex(nodeIndex: Int): Int = (nodeIndex << 1) + 1
-
- /**
- * Get the parent index of the given node, or 0 if it is the root.
- */
- def parentIndex(nodeIndex: Int): Int = nodeIndex >> 1
-
- /**
- * Return the level of a tree which the given node is in.
- */
- def indexToLevel(nodeIndex: Int): Int = if (nodeIndex == 0) {
- throw new IllegalArgumentException(s"0 is not a valid node index.")
- } else {
- java.lang.Integer.numberOfTrailingZeros(java.lang.Integer.highestOneBit(nodeIndex))
- }
-
- /**
- * Returns true if this is a left child.
- * Note: Returns false for the root.
- */
- def isLeftChild(nodeIndex: Int): Boolean = nodeIndex > 1 && nodeIndex % 2 == 0
-
- /**
- * Return the maximum number of nodes which can be in the given level of the tree.
- * @param level Level of tree (0 = root).
- */
- def maxNodesInLevel(level: Int): Int = 1 << level
-
- /**
- * Return the index of the first node in the given level.
- * @param level Level of tree (0 = root).
- */
- def startIndexInLevel(level: Int): Int = 1 << level
-
- /**
- * Traces down from a root node to get the node with the given node index.
- * This assumes the node exists.
- */
- def getNode(nodeIndex: Int, rootNode: LearningNode): LearningNode = {
- var tmpNode: LearningNode = rootNode
- var levelsToGo = indexToLevel(nodeIndex)
- while (levelsToGo > 0) {
- if ((nodeIndex & (1 << levelsToGo - 1)) == 0) {
- tmpNode = tmpNode.leftChild.get
- } else {
- tmpNode = tmpNode.rightChild.get
- }
- levelsToGo -= 1
- }
- tmpNode
- }
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/Split.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/Split.scala
deleted file mode 100644
index dbea593..0000000
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/Split.scala
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree
-
-import java.util.Objects
-
-import org.apache.spark.annotation.Since
-import org.apache.spark.ml.linalg.Vector
-import org.apache.spark.mllib.tree.configuration.{FeatureType => OldFeatureType}
-import org.apache.spark.mllib.tree.model.{Split => OldSplit}
-
-
-/**
- * Interface for a "Split," which specifies a test made at a decision tree node
- * to choose the left or right path.
- */
-sealed trait SplitBase extends Serializable {
-
- /** Index of feature which this split tests */
- def featureIndex: Int
-
- /**
- * Return true (split to left) or false (split to right).
- * @param binnedFeature Binned feature value.
- * @param splits All splits for the given feature.
- */
- private[tree] def shouldGoLeft(binnedFeature: Char, splits: Array[SplitBase]): Boolean
-}
-
-sealed trait Split extends SplitBase {
- /**
- * Return true (split to left) or false (split to right).
- * @param features Vector of features (original values, not binned).
- */
- private[ml] def shouldGoLeft(features: Vector): Boolean
-
- /**
- * Return true (split to left) or false (split to right).
- * @param binnedFeature Binned feature value.
- * @param splits All splits for the given feature.
- */
- private[tree] def shouldGoLeft(binnedFeature: Int, splits: Array[Split]): Boolean
-
- /** Convert to old Split format */
- private[tree] def toOld: OldSplit
-}
-
-private[tree] object Split {
-
- def fromOld(oldSplit: OldSplit, categoricalFeatures: Map[Int, Int]): Split = {
- oldSplit.featureType match {
- case OldFeatureType.Categorical =>
- new CategoricalSplit(featureIndex = oldSplit.feature,
- _leftCategories = oldSplit.categories.toArray, categoricalFeatures(oldSplit.feature))
- case OldFeatureType.Continuous =>
- new ContinuousSplit(featureIndex = oldSplit.feature, threshold = oldSplit.threshold)
- }
- }
-
- def toBase(split: Split, binIdx: Int): SplitBase = {
- split match {
- case value: CategoricalSplit =>
- value
- case value: ContinuousSplit =>
- new ContinuousSplitLearning(value.featureIndex, binIdx)
- }
- }
-
- def fromBase(baseSplit: SplitBase, splits: Array[Array[Split]]): Split = {
- baseSplit match {
- case value: CategoricalSplit =>
- value
- case value: ContinuousSplit =>
- value
- case value: ContinuousSplitLearning =>
- val thresh =
- splits(value.featureIndex)(value.binIndex).asInstanceOf[ContinuousSplit].threshold
- new ContinuousSplit(value.featureIndex, thresh)
- }
- }
-}
-
-/**
- * Split which tests a categorical feature.
- * @param featureIndex Index of the feature to test
- * @param _leftCategories If the feature value is in this set of categories, then the split goes
- * left. Otherwise, it goes right.
- * @param numCategories Number of categories for this feature.
- */
-class CategoricalSplit private[ml] (
- override val featureIndex: Int,
- _leftCategories: Array[Double],
- @Since("2.0.0") val numCategories: Int)
- extends Split {
-
- require(_leftCategories.forall(cat => 0 <= cat && cat < numCategories), "Invalid leftCategories" +
- s" (should be in range [0, $numCategories)): ${_leftCategories.mkString(",")}")
-
- /**
- * If true, then "categories" is the set of categories for splitting to the left, and vice versa.
- */
- private val isLeft: Boolean = _leftCategories.length <= numCategories / 2
-
- /** Set of categories determining the splitting rule, along with [[isLeft]]. */
- private val categories: Set[Double] = {
- if (isLeft) {
- _leftCategories.toSet
- } else {
- setComplement(_leftCategories.toSet)
- }
- }
-
- override private[ml] def shouldGoLeft(features: Vector): Boolean = {
- if (isLeft) {
- categories.contains(features(featureIndex))
- } else {
- !categories.contains(features(featureIndex))
- }
- }
-
- override private[tree] def shouldGoLeft(binnedFeature: Int, splits: Array[Split]): Boolean = {
- if (isLeft) {
- categories.contains(binnedFeature.toDouble)
- } else {
- !categories.contains(binnedFeature.toDouble)
- }
- }
-
- override private[tree] def shouldGoLeft(
- binnedFeature: Char,
- splits: Array[SplitBase]): Boolean = {
- if (isLeft) {
- categories.contains(binnedFeature.toDouble)
- } else {
- !categories.contains(binnedFeature.toDouble)
- }
- }
-
- override def hashCode(): Int = {
- val state = Seq(featureIndex, isLeft, categories)
- state.map(Objects.hashCode).foldLeft(0)((a, b) => 31 * a + b)
- }
-
- override def equals(o: Any): Boolean = o match {
- case other: CategoricalSplit => featureIndex == other.featureIndex &&
- isLeft == other.isLeft && categories == other.categories
- case _ => false
- }
-
- override private[tree] def toOld: OldSplit = {
- val oldCats = if (isLeft) {
- categories
- } else {
- setComplement(categories)
- }
- OldSplit(featureIndex, threshold = 0.0, OldFeatureType.Categorical, oldCats.toList)
- }
-
- /** Get sorted categories which split to the left */
- def leftCategories: Array[Double] = {
- val cats = if (isLeft) categories else setComplement(categories)
- cats.toArray.sorted
- }
-
- /** Get sorted categories which split to the right */
- def rightCategories: Array[Double] = {
- val cats = if (isLeft) setComplement(categories) else categories
- cats.toArray.sorted
- }
-
- /** [0, numCategories) \ cats */
- private def setComplement(cats: Set[Double]): Set[Double] = {
- Range(0, numCategories).map(_.toDouble).filter(cat => !cats.contains(cat)).toSet
- }
-}
-
-/**
- * Split which tests a continuous feature.
- * @param featureIndex Index of the feature to test
- * @param threshold If the feature value is less than or equal to this threshold, then the
- * split goes left. Otherwise, it goes right.
- */
-class ContinuousSplit private[ml] (override val featureIndex: Int, val threshold: Double)
- extends Split {
-
- override private[ml] def shouldGoLeft(features: Vector): Boolean = {
- features(featureIndex) <= threshold
- }
-
- override private[tree] def shouldGoLeft(binnedFeature: Int, splits: Array[Split]): Boolean = {
- if (binnedFeature == splits.length) {
- // > last split, so split right
- false
- } else {
- val featureValueUpperBound = splits(binnedFeature).asInstanceOf[ContinuousSplit].threshold
- featureValueUpperBound <= threshold
- }
- }
-
- override private[tree] def shouldGoLeft(
- binnedFeature: Char,
- splits: Array[SplitBase]): Boolean = {
-
- if (binnedFeature == splits.length) {
- // > last split, so split right
- false
- } else {
- val featureValueUpperBound = splits(binnedFeature).asInstanceOf[ContinuousSplit].threshold
- featureValueUpperBound <= threshold
- }
- }
-
- override def equals(o: Any): Boolean = {
- o match {
- case other: ContinuousSplit =>
- featureIndex == other.featureIndex && threshold == other.threshold
- case _ =>
- false
- }
- }
-
- override def hashCode(): Int = {
- val state = Seq(featureIndex, threshold)
- state.map(Objects.hashCode).foldLeft(0)((a, b) => 31 * a + b)
- }
-
- override private[tree] def toOld: OldSplit = {
- OldSplit(featureIndex, threshold, OldFeatureType.Continuous, List.empty[Double])
- }
-}
-
-/**
- * Split which tests a continuous feature.
- * @param featureIndex Index of the feature to test
- * @param binIndex If the binned feature value is less than or equal to this bin index, then the
- * split goes left. Otherwise, it goes right.
- */
-class ContinuousSplitLearning private[ml] (override val featureIndex: Int, val binIndex: Int)
- extends SplitBase {
-
- override private[tree] def shouldGoLeft(
- binnedFeature: Char,
- splits: Array[SplitBase]): Boolean = {
-
- if (binnedFeature == splits.length) {
- // > last split, so split right
- false
- } else {
- binnedFeature <= binIndex
- }
- }
-
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/BaggedPoint.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/BaggedPoint.scala
deleted file mode 100644
index c2f8822..0000000
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/BaggedPoint.scala
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import org.apache.commons.math3.distribution.PoissonDistribution
-
-import org.apache.spark.rdd.RDD
-import org.apache.spark.util.Utils
-import org.apache.spark.util.random.XORShiftRandom
-
-/**
- * Internal representation of a datapoint which belongs to several subsamples of the same dataset,
- * particularly for bagging (e.g., for random forests).
- *
- * This holds one instance, as well as an array of weights which represent the (weighted)
- * number of times which this instance appears in each subsamplingRate.
- * E.g., (datum, [1, 0, 4]) indicates that there are 3 subsamples of the dataset and that
- * this datum has 1 copy, 0 copies, and 4 copies in the 3 subsamples, respectively.
- *
- * @param datum Data instance
- * @param subsampleWeights Weight of this instance in each subsampled dataset.
- * @param sampleId ID of sample
- *
- * TODO: This does not currently support (Double) weighted instances. Once MLlib has weighted
- * dataset support, update. (We store subsampleWeights as Double for this future extension.)
- */
-private[spark] class BaggedPoint[Datum](
- val datum: Datum,
- val subsampleWeights: Array[Int],
- var sampleId: Short = 0)
- extends Serializable
-
-private[spark] object BaggedPoint {
-
- /**
- * Convert an input dataset into its BaggedPoint representation,
- * choosing subsamplingRate counts for each instance.
- * Each subsamplingRate has the same number of instances as the original dataset,
- * and is created by subsampling without replacement.
- * @param input Input dataset.
- * @param subsamplingRate Fraction of the training data used for learning decision tree.
- * @param numSubsamples Number of subsamples of this RDD to take.
- * @param withReplacement Sampling with/without replacement.
- * @param seed Random seed.
- * @return BaggedPoint dataset representation.
- */
- def convertToBaggedRDD[Datum] (
- input: RDD[Datum],
- subsamplingRate: Double,
- numSubsamples: Int,
- withReplacement: Boolean,
- seed: Long = Utils.random.nextLong()): RDD[BaggedPoint[Datum]] = {
- if (withReplacement) {
- convertToBaggedRDDSamplingWithReplacement(input, subsamplingRate, numSubsamples, seed)
- } else {
- if (numSubsamples == 1 && subsamplingRate == 1.0) {
- convertToBaggedRDDWithoutSampling(input)
- } else {
- convertToBaggedRDDSamplingWithoutReplacement(input, subsamplingRate, numSubsamples, seed)
- }
- }
- }
-
- private def convertToBaggedRDDSamplingWithoutReplacement[Datum] (
- input: RDD[Datum],
- subsamplingRate: Double,
- numSubsamples: Int,
- seed: Long): RDD[BaggedPoint[Datum]] = {
- input.mapPartitionsWithIndex { (partitionIndex, instances) =>
- // Use random seed = seed + partitionIndex + 1 to make generation reproducible.
- val rng = new XORShiftRandom
- rng.setSeed(seed + partitionIndex + 1)
- instances.map { instance =>
- val subsampleWeights = new Array[Int](numSubsamples)
- var subsampleIndex = 0
- while (subsampleIndex < numSubsamples) {
- val x = rng.nextDouble()
- subsampleWeights(subsampleIndex) = {
- if (x < subsamplingRate) 1 else 0
- }
- subsampleIndex += 1
- }
- new BaggedPoint(instance, subsampleWeights)
- }
- }
- }
-
- private def convertToBaggedRDDSamplingWithReplacement[Datum] (
- input: RDD[Datum],
- subsample: Double,
- numSubsamples: Int,
- seed: Long): RDD[BaggedPoint[Datum]] = {
- input.mapPartitionsWithIndex { (partitionIndex, instances) =>
- // Use random seed = seed + partitionIndex + 1 to make generation reproducible.
- val poisson = new PoissonDistribution(subsample)
- poisson.reseedRandomGenerator(seed + partitionIndex + 1)
- instances.map { instance =>
- val subsampleWeights = new Array[Int](numSubsamples)
- var subsampleIndex = 0
- while (subsampleIndex < numSubsamples) {
- subsampleWeights(subsampleIndex) = poisson.sample()
- subsampleIndex += 1
- }
- new BaggedPoint(instance, subsampleWeights)
- }
- }
- }
-
- private def convertToBaggedRDDWithoutSampling[Datum] (
- input: RDD[Datum]): RDD[BaggedPoint[Datum]] = {
- input.map(datum => new BaggedPoint(datum, Array(1)))
- }
-
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/DTFeatureStatsAggregator.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/DTFeatureStatsAggregator.scala
deleted file mode 100644
index 3d98a41..0000000
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/DTFeatureStatsAggregator.scala
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import org.apache.spark.mllib.tree.impurity._
-
-
-/**
- * DecisionTree statistics aggregator for a feature for a node.
- * This class is abstract to support learning with and without feature subsampling.
- */
-private[spark] class DTFeatureStatsAggregator(
- val metadata: DecisionTreeMetadata,
- val _featureIndex: Int) extends Serializable {
-
- /**
- * [[ImpurityAggregator]] instance specifying the impurity type.
- */
-
- val impurityAggregator = new VarianceAggregator()
-
- val featureIndex: Int = _featureIndex
-
- /**
- * Number of elements (Double values) used for the sufficient statistics of each bin.
- */
- private val statsSize: Int = impurityAggregator.statsSize
-
- /**
- * Number of bins for the feature.
- */
- private val numBins: Int = {
- metadata.numBins(featureIndex)
- }
-
- /**
- * Total number of elements stored in this aggregator
- */
- private val allStatsSize: Int = numBins * statsSize
-
- /**
- * Flat array of elements.
- */
- private val allStats: Array[Double] = new Array[Double](allStatsSize)
-
- /**
- * Array of parent node sufficient stats.
- */
- private val parentStats: Array[Double] = new Array[Double](statsSize)
-
- /**
- * Get an [[ImpurityCalculator]] for a given (node, feature, bin).
- */
- def getImpurityCalculator(featureOffset: Int, binIndex: Int): ImpurityCalculator = {
- impurityAggregator.getCalculator(allStats, binIndex * statsSize)
- }
-
- /**
- * Get an [[ImpurityCalculator]] for the parent node.
- */
- def getParentImpurityCalculator(): ImpurityCalculator = {
- impurityAggregator.getCalculator(parentStats, 0)
- }
-
- /**
- * Update the stats for a given bin for ordered features, using the given label.
- */
- def updateX(featureIndex: Int, binIndex: Int, label: Double): Unit = {
- val i = binIndex * statsSize
- impurityAggregator.updateX(allStats, i, label)
- }
-
- /**
- * Pre-compute feature offset for use with [[featureUpdate]].
- * For ordered features only.
- */
- def getFeatureOffset(featureIndex: Int): Int = 0
-
- /**
- * For a given feature, merge the stats for two bins.
- *
- * @param featureOffset This is a pre-computed feature offset
- * from [[getFeatureOffset]].
- * @param binIndex The other bin is merged into this bin.
- * @param otherBinIndex This bin is not modified. X
- */
- def mergeForFeature(featureOffset: Int, binIndex: Int, otherBinIndex: Int): Unit = {
- impurityAggregator.merge(allStats, binIndex * statsSize, otherBinIndex * statsSize)
- }
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/DTStatsAggregator.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/DTStatsAggregator.scala
deleted file mode 100644
index e18154f..0000000
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/DTStatsAggregator.scala
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import org.apache.spark.mllib.tree.impurity._
-
-
-
-/**
- * DecisionTree statistics aggregator for a node.
- * This holds a flat array of statistics for a set of (features, bins)
- * and helps with indexing.
- * This class is abstract to support learning with and without feature subsampling.
- */
-private[spark] class DTStatsAggregator(
- val metadata: DecisionTreeMetadata,
- featureSubset: Option[Array[Int]]) extends Serializable {
-
- /**
- * [[ImpurityAggregator]] instance specifying the impurity type.
- */
- val impurityAggregator: ImpurityAggregator = metadata.impurity match {
- case Gini => new GiniAggregator(metadata.numClasses)
- case Entropy => new EntropyAggregator(metadata.numClasses)
- case Variance => new VarianceAggregator()
- case _ => throw new IllegalArgumentException(s"Bad impurity parameter: ${metadata.impurity}")
- }
-
- /**
- * Number of elements (Double values) used for the sufficient statistics of each bin.
- */
- private val statsSize: Int = impurityAggregator.statsSize
-
- /**
- * Number of bins for each feature. This is indexed by the feature index.
- */
- private val numBins: Array[Int] = {
- if (featureSubset.isDefined) {
- featureSubset.get.map(metadata.numBins(_))
- } else {
- metadata.numBins
- }
- }
-
- /**
- * Offset for each feature for calculating indices into the [[allStats]] array.
- */
- private val featureOffsets: Array[Int] = {
- numBins.scanLeft(0)((total, nBins) => total + statsSize * nBins)
- }
-
- /**
- * Total number of elements stored in this aggregator
- */
- private val allStatsSize: Int = featureOffsets.last
-
- /**
- * Flat array of elements.
- * Index for start of stats for a (feature, bin) is:
- * index = featureOffsets(featureIndex) + binIndex * statsSize
- */
- private val allStats: Array[Double] = new Array[Double](allStatsSize)
-
- /**
- * Array of parent node sufficient stats.
- * Note: parent stats need to be explicitly tracked in the [[DTStatsAggregator]] for unordered
- * categorical features, because the parent [[Node]] object does not have [[ImpurityStats]]
- * on the first iteration.
- */
- private val parentStats: Array[Double] = new Array[Double](statsSize)
-
- /**
- * Get an [[ImpurityCalculator]] for a given (node, feature, bin).
- *
- * @param featureOffset This is a pre-computed (node, feature) offset
- * from [[getFeatureOffset]].
- */
- def getImpurityCalculator(featureOffset: Int, binIndex: Int): ImpurityCalculator = {
- impurityAggregator.getCalculator(allStats, featureOffset + binIndex * statsSize)
- }
-
- /**
- * Get an [[ImpurityCalculator]] for the parent node.
- */
- def getParentImpurityCalculator(): ImpurityCalculator = {
- impurityAggregator.getCalculator(parentStats, 0)
- }
-
- /**
- * Update the stats for a given (feature, bin) for ordered features, using the given label.
- */
- def update(featureIndex: Int, binIndex: Int, label: Double, instanceWeight: Int): Unit = {
- val i = featureOffsets(featureIndex) + binIndex * statsSize
- impurityAggregator.update(allStats, i, label, instanceWeight)
- }
-
- /**
- * Update the parent node stats using the given label.
- */
- def updateParent(label: Double, instanceWeight: Int): Unit = {
- impurityAggregator.update(parentStats, 0, label, instanceWeight)
- }
-
- /**
- * Faster version of [[update]].
- * Update the stats for a given (feature, bin), using the given label.
- *
- * @param featureOffset This is a pre-computed feature offset
- * from [[getFeatureOffset]].
- */
- def featureUpdate(
- featureOffset: Int,
- binIndex: Int,
- label: Double,
- instanceWeight: Int): Unit = {
- impurityAggregator.update(allStats, featureOffset + binIndex * statsSize,
- label, instanceWeight)
- }
-
- /**
- * Pre-compute feature offset for use with [[featureUpdate]].
- * For ordered features only.
- */
- def getFeatureOffset(featureIndex: Int): Int = featureOffsets(featureIndex)
-
- /**
- * For a given feature, merge the stats for two bins.
- *
- * @param featureOffset This is a pre-computed feature offset
- * from [[getFeatureOffset]].
- * @param binIndex The other bin is merged into this bin.
- * @param otherBinIndex This bin is not modified.
- */
- def mergeForFeature(featureOffset: Int, binIndex: Int, otherBinIndex: Int): Unit = {
- impurityAggregator.merge(allStats, featureOffset + binIndex * statsSize,
- featureOffset + otherBinIndex * statsSize)
- }
-
- /**
- * Merge this aggregator with another, and returns this aggregator.
- * This method modifies this aggregator in-place.
- */
- def merge(other: DTStatsAggregator): DTStatsAggregator = {
- require(allStatsSize == other.allStatsSize,
- s"DTStatsAggregator.merge requires that both aggregators have the same length stats vectors."
- + s" This aggregator is of length $allStatsSize, but the other is ${other.allStatsSize}.")
- var i = 0
- // TODO: Test BLAS.axpy
- while (i < allStatsSize) {
- allStats(i) += other.allStats(i)
- i += 1
- }
-
- require(statsSize == other.statsSize,
- s"DTStatsAggregator.merge requires that both aggregators have the same length parent " +
- s"stats vectors. This aggregator's parent stats are length $statsSize, " +
- s"but the other is ${other.statsSize}.")
- var j = 0
- while (j < statsSize) {
- parentStats(j) += other.parentStats(j)
- j += 1
- }
-
- this
- }
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTreesCore.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTreesCore.scala
deleted file mode 100644
index 24e1930..0000000
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTreesCore.scala
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.tree.impl
-
-import it.unimi.dsi.fastutil.objects.ObjectArrayList
-
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.tree.{CategoricalSplit, ContinuousSplit, LearningNode, Split}
-import org.apache.spark.mllib.tree.impurity.ImpurityCalculator
-import org.apache.spark.mllib.tree.model.ImpurityStats
-
-object GradientBoostedTreesCore extends Logging{
- private[tree] class NodeIndexInfo(
- val nodeIndexInGroup: Int,
- val featureSubset: Option[Array[Int]],
- val featureSubsetHashSetX: Option[scala.collection.mutable.HashSet[Int]] = None)
- extends Serializable
-
- /**
- * Calculate the impurity statistics for a given (feature, split) based upon left/right
- * aggregates.
- *
- * @param stats the recycle impurity statistics for this feature's all splits,
- * only 'impurity' and 'impurityCalculator' are valid between each iteration
- * @param leftImpurityCalculator left node aggregates for this (feature, split)
- * @param rightImpurityCalculator right node aggregate for this (feature, split)
- * @param metadata learning and dataset metadata for DecisionTree
- * @return Impurity statistics for this (feature, split)
- */
- private def calculateImpurityStats(
- stats: ImpurityStats,
- leftImpurityCalculator: ImpurityCalculator,
- rightImpurityCalculator: ImpurityCalculator,
- metadata: DecisionTreeMetadata): ImpurityStats = {
-
- val parentImpurityCalculator: ImpurityCalculator = if (stats == null) {
- leftImpurityCalculator.copy.add(rightImpurityCalculator)
- } else {
- stats.impurityCalculator
- }
-
- val impurity: Double = if (stats == null) {
- parentImpurityCalculator.calculate()
- } else {
- stats.impurity
- }
-
- val leftCount = leftImpurityCalculator.count
- val rightCount = rightImpurityCalculator.count
-
- val totalCount = leftCount + rightCount
-
- // If left child or right child doesn't satisfy minimum instances per node,
- // then this split is invalid, return invalid information gain stats.
- if ((leftCount < metadata.minInstancesPerNode) ||
- (rightCount < metadata.minInstancesPerNode)) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- val leftImpurity = leftImpurityCalculator.calculate() // Note: This equals 0 if count = 0
- val rightImpurity = rightImpurityCalculator.calculate()
-
- val leftWeight = leftCount / totalCount.toDouble
- val rightWeight = rightCount / totalCount.toDouble
-
- val gain = impurity - leftWeight * leftImpurity - rightWeight * rightImpurity
-
- // if information gain doesn't satisfy minimum information gain,
- // then this split is invalid, return invalid information gain stats.
- if (gain < metadata.minInfoGain) {
- return ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator)
- }
-
- new ImpurityStats(gain, impurity, parentImpurityCalculator,
- leftImpurityCalculator, rightImpurityCalculator)
- }
-
- /**
- * Find the best split for a node.
- *
- * @param binAggregates Bin statistics.
- * @return tuple for best split: (Split, information gain, prediction at node)
- */
- private[tree] def binsToBestSplitX(
- binAggregates: DTFeatureStatsAggregator,
- splits: ObjectArrayList[Split],
- featureIndex: Int,
- node: LearningNode): (Split, ImpurityStats) = {
-
- // Calculate InformationGain and ImpurityStats if current node is top node
- val level = LearningNode.indexToLevel(node.id)
- var gainAndImpurityStats: ImpurityStats = if (level == 0) {
- null
- } else {
- node.stats
- }
-
- if (binAggregates.metadata.numSplits(featureIndex) != 0) {
- val featureIndexIdx = featureIndex
- val numSplits = binAggregates.metadata.numSplits(featureIndex)
- if (binAggregates.metadata.isContinuous(featureIndex)) {
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- var splitIndex = 0
- while (splitIndex < numSplits) {
- binAggregates.mergeForFeature(0, splitIndex + 1, splitIndex)
- splitIndex += 1
- }
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { case splitIdx =>
- val leftChildStats = binAggregates.getImpurityCalculator(0, splitIdx)
- val rightChildStats =
- binAggregates.getImpurityCalculator(0, numSplits)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIdx, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits.get(bestFeatureSplitIndex), bestFeatureGainStats)
- } else if (binAggregates.metadata.isUnordered(featureIndex)) {
- // unreachable for GBDT
- // Unordered categorical feature
- // val leftChildOffset = binAggregates.getFeatureOffset(featureIndexIdx)
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val leftChildStats = binAggregates.getImpurityCalculator(0, splitIndex)
- val rightChildStats = binAggregates.getImpurityCalculator(0, numSplits)
- .subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- (splits.get(bestFeatureSplitIndex), bestFeatureGainStats)
- } else {
- // Ordered categorical feature
- val numCategories = binAggregates.metadata.numBins(featureIndex)
-
- /* Each bin is one category (feature value).
- * The bins are ordered based on centroidForCategories, and this ordering determines which
- * splits are considered. (With K categories, we consider K - 1 possible splits.)
- *
- * centroidForCategories is a list: (category, centroid)
- */
- val centroidForCategories = Range(0, numCategories).map { case featureValue =>
- val categoryStats =
- binAggregates.getImpurityCalculator(0, featureValue)
- val centroid = if (categoryStats.count != 0) {
- if (binAggregates.metadata.isMulticlass) {
- // unreachable for GBDT
- // multiclass classification
- // For categorical variables in multiclass classification,
- // the bins are ordered by the impurity of their corresponding labels.
- categoryStats.calculate()
- } else if (binAggregates.metadata.isClassification) {
- // unreachable for GBDT
- // binary classification
- // For categorical variables in binary classification,
- // the bins are ordered by the count of class 1.
- categoryStats.stats(1)
- } else {
- // regression
- // For categorical variables in regression and binary classification,
- // the bins are ordered by the prediction.
- categoryStats.predict
- }
- } else {
- Double.MaxValue
- }
- (featureValue, centroid)
- }
-
- logDebug(s"Centroids for categorical variable: ${centroidForCategories.mkString(",")}")
-
- // bins sorted by centroids
- val categoriesSortedByCentroid = centroidForCategories.toList.sortBy(_._2)
-
- logDebug("Sorted centroids for categorical variable = " +
- categoriesSortedByCentroid.mkString(","))
-
- // Cumulative sum (scanLeft) of bin statistics.
- // Afterwards, binAggregates for a bin is the sum of aggregates for
- // that bin + all preceding bins.
- var splitIndex = 0
- while (splitIndex < numSplits) {
- val currentCategory = categoriesSortedByCentroid(splitIndex)._1
- val nextCategory = categoriesSortedByCentroid(splitIndex + 1)._1
- binAggregates.mergeForFeature(0, nextCategory, currentCategory)
- splitIndex += 1
- }
- // lastCategory = index of bin with total aggregates for this (node, feature)
- val lastCategory = categoriesSortedByCentroid.last._1
- // Find best split.
- val (bestFeatureSplitIndex, bestFeatureGainStats) =
- Range(0, numSplits).map { splitIndex =>
- val featureValue = categoriesSortedByCentroid(splitIndex)._1
- val leftChildStats =
- binAggregates.getImpurityCalculator(0, featureValue)
- val rightChildStats =
- binAggregates.getImpurityCalculator(0, lastCategory)
- rightChildStats.subtract(leftChildStats)
- gainAndImpurityStats = calculateImpurityStats(gainAndImpurityStats,
- leftChildStats, rightChildStats, binAggregates.metadata)
- (splitIndex, gainAndImpurityStats)
- }.maxBy(_._2.gain)
- val categoriesForSplit =
- categoriesSortedByCentroid.map(_._1.toDouble).slice(0, bestFeatureSplitIndex + 1)
- val bestFeatureSplit =
- new CategoricalSplit(featureIndex, categoriesForSplit.toArray, numCategories)
- (bestFeatureSplit, bestFeatureGainStats)
- }
- } else {
- // If no valid splits for features, then this split is invalid,
- // return invalid information gain stats. Take any split and continue.
- // Splits is empty, so arbitrarily choose to split on any threshold
- // val parentImpurityCalculator = binAggregates.getParentImpurityCalculator()
- // No split, no need to merge
- val featureIndexIdx = featureIndex
- val numSplits = binAggregates.metadata.numSplits(featureIndex)
- val parentImpurityCalculator = binAggregates.getImpurityCalculator(0, numSplits)
- if (binAggregates.metadata.isContinuous(featureIndex)) {
- (new ContinuousSplit(featureIndex, 0),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- } else {
- // Seems like unreachable for GBDT (as well as RF)
- val numCategories = binAggregates.metadata.featureArity(featureIndex)
- (new CategoricalSplit(featureIndex, Array(), numCategories),
- ImpurityStats.getInvalidImpurityStats(parentImpurityCalculator))
- }
- }
-
- // For each (feature, split), calculate the gain, and select the best (feature, split).
- }
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointX.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointX.scala
index 7329562..0b8392a 100644
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointX.scala
+++ b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointX.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
diff --git a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointY.scala b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointY.scala
index 036cb97..4272edb 100644
--- a/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointY.scala
+++ b/ml-core/src/main/scala/org/apache/spark/ml/tree/impl/TreePointY.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/clustering/LDAUtilsX.scala b/ml-core/src/main/scala/org/apache/spark/mllib/clustering/LDAUtilsX.scala
index 4a30b9e..fc9420a 100644
--- a/ml-core/src/main/scala/org/apache/spark/mllib/clustering/LDAUtilsX.scala
+++ b/ml-core/src/main/scala/org/apache/spark/mllib/clustering/LDAUtilsX.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/clustering/OnlineLDAOptimizerXObj.scala b/ml-core/src/main/scala/org/apache/spark/mllib/clustering/OnlineLDAOptimizerXObj.scala
index 50f3337..c2b1589 100644
--- a/ml-core/src/main/scala/org/apache/spark/mllib/clustering/OnlineLDAOptimizerXObj.scala
+++ b/ml-core/src/main/scala/org/apache/spark/mllib/clustering/OnlineLDAOptimizerXObj.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -25,7 +19,7 @@ package org.apache.spark.mllib.clustering
import breeze.linalg.{sum, DenseMatrix => BDM, DenseVector => BDV}
import breeze.numerics.{abs, exp}
-import breeze.stats.distributions.Gamma
+import breeze.stats.distributions.{Gamma, RandBasis}
import org.apache.spark.mllib.linalg.{DenseVector, SparseVector, Vector}
@@ -34,7 +28,7 @@ import org.apache.spark.mllib.linalg.{DenseVector, SparseVector, Vector}
* Serializable companion object containing helper methods and shared code for
* [[OnlineLDAOptimizer]] and [[LocalLDAModel]].
*/
-private[clustering] object OnlineLDAOptimizerXObj {
+private[spark] object OnlineLDAOptimizerXObj {
/**
* Uses variational inference to infer the topic distribution `gammad` given the term counts
* for a document. `termCounts` must contain at least one non-zero entry, otherwise Breeze will
@@ -47,25 +41,24 @@ private[clustering] object OnlineLDAOptimizerXObj {
* @return Returns a tuple of `gammad` - estimate of gamma, the topic distribution, `sstatsd` -
* statistics for updating lambda and `ids` - list of termCounts vector indices.
*/
- private[clustering] def variationalTopicInference(
- termCounts: Vector,
+ private[spark] def variationalTopicInference(
+ indices: List[Int],
+ values: Array[Double],
expElogbeta: BDM[Double],
alpha: breeze.linalg.Vector[Double],
gammaShape: Double,
- k: Int): (BDV[Double], BDM[Double], List[Int]) = {
- val (ids: List[Int], cts: Array[Double]) = termCounts match {
- case v: DenseVector => ((0 until v.size).toList, v.values)
- case v: SparseVector => (v.indices.toList, v.values)
- }
+ k: Int,
+ seed: Long): (BDV[Double], BDM[Double], List[Int]) = {
// Initialize the variational distribution q(theta|gamma) for the mini-batch
+ val randBasis = new RandBasis(new org.apache.commons.math3.random.MersenneTwister(seed))
val gammad: BDV[Double] =
- new Gamma(gammaShape, 1.0 / gammaShape).samplesVector(k) // K
+ new Gamma(gammaShape, 1.0 / gammaShape)(randBasis).samplesVector(k) // K
val expElogthetad: BDV[Double] = exp(LDAUtilsX.dirichletExpectation(gammad)) // K
- val expElogbetad = expElogbeta(ids, ::).toDenseMatrix // ids * K
+ val expElogbetad = expElogbeta(indices, ::).toDenseMatrix // ids * K
val phiNorm: BDV[Double] = expElogbetad * expElogthetad +:+ 1e-100 // ids
var meanGammaChange = 1D
- val ctsVector = new BDV[Double](cts) // ids
+ val ctsVector = new BDV[Double](values) // ids
// Iterate between gamma and phi until convergence
while (meanGammaChange > 1e-3) {
@@ -79,6 +72,20 @@ private[clustering] object OnlineLDAOptimizerXObj {
}
val sstatsd = expElogthetad.asDenseMatrix.t * (ctsVector /:/ phiNorm).asDenseMatrix
- (gammad, sstatsd, ids)
+ (gammad, sstatsd, indices)
+ }
+
+ private[clustering] def variationalTopicInference(
+ termCounts: Vector,
+ expElogbeta: BDM[Double],
+ alpha: breeze.linalg.Vector[Double],
+ gammaShape: Double,
+ k: Int,
+ seed: Long): (BDV[Double], BDM[Double], List[Int]) = {
+ val (ids: List[Int], cts: Array[Double]) = termCounts match {
+ case v: DenseVector => (List.range(0, v.size), v.values)
+ case v: SparseVector => (v.indices.toList, v.values)
+ }
+ variationalTopicInference(ids, cts, expElogbeta, alpha, gammaShape, k, seed)
}
}
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/fpm/LocalPrefixSpan.scala b/ml-core/src/main/scala/org/apache/spark/mllib/fpm/LocalPrefixSpan.scala
index 43e76b2..789c299 100644
--- a/ml-core/src/main/scala/org/apache/spark/mllib/fpm/LocalPrefixSpan.scala
+++ b/ml-core/src/main/scala/org/apache/spark/mllib/fpm/LocalPrefixSpan.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpanBase.scala b/ml-core/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpanBase.scala
index 573aace..313dfa5 100644
--- a/ml-core/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpanBase.scala
+++ b/ml-core/src/main/scala/org/apache/spark/mllib/fpm/PrefixSpanBase.scala
@@ -1,9 +1,3 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Entropy.scala b/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Entropy.scala
deleted file mode 100644
index 7406c0d..0000000
--- a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Entropy.scala
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.impurity
-
-import org.apache.spark.annotation.{DeveloperApi, Since}
-
-/**
- * Class for calculating entropy during multiclass classification.
- */
-@Since("1.0.0")
-object Entropy extends Impurity {
-
- private[tree] def log2(x: Double) = scala.math.log(x) / scala.math.log(2)
-
- /**
- * :: DeveloperApi ::
- * information calculation for multiclass classification
- * @param counts Array[Double] with counts for each label
- * @param totalCount sum of counts for all labels
- * @return information value, or 0 if totalCount = 0
- */
- @Since("1.1.0")
- @DeveloperApi
- override def calculate(counts: Array[Double], totalCount: Double): Double = {
- if (totalCount == 0) {
- return 0
- }
- val numClasses = counts.length
- var impurity = 0.0
- var classIndex = 0
- while (classIndex < numClasses) {
- val classCount = counts(classIndex)
- if (classCount != 0) {
- val freq = classCount / totalCount
- impurity -= freq * log2(freq)
- }
- classIndex += 1
- }
- impurity
- }
-
- /**
- * :: DeveloperApi ::
- * variance calculation
- * @param count number of instances
- * @param sum sum of labels
- * @param sumSquares summation of squares of the labels
- * @return information value, or 0 if count = 0
- */
- @Since("1.0.0")
- @DeveloperApi
- override def calculate(count: Double, sum: Double, sumSquares: Double): Double =
- throw new UnsupportedOperationException("Entropy.calculate")
-
- /**
- * Get this impurity instance.
- * This is useful for passing impurity parameters to a Strategy in Java.
- */
- @Since("1.1.0")
- def instance: this.type = this
-
-}
-
-/**
- * Class for updating views of a vector of sufficient statistics,
- * in order to compute impurity from a sample.
- * Note: Instances of this class do not hold the data; they operate on views of the data.
- * @param numClasses Number of classes for label.
- */
-private[spark] class EntropyAggregator(numClasses: Int)
- extends ImpurityAggregator(numClasses) with Serializable {
-
- /**
- * Update stats for one (node, feature, bin) with the given label.
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def update(allStats: Array[Double], offset: Int, label: Double, instanceWeight: Int): Unit = {
- if (label >= statsSize) {
- throw new IllegalArgumentException(s"EntropyAggregator given label $label" +
- s" but requires label < numClasses (= $statsSize).")
- }
- if (label < 0) {
- throw new IllegalArgumentException(s"EntropyAggregator given label $label" +
- s"but requires label is non-negative.")
- }
- allStats(offset + label.toInt) += instanceWeight
- }
-
- /**
- * Get an [[ImpurityCalculator]] for a (node, feature, bin).
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def getCalculator(allStats: Array[Double], offset: Int): EntropyCalculator = {
- new EntropyCalculator(allStats.view(offset, offset + statsSize).toArray)
- }
-}
-
-/**
- * Stores statistics for one (node, feature, bin) for calculating impurity.
- * Unlike [[EntropyAggregator]], this class stores its own data and is for a specific
- * (node, feature, bin).
- * @param stats Array of sufficient statistics for a (node, feature, bin).
- */
-private[spark] class EntropyCalculator(stats: Array[Double]) extends ImpurityCalculator(stats) {
-
- /**
- * Make a deep copy of this [[ImpurityCalculator]].
- */
- def copy: EntropyCalculator = new EntropyCalculator(stats.clone())
-
- /**
- * Calculate the impurity from the stored sufficient statistics.
- */
- def calculate(): Double = Entropy.calculate(stats, stats.sum)
-
- /**
- * Number of data points accounted for in the sufficient statistics.
- */
- def count: Long = stats.sum.toLong
-
- /**
- * Prediction which should be made based on the sufficient statistics.
- */
- def predict: Double = if (count == 0) {
- 0
- } else {
- indexOfLargestArrayElement(stats)
- }
-
- /**
- * Probability of the label given by [[predict]].
- */
- override def prob(label: Double): Double = {
- val lbl = label.toInt
- require(lbl < stats.length,
- s"EntropyCalculator.prob given invalid label: $lbl (should be < ${stats.length}")
- require(lbl >= 0, "Entropy does not support negative labels")
- val cnt = count
- if (cnt == 0) {
- 0
- } else {
- stats(lbl) / cnt
- }
- }
-
- override def toString: String = s"EntropyCalculator(stats = [${stats.mkString(", ")}])"
-
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Gini.scala b/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Gini.scala
deleted file mode 100644
index f182519..0000000
--- a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Gini.scala
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.impurity
-
-import org.apache.spark.annotation.{DeveloperApi, Since}
-
-/**
- * Class for calculating the Gini impurity
- * (http://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity)
- * during multiclass classification.
- */
-@Since("1.0.0")
-object Gini extends Impurity {
-
- /**
- * :: DeveloperApi ::
- * information calculation for multiclass classification
- * @param counts Array[Double] with counts for each label
- * @param totalCount sum of counts for all labels
- * @return information value, or 0 if totalCount = 0
- */
- @Since("1.1.0")
- @DeveloperApi
- override def calculate(counts: Array[Double], totalCount: Double): Double = {
- if (totalCount == 0) {
- return 0
- }
- val numClasses = counts.length
- var impurity = 1.0
- var classIndex = 0
- while (classIndex < numClasses) {
- val freq = counts(classIndex) / totalCount
- impurity -= freq * freq
- classIndex += 1
- }
- impurity
- }
-
- /**
- * :: DeveloperApi ::
- * variance calculation
- * @param count number of instances
- * @param sum sum of labels
- * @param sumSquares summation of squares of the labels
- * @return information value, or 0 if count = 0
- */
- @Since("1.0.0")
- @DeveloperApi
- override def calculate(count: Double, sum: Double, sumSquares: Double): Double =
- throw new UnsupportedOperationException("Gini.calculate")
-
- /**
- * Get this impurity instance.
- * This is useful for passing impurity parameters to a Strategy in Java.
- */
- @Since("1.1.0")
- def instance: this.type = this
-
-}
-
-/**
- * Class for updating views of a vector of sufficient statistics,
- * in order to compute impurity from a sample.
- * Note: Instances of this class do not hold the data; they operate on views of the data.
- * @param numClasses Number of classes for label.
- */
-private[spark] class GiniAggregator(numClasses: Int)
- extends ImpurityAggregator(numClasses) with Serializable {
-
- /**
- * Update stats for one (node, feature, bin) with the given label.
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def update(allStats: Array[Double], offset: Int, label: Double, instanceWeight: Int): Unit = {
- if (label >= statsSize) {
- throw new IllegalArgumentException(s"GiniAggregator given label $label" +
- s" but requires label < numClasses (= $statsSize).")
- }
- if (label < 0) {
- throw new IllegalArgumentException(s"GiniAggregator given label $label" +
- s"but requires label is non-negative.")
- }
- allStats(offset + label.toInt) += instanceWeight
- }
-
- /**
- * Get an [[ImpurityCalculator]] for a (node, feature, bin).
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def getCalculator(allStats: Array[Double], offset: Int): GiniCalculator = {
- new GiniCalculator(allStats.view(offset, offset + statsSize).toArray)
- }
-}
-
-/**
- * Stores statistics for one (node, feature, bin) for calculating impurity.
- * Unlike [[GiniAggregator]], this class stores its own data and is for a specific
- * (node, feature, bin).
- * @param stats Array of sufficient statistics for a (node, feature, bin).
- */
-private[spark] class GiniCalculator(stats: Array[Double]) extends ImpurityCalculator(stats) {
-
- /**
- * Make a deep copy of this [[ImpurityCalculator]].
- */
- def copy: GiniCalculator = new GiniCalculator(stats.clone())
-
- /**
- * Calculate the impurity from the stored sufficient statistics.
- */
- def calculate(): Double = Gini.calculate(stats, stats.sum)
-
- /**
- * Number of data points accounted for in the sufficient statistics.
- */
- def count: Long = stats.sum.toLong
-
- /**
- * Prediction which should be made based on the sufficient statistics.
- */
- def predict: Double = if (count == 0) {
- 0
- } else {
- indexOfLargestArrayElement(stats)
- }
-
- /**
- * Probability of the label given by [[predict]].
- */
- override def prob(label: Double): Double = {
- val lbl = label.toInt
- require(lbl < stats.length,
- s"GiniCalculator.prob given invalid label: $lbl (should be < ${stats.length}")
- require(lbl >= 0, "GiniImpurity does not support negative labels")
- val cnt = count
- if (cnt == 0) {
- 0
- } else {
- stats(lbl) / cnt
- }
- }
-
- override def toString: String = s"GiniCalculator(stats = [${stats.mkString(", ")}])"
-
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Impurities.scala b/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Impurities.scala
deleted file mode 100644
index f470091..0000000
--- a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Impurities.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.impurity
-
-/**
- * Factory for Impurity instances.
- */
-private[mllib] object Impurities {
-
- def fromString(name: String): Impurity = name match {
- case "gini" => Gini
- case "entropy" => Entropy
- case "variance" => Variance
- case _ => throw new IllegalArgumentException(s"Did not recognize Impurity name: $name")
- }
-
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Impurity.scala b/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Impurity.scala
deleted file mode 100644
index 0492e1c..0000000
--- a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Impurity.scala
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.impurity
-
-import java.util.Locale
-
-import org.apache.spark.annotation.{DeveloperApi, Since}
-
-/**
- * Trait for calculating information gain.
- * This trait is used for
- * (a) setting the impurity parameter in [[org.apache.spark.mllib.tree.configuration.Strategy]]
- * (b) calculating impurity values from sufficient statistics.
- */
-@Since("1.0.0")
-trait Impurity extends Serializable {
-
- /**
- * :: DeveloperApi ::
- * information calculation for multiclass classification
- * @param counts Array[Double] with counts for each label
- * @param totalCount sum of counts for all labels
- * @return information value, or 0 if totalCount = 0
- */
- @Since("1.1.0")
- @DeveloperApi
- def calculate(counts: Array[Double], totalCount: Double): Double
-
- /**
- * :: DeveloperApi ::
- * information calculation for regression
- * @param count number of instances
- * @param sum sum of labels
- * @param sumSquares summation of squares of the labels
- * @return information value, or 0 if count = 0
- */
- @Since("1.0.0")
- @DeveloperApi
- def calculate(count: Double, sum: Double, sumSquares: Double): Double
-}
-
-/**
- * Interface for updating views of a vector of sufficient statistics,
- * in order to compute impurity from a sample.
- * Note: Instances of this class do not hold the data; they operate on views of the data.
- * @param statsSize Length of the vector of sufficient statistics for one bin.
- */
-private[spark] abstract class ImpurityAggregator(val statsSize: Int) extends Serializable {
-
- /**
- * Merge the stats from one bin into another.
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for (node, feature, bin) which is modified by the merge.
- * @param otherOffset Start index of stats for (node, feature, other bin) which is not modified.
- */
- def merge(allStats: Array[Double], offset: Int, otherOffset: Int): Unit = {
- var i = 0
- while (i < statsSize) {
- allStats(offset + i) += allStats(otherOffset + i)
- i += 1
- }
- }
-
- /**
- * Update stats for one (node, feature, bin) with the given label.
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def update(allStats: Array[Double], offset: Int, label: Double, instanceWeight: Int): Unit
-
- /**
- * Get an [[ImpurityCalculator]] for a (node, feature, bin).
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def getCalculator(allStats: Array[Double], offset: Int): ImpurityCalculator
-}
-
-/**
- * Stores statistics for one (node, feature, bin) for calculating impurity.
- * Unlike [[ImpurityAggregator]], this class stores its own data and is for a specific
- * (node, feature, bin).
- * @param stats Array of sufficient statistics for a (node, feature, bin).
- */
-private[spark] abstract class ImpurityCalculator(val stats: Array[Double]) extends Serializable {
-
- /**
- * Make a deep copy of this [[ImpurityCalculator]].
- */
- def copy: ImpurityCalculator
-
- /**
- * Calculate the impurity from the stored sufficient statistics.
- */
- def calculate(): Double
-
- /**
- * Add the stats from another calculator into this one, modifying and returning this calculator.
- */
- def add(other: ImpurityCalculator): ImpurityCalculator = {
- require(stats.length == other.stats.length,
- s"Two ImpurityCalculator instances cannot be added with different counts sizes." +
- s" Sizes are ${stats.length} and ${other.stats.length}.")
- var i = 0
- val len = other.stats.length
- while (i < len) {
- stats(i) += other.stats(i)
- i += 1
- }
- this
- }
-
- /**
- * Subtract the stats from another calculator from this one, modifying and returning this
- * calculator.
- */
- def subtract(other: ImpurityCalculator): ImpurityCalculator = {
- require(stats.length == other.stats.length,
- s"Two ImpurityCalculator instances cannot be subtracted with different counts sizes." +
- s" Sizes are ${stats.length} and ${other.stats.length}.")
- var i = 0
- val len = other.stats.length
- while (i < len) {
- stats(i) -= other.stats(i)
- i += 1
- }
- this
- }
-
- /**
- * Number of data points accounted for in the sufficient statistics.
- */
- def count: Long
-
- /**
- * Prediction which should be made based on the sufficient statistics.
- */
- def predict: Double
-
- /**
- * Probability of the label given by [[predict]], or -1 if no probability is available.
- */
- def prob(label: Double): Double = -1
-
- /**
- * Return the index of the largest array element.
- * Fails if the array is empty.
- */
- protected def indexOfLargestArrayElement(array: Array[Double]): Int = {
- val result = array.foldLeft((-1, Double.MinValue, 0)) {
- case ((maxIndex, maxValue, currentIndex), currentValue) =>
- if (currentValue > maxValue) {
- (currentIndex, currentValue, currentIndex + 1)
- } else {
- (maxIndex, maxValue, currentIndex + 1)
- }
- }
- if (result._1 < 0) {
- throw new RuntimeException("ImpurityCalculator internal error:" +
- " indexOfLargestArrayElement failed")
- }
- result._1
- }
-
-}
-
-private[spark] object ImpurityCalculator {
-
- /**
- * Create an [[ImpurityCalculator]] instance of the given impurity type and with
- * the given stats.
- */
- def getCalculator(impurity: String, stats: Array[Double]): ImpurityCalculator = {
- impurity.toLowerCase(Locale.ROOT) match {
- case "gini" => new GiniCalculator(stats)
- case "entropy" => new EntropyCalculator(stats)
- case "variance" => new VarianceCalculator(stats)
- case _ =>
- throw new IllegalArgumentException(
- s"ImpurityCalculator builder did not recognize impurity type: $impurity")
- }
- }
-}
diff --git a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Variance.scala b/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Variance.scala
deleted file mode 100644
index 732ceaa..0000000
--- a/ml-core/src/main/scala/org/apache/spark/mllib/tree/impurity/Variance.scala
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * 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.impurity
-
-import org.apache.spark.annotation.{DeveloperApi, Since}
-
-/**
- * Class for calculating variance during regression
- */
-@Since("1.0.0")
-object Variance extends Impurity {
-
- /**
- * :: DeveloperApi ::
- * information calculation for multiclass classification
- * @param counts Array[Double] with counts for each label
- * @param totalCount sum of counts for all labels
- * @return information value, or 0 if totalCount = 0
- */
- @Since("1.1.0")
- @DeveloperApi
- override def calculate(counts: Array[Double], totalCount: Double): Double =
- throw new UnsupportedOperationException("Variance.calculate")
-
- /**
- * :: DeveloperApi ::
- * variance calculation
- * @param count number of instances
- * @param sum sum of labels
- * @param sumSquares summation of squares of the labels
- * @return information value, or 0 if count = 0
- */
- @Since("1.0.0")
- @DeveloperApi
- override def calculate(count: Double, sum: Double, sumSquares: Double): Double = {
- if (count == 0) {
- return 0
- }
- val squaredLoss = sumSquares - (sum * sum) / count
- squaredLoss / count
- }
-
- /**
- * Get this impurity instance.
- * This is useful for passing impurity parameters to a Strategy in Java.
- */
- @Since("1.0.0")
- def instance: this.type = this
-
-}
-
-/**
- * Class for updating views of a vector of sufficient statistics,
- * in order to compute impurity from a sample.
- * Note: Instances of this class do not hold the data; they operate on views of the data.
- */
-private[spark] class VarianceAggregator()
- extends ImpurityAggregator(statsSize = 3) with Serializable {
-
- /**
- * Update stats for one (node, feature, bin) with the given label.
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def update(allStats: Array[Double], offset: Int, label: Double, instanceWeight: Int): Unit = {
- allStats(offset) += instanceWeight
- allStats(offset + 1) += instanceWeight * label
- allStats(offset + 2) += instanceWeight * label * label
- }
-
- def updateX(allStats: Array[Double], offset: Int, label: Double): Unit = {
- allStats(offset) += 1.0
- allStats(offset + 1) += label
- allStats(offset + 2) += label * label
- }
-
- /**
- * Get an [[ImpurityCalculator]] for a (node, feature, bin).
- * @param allStats Flat stats array, with stats for this (node, feature, bin) contiguous.
- * @param offset Start index of stats for this (node, feature, bin).
- */
- def getCalculator(allStats: Array[Double], offset: Int): VarianceCalculator = {
- new VarianceCalculator(allStats.view(offset, offset + statsSize).toArray)
- }
-}
-
-/**
- * Stores statistics for one (node, feature, bin) for calculating impurity.
- * Unlike [[GiniAggregator]], this class stores its own data and is for a specific
- * (node, feature, bin).
- * @param stats Array of sufficient statistics for a (node, feature, bin).
- */
-private[spark] class VarianceCalculator(stats: Array[Double]) extends ImpurityCalculator(stats) {
-
- require(stats.length == 3,
- s"VarianceCalculator requires sufficient statistics array stats to be of length 3," +
- s" but was given array of length ${stats.length}.")
-
- /**
- * Make a deep copy of this [[ImpurityCalculator]].
- */
- def copy: VarianceCalculator = new VarianceCalculator(stats.clone())
-
- /**
- * Calculate the impurity from the stored sufficient statistics.
- */
- def calculate(): Double = Variance.calculate(stats(0), stats(1), stats(2))
-
- /**
- * Number of data points accounted for in the sufficient statistics.
- */
- def count: Long = stats(0).toLong
-
- /**
- * Prediction which should be made based on the sufficient statistics.
- */
- def predict: Double = if (count == 0) {
- 0
- } else {
- stats(1) / count
- }
-
- override def toString: String = {
- s"VarianceAggregator(cnt = ${stats(0)}, sum = ${stats(1)}, sum2 = ${stats(2)})"
- }
-
-}
diff --git a/ml-kernel-client-core/pom.xml b/ml-kernel-client-core/pom.xml
index 561c79e..e0e7f74 100644
--- a/ml-kernel-client-core/pom.xml
+++ b/ml-kernel-client-core/pom.xml
@@ -6,7 +6,7 @@
4.0.0
- boostkit-ml-kernel-client-core_2.11
+ boostkit-ml-kernel-client-core_2.12
2.1.0
${project.artifactId}
Spark ml core
diff --git a/ml-kernel-client/pom.xml b/ml-kernel-client/pom.xml
index 2be4e38..7434007 100644
--- a/ml-kernel-client/pom.xml
+++ b/ml-kernel-client/pom.xml
@@ -6,7 +6,7 @@
4.0.0
- boostkit-ml-kernel-client_2.11
+ boostkit-ml-kernel-client_2.12
2.1.0
${project.artifactId}
Spark ml core
@@ -14,7 +14,7 @@
org.apache.spark
- boostkit-ml-core_2.11
+ boostkit-ml-core_2.12
${project.version}
${spark.version}
diff --git a/ml-kernel-client/src/main/scala/breeze/linalg/blas/YTYUtils.scala b/ml-kernel-client/src/main/scala/breeze/linalg/blas/YTYUtils.scala
index 8dd48df..8c43aa4 100644
--- a/ml-kernel-client/src/main/scala/breeze/linalg/blas/YTYUtils.scala
+++ b/ml-kernel-client/src/main/scala/breeze/linalg/blas/YTYUtils.scala
@@ -6,7 +6,10 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* */
/*
- * Copyright (c). Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
+ * This file to You under the Apache License, Version 2.0;
+ * 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
*/
package breeze.linalg.blas
diff --git a/ml-kernel-client/src/main/scala/breeze/optimize/ACC.scala b/ml-kernel-client/src/main/scala/breeze/optimize/ACC.scala
deleted file mode 100644
index bd2f43a..0000000
--- a/ml-kernel-client/src/main/scala/breeze/optimize/ACC.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * This file to You under the Apache License, Version 2.0;
- * 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
- */
-
-package breeze.optimize
-
-import breeze.math.MutableInnerProductModule
-
-object ACC{
-
- def update[T](
- step: T,
- delta: T,
- mStep: IndexedSeq[T],
- g: IndexedSeq[T],
- m: Int) (implicit space: MutableInnerProductModule[T, Double]):
- (IndexedSeq[T], IndexedSeq[T]) = {
- null
- }
-
- def updateMomentum[T](
- m: T,
- dir: T,
- coeff: Double,
- uCoeff: Double) (implicit space: MutableInnerProductModule[T, Double]): T = {
- null.asInstanceOf[T]
- }
-
- def getInverseOfHessian[T](
- g: T,
- deltaA: IndexedSeq[T],
- deltaB: IndexedSeq[T],
- m: Int,
- size: Int)(implicit space: MutableInnerProductModule[T, Double]): T = {
- null.asInstanceOf[T]
- }
-}
diff --git a/ml-kernel-client/src/main/scala/breeze/optimize/LBFGSL.scala b/ml-kernel-client/src/main/scala/breeze/optimize/LBFGSL.scala
deleted file mode 100644
index ac14511..0000000
--- a/ml-kernel-client/src/main/scala/breeze/optimize/LBFGSL.scala
+++ /dev/null
@@ -1,84 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * This file to You under the Apache License, Version 2.0;
- * 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
- */
-
-package breeze.optimize
-
-import breeze.linalg.DenseVector
-import breeze.util.SerializableLogging
-
-class LBFGSL(
- var lowerBounds: DenseVector[Double],
- var upperBounds: DenseVector[Double],
- maxIterations: Int,
- maxFCalls: Int,
- m: Int,
- fTolerance: Double,
- xTolerance: Double)
- extends FirstOrderMinimizer[DenseVector[Double], DiffFunction[DenseVector[Double]]](null)
- with SerializableLogging {
-
- def this(
- lowerBounds: DenseVector[Double],
- upperBounds: DenseVector[Double],
- maxIterations: Int,
- m: Int,
- fTolerance: Double) = {
- this(lowerBounds, upperBounds, maxIterations, 0, m, fTolerance, 0.0)
- }
-
- def this(maxIterations: Int, m: Int, fTolerance: Double) = {
- this(null, null, maxIterations, 0, m, fTolerance, 0.0)
- }
-
- override def iterations(f: DiffFunction[DenseVector[Double]], x0: DenseVector[Double]):
- Iterator[FirstOrderMinimizer.State[DenseVector[Double], convergenceCheck.Info, History]] = {
- null
- }
-
- case class History()
-
- override def initialHistory(
- f: DiffFunction[DenseVector[Double]],
- init: DenseVector[Double]): History = {
- null
- }
-
- override def updateHistory(
- newX: DenseVector[Double],
- newGrad: DenseVector[Double],
- newVal: Double,
- f: DiffFunction[DenseVector[Double]],
- oldState: State): History = {
- null
- }
-
- override def chooseDescentDirection(state: State, f: DiffFunction[DenseVector[Double]]):
- DenseVector[Double] = {
- null
- }
-
- override def determineStepSize(
- state: State,
- f: DiffFunction[DenseVector[Double]],
- direction: DenseVector[Double]): Double = {
- 0.0
- }
-
- override def takeStep(
- state: State,
- dir: DenseVector[Double],
- stepSize: Double): DenseVector[Double] = {
- null
- }
-}
diff --git a/ml-kernel-client/src/main/scala/breeze/optimize/OWLQNL.scala b/ml-kernel-client/src/main/scala/breeze/optimize/OWLQNL.scala
deleted file mode 100644
index abb342d..0000000
--- a/ml-kernel-client/src/main/scala/breeze/optimize/OWLQNL.scala
+++ /dev/null
@@ -1,78 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * This file to You under the Apache License, Version 2.0;
- * 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
- */
-
-package breeze.optimize
-
-import breeze.linalg.DenseVector
-import breeze.util.SerializableLogging
-
-class OWLQNL(
- maxIterations: Int,
- maxFCalls: Int,
- m: Int,
- fTolerance: Double,
- xTolerance: Double,
- var l1RegParam: DenseVector[Double])
- extends FirstOrderMinimizer[DenseVector[Double], DiffFunction[DenseVector[Double]]](null)
- with SerializableLogging {
-
- def this(
- maxIterations: Int,
- m: Int,
- fTolerance: Double,
- l1RegParam: DenseVector[Double]) = {
- this(maxIterations, 0, m, fTolerance, 0.0, l1RegParam)
- }
-
- override def iterations(f: DiffFunction[DenseVector[Double]], x0: DenseVector[Double]):
- Iterator[FirstOrderMinimizer.State[DenseVector[Double], convergenceCheck.Info, History]] = {
- null
- }
-
- case class History()
-
- override def initialHistory(
- f: DiffFunction[DenseVector[Double]],
- init: DenseVector[Double]): History = {
- null
- }
-
- override def updateHistory(
- newX: DenseVector[Double],
- newGrad: DenseVector[Double],
- newVal: Double,
- f: DiffFunction[DenseVector[Double]],
- oldState: State): History = {
- null
- }
-
- override def chooseDescentDirection(state: State, f: DiffFunction[DenseVector[Double]]):
- DenseVector[Double] = {
- null
- }
-
- override def determineStepSize(
- state: State,
- f: DiffFunction[DenseVector[Double]],
- direction: DenseVector[Double]): Double = {
- 0.0
- }
-
- override def takeStep(
- state: State,
- dir: DenseVector[Double],
- stepSize: Double): DenseVector[Double] = {
- null
- }
-}
diff --git a/ml-kernel-client/src/main/scala/org/apache/spark/ml/recommendation/ALSUtils.scala b/ml-kernel-client/src/main/scala/org/apache/spark/ml/recommendation/ALSUtils.scala
index dca6a58..bf33ee6 100644
--- a/ml-kernel-client/src/main/scala/org/apache/spark/ml/recommendation/ALSUtils.scala
+++ b/ml-kernel-client/src/main/scala/org/apache/spark/ml/recommendation/ALSUtils.scala
@@ -6,7 +6,10 @@
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* */
/*
- * Copyright (c). Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
+ * This file to You under the Apache License, Version 2.0;
+ * 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
*/
package org.apache.spark.ml.recommendation
diff --git a/ml-kernel-client/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTreesUtil.scala b/ml-kernel-client/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTreesUtil.scala
deleted file mode 100644
index 736cfaf..0000000
--- a/ml-kernel-client/src/main/scala/org/apache/spark/ml/tree/impl/GradientBoostedTreesUtil.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * This file to You under the Apache License, Version 2.0;
- * 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
- */
-
-package org.apache.spark.ml.tree.impl
-
-import it.unimi.dsi.fastutil.doubles.DoubleArrayList
-import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
-import it.unimi.dsi.fastutil.ints.IntArrayList
-import it.unimi.dsi.fastutil.objects.ObjectArrayList
-
-import org.apache.spark.broadcast.Broadcast
-import org.apache.spark.internal.Logging
-import org.apache.spark.ml.feature.LabeledPoint
-import org.apache.spark.ml.tree.LearningNode
-import org.apache.spark.ml.tree.Split
-import org.apache.spark.ml.tree.impl.GradientBoostedTreesCore.NodeIndexInfo
-import org.apache.spark.mllib.tree.configuration.{Strategy => OldStrategy}
-import org.apache.spark.mllib.tree.model.ImpurityStats
-import org.apache.spark.rdd.RDD
-
-object GradientBoostedTreesUtil extends Logging {
-
- def dataProcessX(
- input: RDD[LabeledPoint],
- splits: Array[Array[Split]],
- treeStrategy: OldStrategy,
- metadata: DecisionTreeMetadata,
- timer: TimeTracker,
- seed: Long): (RDD[TreePoint], RDD[(Int, (IntArrayList, ObjectArrayList[Split]))],
- Broadcast[DoubleArrayList], Broadcast[Int2ObjectOpenHashMap[IntArrayList]]) = {
- null
- }
-
- def nodeIdCacheXConstruction(
- nodes: Array[LearningNode],
- rawPartInfoBc: Broadcast[Int2ObjectOpenHashMap[IntArrayList]])
- : Int2ObjectOpenHashMap[Int2ObjectOpenHashMap[IntArrayList]] = {
- null
- }
-
- def chooseBestSplits(
- input: RDD[(Int, (IntArrayList, ObjectArrayList[Split]))],
- nodeIndexInfo: Map[Int, Map[Int, NodeIndexInfo]],
- metadata: DecisionTreeMetadata,
- nodeIdCacheBc: Broadcast[Int2ObjectOpenHashMap[Int2ObjectOpenHashMap[IntArrayList]]],
- labelArrayBc: Broadcast[DoubleArrayList],
- nodes: Array[LearningNode]): scala.collection.Map[Int, (Split, ImpurityStats)] = {
- null
- }
-
-
-
-
- def updateNodeIdCache(
- nodeIdCache: Int2ObjectOpenHashMap[Int2ObjectOpenHashMap[IntArrayList]],
- nodeIdCacheBc: Broadcast[Int2ObjectOpenHashMap[Int2ObjectOpenHashMap[IntArrayList]]],
- input: RDD[TreePoint],
- nodesForGroup: Map[Int, Array[LearningNode]],
- nodeIndexInfo: Map[Int, Map[Int, NodeIndexInfo]],
- splits: Array[Array[Split]],
- rawPartInfoBc: Broadcast[Int2ObjectOpenHashMap[IntArrayList]],
- metadata: DecisionTreeMetadata,
- timer: TimeTracker): Unit = {
- }
-
-}
diff --git a/ml-kernel-client/src/main/scala/org/apache/spark/mllib.clustering/KmeansUtil.scala b/ml-kernel-client/src/main/scala/org/apache/spark/mllib.clustering/KmeansUtil.scala
deleted file mode 100644
index 83de295..0000000
--- a/ml-kernel-client/src/main/scala/org/apache/spark/mllib.clustering/KmeansUtil.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-// scalastyle:off header.matches
-/*
-* Copyright (C) 2021. Huawei Technologies Co., Ltd.
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-* */
-/*
- * This file to You under the Apache License, Version 2.0;
- * 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
- */
-
-package org.apache.spark.mllib.clustering
-
-object KmeansUtil {
-
- def generateDisMatrix(
- centers: Array[VectorWithNorm], parLevel: Int): Array[Double] = {
- val cl = centers.length
- Array.fill(cl * cl)(0.0)
- }
-
- def findClosest(
- centers: TraversableOnce[VectorWithNorm],
- point: VectorWithNorm,
- s: Array[Double]): (Int, Double) = {
- (-1, -1.0)
- }
-
- def fastDistance(
- v1: VectorWithNorm,
- v2: VectorWithNorm): Double = {
- -1.0
- }
-
-}
diff --git a/ml-kernel-client/src/main/scala/org/apache/spark/mllib.clustering/LDAUtilsXOpt.scala b/ml-kernel-client/src/main/scala/org/apache/spark/mllib.clustering/LDAUtilsXOpt.scala
index e5c042f..e06a3d6 100644
--- a/ml-kernel-client/src/main/scala/org/apache/spark/mllib.clustering/LDAUtilsXOpt.scala
+++ b/ml-kernel-client/src/main/scala/org/apache/spark/mllib.clustering/LDAUtilsXOpt.scala
@@ -50,7 +50,8 @@ object LDAUtilsXOpt {
vocabSize: Int,
logphatPartOptionBase: () => Option[BDV[Double]],
alpha: BV[Double],
- gammaShape: Double): RDD[(BDM[Double], Option[BDV[Double]], Long)] = {
+ gammaShape: Double,
+ seed: Long): RDD[(BDM[Double], Option[BDV[Double]], Long)] = {
null
}
diff --git a/ml-xgboost/.clang-tidy b/ml-xgboost/.clang-tidy
deleted file mode 100644
index 3be1d9e..0000000
--- a/ml-xgboost/.clang-tidy
+++ /dev/null
@@ -1,21 +0,0 @@
-Checks: 'modernize-*,-modernize-make-*,-modernize-use-auto,-modernize-raw-string-literal,-modernize-avoid-c-arrays,-modernize-use-trailing-return-type,google-*,-google-default-arguments,-clang-diagnostic-#pragma-messages,readability-identifier-naming'
-CheckOptions:
- - { key: readability-identifier-naming.ClassCase, value: CamelCase }
- - { key: readability-identifier-naming.StructCase, value: CamelCase }
- - { key: readability-identifier-naming.TypeAliasCase, value: CamelCase }
- - { key: readability-identifier-naming.TypedefCase, value: CamelCase }
- - { key: readability-identifier-naming.TypeTemplateParameterCase, value: CamelCase }
- - { key: readability-identifier-naming.MemberCase, value: lower_case }
- - { key: readability-identifier-naming.PrivateMemberSuffix, value: '_' }
- - { key: readability-identifier-naming.ProtectedMemberSuffix, value: '_' }
- - { key: readability-identifier-naming.EnumCase, value: CamelCase }
- - { key: readability-identifier-naming.EnumConstant, value: CamelCase }
- - { key: readability-identifier-naming.EnumConstantPrefix, value: k }
- - { key: readability-identifier-naming.GlobalConstantCase, value: CamelCase }
- - { key: readability-identifier-naming.GlobalConstantPrefix, value: k }
- - { key: readability-identifier-naming.StaticConstantCase, value: CamelCase }
- - { key: readability-identifier-naming.StaticConstantPrefix, value: k }
- - { key: readability-identifier-naming.ConstexprVariableCase, value: CamelCase }
- - { key: readability-identifier-naming.ConstexprVariablePrefix, value: k }
- - { key: readability-identifier-naming.FunctionCase, value: CamelCase }
- - { key: readability-identifier-naming.NamespaceCase, value: lower_case }
diff --git a/ml-xgboost/.editorconfig b/ml-xgboost/.editorconfig
deleted file mode 100644
index 97a7bc1..0000000
--- a/ml-xgboost/.editorconfig
+++ /dev/null
@@ -1,11 +0,0 @@
-root = true
-
-[*]
-charset=utf-8
-indent_style = space
-indent_size = 2
-insert_final_newline = true
-
-[*.py]
-indent_style = space
-indent_size = 4
diff --git a/ml-xgboost/.gitmodules b/ml-xgboost/.gitmodules
deleted file mode 100644
index 35afd1d..0000000
--- a/ml-xgboost/.gitmodules
+++ /dev/null
@@ -1,3 +0,0 @@
-[submodule "cub"]
- path = cub
- url = https://github.com/NVlabs/cub
diff --git a/ml-xgboost/.travis.yml b/ml-xgboost/.travis.yml
deleted file mode 100644
index de23566..0000000
--- a/ml-xgboost/.travis.yml
+++ /dev/null
@@ -1,79 +0,0 @@
-# disable sudo for container build.
-sudo: required
-
-# Enabling test OS X
-os:
- - linux
- - osx
-
-osx_image: xcode10.1
-dist: bionic
-
-# Use Build Matrix to do lint and build seperately
-env:
- matrix:
- # python package test
- - TASK=python_test
- # test installation of Python source distribution
- - TASK=python_sdist_test
- # java package test
- - TASK=java_test
- # cmake test
- - TASK=cmake_test
-
- global:
- - secure: "PR16i9F8QtNwn99C5NDp8nptAS+97xwDtXEJJfEiEVhxPaaRkOp0MPWhogCaK0Eclxk1TqkgWbdXFknwGycX620AzZWa/A1K3gAs+GrpzqhnPMuoBJ0Z9qxXTbSJvCyvMbYwVrjaxc/zWqdMU8waWz8A7iqKGKs/SqbQ3rO6v7c="
- - secure: "dAGAjBokqm/0nVoLMofQni/fWIBcYSmdq4XvCBX1ZAMDsWnuOfz/4XCY6h2lEI1rVHZQ+UdZkc9PioOHGPZh5BnvE49/xVVWr9c4/61lrDOlkD01ZjSAeoV0fAZq+93V/wPl4QV+MM+Sem9hNNzFSbN5VsQLAiWCSapWsLdKzqA="
-
-matrix:
- exclude:
- - os: linux
- env: TASK=python_test
- - os: linux
- env: TASK=java_test
- - os: linux
- env: TASK=cmake_test
-
-# dependent brew packages
-addons:
- homebrew:
- packages:
- - cmake
- - libomp
- - graphviz
- - openssl
- - libgit2
- - wget
- - r
- update: true
-
-before_install:
- - source tests/travis/travis_setup_env.sh
- - if [ "${TASK}" != "python_sdist_test" ]; then export PYTHONPATH=${PYTHONPATH}:${PWD}/python-package; fi
- - echo "MAVEN_OPTS='-Xmx2g -XX:MaxPermSize=1024m -XX:ReservedCodeCacheSize=512m -Dorg.slf4j.simpleLogger.defaultLogLevel=error'" > ~/.mavenrc
-
-install:
- - source tests/travis/setup.sh
-
-script:
- - tests/travis/run_test.sh
-
-cache:
- directories:
- - ${HOME}/.cache/usr
- - ${HOME}/.cache/pip
-
-before_cache:
- - tests/travis/travis_before_cache.sh
-
-after_failure:
- - tests/travis/travis_after_failure.sh
-
-after_success:
- - tree build
- - bash <(curl -s https://codecov.io/bash) -a '-o src/ src/*.c'
-
-notifications:
- email:
- on_success: change
- on_failure: always
diff --git a/ml-xgboost/CITATION b/ml-xgboost/CITATION
deleted file mode 100644
index 1890625..0000000
--- a/ml-xgboost/CITATION
+++ /dev/null
@@ -1,18 +0,0 @@
-@inproceedings{Chen:2016:XST:2939672.2939785,
- author = {Chen, Tianqi and Guestrin, Carlos},
- title = {{XGBoost}: A Scalable Tree Boosting System},
- booktitle = {Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining},
- series = {KDD '16},
- year = {2016},
- isbn = {978-1-4503-4232-2},
- location = {San Francisco, California, USA},
- pages = {785--794},
- numpages = {10},
- url = {http://doi.acm.org/10.1145/2939672.2939785},
- doi = {10.1145/2939672.2939785},
- acmid = {2939785},
- publisher = {ACM},
- address = {New York, NY, USA},
- keywords = {large-scale machine learning},
-}
-
diff --git a/ml-xgboost/CMakeLists.txt b/ml-xgboost/CMakeLists.txt
deleted file mode 100644
index dbc7ae0..0000000
--- a/ml-xgboost/CMakeLists.txt
+++ /dev/null
@@ -1,310 +0,0 @@
-cmake_minimum_required(VERSION 3.13)
-set(CMAKE_CXX_FLAGS "-fstack-protector-all -D_FORTIFY_SOURCE=2 -O2 -Wl,-z,relro,-z,now,-z,noexecstack -s ${CMAKE_CXX_FLAGS}")
-set(CMAKE_SKIP_RPATH TRUE)
-project(xgboost LANGUAGES CXX C VERSION 1.1.0)
-include(cmake/Utils.cmake)
-list(APPEND CMAKE_MODULE_PATH "${xgboost_SOURCE_DIR}/cmake/modules")
-cmake_policy(SET CMP0022 NEW)
-cmake_policy(SET CMP0079 NEW)
-cmake_policy(SET CMP0063 NEW)
-
-if ((${CMAKE_VERSION} VERSION_GREATER 3.13) OR (${CMAKE_VERSION} VERSION_EQUAL 3.13))
- cmake_policy(SET CMP0077 NEW)
-endif ((${CMAKE_VERSION} VERSION_GREATER 3.13) OR (${CMAKE_VERSION} VERSION_EQUAL 3.13))
-
-message(STATUS "CMake version ${CMAKE_VERSION}")
-
-if (CMAKE_COMPILER_IS_GNUCC AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)
- message(FATAL_ERROR "GCC version must be at least 5.0!")
-endif()
-
-include(${xgboost_SOURCE_DIR}/cmake/FindPrefetchIntrinsics.cmake)
-find_prefetch_intrinsics()
-include(${xgboost_SOURCE_DIR}/cmake/Version.cmake)
-write_version()
-set_default_configuration_release()
-
-#-- Options
-option(BUILD_C_DOC "Build documentation for C APIs using Doxygen." OFF)
-option(USE_OPENMP "Build with OpenMP support." ON)
-option(BUILD_STATIC_LIB "Build static library" OFF)
-## Bindings
-option(JVM_BINDINGS "Build JVM bindings" ON)
-option(R_LIB "Build shared library for R package" OFF)
-## Dev
-option(USE_DEBUG_OUTPUT "Dump internal training results like gradients and predictions to stdout.
-Should only be used for debugging." OFF)
-option(GOOGLE_TEST "Build google tests" OFF)
-option(WITH_CODE_COVERAGE "with code coverage" OFF)
-option(USE_DMLC_GTEST "Use google tests bundled with dmlc-core submodule" OFF)
-option(USE_NVTX "Build with cuda pwrofiling annotations. Developers only." OFF)
-set(NVTX_HEADER_DIR "" CACHE PATH "Path to the stand-alone nvtx header")
-option(RABIT_MOCK "Build rabit with mock" OFF)
-option(HIDE_CXX_SYMBOLS "Build shared library and hide all C++ symbols" OFF)
-## CUDA
-option(USE_CUDA "Build with GPU acceleration" OFF)
-option(USE_NCCL "Build with NCCL to enable distributed GPU support." OFF)
-option(BUILD_WITH_SHARED_NCCL "Build with shared NCCL library." OFF)
-set(GPU_COMPUTE_VER "" CACHE STRING
- "Semicolon separated list of compute versions to be built against, e.g. '35;61'")
-## Copied From dmlc
-option(USE_HDFS "Build with HDFS support" OFF)
-option(USE_AZURE "Build with AZURE support" OFF)
-option(USE_S3 "Build with S3 support" OFF)
-## Sanitizers
-option(USE_SANITIZER "Use santizer flags" OFF)
-option(SANITIZER_PATH "Path to sanitizes.")
-set(ENABLED_SANITIZERS "address" "leak" CACHE STRING
- "Semicolon separated list of sanitizer names. E.g 'address;leak'. Supported sanitizers are
-address, leak, undefined and thread.")
-## Plugins
-option(PLUGIN_LZ4 "Build lz4 plugin" OFF)
-option(PLUGIN_DENSE_PARSER "Build dense parser plugin" OFF)
-## Force AVX
-option(USE_AVX "Use AVX" ON)
-
-#-- Checks for building XGBoost
-if (USE_DEBUG_OUTPUT AND (NOT (CMAKE_BUILD_TYPE MATCHES Debug)))
- message(SEND_ERROR "Do not enable `USE_DEBUG_OUTPUT' with release build.")
-endif (USE_DEBUG_OUTPUT AND (NOT (CMAKE_BUILD_TYPE MATCHES Debug)))
-if (USE_NCCL AND NOT (USE_CUDA))
- message(SEND_ERROR "`USE_NCCL` must be enabled with `USE_CUDA` flag.")
-endif (USE_NCCL AND NOT (USE_CUDA))
-if (BUILD_WITH_SHARED_NCCL AND (NOT USE_NCCL))
- message(SEND_ERROR "Build XGBoost with -DUSE_NCCL=ON to enable BUILD_WITH_SHARED_NCCL.")
-endif (BUILD_WITH_SHARED_NCCL AND (NOT USE_NCCL))
-if (JVM_BINDINGS AND R_LIB)
- message(SEND_ERROR "`R_LIB' is not compatible with `JVM_BINDINGS' as they both have customized configurations.")
-endif (JVM_BINDINGS AND R_LIB)
-if (R_LIB AND GOOGLE_TEST)
- message(WARNING "Some C++ unittests will fail with `R_LIB` enabled,
- as R package redirects some functions to R runtime implementation.")
-endif (R_LIB AND GOOGLE_TEST)
-
-include(CheckSymbolExists)
-include(CheckIncludeFile)
-include(CheckIncludeFileCXX)
-if(USE_AVX)
- if(MSVC)
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX")
- else()
- EXECUTE_PROCESS(COMMAND uname -a OUTPUT_VARIABLE ARCH)
- message(STATUS "Current architechture is ${ARCH}")
-
- if (${ARCH} MATCHES ".*aarch64.*")
- message(STATUS "Turn on ARM intrinsics")
- add_compile_options(-DUSE_ARM_INTRINSICS)
- endif()
- if (${ARCH} MATCHES ".*x86.*")
- message(STATUS "Turn on Intel intrinsics")
- add_compile_options(-mavx -DUSE_INTEL_INTRINSICS)
- endif()
- endif()
-endif()
-
-if(WITH_CODE_COVERAGE)
- message(STATUS "Enabled code coverage options")
- add_compile_options("-ftest-coverage" "-fprofile-arcs")
- # actually these options are for compiling but for some targets they are needed in link options
- add_link_options("-ftest-coverage" "-fprofile-arcs")
- add_link_options("-lgcov")
-endif()
-
-#-- Sanitizer
-if (USE_SANITIZER)
- include(cmake/Sanitizer.cmake)
- enable_sanitizers("${ENABLED_SANITIZERS}")
-endif (USE_SANITIZER)
-
-if (USE_CUDA)
- SET(USE_OPENMP ON CACHE BOOL "CUDA requires OpenMP" FORCE)
- # `export CXX=' is ignored by CMake CUDA.
- set(CMAKE_CUDA_HOST_COMPILER ${CMAKE_CXX_COMPILER})
- message(STATUS "Configured CUDA host compiler: ${CMAKE_CUDA_HOST_COMPILER}")
-
- enable_language(CUDA)
- set(GEN_CODE "")
- format_gencode_flags("${GPU_COMPUTE_VER}" GEN_CODE)
- message(STATUS "CUDA GEN_CODE: ${GEN_CODE}")
-endif (USE_CUDA)
-
-find_package(Threads REQUIRED)
-
-if (USE_OPENMP)
- if (APPLE)
- # Require CMake 3.16+ on Mac OSX, as previous versions of CMake had trouble locating
- # OpenMP on Mac. See https://github.com/dmlc/xgboost/pull/5146#issuecomment-568312706
- cmake_minimum_required(VERSION 3.16)
- endif (APPLE)
- find_package(OpenMP REQUIRED)
-endif (USE_OPENMP)
-
-# dmlc-core
-msvc_use_static_runtime()
-add_subdirectory(${xgboost_SOURCE_DIR}/dmlc-core)
-set_target_properties(dmlc PROPERTIES
- CXX_STANDARD 14
- CXX_STANDARD_REQUIRED ON
- POSITION_INDEPENDENT_CODE ON)
-list(APPEND LINKED_LIBRARIES_PRIVATE dmlc)
-
-# rabit
-set(RABIT_BUILD_DMLC OFF)
-set(DMLC_ROOT ${xgboost_SOURCE_DIR}/dmlc-core)
-set(RABIT_WITH_R_LIB ${R_LIB})
-add_subdirectory(rabit)
-
-if (RABIT_MOCK)
- list(APPEND LINKED_LIBRARIES_PRIVATE rabit_mock_static)
-else()
- list(APPEND LINKED_LIBRARIES_PRIVATE rabit)
-endif(RABIT_MOCK)
-foreach(lib rabit rabit_base rabit_empty rabit_mock rabit_mock_static)
- # Explicitly link dmlc to rabit, so that configured header (build_config.h)
- # from dmlc is correctly applied to rabit.
- if (TARGET ${lib})
- target_link_libraries(${lib} dmlc ${CMAKE_THREAD_LIBS_INIT})
- if (HIDE_CXX_SYMBOLS) # Hide all C++ symbols from Rabit
- set_target_properties(${lib} PROPERTIES CXX_VISIBILITY_PRESET hidden)
- endif (HIDE_CXX_SYMBOLS)
- endif (TARGET ${lib})
-endforeach()
-
-# Exports some R specific definitions and objects
-if (R_LIB)
- add_subdirectory(${xgboost_SOURCE_DIR}/R-package)
-endif (R_LIB)
-
-# core xgboost
-list(APPEND LINKED_LIBRARIES_PRIVATE Threads::Threads ${CMAKE_THREAD_LIBS_INIT})
-add_subdirectory(${xgboost_SOURCE_DIR}/plugin)
-add_subdirectory(${xgboost_SOURCE_DIR}/src)
-target_link_libraries(objxgboost PUBLIC dmlc)
-set(XGBOOST_OBJ_SOURCES "${XGBOOST_OBJ_SOURCES};$")
-
-#-- library
-if (BUILD_STATIC_LIB)
- add_library(xgboost STATIC ${XGBOOST_OBJ_SOURCES})
- string(TIMESTAMP time_stamp "%s")
- add_custom_command(TARGET xgboost
- POST_BUILD
- COMMAND mkdir ${CMAKE_CURRENT_SOURCE_DIR}/lib/tmp_${time_stamp}
- COMMAND mv ${CMAKE_CURRENT_SOURCE_DIR}/lib/libxgboost.a ${CMAKE_CURRENT_SOURCE_DIR}/lib/tmp_${time_stamp}/
- COMMAND cp ${CMAKE_CURRENT_SOURCE_DIR}/lib/libboostkit_xgboost_kernel.a ${CMAKE_CURRENT_SOURCE_DIR}/lib/tmp_${time_stamp}/
- VERBATIM
- )
- add_custom_command(TARGET xgboost
- POST_BUILD
- COMMAND ar -x libxgboost.a
- COMMAND ar -x libboostkit_xgboost_kernel.a
- COMMAND sh -c "ar -qcs ${CMAKE_CURRENT_SOURCE_DIR}/lib/libxgboost.a ${CMAKE_CURRENT_SOURCE_DIR}/lib/tmp_${time_stamp}/*.o"
- WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/lib/tmp_${time_stamp}/
- VERBATIM
- )
- add_custom_command(TARGET xgboost
- POST_BUILD
- COMMAND rm -rf ${CMAKE_CURRENT_SOURCE_DIR}/lib/tmp_${time_stamp}
- VERBATIM
- )
-else (BUILD_STATIC_LIB)
- add_library(xgboost SHARED ${XGBOOST_OBJ_SOURCES})
- target_link_libraries(xgboost PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/lib/libboostkit_xgboost_kernel.so)
-endif (BUILD_STATIC_LIB)
-
-#-- Hide all C++ symbols
-if (HIDE_CXX_SYMBOLS)
- set_target_properties(objxgboost PROPERTIES CXX_VISIBILITY_PRESET hidden)
- set_target_properties(xgboost PROPERTIES CXX_VISIBILITY_PRESET hidden)
-endif (HIDE_CXX_SYMBOLS)
-
-target_include_directories(xgboost
- INTERFACE
- $
- $)
-target_link_libraries(xgboost PRIVATE ${LINKED_LIBRARIES_PRIVATE})
-
-# This creates its own shared library `xgboost4j'.
-if (JVM_BINDINGS)
- # To ensure open source independently compliation
- add_subdirectory(${PROJECT_SOURCE_DIR}/kernel_include/boostkit_xgboost_kernel_client)
- add_subdirectory(${xgboost_SOURCE_DIR}/jvm-packages)
-endif (JVM_BINDINGS)
-#-- End shared library
-
-#-- CLI for xgboost
-add_executable(runxgboost ${xgboost_SOURCE_DIR}/src/cli_main.cc ${XGBOOST_OBJ_SOURCES})
-
-target_include_directories(runxgboost
- PRIVATE
- ${xgboost_SOURCE_DIR}/include
- ${xgboost_SOURCE_DIR}/dmlc-core/include
- ${xgboost_SOURCE_DIR}/rabit/include
- ${xgboost_SOURCE_DIR}/kernel_include)
-target_link_libraries(runxgboost PRIVATE ${LINKED_LIBRARIES_PRIVATE})
-target_link_libraries(runxgboost PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/lib/libboostkit_xgboost_kernel.so)
-set_target_properties(
- runxgboost PROPERTIES
- OUTPUT_NAME xgboost
- CXX_STANDARD 14
- CXX_STANDARD_REQUIRED ON)
-#-- End CLI for xgboost
-
-set_output_directory(runxgboost ${xgboost_SOURCE_DIR})
-set_output_directory(xgboost ${xgboost_SOURCE_DIR}/lib)
-# Ensure these two targets do not build simultaneously, as they produce outputs with conflicting names
-add_dependencies(xgboost runxgboost)
-
-#-- Installing XGBoost
-if (R_LIB)
- set_target_properties(xgboost PROPERTIES PREFIX "")
- if (APPLE)
- set_target_properties(xgboost PROPERTIES SUFFIX ".so")
- endif (APPLE)
- setup_rpackage_install_target(xgboost ${CMAKE_CURRENT_BINARY_DIR})
- set(CMAKE_INSTALL_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/dummy_inst")
-endif (R_LIB)
-if (MINGW)
- set_target_properties(xgboost PROPERTIES PREFIX "")
-endif (MINGW)
-
-if (BUILD_C_DOC)
- include(cmake/Doc.cmake)
- run_doxygen()
-endif (BUILD_C_DOC)
-
-include(GNUInstallDirs)
-# Install all headers. Please note that currently the C++ headers does not form an "API".
-install(DIRECTORY ${xgboost_SOURCE_DIR}/include/xgboost
- DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
-
-install(TARGETS xgboost runxgboost
- EXPORT XGBoostTargets
- ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
- LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
- RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
- INCLUDES DESTINATION ${LIBLEGACY_INCLUDE_DIRS})
-install(EXPORT XGBoostTargets
- FILE XGBoostTargets.cmake
- NAMESPACE xgboost::
- DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/xgboost)
-
-include(CMakePackageConfigHelpers)
-configure_package_config_file(
- ${CMAKE_CURRENT_LIST_DIR}/cmake/xgboost-config.cmake.in
- ${CMAKE_CURRENT_BINARY_DIR}/cmake/xgboost-config.cmake
- INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/xgboost)
-write_basic_package_version_file(
- ${CMAKE_BINARY_DIR}/cmake/xgboost-config-version.cmake
- VERSION ${XGBOOST_VERSION}
- COMPATIBILITY AnyNewerVersion)
-install(
- FILES
- ${CMAKE_BINARY_DIR}/cmake/xgboost-config.cmake
- ${CMAKE_BINARY_DIR}/cmake/xgboost-config-version.cmake
- DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/xgboost)
-
-
-# For MSVC: Call msvc_use_static_runtime() once again to completely
-# replace /MD with /MT. See https://github.com/dmlc/xgboost/issues/4462
-# for issues caused by mixing of /MD and /MT flags
-msvc_use_static_runtime()
diff --git a/ml-xgboost/CONTRIBUTORS.md b/ml-xgboost/CONTRIBUTORS.md
deleted file mode 100644
index e426f85..0000000
--- a/ml-xgboost/CONTRIBUTORS.md
+++ /dev/null
@@ -1,104 +0,0 @@
-Contributors of DMLC/XGBoost
-============================
-XGBoost has been developed and used by a group of active community. Everyone is more than welcomed to is a great way to make the project better and more accessible to more users.
-
-Project Management Committee(PMC)
-----------
-The Project Management Committee(PMC) consists group of active committers that moderate the discussion, manage the project release, and proposes new committer/PMC members.
-
-* [Tianqi Chen](https://github.com/tqchen), University of Washington
- - Tianqi is a Ph.D. student working on large-scale machine learning. He is the creator of the project.
-* [Michael Benesty](https://github.com/pommedeterresautee)
- - Michael is a lawyer and data scientist in France. He is the creator of XGBoost interactive analysis module in R.
-* [Yuan Tang](https://github.com/terrytangyuan), Ant Financial
- - Yuan is a software engineer in Ant Financial. He contributed mostly in R and Python packages.
-* [Nan Zhu](https://github.com/CodingCat), Uber
- - Nan is a software engineer in Uber. He contributed mostly in JVM packages.
-* [Jiaming Yuan](https://github.com/trivialfis)
- - Jiaming contributed to the GPU algorithms. He has also introduced new abstractions to improve the quality of the C++ codebase.
-* [Hyunsu Cho](http://hyunsu-cho.io/), NVIDIA
- - Hyunsu is the maintainer of the XGBoost Python package. He also manages the Jenkins continuous integration system (https://xgboost-ci.net/). He is the initial author of the CPU 'hist' updater.
-* [Rory Mitchell](https://github.com/RAMitchell), University of Waikato
- - Rory is a Ph.D. student at University of Waikato. He is the original creator of the GPU training algorithms. He improved the CMake build system and continuous integration.
-* [Hongliang Liu](https://github.com/phunterlau)
-
-
-Committers
-----------
-Committers are people who have made substantial contribution to the project and granted write access to the project.
-
-* [Tong He](https://github.com/hetong007), Amazon AI
- - Tong is an applied scientist in Amazon AI. He is the maintainer of XGBoost R package.
-* [Vadim Khotilovich](https://github.com/khotilov)
- - Vadim contributes many improvements in R and core packages.
-* [Bing Xu](https://github.com/antinucleon)
- - Bing is the original creator of XGBoost Python package and currently the maintainer of [XGBoost.jl](https://github.com/antinucleon/XGBoost.jl).
-* [Sergei Lebedev](https://github.com/superbobry), Criteo
- - Sergei is a software engineer in Criteo. He contributed mostly in JVM packages.
-* [Scott Lundberg](http://scottlundberg.com/), University of Washington
- - Scott is a Ph.D. student at University of Washington. He is the creator of SHAP, a unified approach to explain the output of machine learning models such as decision tree ensembles. He also helps maintain the XGBoost Julia package.
-
-
-Become a Committer
-------------------
-XGBoost is a opensource project and we are actively looking for new committers who are willing to help maintaining and lead the project.
-Committers comes from contributors who:
-* Made substantial contribution to the project.
-* Willing to spent time on maintaining and lead the project.
-
-New committers will be proposed by current committer members, with support from more than two of current committers.
-
-List of Contributors
---------------------
-* [Full List of Contributors](https://github.com/dmlc/xgboost/graphs/contributors)
- - To contributors: please add your name to the list when you submit a patch to the project:)
-* [Kailong Chen](https://github.com/kalenhaha)
- - Kailong is an early contributor of XGBoost, he is creator of ranking objectives in XGBoost.
-* [Skipper Seabold](https://github.com/jseabold)
- - Skipper is the major contributor to the scikit-learn module of XGBoost.
-* [Zygmunt Zając](https://github.com/zygmuntz)
- - Zygmunt is the master behind the early stopping feature frequently used by kagglers.
-* [Ajinkya Kale](https://github.com/ajkl)
-* [Boliang Chen](https://github.com/cblsjtu)
-* [Yangqing Men](https://github.com/yanqingmen)
- - Yangqing is the creator of XGBoost java package.
-* [Engpeng Yao](https://github.com/yepyao)
-* [Giulio](https://github.com/giuliohome)
- - Giulio is the creator of Windows project of XGBoost
-* [Jamie Hall](https://github.com/nerdcha)
- - Jamie is the initial creator of XGBoost scikit-learn module.
-* [Yen-Ying Lee](https://github.com/white1033)
-* [Masaaki Horikoshi](https://github.com/sinhrks)
- - Masaaki is the initial creator of XGBoost Python plotting module.
-* [daiyl0320](https://github.com/daiyl0320)
- - daiyl0320 contributed patch to XGBoost distributed version more robust, and scales stably on TB scale datasets.
-* [Huayi Zhang](https://github.com/irachex)
-* [Johan Manders](https://github.com/johanmanders)
-* [yoori](https://github.com/yoori)
-* [Mathias Müller](https://github.com/far0n)
-* [Sam Thomson](https://github.com/sammthomson)
-* [ganesh-krishnan](https://github.com/ganesh-krishnan)
-* [Damien Carol](https://github.com/damiencarol)
-* [Alex Bain](https://github.com/convexquad)
-* [Baltazar Bieniek](https://github.com/bbieniek)
-* [Adam Pocock](https://github.com/Craigacp)
-* [Gideon Whitehead](https://github.com/gaw89)
-* [Yi-Lin Juang](https://github.com/frankyjuang)
-* [Andrew Hannigan](https://github.com/andrewhannigan)
-* [Andy Adinets](https://github.com/canonizer)
-* [Henry Gouk](https://github.com/henrygouk)
-* [Pierre de Sahb](https://github.com/pdesahb)
-* [liuliang01](https://github.com/liuliang01)
- - liuliang01 added support for the qid column for LibSVM input format. This makes ranking task easier in distributed setting.
-* [Andrew Thia](https://github.com/BlueTea88)
- - Andrew Thia implemented feature interaction constraints
-* [Wei Tian](https://github.com/weitian)
-* [Chen Qin](https://github.com/chenqin)
-* [Sam Wilkinson](https://samwilkinson.io)
-* [Matthew Jones](https://github.com/mt-jones)
-* [Jiaxiang Li](https://github.com/JiaxiangBU)
-* [Bryan Woods](https://github.com/bryan-woods)
- - Bryan added support for cross-validation for the ranking objective
-* [Haoda Fu](https://github.com/fuhaoda)
-* [Evan Kepner](https://github.com/EvanKepner)
- - Evan Kepner added support for os.PathLike file paths in Python
diff --git a/ml-xgboost/Jenkinsfile b/ml-xgboost/Jenkinsfile
deleted file mode 100644
index f2bd51c..0000000
--- a/ml-xgboost/Jenkinsfile
+++ /dev/null
@@ -1,435 +0,0 @@
-#!/usr/bin/groovy
-// -*- mode: groovy -*-
-// Jenkins pipeline
-// See documents at https://jenkins.io/doc/book/pipeline/jenkinsfile/
-
-// Command to run command inside a docker container
-dockerRun = 'tests/ci_build/ci_build.sh'
-
-import groovy.transform.Field
-
-@Field
-def commit_id // necessary to pass a variable from one stage to another
-
-pipeline {
- // Each stage specify its own agent
- agent none
-
- environment {
- DOCKER_CACHE_ECR_ID = '492475357299'
- DOCKER_CACHE_ECR_REGION = 'us-west-2'
- }
-
- // Setup common job properties
- options {
- ansiColor('xterm')
- timestamps()
- timeout(time: 240, unit: 'MINUTES')
- buildDiscarder(logRotator(numToKeepStr: '10'))
- preserveStashes()
- }
-
- // Build stages
- stages {
- stage('Jenkins Linux: Get sources') {
- agent { label 'linux && cpu' }
- steps {
- script {
- checkoutSrcs()
- commit_id = "${GIT_COMMIT}"
- }
- stash name: 'srcs'
- milestone ordinal: 1
- }
- }
- stage('Jenkins Linux: Formatting Check') {
- agent none
- steps {
- script {
- parallel ([
- 'clang-tidy': { ClangTidy() },
- 'lint': { Lint() },
- 'sphinx-doc': { SphinxDoc() },
- 'doxygen': { Doxygen() }
- ])
- }
- milestone ordinal: 2
- }
- }
- stage('Jenkins Linux: Build') {
- agent none
- steps {
- script {
- parallel ([
- 'build-cpu': { BuildCPU() },
- 'build-cpu-rabit-mock': { BuildCPUMock() },
- 'build-cpu-non-omp': { BuildCPUNonOmp() },
- 'build-gpu-cuda10.0': { BuildCUDA(cuda_version: '10.0') },
- 'build-gpu-cuda10.1': { BuildCUDA(cuda_version: '10.1') },
- 'build-jvm-packages': { BuildJVMPackages(spark_version: '2.4.3') },
- 'build-jvm-doc': { BuildJVMDoc() }
- ])
- }
- milestone ordinal: 3
- }
- }
- stage('Jenkins Linux: Test') {
- agent none
- steps {
- script {
- parallel ([
- 'test-python-cpu': { TestPythonCPU() },
- 'test-python-gpu-cuda9.0': { TestPythonGPU(cuda_version: '9.0') },
- 'test-python-gpu-cuda10.0': { TestPythonGPU(cuda_version: '10.0') },
- 'test-python-gpu-cuda10.1': { TestPythonGPU(cuda_version: '10.1') },
- 'test-python-mgpu-cuda10.1': { TestPythonGPU(cuda_version: '10.1', multi_gpu: true) },
- 'test-cpp-gpu': { TestCppGPU(cuda_version: '10.1') },
- 'test-cpp-mgpu': { TestCppGPU(cuda_version: '10.1', multi_gpu: true) },
- 'test-jvm-jdk8': { CrossTestJVMwithJDK(jdk_version: '8', spark_version: '2.4.3') },
- 'test-jvm-jdk11': { CrossTestJVMwithJDK(jdk_version: '11') },
- 'test-jvm-jdk12': { CrossTestJVMwithJDK(jdk_version: '12') },
- 'test-r-3.5.3': { TestR(use_r35: true) }
- ])
- }
- milestone ordinal: 4
- }
- }
- stage('Jenkins Linux: Deploy') {
- agent none
- steps {
- script {
- parallel ([
- 'deploy-jvm-packages': { DeployJVMPackages(spark_version: '2.4.3') }
- ])
- }
- milestone ordinal: 5
- }
- }
- }
-}
-
-// check out source code from git
-def checkoutSrcs() {
- retry(5) {
- try {
- timeout(time: 2, unit: 'MINUTES') {
- checkout scm
- sh 'git submodule update --init'
- }
- } catch (exc) {
- deleteDir()
- error "Failed to fetch source codes"
- }
- }
-}
-
-def ClangTidy() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Running clang-tidy job..."
- def container_type = "clang_tidy"
- def docker_binary = "docker"
- def dockerArgs = "--build-arg CUDA_VERSION=10.1"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} ${dockerArgs} python3 tests/ci_build/tidy.py
- """
- deleteDir()
- }
-}
-
-def Lint() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Running lint..."
- def container_type = "cpu"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} make lint
- """
- deleteDir()
- }
-}
-
-def SphinxDoc() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Running sphinx-doc..."
- def container_type = "cpu"
- def docker_binary = "docker"
- def docker_extra_params = "CI_DOCKER_EXTRA_PARAMS_INIT='-e SPHINX_GIT_BRANCH=${BRANCH_NAME}'"
- sh """#!/bin/bash
- ${docker_extra_params} ${dockerRun} ${container_type} ${docker_binary} make -C doc html
- """
- deleteDir()
- }
-}
-
-def Doxygen() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Running doxygen..."
- def container_type = "cpu"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/doxygen.sh ${BRANCH_NAME}
- """
- echo 'Uploading doc...'
- s3Upload file: "build/${BRANCH_NAME}.tar.bz2", bucket: 'xgboost-docs', acl: 'PublicRead', path: "doxygen/${BRANCH_NAME}.tar.bz2"
- deleteDir()
- }
-}
-
-def BuildCPU() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Build CPU"
- def container_type = "cpu"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} rm -fv dmlc-core/include/dmlc/build_config_default.h
- # This step is not necessary, but here we include it, to ensure that DMLC_CORE_USE_CMAKE flag is correctly propagated
- # We want to make sure that we use the configured header build/dmlc/build_config.h instead of include/dmlc/build_config_default.h.
- # See discussion at https://github.com/dmlc/xgboost/issues/5510
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/build_via_cmake.sh
- ${dockerRun} ${container_type} ${docker_binary} build/testxgboost
- """
- // Sanitizer test
- def docker_extra_params = "CI_DOCKER_EXTRA_PARAMS_INIT='-e ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer -e ASAN_OPTIONS=symbolize=1 -e UBSAN_OPTIONS=print_stacktrace=1:log_path=ubsan_error.log --cap-add SYS_PTRACE'"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/build_via_cmake.sh -DUSE_SANITIZER=ON -DENABLED_SANITIZERS="address;leak;undefined" \
- -DCMAKE_BUILD_TYPE=Debug -DSANITIZER_PATH=/usr/lib/x86_64-linux-gnu/
- ${docker_extra_params} ${dockerRun} ${container_type} ${docker_binary} build/testxgboost
- """
-
- stash name: 'xgboost_cli', includes: 'xgboost'
- deleteDir()
- }
-}
-
-def BuildCPUMock() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Build CPU with rabit mock"
- def container_type = "cpu"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/build_mock_cmake.sh
- """
- echo 'Stashing rabit C++ test executable (xgboost)...'
- stash name: 'xgboost_rabit_tests', includes: 'xgboost'
- deleteDir()
- }
-}
-
-def BuildCPUNonOmp() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Build CPU without OpenMP"
- def container_type = "cpu"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/build_via_cmake.sh -DUSE_OPENMP=OFF
- """
- echo "Running Non-OpenMP C++ test..."
- sh """
- ${dockerRun} ${container_type} ${docker_binary} build/testxgboost
- """
- deleteDir()
- }
-}
-
-def BuildCUDA(args) {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Build with CUDA ${args.cuda_version}"
- def container_type = "gpu_build"
- def docker_binary = "docker"
- def docker_args = "--build-arg CUDA_VERSION=${args.cuda_version}"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} ${docker_args} tests/ci_build/build_via_cmake.sh -DUSE_CUDA=ON -DUSE_NCCL=ON -DOPEN_MP:BOOL=ON -DHIDE_CXX_SYMBOLS=ON
- ${dockerRun} ${container_type} ${docker_binary} ${docker_args} bash -c "cd python-package && rm -rf dist/* && python setup.py bdist_wheel --universal"
- ${dockerRun} ${container_type} ${docker_binary} ${docker_args} python3 tests/ci_build/rename_whl.py python-package/dist/*.whl ${commit_id} manylinux2010_x86_64
- """
- // Stash wheel for CUDA 10.0 target
- if (args.cuda_version == '10.0') {
- echo 'Stashing Python wheel...'
- stash name: 'xgboost_whl_cuda10', includes: 'python-package/dist/*.whl'
- path = ("${BRANCH_NAME}" == 'master') ? '' : "${BRANCH_NAME}/"
- s3Upload bucket: 'xgboost-nightly-builds', path: path, acl: 'PublicRead', workingDir: 'python-package/dist', includePathPattern:'**/*.whl'
- echo 'Stashing C++ test executable (testxgboost)...'
- stash name: 'xgboost_cpp_tests', includes: 'build/testxgboost'
- }
- deleteDir()
- }
-}
-
-def BuildJVMPackages(args) {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Build Boostkit-XGBoost4J-Spark with Spark ${args.spark_version}"
- def container_type = "jvm"
- def docker_binary = "docker"
- // Use only 4 CPU cores
- def docker_extra_params = "CI_DOCKER_EXTRA_PARAMS_INIT='--cpuset-cpus 0-3'"
- sh """
- ${docker_extra_params} ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/build_jvm_packages.sh ${args.spark_version}
- """
- echo 'Stashing Boostkit-XGBoost4J JAR...'
- stash name: 'boostkit-xgboost4j_jar', includes: "jvm-packages/boostkit-xgboost4j/target/*.jar,jvm-packages/boostkit-xgboost4j-spark/target/*.jar,jvm-packages/boostkit-xgboost4j-example/target/*.jar"
- deleteDir()
- }
-}
-
-def BuildJVMDoc() {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Building JVM doc..."
- def container_type = "jvm"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/build_jvm_doc.sh ${BRANCH_NAME}
- """
- echo 'Uploading doc...'
- s3Upload file: "jvm-packages/${BRANCH_NAME}.tar.bz2", bucket: 'xgboost-docs', acl: 'PublicRead', path: "${BRANCH_NAME}.tar.bz2"
- deleteDir()
- }
-}
-
-def TestPythonCPU() {
- node('linux && cpu') {
- unstash name: 'xgboost_whl_cuda10'
- unstash name: 'srcs'
- unstash name: 'xgboost_cli'
- echo "Test Python CPU"
- def container_type = "cpu"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/test_python.sh cpu
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/test_python.sh cpu-py35
- """
- deleteDir()
- }
-}
-
-def TestPythonGPU(args) {
- nodeReq = (args.multi_gpu) ? 'linux && mgpu' : 'linux && gpu'
- node(nodeReq) {
- unstash name: 'xgboost_whl_cuda10'
- unstash name: 'srcs'
- echo "Test Python GPU: CUDA ${args.cuda_version}"
- def container_type = "gpu"
- def docker_binary = "nvidia-docker"
- def docker_args = "--build-arg CUDA_VERSION=${args.cuda_version}"
- if (args.multi_gpu) {
- echo "Using multiple GPUs"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} ${docker_args} tests/ci_build/test_python.sh mgpu
- """
- if (args.cuda_version != '9.0') {
- echo "Running tests with cuDF..."
- sh """
- ${dockerRun} cudf ${docker_binary} ${docker_args} tests/ci_build/test_python.sh mgpu-cudf
- """
- }
- } else {
- echo "Using a single GPU"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} ${docker_args} tests/ci_build/test_python.sh gpu
- """
- if (args.cuda_version != '9.0') {
- echo "Running tests with cuDF..."
- sh """
- ${dockerRun} cudf ${docker_binary} ${docker_args} tests/ci_build/test_python.sh cudf
- """
- }
- }
- // For CUDA 10.0 target, run cuDF tests too
- deleteDir()
- }
-}
-
-def TestCppRabit() {
- node(nodeReq) {
- unstash name: 'xgboost_rabit_tests'
- unstash name: 'srcs'
- echo "Test C++, rabit mock on"
- def container_type = "cpu"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/runxgb.sh xgboost tests/ci_build/approx.conf.in
- """
- deleteDir()
- }
-}
-
-def TestCppGPU(args) {
- nodeReq = (args.multi_gpu) ? 'linux && mgpu' : 'linux && gpu'
- node(nodeReq) {
- unstash name: 'xgboost_cpp_tests'
- unstash name: 'srcs'
- echo "Test C++, CUDA ${args.cuda_version}"
- def container_type = "gpu"
- def docker_binary = "nvidia-docker"
- def docker_args = "--build-arg CUDA_VERSION=${args.cuda_version}"
- if (args.multi_gpu) {
- echo "Using multiple GPUs"
- sh "${dockerRun} ${container_type} ${docker_binary} ${docker_args} build/testxgboost --gtest_filter=*.MGPU_*"
- } else {
- echo "Using a single GPU"
- sh "${dockerRun} ${container_type} ${docker_binary} ${docker_args} build/testxgboost --gtest_filter=-*.MGPU_*"
- }
- deleteDir()
- }
-}
-
-def CrossTestJVMwithJDK(args) {
- node('linux && cpu') {
- unstash name: 'boostkit-xgboost4j_jar'
- unstash name: 'srcs'
- if (args.spark_version != null) {
- echo "Test Boostkit-XGBoost4J on a machine with JDK ${args.jdk_version}, Spark ${args.spark_version}"
- } else {
- echo "Test Boostkit-XGBoost4J on a machine with JDK ${args.jdk_version}"
- }
- def container_type = "jvm_cross"
- def docker_binary = "docker"
- def spark_arg = (args.spark_version != null) ? "--build-arg SPARK_VERSION=${args.spark_version}" : ""
- def docker_args = "--build-arg JDK_VERSION=${args.jdk_version} ${spark_arg}"
- // Run integration tests only when spark_version is given
- def docker_extra_params = (args.spark_version != null) ? "CI_DOCKER_EXTRA_PARAMS_INIT='-e RUN_INTEGRATION_TEST=1'" : ""
- sh """
- ${docker_extra_params} ${dockerRun} ${container_type} ${docker_binary} ${docker_args} tests/ci_build/test_jvm_cross.sh
- """
- deleteDir()
- }
-}
-
-def TestR(args) {
- node('linux && cpu') {
- unstash name: 'srcs'
- echo "Test R package"
- def container_type = "rproject"
- def docker_binary = "docker"
- def use_r35_flag = (args.use_r35) ? "1" : "0"
- def docker_args = "--build-arg USE_R35=${use_r35_flag}"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} ${docker_args} tests/ci_build/build_test_rpkg.sh || tests/ci_build/print_r_stacktrace.sh
- """
- deleteDir()
- }
-}
-
-def DeployJVMPackages(args) {
- node('linux && cpu') {
- unstash name: 'srcs'
- if (env.BRANCH_NAME == 'master' || env.BRANCH_NAME.startsWith('release')) {
- echo 'Deploying to xgboost-maven-repo S3 repo...'
- def container_type = "jvm"
- def docker_binary = "docker"
- sh """
- ${dockerRun} ${container_type} ${docker_binary} tests/ci_build/deploy_jvm_packages.sh ${args.spark_version}
- """
- }
- deleteDir()
- }
-}
diff --git a/ml-xgboost/Jenkinsfile-win64 b/ml-xgboost/Jenkinsfile-win64
deleted file mode 100644
index 15dc345..0000000
--- a/ml-xgboost/Jenkinsfile-win64
+++ /dev/null
@@ -1,151 +0,0 @@
-#!/usr/bin/groovy
-// -*- mode: groovy -*-
-
-/* Jenkins pipeline for Windows AMD64 target */
-
-import groovy.transform.Field
-
-@Field
-def commit_id // necessary to pass a variable from one stage to another
-
-pipeline {
- agent none
- // Build stages
- stages {
- stage('Jenkins Win64: Get sources') {
- agent { label 'win64 && build' }
- steps {
- script {
- checkoutSrcs()
- commit_id = "${GIT_COMMIT}"
- }
- stash name: 'srcs'
- milestone ordinal: 1
- }
- }
- stage('Jenkins Win64: Build') {
- agent none
- steps {
- script {
- parallel ([
- 'build-win64-cuda9.0': { BuildWin64() }
- ])
- }
- milestone ordinal: 2
- }
- }
- stage('Jenkins Win64: Test') {
- agent none
- steps {
- script {
- parallel ([
- 'test-win64-cpu': { TestWin64CPU() },
- 'test-win64-gpu-cuda9.0': { TestWin64GPU(cuda_target: 'cuda9') },
- 'test-win64-gpu-cuda10.0': { TestWin64GPU(cuda_target: 'cuda10_0') },
- 'test-win64-gpu-cuda10.1': { TestWin64GPU(cuda_target: 'cuda10_1') }
- ])
- }
- milestone ordinal: 3
- }
- }
- }
-}
-
-// check out source code from git
-def checkoutSrcs() {
- retry(5) {
- try {
- timeout(time: 2, unit: 'MINUTES') {
- checkout scm
- sh 'git submodule update --init'
- }
- } catch (exc) {
- deleteDir()
- error "Failed to fetch source codes"
- }
- }
-}
-
-def BuildWin64() {
- node('win64 && build') {
- unstash name: 'srcs'
- echo "Building XGBoost for Windows AMD64 target..."
- bat "nvcc --version"
- bat """
- mkdir build
- cd build
- cmake .. -G"Visual Studio 15 2017 Win64" -DUSE_CUDA=ON -DCMAKE_VERBOSE_MAKEFILE=ON -DGOOGLE_TEST=ON -DUSE_DMLC_GTEST=ON
- """
- bat """
- cd build
- "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\MSBuild\\15.0\\Bin\\MSBuild.exe" xgboost.sln /m /p:Configuration=Release /nodeReuse:false
- """
- bat """
- cd python-package
- conda activate && python setup.py bdist_wheel --universal && for /R %%i in (dist\\*.whl) DO python ../tests/ci_build/rename_whl.py "%%i" ${commit_id} win_amd64
- """
- echo "Insert vcomp140.dll (OpenMP runtime) into the wheel..."
- bat """
- cd python-package\\dist
- COPY /B ..\\..\\tests\\ci_build\\insert_vcomp140.py
- conda activate && python insert_vcomp140.py *.whl
- """
- echo 'Stashing Python wheel...'
- stash name: 'xgboost_whl', includes: 'python-package/dist/*.whl'
- path = ("${BRANCH_NAME}" == 'master') ? '' : "${BRANCH_NAME}/"
- s3Upload bucket: 'xgboost-nightly-builds', path: path, acl: 'PublicRead', workingDir: 'python-package/dist', includePathPattern:'**/*.whl'
- echo 'Stashing C++ test executable (testxgboost)...'
- stash name: 'xgboost_cpp_tests', includes: 'build/testxgboost.exe'
- stash name: 'xgboost_cli', includes: 'xgboost.exe'
- deleteDir()
- }
-}
-
-def TestWin64CPU() {
- node('win64 && cpu') {
- unstash name: 'srcs'
- unstash name: 'xgboost_whl'
- unstash name: 'xgboost_cli'
- echo "Test Win64 CPU"
- echo "Installing Python wheel..."
- bat "conda activate && (python -m pip uninstall -y xgboost || cd .)"
- bat """
- conda activate && for /R %%i in (python-package\\dist\\*.whl) DO python -m pip install "%%i"
- """
- echo "Installing Python dependencies..."
- bat """
- conda activate && conda upgrade scikit-learn pandas numpy
- """
- echo "Running Python tests..."
- bat "conda activate && python -m pytest -v -s --fulltrace tests\\python"
- bat "conda activate && python -m pip uninstall -y xgboost"
- deleteDir()
- }
-}
-
-def TestWin64GPU(args) {
- node("win64 && gpu && ${args.cuda_target}") {
- unstash name: 'srcs'
- unstash name: 'xgboost_whl'
- unstash name: 'xgboost_cpp_tests'
- echo "Test Win64 GPU (${args.cuda_target})"
- bat "nvcc --version"
- echo "Running C++ tests..."
- bat "build\\testxgboost.exe"
- echo "Installing Python wheel..."
- bat "conda activate && (python -m pip uninstall -y xgboost || cd .)"
- bat """
- conda activate && for /R %%i in (python-package\\dist\\*.whl) DO python -m pip install "%%i"
- """
- echo "Installing Python dependencies..."
- bat """
- conda activate && conda upgrade scikit-learn pandas numpy
- """
- echo "Running Python tests..."
- bat """
- conda activate && python -m pytest -v -s --fulltrace -m "(not slow) and (not mgpu)" tests\\python-gpu
- """
- bat "conda activate && python -m pip uninstall -y xgboost"
- deleteDir()
- }
-}
diff --git a/ml-xgboost/LICENSE b/ml-xgboost/LICENSE
deleted file mode 100644
index 90c0ff9..0000000
--- a/ml-xgboost/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright (c) 2019 by Contributors
-
- Licensed 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.
diff --git a/ml-xgboost/Makefile b/ml-xgboost/Makefile
deleted file mode 100644
index a49d307..0000000
--- a/ml-xgboost/Makefile
+++ /dev/null
@@ -1,147 +0,0 @@
-ifndef DMLC_CORE
- DMLC_CORE = dmlc-core
-endif
-
-ifndef RABIT
- RABIT = rabit
-endif
-
-ROOTDIR = $(CURDIR)
-
-# workarounds for some buggy old make & msys2 versions seen in windows
-ifeq (NA, $(shell test ! -d "$(ROOTDIR)" && echo NA ))
- $(warning Attempting to fix non-existing ROOTDIR [$(ROOTDIR)])
- ROOTDIR := $(shell pwd)
- $(warning New ROOTDIR [$(ROOTDIR)] $(shell test -d "$(ROOTDIR)" && echo " is OK" ))
-endif
-MAKE_OK := $(shell "$(MAKE)" -v 2> /dev/null)
-ifndef MAKE_OK
- $(warning Attempting to recover non-functional MAKE [$(MAKE)])
- MAKE := $(shell which make 2> /dev/null)
- MAKE_OK := $(shell "$(MAKE)" -v 2> /dev/null)
-endif
-$(warning MAKE [$(MAKE)] - $(if $(MAKE_OK),checked OK,PROBLEM))
-
-include $(DMLC_CORE)/make/dmlc.mk
-
-# set compiler defaults for OSX versus *nix
-# let people override either
-OS := $(shell uname)
-ifeq ($(OS), Darwin)
-ifndef CC
-export CC = $(if $(shell which clang), clang, gcc)
-endif
-ifndef CXX
-export CXX = $(if $(shell which clang++), clang++, g++)
-endif
-else
-# linux defaults
-ifndef CC
-export CC = gcc
-endif
-ifndef CXX
-export CXX = g++
-endif
-endif
-
-export CFLAGS= -DDMLC_LOG_CUSTOMIZE=1 -std=c++11 -Wall -Wno-unknown-pragmas -Iinclude $(ADD_CFLAGS)
-CFLAGS += -I$(DMLC_CORE)/include -I$(RABIT)/include -I$(GTEST_PATH)/include
-
-ifeq ($(TEST_COVER), 1)
- CFLAGS += -g -O0 -fprofile-arcs -ftest-coverage
-else
- CFLAGS += -O3 -funroll-loops
-endif
-
-ifndef LINT_LANG
- LINT_LANG= "all"
-endif
-
-# specify tensor path
-.PHONY: clean all lint clean_all doxygen rcpplint pypack Rpack Rbuild Rcheck
-
-build/%.o: src/%.cc
- @mkdir -p $(@D)
- $(CXX) $(CFLAGS) -MM -MT build/$*.o $< >build/$*.d
- $(CXX) -c $(CFLAGS) $< -o $@
-
-# The should be equivalent to $(ALL_OBJ) except for build/cli_main.o
-amalgamation/xgboost-all0.o: amalgamation/xgboost-all0.cc
- $(CXX) -c $(CFLAGS) $< -o $@
-
-rcpplint:
- python3 dmlc-core/scripts/lint.py xgboost ${LINT_LANG} R-package/src
-
-lint: rcpplint
- python3 dmlc-core/scripts/lint.py --exclude_path python-package/xgboost/dmlc-core \
- python-package/xgboost/include python-package/xgboost/lib \
- python-package/xgboost/make python-package/xgboost/rabit \
- python-package/xgboost/src --pylint-rc ${PWD}/python-package/.pylintrc xgboost \
- ${LINT_LANG} include src python-package
-
-ifeq ($(TEST_COVER), 1)
-cover: check
- @- $(foreach COV_OBJ, $(COVER_OBJ), \
- gcov -pbcul -o $(shell dirname $(COV_OBJ)) $(COV_OBJ) > gcov.log || cat gcov.log; \
- )
-endif
-
-clean:
- $(RM) -rf build lib bin *~ */*~ */*/*~ */*/*/*~ */*.o */*/*.o */*/*/*.o #xgboost
- $(RM) -rf build_tests *.gcov tests/cpp/xgboost_test
- if [ -d "R-package/src" ]; then \
- cd R-package/src; \
- $(RM) -rf rabit src include dmlc-core amalgamation *.so *.dll; \
- cd $(ROOTDIR); \
- fi
-
-clean_all: clean
- cd $(DMLC_CORE); "$(MAKE)" clean; cd $(ROOTDIR)
- cd $(RABIT); "$(MAKE)" clean; cd $(ROOTDIR)
-
-# create pip source dist (sdist) pack for PyPI
-pippack: clean_all
- cd python-package; python setup.py sdist; mv dist/*.tar.gz ..; cd ..
-
-# Script to make a clean installable R package.
-Rpack: clean_all
- rm -rf xgboost xgboost*.tar.gz
- cp -r R-package xgboost
- rm -rf xgboost/src/*.o xgboost/src/*.so xgboost/src/*.dll
- rm -rf xgboost/src/*/*.o
- rm -rf xgboost/demo/*.model xgboost/demo/*.buffer xgboost/demo/*.txt
- rm -rf xgboost/demo/runall.R
- cp -r src xgboost/src/src
- cp -r include xgboost/src/include
- cp -r amalgamation xgboost/src/amalgamation
- mkdir -p xgboost/src/rabit
- cp -r rabit/include xgboost/src/rabit/include
- cp -r rabit/src xgboost/src/rabit/src
- rm -rf xgboost/src/rabit/src/*.o
- mkdir -p xgboost/src/dmlc-core
- cp -r dmlc-core/include xgboost/src/dmlc-core/include
- cp -r dmlc-core/src xgboost/src/dmlc-core/src
- cp ./LICENSE xgboost
-# Modify PKGROOT in Makevars.in
- cat R-package/src/Makevars.in|sed '2s/.*/PKGROOT=./' > xgboost/src/Makevars.in
-# Configure Makevars.win (Windows-specific Makevars, likely using MinGW)
- cp xgboost/src/Makevars.in xgboost/src/Makevars.win
- cat xgboost/src/Makevars.in| sed '3s/.*/ENABLE_STD_THREAD=0/' > xgboost/src/Makevars.win
- sed -i -e 's/@OPENMP_CXXFLAGS@/$$\(SHLIB_OPENMP_CXXFLAGS\)/g' xgboost/src/Makevars.win
- sed -i -e 's/-pthread/$$\(SHLIB_PTHREAD_FLAGS\)/g' xgboost/src/Makevars.win
- sed -i -e 's/@ENDIAN_FLAG@/-DDMLC_CMAKE_LITTLE_ENDIAN=1/g' xgboost/src/Makevars.win
- sed -i -e 's/@BACKTRACE_LIB@//g' xgboost/src/Makevars.win
- sed -i -e 's/@OPENMP_LIB@//g' xgboost/src/Makevars.win
- rm -f xgboost/src/Makevars.win-e # OSX sed create this extra file; remove it
- bash R-package/remove_warning_suppression_pragma.sh
- rm xgboost/remove_warning_suppression_pragma.sh
-
-Rbuild: Rpack
- R CMD build --no-build-vignettes xgboost
- rm -rf xgboost
-
-Rcheck: Rbuild
- R CMD check xgboost*.tar.gz
-
--include build/*.d
--include build/*/*.d
diff --git a/ml-xgboost/NEWS.md b/ml-xgboost/NEWS.md
deleted file mode 100644
index 777fa6c..0000000
--- a/ml-xgboost/NEWS.md
+++ /dev/null
@@ -1,1100 +0,0 @@
-XGBoost Change Log
-==================
-
-This file records the changes in xgboost library in reverse chronological order.
-
-## v1.0.0 (2020.02.19)
-This release marks a major milestone for the XGBoost project.
-
-### Apache-style governance, contribution policy, and semantic versioning (#4646, #4659)
-* Starting with 1.0.0 release, the XGBoost Project is adopting Apache-style governance. The full community guideline is [available in the doc website](https://xgboost.readthedocs.io/en/release_1.0.0/contrib/community.html). Note that we now have Project Management Committee (PMC) who would steward the project on the long-term basis. The PMC is also entrusted to run and fund the project's continuous integration (CI) infrastructure (https://xgboost-ci.net).
-* We also adopt the [semantic versioning](https://semver.org/). See [our release versioning policy](https://xgboost.readthedocs.io/en/release_1.0.0/contrib/release.html).
-
-### Better performance scaling for multi-core CPUs (#4502, #4529, #4716, #4851, #5008, #5107, #5138, #5156)
-* Poor performance scaling of the `hist` algorithm for multi-core CPUs has been under investigation (#3810). Previous effort #4529 was replaced with a series of pull requests (#5107, #5138, #5156) aimed at achieving the same performance benefits while keeping the C++ codebase legible. The latest performance benchmark results show [up to 5x speedup on Intel CPUs with many cores](https://github.com/dmlc/xgboost/pull/5156#issuecomment-580024413). Note: #5244, which concludes the effort, will become part of the upcoming release 1.1.0.
-
-### Improved installation experience on Mac OSX (#4672, #5074, #5080, #5146, #5240)
-* It used to be quite complicated to install XGBoost on Mac OSX. XGBoost uses OpenMP to distribute work among multiple CPU cores, and Mac's default C++ compiler (Apple Clang) does not come with OpenMP. Existing work-around (using another C++ compiler) was complex and prone to fail with cryptic diagnosis (#4933, #4949, #4969).
-* Now it only takes two commands to install XGBoost: `brew install libomp` followed by `pip install xgboost`. The installed XGBoost will use all CPU cores.
-* Even better, XGBoost is now available from Homebrew: `brew install xgboost`. See Homebrew/homebrew-core#50467.
-* Previously, if you installed the XGBoost R package using the command `install.packages('xgboost')`, it could only use a single CPU core and you would experience slow training performance. With 1.0.0 release, the R package will use all CPU cores out of box.
-
-### Distributed XGBoost now available on Kubernetes (#4621, #4939)
-* Check out the [tutorial for setting up distributed XGBoost on a Kubernetes cluster](https://xgboost.readthedocs.io/en/release_1.0.0/tutorials/kubernetes.html).
-
-### Ruby binding for XGBoost (#4856)
-
-### New Native Dask interface for multi-GPU and multi-node scaling (#4473, #4507, #4617, #4819, #4907, #4914, #4941, #4942, #4951, #4973, #5048, #5077, #5144, #5270)
-* XGBoost now integrates seamlessly with [Dask](https://dask.org/), a lightweight distributed framework for data processing. Together with the first-class support for cuDF data frames (see below), it is now easier than ever to create end-to-end data pipeline running on one or more NVIDIA GPUs.
-* Multi-GPU training with Dask is now up to 20% faster than the previous release (#4914, #4951).
-
-### First-class support for cuDF data frames and cuPy arrays (#4737, #4745, #4794, #4850, #4891, #4902, #4918, #4927, #4928, #5053, #5189, #5194, #5206, #5219, #5225)
-* [cuDF](https://github.com/rapidsai/cudf) is a data frame library for loading and processing tabular data on NVIDIA GPUs. It provides a Pandas-like API.
-* [cuPy](https://github.com/cupy/cupy) implements a NumPy-compatible multi-dimensional array on NVIDIA GPUs.
-* Now users can keep the data on the GPU memory throughout the end-to-end data pipeline, obviating the need for copying data between the main memory and GPU memory.
-* XGBoost can accept any data structure that exposes `__array_interface__` signature, opening way to support other columar formats that are compatible with Apache Arrow.
-
-### [Feature interaction constraint](https://xgboost.readthedocs.io/en/release_1.0.0/tutorials/feature_interaction_constraint.html) is now available with `approx` and `gpu_hist` algorithms (#4534, #4587, #4596, #5034).
-
-### Learning to rank is now GPU accelerated (#4873, #5004, #5129)
-* Supported ranking objectives: NDGC, Map, Pairwise.
-* [Up to 2x improved training performance on GPUs](https://devblogs.nvidia.com/learning-to-rank-with-xgboost-and-gpu/).
-
-### Enable `gamma` parameter for GPU training (#4874, #4953)
-* The `gamma` parameter specifies the minimum loss reduction required to add a new split in a tree. A larger value for `gamma` has the effect of pre-pruning the tree, by making harder to add splits.
-
-### External memory for GPU training (#4486, #4526, #4747, #4833, #4879, #5014)
-* It is now possible to use NVIDIA GPUs even when the size of training data exceeds the available GPU memory. Note that the external memory support for GPU is still experimental. #5093 will further improve performance and will become part of the upcoming release 1.1.0.
-* RFC for enabling external memory with GPU algorithms: #4357
-
-### Improve Scikit-Learn interface (#4558, #4842, #4929, #5049, #5151, #5130, #5227)
-* Many users of XGBoost enjoy the convenience and breadth of Scikit-Learn ecosystem. In this release, we revise the Scikit-Learn API of XGBoost (`XGBRegressor`, `XGBClassifier`, and `XGBRanker`) to achieve feature parity with the traditional XGBoost interface (`xgboost.train()`).
-* Insert check to validate data shapes.
-* Produce an error message if `eval_set` is not a tuple. An error message is better than silently crashing.
-* Allow using `numpy.RandomState` object.
-* Add `n_jobs` as an alias of `nthread`.
-* Roadmap: #5152
-
-### XGBoost4J-Spark: Redesigning checkpointing mechanism
-* RFC is available at #4786
-* Clean up checkpoint file after a successful training job (#4754): The current implementation in XGBoost4J-Spark does not clean up the checkpoint file after a successful training job. If the user runs another job with the same checkpointing directory, she will get a wrong model because the second job will re-use the checkpoint file left over from the first job. To prevent this scenario, we propose to always clean up the checkpoint file after every successful training job.
-* Avoid Multiple Jobs for Checkpointing (#5082): The current method for checkpoint is to collect the booster produced at the last iteration of each checkpoint internal to Driver and persist it in HDFS. The major issue with this approach is that it needs to re-perform the data preparation for training if the user did not choose to cache the training dataset. To avoid re-performing data prep, we build external-memory checkpointing in the XGBoost4J layer as well.
-* Enable deterministic repartitioning when checkpoint is enabled (#4807): Distributed algorithm for gradient boosting assumes a fixed partition of the training data between multiple iterations. In previous versions, there was no guarantee that data partition would stay the same, especially when a worker goes down and some data had to recovered from previous checkpoint. In this release, we make data partition deterministic by using the data hash value of each data row in computing the partition.
-
-### XGBoost4J-Spark: handle errors thrown by the native code (#4560)
-* All core logic of XGBoost is written in C++, so XGBoost4J-Spark internally uses the C++ code via Java Native Interface (JNI). #4560 adds a proper error handling for any errors or exceptions arising from the C++ code, so that the XGBoost Spark application can be torn down in an orderly fashion.
-
-### XGBoost4J-Spark: Refine method to count the number of alive cores (#4858)
-* The `SparkParallelismTracker` class ensures that sufficient number of executor cores are alive. To that end, it is important to query the number of alive cores reliably.
-
-### XGBoost4J: Add `BigDenseMatrix` to store more than `Integer.MAX_VALUE` elements (#4383)
-
-### Robust model serialization with JSON (#4632, #4708, #4739, #4868, #4936, #4945, #4974, #5086, #5087, #5089, #5091, #5094, #5110, #5111, #5112, #5120, #5137, #5218, #5222, #5236, #5245, #5248, #5281)
-* In this release, we introduce an experimental support of using [JSON](https://www.json.org/json-en.html) for serializing (saving/loading) XGBoost models and related hyperparameters for training. We would like to eventually replace the old binary format with JSON, since it is an open format and parsers are available in many programming languages and platforms. See [the documentation for model I/O using JSON](https://xgboost.readthedocs.io/en/release_1.0.0/tutorials/saving_model.html). #3980 explains why JSON was chosen over other alternatives.
-* To maximize interoperability and compatibility of the serialized models, we now split serialization into two parts (#4855):
- 1. Model, e.g. decision trees and strictly related metadata like `num_features`.
- 2. Internal configuration, consisting of training parameters and other configurable parameters. For example, `max_delta_step`, `tree_method`, `objective`, `predictor`, `gpu_id`.
-
- Previously, users often ran into issues where the model file produced by one machine could not load or run on another machine. For example, models trained using a machine with an NVIDIA GPU could not run on another machine without a GPU (#5291, #5234). The reason is that the old binary format saved some internal configuration that were not universally applicable to all machines, e.g. `predictor='gpu_predictor'`.
-
- Now, model saving function (`Booster.save_model()` in Python) will save only the model, without internal configuration. This will guarantee that your model file would be used anywhere. Internal configuration will be serialized in limited circumstances such as:
- * Multiple nodes in a distributed system exchange model details over the network.
- * Model checkpointing, to recover from possible crashes.
-
- This work proved to be useful for parameter validation as well (see below).
-* Starting with 1.0.0 release, we will use semantic versioning to indicate whether the model produced by one version of XGBoost would be compatible with another version of XGBoost. Any change in the major version indicates a breaking change in the serialization format.
-* We now provide a robust method to save and load scikit-learn related attributes (#5245). Previously, we used Python pickle to save Python attributes related to `XGBClassifier`, `XGBRegressor`, and `XGBRanker` objects. The attributes are necessary to properly interact with scikit-learn. See #4639 for more details. The use of pickling hampered interoperability, as a pickle from one machine may not necessarily work on another machine. Starting with this release, we use an alternative method to serialize the scikit-learn related attributes. The use of Python pickle is now discouraged (#5236, #5281).
-
-### Parameter validation: detection of unused or incorrect parameters (#4553, #4577, #4738, #4801, #4961, #5101, #5157, #5167, #5256)
-* Mis-spelled training parameter is a common user mistake. In previous versions of XGBoost, mis-spelled parameters were silently ignored. Starting with 1.0.0 release, XGBoost will produce a warning message if there is any unused training parameters. Currently, parameter validation is available to R users and Python XGBoost API users. We are working to extend its support to scikit-learn users.
-* Configuration steps now have well-defined semantics (#4542, #4738), so we know exactly where and how the internal configurable parameters are changed.
-* The user can now use `save_config()` function to inspect all (used) training parameters. This is helpful for debugging model performance.
-
-### Allow individual workers to recover from faults (#4808, #4966)
-* Status quo: if a worker fails, all workers are shut down and restarted, and learning resumes from the last checkpoint. This involves requesting resources from the scheduler (e.g. Spark) and shuffling all the data again from scratch. Both of these operations can be quite costly and block training for extended periods of time, especially if the training data is big and the number of worker nodes is in the hundreds.
-* The proposed solution is to recover the single node that failed, instead of shutting down all workers. The rest of the clusters wait until the single failed worker is bootstrapped and catches up with the rest.
-* See roadmap at #4753. Note that this is work in progress. In particular, the feature is not yet available from XGBoost4J-Spark.
-
-### Accurate prediction for DART models
-* Use DART tree weights when computing SHAPs (#5050)
-* Don't drop trees during DART prediction by default (#5115)
-* Fix DART prediction in R (#5204)
-
-### Make external memory more robust
-* Fix issues with training with external memory on cpu (#4487)
-* Fix crash with approx tree method on cpu (#4510)
-* Fix external memory race in `exact` (#4980). Note: `dmlc::ThreadedIter` is not actually thread-safe. We would like to re-design it in the long term.
-
-### Major refactoring of the `DMatrix` class (#4686, #4744, #4748, #5044, #5092, #5108, #5188, #5198)
-* Goal 1: improve performance and reduce memory consumption. Right now, if the user trains a model with a NumPy array as training data, the array gets copies 2-3 times before training begins. We'd like to reduce duplication of the data matrix.
-* Goal 2: Expose a common interface to external data, unify the way DMatrix objects are constructed and simplify the process of adding new external data sources. This work is essential for ingesting cuPy arrays.
-* Goal 3: Handle missing values consistently.
-* RFC: #4354, Roadmap: #5143
-* This work is also relevant to external memory support on GPUs.
-
-### Breaking: XGBoost Python package now requires Python 3.5 or newer (#5021, #5274)
-* Python 3.4 has reached its end-of-life on March 16, 2019, so we now require Python 3.5 or newer.
-
-### Breaking: GPU algorithm now requires CUDA 9.0 and higher (#4527, #4580)
-
-### Breaking: `n_gpus` parameter removed; multi-GPU training now requires a distributed framework (#4579, #4749, #4773, #4810, #4867, #4908)
-* #4531 proposed removing support for single-process multi-GPU training. Contributors would focus on multi-GPU support through distributed frameworks such as Dask and Spark, where the framework would be expected to assign a worker process for each GPU independently. By delegating GPU management and data movement to the distributed framework, we can greatly simplify the core XGBoost codebase, make multi-GPU training more robust, and reduce burden for future development.
-
-### Breaking: Some deprecated features have been removed
-* ``gpu_exact`` training method (#4527, #4742, #4777). Use ``gpu_hist`` instead.
-* ``learning_rates`` parameter in Python (#5155). Use the callback API instead.
-* ``num_roots`` (#5059, #5165), since the current training code always uses a single root node.
-* GPU-specific objectives (#4690), such as `gpu:reg:linear`. Use objectives without `gpu:` prefix; GPU will be used automatically if your machine has one.
-
-### Breaking: the C API function `XGBoosterPredict()` now asks for an extra parameter `training`.
-
-### Breaking: We now use CMake exclusively to build XGBoost. `Makefile` is being sunset.
-* Exception: the R package uses Autotools, as the CRAN ecosystem did not yet adopt CMake widely.
-
-### Performance improvements
-* Smarter choice of histogram construction for distributed `gpu_hist` (#4519)
-* Optimizations for quantization on device (#4572)
-* Introduce caching memory allocator to avoid latency associated with GPU memory allocation (#4554, #4615)
-* Optimize the initialization stage of the CPU `hist` algorithm for sparse datasets (#4625)
-* Prevent unnecessary data copies from GPU memory to the host (#4795)
-* Improve operation efficiency for single prediction (#5016)
-* Group builder modified for incremental building, to speed up building large `DMatrix` (#5098)
-
-### Bug-fixes
-* Eliminate `FutureWarning: Series.base is deprecated` (#4337)
-* Ensure pandas DataFrame column names are treated as strings in type error message (#4481)
-* [jvm-packages] Add back `reg:linear` for scala, as it is only deprecated and not meant to be removed yet (#4490)
-* Fix library loading for Cygwin users (#4499)
-* Fix prediction from loaded pickle (#4516)
-* Enforce exclusion between `pred_interactions=True` and `pred_interactions=True` (#4522)
-* Do not return dangling reference to local `std::string` (#4543)
-* Set the appropriate device before freeing device memory (#4566)
-* Mark `SparsePageDmatrix` destructor default. (#4568)
-* Choose the appropriate tree method only when the tree method is 'auto' (#4571)
-* Fix `benchmark_tree.py` (#4593)
-* [jvm-packages] Fix silly bug in feature scoring (#4604)
-* Fix GPU predictor when the test data matrix has different number of features than the training data matrix used to train the model (#4613)
-* Fix external memory for get column batches. (#4622)
-* [R] Use built-in label when xgb.DMatrix is given to xgb.cv() (#4631)
-* Fix early stopping in the Python package (#4638)
-* Fix AUC error in distributed mode caused by imbalanced dataset (#4645, #4798)
-* [jvm-packages] Expose `setMissing` method in `XGBoostClassificationModel` / `XGBoostRegressionModel` (#4643)
-* Remove initializing stringstream reference. (#4788)
-* [R] `xgb.get.handle` now checks all class listed of `object` (#4800)
-* Do not use `gpu_predictor` unless data comes from GPU (#4836)
-* Fix data loading (#4862)
-* Workaround `isnan` across different environments. (#4883)
-* [jvm-packages] Handle Long-type parameter (#4885)
-* Don't `set_params` at the end of `set_state` (#4947). Ensure that the model does not change after pickling and unpickling multiple times.
-* C++ exceptions should not crash OpenMP loops (#4960)
-* Fix `usegpu` flag in DART. (#4984)
-* Run training with empty `DMatrix` (#4990, #5159)
-* Ensure that no two processes can use the same GPU (#4990)
-* Fix repeated split and 0 cover nodes (#5010)
-* Reset histogram hit counter between multiple data batches (#5035)
-* Fix `feature_name` crated from int64index dataframe. (#5081)
-* Don't use 0 for "fresh leaf" (#5084)
-* Throw error when user attempts to use multi-GPU training and XGBoost has not been compiled with NCCL (#5170)
-* Fix metric name loading (#5122)
-* Quick fix for memory leak in CPU `hist` algorithm (#5153)
-* Fix wrapping GPU ID and prevent data copying (#5160)
-* Fix signature of Span constructor (#5166)
-* Lazy initialization of device vector, so that XGBoost compiled with CUDA can run on a machine without any GPU (#5173)
-* Model loading should not change system locale (#5314)
-* Distributed training jobs would sometimes hang; revert Rabit to fix this regression (dmlc/rabit#132, #5237)
-
-### API changes
-* Add support for cross-validation using query ID (#4474)
-* Enable feature importance property for DART model (#4525)
-* Add `rmsle` metric and `reg:squaredlogerror` objective (#4541)
-* All objective and evaluation metrics are now exposed to JVM packages (#4560)
-* `dump_model()` and `get_dump()` now support exporting in GraphViz language (#4602)
-* Support metrics `ndcg-` and `map-` (#4635)
-* [jvm-packages] Allow chaining prediction (transform) in XGBoost4J-Spark (#4667)
-* [jvm-packages] Add option to bypass missing value check in the Spark layer (#4805). Only use this option if you know what you are doing.
-* [jvm-packages] Add public group getter (#4838)
-* `XGDMatrixSetGroup` C API is now deprecated (#4864). Use `XGDMatrixSetUIntInfo` instead.
-* [R] Added new `train_folds` parameter to `xgb.cv()` (#5114)
-* Ingest meta information from Pandas DataFrame, such as data weights (#5216)
-
-### Maintenance: Refactor code for legibility and maintainability
-* De-duplicate GPU parameters (#4454)
-* Simplify INI-style config reader using C++11 STL (#4478, #4521)
-* Refactor histogram building code for `gpu_hist` (#4528)
-* Overload device memory allocator, to enable instrumentation for compiling memory usage statistics (#4532)
-* Refactor out row partitioning logic from `gpu_hist` (#4554)
-* Remove an unused variable (#4588)
-* Implement tree model dump with code generator, to de-duplicate code for generating dumps in 3 different formats (#4602)
-* Remove `RowSet` class which is no longer being used (#4697)
-* Remove some unused functions as reported by cppcheck (#4743)
-* Mimic CUDA assert output in Span check (#4762)
-* [jvm-packages] Refactor `XGBoost.scala` to put all params processing in one place (#4815)
-* Add some comments for GPU row partitioner (#4832)
-* Span: use `size_t' for index_type, add `front' and `back'. (#4935)
-* Remove dead code in `exact` algorithm (#5034, #5105)
-* Unify integer types used for row and column indices (#5034)
-* Extract feature interaction constraint from `SplitEvaluator` class. (#5034)
-* [Breaking] De-duplicate paramters and docstrings in the constructors of Scikit-Learn models (#5130)
-* Remove benchmark code from GPU tests (#5141)
-* Clean up Python 2 compatibility code. (#5161)
-* Extensible binary serialization format for `DMatrix::MetaInfo` (#5187). This will be useful for implementing censored labels for survival analysis applications.
-* Cleanup clang-tidy warnings. (#5247)
-
-### Maintenance: testing, continuous integration, build system
-* Use `yaml.safe_load` instead of `yaml.load`. (#4537)
-* Ensure GCC is at least 5.x (#4538)
-* Remove all mention of `reg:linear` from tests (#4544)
-* [jvm-packages] Upgrade to Scala 2.12 (#4574)
-* [jvm-packages] Update kryo dependency to 2.22 (#4575)
-* [CI] Specify account ID when logging into ECR Docker registry (#4584)
-* Use Sphinx 2.1+ to compile documentation (#4609)
-* Make Pandas optional for running Python unit tests (#4620)
-* Fix spark tests on machines with many cores (#4634)
-* [jvm-packages] Update local dev build process (#4640)
-* Add optional dependencies to setup.py (#4655)
-* [jvm-packages] Fix maven warnings (#4664)
-* Remove extraneous files from the R package, to comply with CRAN policy (#4699)
-* Remove VC-2013 support, since it is not C++11 compliant (#4701)
-* [CI] Fix broken installation of Pandas (#4704, #4722)
-* [jvm-packages] Clean up temporary files afer running tests (#4706)
-* Specify version macro in CMake. (#4730)
-* Include dmlc-tracker into XGBoost Python package (#4731)
-* [CI] Use long key ID for Ubuntu repository fingerprints. (#4783)
-* Remove plugin, cuda related code in automake & autoconf files (#4789)
-* Skip related tests when scikit-learn is not installed. (#4791)
-* Ignore vscode and clion files (#4866)
-* Use bundled Google Test by default (#4900)
-* [CI] Raise timeout threshold in Jenkins (#4938)
-* Copy CMake parameter from dmlc-core. (#4948)
-* Set correct file permission. (#4964)
-* [CI] Update lint configuration to support latest pylint convention (#4971)
-* [CI] Upload nightly builds to S3 (#4976, #4979)
-* Add asan.so.5 to cmake script. (#4999)
-* [CI] Fix Travis tests. (#5062)
-* [CI] Locate vcomp140.dll from System32 directory (#5078)
-* Implement training observer to dump internal states of objects (#5088). This will be useful for debugging.
-* Fix visual studio output library directories (#5119)
-* [jvm-packages] Comply with scala style convention + fix broken unit test (#5134)
-* [CI] Repair download URL for Maven 3.6.1 (#5139)
-* Don't use modernize-use-trailing-return-type in clang-tidy. (#5169)
-* Explicitly use UTF-8 codepage when using MSVC (#5197)
-* Add CMake option to run Undefined Behavior Sanitizer (UBSan) (#5211)
-* Make some GPU tests deterministic (#5229)
-* [R] Robust endian detection in CRAN xgboost build (#5232)
-* Support FreeBSD (#5233)
-* Make `pip install xgboost*.tar.gz` work by fixing build-python.sh (#5241)
-* Fix compilation error due to 64-bit integer narrowing to `size_t` (#5250)
-* Remove use of `std::cout` from R package, to comply with CRAN policy (#5261)
-* Update DMLC-Core submodule (#4674, #4688, #4726, #4924)
-* Update Rabit submodule (#4560, #4667, #4718, #4808, #4966, #5237)
-
-### Usability Improvements, Documentation
-* Add Random Forest API to Python API doc (#4500)
-* Fix Python demo and doc. (#4545)
-* Remove doc about not supporting cuda 10.1 (#4578)
-* Address some sphinx warnings and errors, add doc for building doc. (#4589)
-* Add instruction to run formatting checks locally (#4591)
-* Fix docstring for `XGBModel.predict()` (#4592)
-* Doc and demo for customized metric and objective (#4598, #4608)
-* Add to documentation how to run tests locally (#4610)
-* Empty evaluation list in early stopping should produce meaningful error message (#4633)
-* Fixed year to 2019 in conf.py, helpers.h and LICENSE (#4661)
-* Minor updates to links and grammar (#4673)
-* Remove `silent` in doc (#4689)
-* Remove old Python trouble shooting doc (#4729)
-* Add `os.PathLike` support for file paths to DMatrix and Booster Python classes (#4757)
-* Update XGBoost4J-Spark doc (#4804)
-* Regular formatting for evaluation metrics (#4803)
-* [jvm-packages] Refine documentation for handling missing values in XGBoost4J-Spark (#4805)
-* Monitor for distributed envorinment (#4829). This is useful for identifying performance bottleneck.
-* Add check for length of weights and produce a good error message (#4872)
-* Fix DMatrix doc (#4884)
-* Export C++ headers in CMake installation (#4897)
-* Update license year in README.md to 2019 (#4940)
-* Fix incorrectly displayed Note in the doc (#4943)
-* Follow PEP 257 Docstring Conventions (#4959)
-* Document minimum version required for Google Test (#5001)
-* Add better error message for invalid feature names (#5024)
-* Some guidelines on device memory usage (#5038)
-* [doc] Some notes for external memory. (#5065)
-* Update document for `tree_method` (#5106)
-* Update demo for ranking. (#5154)
-* Add new lines for Spark XGBoost missing values section (#5180)
-* Fix simple typo: utilty -> utility (#5182)
-* Update R doc by roxygen2 (#5201)
-* [R] Direct user to use `set.seed()` instead of setting `seed` parameter (#5125)
-* Add Optuna badge to `README.md` (#5208)
-* Fix compilation error in `c-api-demo.c` (#5215)
-
-### Acknowledgement
-**Contributors**: Nan Zhu (@CodingCat), Crissman Loomis (@Crissman), Cyprien Ricque (@Cyprien-Ricque), Evan Kepner (@EvanKepner), K.O. (@Hi-king), KaiJin Ji (@KerryJi), Peter Badida (@KeyWeeUsr), Kodi Arfer (@Kodiologist), Rory Mitchell (@RAMitchell), Egor Smirnov (@SmirnovEgorRu), Jacob Kim (@TheJacobKim), Vibhu Jawa (@VibhuJawa), Marcos (@astrowonk), Andy Adinets (@canonizer), Chen Qin (@chenqin), Christopher Cowden (@cowden), @cpfarrell, @david-cortes, Liangcai Li (@firestarman), @fuhaoda, Philip Hyunsu Cho (@hcho3), @here-nagini, Tong He (@hetong007), Michal Kurka (@michalkurka), Honza Sterba (@honzasterba), @iblumin, @koertkuipers, mattn (@mattn), Mingjie Tang (@merlintang), OrdoAbChao (@mglowacki100), Matthew Jones (@mt-jones), mitama (@nigimitama), Nathan Moore (@nmoorenz), Daniel Stahl (@phillyfan1138), Michaël Benesty (@pommedeterresautee), Rong Ou (@rongou), Sebastian (@sfahnens), Xu Xiao (@sperlingxx), @sriramch, Sean Owen (@srowen), Stephanie Yang (@stpyang), Yuan Tang (@terrytangyuan), Mathew Wicks (@thesuperzapper), Tim Gates (@timgates42), TinkleG (@tinkle1129), Oleksandr Pryimak (@trams), Jiaming Yuan (@trivialfis), Matvey Turkov (@turk0v), Bobby Wang (@wbo4958), yage (@yage99), @yellowdolphin
-
-**Reviewers**: Nan Zhu (@CodingCat), Crissman Loomis (@Crissman), Cyprien Ricque (@Cyprien-Ricque), Evan Kepner (@EvanKepner), John Zedlewski (@JohnZed), KOLANICH (@KOLANICH), KaiJin Ji (@KerryJi), Kodi Arfer (@Kodiologist), Rory Mitchell (@RAMitchell), Egor Smirnov (@SmirnovEgorRu), Nikita Titov (@StrikerRUS), Jacob Kim (@TheJacobKim), Vibhu Jawa (@VibhuJawa), Andrew Kane (@ankane), Arno Candel (@arnocandel), Marcos (@astrowonk), Bryan Woods (@bryan-woods), Andy Adinets (@canonizer), Chen Qin (@chenqin), Thomas Franke (@coding-komek), Peter (@codingforfun), @cpfarrell, Joshua Patterson (@datametrician), @fuhaoda, Philip Hyunsu Cho (@hcho3), Tong He (@hetong007), Honza Sterba (@honzasterba), @iblumin, @jakirkham, Vadim Khotilovich (@khotilov), Keith Kraus (@kkraus14), @koertkuipers, @melonki, Mingjie Tang (@merlintang), OrdoAbChao (@mglowacki100), Daniel Mahler (@mhlr), Matthew Rocklin (@mrocklin), Matthew Jones (@mt-jones), Michaël Benesty (@pommedeterresautee), PSEUDOTENSOR / Jonathan McKinney (@pseudotensor), Rong Ou (@rongou), Vladimir (@sh1ng), Scott Lundberg (@slundberg), Xu Xiao (@sperlingxx), @sriramch, Pasha Stetsenko (@st-pasha), Stephanie Yang (@stpyang), Yuan Tang (@terrytangyuan), Mathew Wicks (@thesuperzapper), Theodore Vasiloudis (@thvasilo), TinkleG (@tinkle1129), Oleksandr Pryimak (@trams), Jiaming Yuan (@trivialfis), Bobby Wang (@wbo4958), yage (@yage99), @yellowdolphin, Yin Lou (@yinlou)
-
-## v0.90 (2019.05.18)
-
-### XGBoost Python package drops Python 2.x (#4379, #4381)
-Python 2.x is reaching its end-of-life at the end of this year. [Many scientific Python packages are now moving to drop Python 2.x](https://python3statement.org/).
-
-### XGBoost4J-Spark now requires Spark 2.4.x (#4377)
-* Spark 2.3 is reaching its end-of-life soon. See discussion at #4389.
-* **Consistent handling of missing values** (#4309, #4349, #4411): Many users had reported issue with inconsistent predictions between XGBoost4J-Spark and the Python XGBoost package. The issue was caused by Spark mis-handling non-zero missing values (NaN, -1, 999 etc). We now alert the user whenever Spark doesn't handle missing values correctly (#4309, #4349). See [the tutorial for dealing with missing values in XGBoost4J-Spark](https://xgboost.readthedocs.io/en/release_0.90/jvm/xgboost4j_spark_tutorial.html#dealing-with-missing-values). This fix also depends on the availability of Spark 2.4.x.
-
-### Roadmap: better performance scaling for multi-core CPUs (#4310)
-* Poor performance scaling of the `hist` algorithm for multi-core CPUs has been under investigation (#3810). #4310 optimizes quantile sketches and other pre-processing tasks. Special thanks to @SmirnovEgorRu.
-
-### Roadmap: Harden distributed training (#4250)
-* Make distributed training in XGBoost more robust by hardening [Rabit](https://github.com/dmlc/rabit), which implements [the AllReduce primitive](https://en.wikipedia.org/wiki/Reduce_%28parallel_pattern%29). In particular, improve test coverage on mechanisms for fault tolerance and recovery. Special thanks to @chenqin.
-
-### New feature: Multi-class metric functions for GPUs (#4368)
-* Metrics for multi-class classification have been ported to GPU: `merror`, `mlogloss`. Special thanks to @trivialfis.
-* With supported metrics, XGBoost will select the correct devices based on your system and `n_gpus` parameter.
-
-### New feature: Scikit-learn-like random forest API (#4148, #4255, #4258)
-* XGBoost Python package now offers `XGBRFClassifier` and `XGBRFRegressor` API to train random forests. See [the tutorial](https://xgboost.readthedocs.io/en/release_0.90/tutorials/rf.html). Special thanks to @canonizer
-
-### New feature: use external memory in GPU predictor (#4284, #4396, #4438, #4457)
-* It is now possible to make predictions on GPU when the input is read from external memory. This is useful when you want to make predictions with big dataset that does not fit into the GPU memory. Special thanks to @rongou, @canonizer, @sriramch.
-
- ```python
- dtest = xgboost.DMatrix('test_data.libsvm#dtest.cache')
- bst.set_param('predictor', 'gpu_predictor')
- bst.predict(dtest)
- ```
-
-* Coming soon: GPU training (`gpu_hist`) with external memory
-
-### New feature: XGBoost can now handle comments in LIBSVM files (#4430)
-* Special thanks to @trivialfis and @hcho3
-
-### New feature: Embed XGBoost in your C/C++ applications using CMake (#4323, #4333, #4453)
-* It is now easier than ever to embed XGBoost in your C/C++ applications. In your CMakeLists.txt, add `xgboost::xgboost` as a linked library:
-
- ```cmake
- find_package(xgboost REQUIRED)
- add_executable(api-demo c-api-demo.c)
- target_link_libraries(api-demo xgboost::xgboost)
- ```
-
- [XGBoost C API documentation is available.](https://xgboost.readthedocs.io/en/release_0.90/dev) Special thanks to @trivialfis
-
-### Performance improvements
-* Use feature interaction constraints to narrow split search space (#4341, #4428)
-* Additional optimizations for `gpu_hist` (#4248, #4283)
-* Reduce OpenMP thread launches in `gpu_hist` (#4343)
-* Additional optimizations for multi-node multi-GPU random forests. (#4238)
-* Allocate unique prediction buffer for each input matrix, to avoid re-sizing GPU array (#4275)
-* Remove various synchronisations from CUDA API calls (#4205)
-* XGBoost4J-Spark
- - Allow the user to control whether to cache partitioned training data, to potentially reduce execution time (#4268)
-
-### Bug-fixes
-* Fix node reuse in `hist` (#4404)
-* Fix GPU histogram allocation (#4347)
-* Fix matrix attributes not sliced (#4311)
-* Revise AUC and AUCPR metrics now work with weighted ranking task (#4216, #4436)
-* Fix timer invocation for InitDataOnce() in `gpu_hist` (#4206)
-* Fix R-devel errors (#4251)
-* Make gradient update in GPU linear updater thread-safe (#4259)
-* Prevent out-of-range access in column matrix (#4231)
-* Don't store DMatrix handle in Python object until it's initialized, to improve exception safety (#4317)
-* XGBoost4J-Spark
- - Fix non-deterministic order within a zipped partition on prediction (#4388)
- - Remove race condition on tracker shutdown (#4224)
- - Allow set the parameter `maxLeaves`. (#4226)
- - Allow partial evaluation of dataframe before prediction (#4407)
- - Automatically set `maximize_evaluation_metrics` if not explicitly given (#4446)
-
-### API changes
-* Deprecate `reg:linear` in favor of `reg:squarederror`. (#4267, #4427)
-* Add attribute getter and setter to the Booster object in XGBoost4J (#4336)
-
-### Maintenance: Refactor C++ code for legibility and maintainability
-* Fix clang-tidy warnings. (#4149)
-* Remove deprecated C APIs. (#4266)
-* Use Monitor class to time functions in `hist`. (#4273)
-* Retire DVec class in favour of c++20 style span for device memory. (#4293)
-* Improve HostDeviceVector exception safety (#4301)
-
-### Maintenance: testing, continuous integration, build system
-* **Major refactor of CMakeLists.txt** (#4323, #4333, #4453): adopt modern CMake and export XGBoost as a target
-* **Major improvement in Jenkins CI pipeline** (#4234)
- - Migrate all Linux tests to Jenkins (#4401)
- - Builds and tests are now de-coupled, to test an artifact against multiple versions of CUDA, JDK, and other dependencies (#4401)
- - Add Windows GPU to Jenkins CI pipeline (#4463, #4469)
-* Support CUDA 10.1 (#4223, #4232, #4265, #4468)
-* Python wheels are now built with CUDA 9.0, so that JIT is not required on Volta architecture (#4459)
-* Integrate with NVTX CUDA profiler (#4205)
-* Add a test for cpu predictor using external memory (#4308)
-* Refactor tests to get rid of duplication (#4358)
-* Remove test dependency on `craigcitro/r-travis`, since it's deprecated (#4353)
-* Add files from local R build to `.gitignore` (#4346)
-* Make XGBoost4J compatible with Java 9+ by revising NativeLibLoader (#4351)
-* Jenkins build for CUDA 10.0 (#4281)
-* Remove remaining `silent` and `debug_verbose` in Python tests (#4299)
-* Use all cores to build XGBoost4J lib on linux (#4304)
-* Upgrade Jenkins Linux build environment to GCC 5.3.1, CMake 3.6.0 (#4306)
-* Make CMakeLists.txt compatible with CMake 3.3 (#4420)
-* Add OpenMP option in CMakeLists.txt (#4339)
-* Get rid of a few trivial compiler warnings (#4312)
-* Add external Docker build cache, to speed up builds on Jenkins CI (#4331, #4334, #4458)
-* Fix Windows tests (#4403)
-* Fix a broken python test (#4395)
-* Use a fixed seed to split data in XGBoost4J-Spark tests, for reproducibility (#4417)
-* Add additional Python tests to test training under constraints (#4426)
-* Enable building with shared NCCL. (#4447)
-
-### Usability Improvements, Documentation
-* Document limitation of one-split-at-a-time Greedy tree learning heuristic (#4233)
-* Update build doc: PyPI wheel now support multi-GPU (#4219)
-* Fix docs for `num_parallel_tree` (#4221)
-* Fix document about `colsample_by*` parameter (#4340)
-* Make the train and test input with same colnames. (#4329)
-* Update R contribute link. (#4236)
-* Fix travis R tests (#4277)
-* Log version number in crash log in XGBoost4J-Spark (#4271, #4303)
-* Allow supression of Rabit output in Booster::train in XGBoost4J (#4262)
-* Add tutorial on handling missing values in XGBoost4J-Spark (#4425)
-* Fix typos (#4345, #4393, #4432, #4435)
-* Added language classifier in setup.py (#4327)
-* Added Travis CI badge (#4344)
-* Add BentoML to use case section (#4400)
-* Remove subtly sexist remark (#4418)
-* Add R vignette about parsing JSON dumps (#4439)
-
-### Acknowledgement
-**Contributors**: Nan Zhu (@CodingCat), Adam Pocock (@Craigacp), Daniel Hen (@Daniel8hen), Jiaxiang Li (@JiaxiangBU), Rory Mitchell (@RAMitchell), Egor Smirnov (@SmirnovEgorRu), Andy Adinets (@canonizer), Jonas (@elcombato), Harry Braviner (@harrybraviner), Philip Hyunsu Cho (@hcho3), Tong He (@hetong007), James Lamb (@jameslamb), Jean-Francois Zinque (@jeffzi), Yang Yang (@jokerkeny), Mayank Suman (@mayanksuman), jess (@monkeywithacupcake), Hajime Morrita (@omo), Ravi Kalia (@project-delphi), @ras44, Rong Ou (@rongou), Shaochen Shi (@shishaochen), Xu Xiao (@sperlingxx), @sriramch, Jiaming Yuan (@trivialfis), Christopher Suchanek (@wsuchy), Bozhao (@yubozhao)
-
-**Reviewers**: Nan Zhu (@CodingCat), Adam Pocock (@Craigacp), Daniel Hen (@Daniel8hen), Jiaxiang Li (@JiaxiangBU), Laurae (@Laurae2), Rory Mitchell (@RAMitchell), Egor Smirnov (@SmirnovEgorRu), @alois-bissuel, Andy Adinets (@canonizer), Chen Qin (@chenqin), Harry Braviner (@harrybraviner), Philip Hyunsu Cho (@hcho3), Tong He (@hetong007), @jakirkham, James Lamb (@jameslamb), Julien Schueller (@jschueller), Mayank Suman (@mayanksuman), Hajime Morrita (@omo), Rong Ou (@rongou), Sara Robinson (@sararob), Shaochen Shi (@shishaochen), Xu Xiao (@sperlingxx), @sriramch, Sean Owen (@srowen), Sergei Lebedev (@superbobry), Yuan (Terry) Tang (@terrytangyuan), Theodore Vasiloudis (@thvasilo), Matthew Tovbin (@tovbinm), Jiaming Yuan (@trivialfis), Xin Yin (@xydrolase)
-
-## v0.82 (2019.03.03)
-This release is packed with many new features and bug fixes.
-
-### Roadmap: better performance scaling for multi-core CPUs (#3957)
-* Poor performance scaling of the `hist` algorithm for multi-core CPUs has been under investigation (#3810). #3957 marks an important step toward better performance scaling, by using software pre-fetching and replacing STL vectors with C-style arrays. Special thanks to @Laurae2 and @SmirnovEgorRu.
-* See #3810 for latest progress on this roadmap.
-
-### New feature: Distributed Fast Histogram Algorithm (`hist`) (#4011, #4102, #4140, #4128)
-* It is now possible to run the `hist` algorithm in distributed setting. Special thanks to @CodingCat. The benefits include:
- 1. Faster local computation via feature binning
- 2. Support for monotonic constraints and feature interaction constraints
- 3. Simpler codebase than `approx`, allowing for future improvement
-* Depth-wise tree growing is now performed in a separate code path, so that cross-node syncronization is performed only once per level.
-
-### New feature: Multi-Node, Multi-GPU training (#4095)
-* Distributed training is now able to utilize clusters equipped with NVIDIA GPUs. In particular, the rabit AllReduce layer will communicate GPU device information. Special thanks to @mt-jones, @RAMitchell, @rongou, @trivialfis, @canonizer, and @jeffdk.
-* Resource management systems will be able to assign a rank for each GPU in the cluster.
-* In Dask, users will be able to construct a collection of XGBoost processes over an inhomogeneous device cluster (i.e. workers with different number and/or kinds of GPUs).
-
-### New feature: Multiple validation datasets in XGBoost4J-Spark (#3904, #3910)
-* You can now track the performance of the model during training with multiple evaluation datasets. By specifying `eval_sets` or call `setEvalSets` over a `XGBoostClassifier` or `XGBoostRegressor`, you can pass in multiple evaluation datasets typed as a `Map` from `String` to `DataFrame`. Special thanks to @CodingCat.
-* See the usage of multiple validation datasets [here](https://github.com/dmlc/xgboost/blob/0c1d5f1120c0a159f2567b267f0ec4ffadee00d0/jvm-packages/xgboost4j-example/src/main/scala/ml/dmlc/xgboost4j/scala/example/spark/SparkTraining.scala#L66-L78)
-
-### New feature: Additional metric functions for GPUs (#3952)
-* Element-wise metrics have been ported to GPU: `rmse`, `mae`, `logloss`, `poisson-nloglik`, `gamma-deviance`, `gamma-nloglik`, `error`, `tweedie-nloglik`. Special thanks to @trivialfis and @RAMitchell.
-* With supported metrics, XGBoost will select the correct devices based on your system and `n_gpus` parameter.
-
-### New feature: Column sampling at individual nodes (splits) (#3971)
-* Columns (features) can now be sampled at individual tree nodes, in addition to per-tree and per-level sampling. To enable per-node sampling, set `colsample_bynode` parameter, which represents the fraction of columns sampled at each node. This parameter is set to 1.0 by default (i.e. no sampling per node). Special thanks to @canonizer.
-* The `colsample_bynode` parameter works cumulatively with other `colsample_by*` parameters: for example, `{'colsample_bynode':0.5, 'colsample_bytree':0.5}` with 100 columns will give 25 features to choose from at each split.
-
-### Major API change: consistent logging level via `verbosity` (#3982, #4002, #4138)
-* XGBoost now allows fine-grained control over logging. You can set `verbosity` to 0 (silent), 1 (warning), 2 (info), and 3 (debug). This is useful for controlling the amount of logging outputs. Special thanks to @trivialfis.
-* Parameters `silent` and `debug_verbose` are now deprecated.
-* Note: Sometimes XGBoost tries to change configurations based on heuristics, which is displayed as warning message. If there's unexpected behaviour, please try to increase value of verbosity.
-
-### Major bug fix: external memory (#4040, #4193)
-* Clarify object ownership in multi-threaded prefetcher, to avoid memory error.
-* Correctly merge two column batches (which uses [CSC layout](https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_(CSC_or_CCS))).
-* Add unit tests for external memory.
-* Special thanks to @trivialfis and @hcho3.
-
-### Major bug fix: early stopping fixed in XGBoost4J and XGBoost4J-Spark (#3928, #4176)
-* Early stopping in XGBoost4J and XGBoost4J-Spark is now consistent with its counterpart in the Python package. Training stops if the current iteration is `earlyStoppingSteps` away from the best iteration. If there are multiple evaluation sets, only the last one is used to determinate early stop.
-* See the updated documentation [here](https://xgboost.readthedocs.io/en/release_0.82/jvm/xgboost4j_spark_tutorial.html#early-stopping)
-* Special thanks to @CodingCat, @yanboliang, and @mingyang.
-
-### Major bug fix: infrequent features should not crash distributed training (#4045)
-* For infrequently occuring features, some partitions may not get any instance. This scenario used to crash distributed training due to mal-formed ranges. The problem has now been fixed.
-* In practice, one-hot-encoded categorical variables tend to produce rare features, particularly when the cardinality is high.
-* Special thanks to @CodingCat.
-
-### Performance improvements
-* Faster, more space-efficient radix sorting in `gpu_hist` (#3895)
-* Subtraction trick in histogram calculation in `gpu_hist` (#3945)
-* More performant re-partition in XGBoost4J-Spark (#4049)
-
-### Bug-fixes
-* Fix semantics of `gpu_id` when running multiple XGBoost processes on a multi-GPU machine (#3851)
-* Fix page storage path for external memory on Windows (#3869)
-* Fix configuration setup so that DART utilizes GPU (#4024)
-* Eliminate NAN values from SHAP prediction (#3943)
-* Prevent empty quantile sketches in `hist` (#4155)
-* Enable running objectives with 0 GPU (#3878)
-* Parameters are no longer dependent on system locale (#3891, #3907)
-* Use consistent data type in the GPU coordinate descent code (#3917)
-* Remove undefined behavior in the CLI config parser on the ARM platform (#3976)
-* Initialize counters in GPU AllReduce (#3987)
-* Prevent deadlocks in GPU AllReduce (#4113)
-* Load correct values from sliced NumPy arrays (#4147, #4165)
-* Fix incorrect GPU device selection (#4161)
-* Make feature binning logic in `hist` aware of query groups when running a ranking task (#4115). For ranking task, query groups are weighted, not individual instances.
-* Generate correct C++ exception type for `LOG(FATAL)` macro (#4159)
-* Python package
- - Python package should run on system without `PATH` environment variable (#3845)
- - Fix `coef_` and `intercept_` signature to be compatible with `sklearn.RFECV` (#3873)
- - Use UTF-8 encoding in Python package README, to support non-English locale (#3867)
- - Add AUC-PR to list of metrics to maximize for early stopping (#3936)
- - Allow loading pickles without `self.booster` attribute, for backward compatibility (#3938, #3944)
- - White-list DART for feature importances (#4073)
- - Update usage of [h2oai/datatable](https://github.com/h2oai/datatable) (#4123)
-* XGBoost4J-Spark
- - Address scalability issue in prediction (#4033)
- - Enforce the use of per-group weights for ranking task (#4118)
- - Fix vector size of `rawPredictionCol` in `XGBoostClassificationModel` (#3932)
- - More robust error handling in Spark tracker (#4046, #4108)
- - Fix return type of `setEvalSets` (#4105)
- - Return correct value of `getMaxLeaves` (#4114)
-
-### API changes
-* Add experimental parameter `single_precision_histogram` to use single-precision histograms for the `gpu_hist` algorithm (#3965)
-* Python package
- - Add option to select type of feature importances in the scikit-learn inferface (#3876)
- - Add `trees_to_df()` method to dump decision trees as Pandas data frame (#4153)
- - Add options to control node shapes in the GraphViz plotting function (#3859)
- - Add `xgb_model` option to `XGBClassifier`, to load previously saved model (#4092)
- - Passing lists into `DMatrix` is now deprecated (#3970)
-* XGBoost4J
- - Support multiple feature importance features (#3801)
-
-### Maintenance: Refactor C++ code for legibility and maintainability
-* Refactor `hist` algorithm code and add unit tests (#3836)
-* Minor refactoring of split evaluator in `gpu_hist` (#3889)
-* Removed unused leaf vector field in the tree model (#3989)
-* Simplify the tree representation by combining `TreeModel` and `RegTree` classes (#3995)
-* Simplify and harden tree expansion code (#4008, #4015)
-* De-duplicate parameter classes in the linear model algorithms (#4013)
-* Robust handling of ranges with C++20 span in `gpu_exact` and `gpu_coord_descent` (#4020, #4029)
-* Simplify tree training code (#3825). Also use Span class for robust handling of ranges.
-
-### Maintenance: testing, continuous integration, build system
-* Disallow `std::regex` since it's not supported by GCC 4.8.x (#3870)
-* Add multi-GPU tests for coordinate descent algorithm for linear models (#3893, #3974)
-* Enforce naming style in Python lint (#3896)
-* Refactor Python tests (#3897, #3901): Use pytest exclusively, display full trace upon failure
-* Address `DeprecationWarning` when using Python collections (#3909)
-* Use correct group for maven site plugin (#3937)
-* Jenkins CI is now using on-demand EC2 instances exclusively, due to unreliability of Spot instances (#3948)
-* Better GPU performance logging (#3945)
-* Fix GPU tests on machines with only 1 GPU (#4053)
-* Eliminate CRAN check warnings and notes (#3988)
-* Add unit tests for tree serialization (#3989)
-* Add unit tests for tree fitting functions in `hist` (#4155)
-* Add a unit test for `gpu_exact` algorithm (#4020)
-* Correct JVM CMake GPU flag (#4071)
-* Fix failing Travis CI on Mac (#4086)
-* Speed up Jenkins by not compiling CMake (#4099)
-* Analyze C++ and CUDA code using clang-tidy, as part of Jenkins CI pipeline (#4034)
-* Fix broken R test: Install Homebrew GCC (#4142)
-* Check for empty datasets in GPU unit tests (#4151)
-* Fix Windows compilation (#4139)
-* Comply with latest convention of cpplint (#4157)
-* Fix a unit test in `gpu_hist` (#4158)
-* Speed up data generation in Python tests (#4164)
-
-### Usability Improvements
-* Add link to [InfoWorld 2019 Technology of the Year Award](https://www.infoworld.com/article/3336072/application-development/infoworlds-2019-technology-of-the-year-award-winners.html) (#4116)
-* Remove outdated AWS YARN tutorial (#3885)
-* Document current limitation in number of features (#3886)
-* Remove unnecessary warning when `gblinear` is selected (#3888)
-* Document limitation of CSV parser: header not supported (#3934)
-* Log training parameters in XGBoost4J-Spark (#4091)
-* Clarify early stopping behavior in the scikit-learn interface (#3967)
-* Clarify behavior of `max_depth` parameter (#4078)
-* Revise Python docstrings for ranking task (#4121). In particular, weights must be per-group in learning-to-rank setting.
-* Document parameter `num_parallel_tree` (#4022)
-* Add Jenkins status badge (#4090)
-* Warn users against using internal functions of `Booster` object (#4066)
-* Reformat `benchmark_tree.py` to comply with Python style convention (#4126)
-* Clarify a comment in `objectiveTrait` (#4174)
-* Fix typos and broken links in documentation (#3890, #3872, #3902, #3919, #3975, #4027, #4156, #4167)
-
-### Acknowledgement
-**Contributors** (in no particular order): Jiaming Yuan (@trivialfis), Hyunsu Cho (@hcho3), Nan Zhu (@CodingCat), Rory Mitchell (@RAMitchell), Yanbo Liang (@yanboliang), Andy Adinets (@canonizer), Tong He (@hetong007), Yuan Tang (@terrytangyuan)
-
-**First-time Contributors** (in no particular order): Jelle Zijlstra (@JelleZijlstra), Jiacheng Xu (@jiachengxu), @ajing, Kashif Rasul (@kashif), @theycallhimavi, Joey Gao (@pjgao), Prabakaran Kumaresshan (@nixphix), Huafeng Wang (@huafengw), @lyxthe, Sam Wilkinson (@scwilkinson), Tatsuhito Kato (@stabacov), Shayak Banerjee (@shayakbanerjee), Kodi Arfer (@Kodiologist), @KyleLi1985, Egor Smirnov (@SmirnovEgorRu), @tmitanitky, Pasha Stetsenko (@st-pasha), Kenichi Nagahara (@keni-chi), Abhai Kollara Dilip (@abhaikollara), Patrick Ford (@pford221), @hshujuan, Matthew Jones (@mt-jones), Thejaswi Rao (@teju85), Adam November (@anovember)
-
-**First-time Reviewers** (in no particular order): Mingyang Hu (@mingyang), Theodore Vasiloudis (@thvasilo), Jakub Troszok (@troszok), Rong Ou (@rongou), @Denisevi4, Matthew Jones (@mt-jones), Jeff Kaplan (@jeffdk)
-
-## v0.81 (2018.11.04)
-### New feature: feature interaction constraints
-* Users are now able to control which features (independent variables) are allowed to interact by specifying feature interaction constraints (#3466).
-* [Tutorial](https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html) is available, as well as [R](https://github.com/dmlc/xgboost/blob/9254c58e4dfff6a59dc0829a2ceb02e45ed17cd0/R-package/demo/interaction_constraints.R) and [Python](https://github.com/dmlc/xgboost/blob/9254c58e4dfff6a59dc0829a2ceb02e45ed17cd0/tests/python/test_interaction_constraints.py) examples.
-
-### New feature: learning to rank using scikit-learn interface
-* Learning to rank task is now available for the scikit-learn interface of the Python package (#3560, #3848). It is now possible to integrate the XGBoost ranking model into the scikit-learn learning pipeline.
-* Examples of using `XGBRanker` class is found at [demo/rank/rank_sklearn.py](https://github.com/dmlc/xgboost/blob/24a268a2e3cb17302db3d72da8f04016b7d352d9/demo/rank/rank_sklearn.py).
-
-### New feature: R interface for SHAP interactions
-* SHAP (SHapley Additive exPlanations) is a unified approach to explain the output of any machine learning model. Previously, this feature was only available from the Python package; now it is available from the R package as well (#3636).
-
-### New feature: GPU predictor now use multiple GPUs to predict
-* GPU predictor is now able to utilize multiple GPUs at once to accelerate prediction (#3738)
-
-### New feature: Scale distributed XGBoost to large-scale clusters
-* Fix OS file descriptor limit assertion error on large cluster (#3835, dmlc/rabit#73) by replacing `select()` based AllReduce/Broadcast with `poll()` based implementation.
-* Mitigate tracker "thundering herd" issue on large cluster. Add exponential backoff retry when workers connect to tracker.
-* With this change, we were able to scale to 1.5k executors on a 12 billion row dataset after some tweaks here and there.
-
-### New feature: Additional objective functions for GPUs
-* New objective functions ported to GPU: `hinge`, `multi:softmax`, `multi:softprob`, `count:poisson`, `reg:gamma`, `"reg:tweedie`.
-* With supported objectives, XGBoost will select the correct devices based on your system and `n_gpus` parameter.
-
-### Major bug fix: learning to rank with XGBoost4J-Spark
-* Previously, `repartitionForData` would shuffle data and lose ordering necessary for ranking task.
-* To fix this issue, data points within each RDD partition is explicitly group by their group (query session) IDs (#3654). Also handle empty RDD partition carefully (#3750).
-
-### Major bug fix: early stopping fixed in XGBoost4J-Spark
-* Earlier implementation of early stopping had incorrect semantics and didn't let users to specify direction for optimizing (maximize / minimize)
-* A parameter `maximize_evaluation_metrics` is defined so as to tell whether a metric should be maximized or minimized as part of early stopping criteria (#3808). Also early stopping now has correct semantics.
-
-### API changes
-* Column sampling by level (`colsample_bylevel`) is now functional for `hist` algorithm (#3635, #3862)
-* GPU tag `gpu:` for regression objectives are now deprecated. XGBoost will select the correct devices automatically (#3643)
-* Add `disable_default_eval_metric` parameter to disable default metric (#3606)
-* Experimental AVX support for gradient computation is removed (#3752)
-* XGBoost4J-Spark
- - Add `rank:ndcg` and `rank:map` to supported objectives (#3697)
-* Python package
- - Add `callbacks` argument to `fit()` function of sciki-learn API (#3682)
- - Add `XGBRanker` to scikit-learn interface (#3560, #3848)
- - Add `validate_features` argument to `predict()` function of scikit-learn API (#3653)
- - Allow scikit-learn grid search over parameters specified as keyword arguments (#3791)
- - Add `coef_` and `intercept_` as properties of scikit-learn wrapper (#3855). Some scikit-learn functions expect these properties.
-
-### Performance improvements
-* Address very high GPU memory usage for large data (#3635)
-* Fix performance regression within `EvaluateSplits()` of `gpu_hist` algorithm. (#3680)
-
-### Bug-fixes
-* Fix a problem in GPU quantile sketch with tiny instance weights. (#3628)
-* Fix copy constructor for `HostDeviceVectorImpl` to prevent dangling pointers (#3657)
-* Fix a bug in partitioned file loading (#3673)
-* Fixed an uninitialized pointer in `gpu_hist` (#3703)
-* Reshared data among GPUs when number of GPUs is changed (#3721)
-* Add back `max_delta_step` to split evaluation (#3668)
-* Do not round up integer thresholds for integer features in JSON dump (#3717)
-* Use `dmlc::TemporaryDirectory` to handle temporaries in cross-platform way (#3783)
-* Fix accuracy problem with `gpu_hist` when `min_child_weight` and `lambda` are set to 0 (#3793)
-* Make sure that `tree_method` parameter is recognized and not silently ignored (#3849)
-* XGBoost4J-Spark
- - Make sure `thresholds` are considered when executing `predict()` method (#3577)
- - Avoid losing precision when computing probabilities by converting to `Double` early (#3576)
- - `getTreeLimit()` should return `Int` (#3602)
- - Fix checkpoint serialization on HDFS (#3614)
- - Throw `ControlThrowable` instead of `InterruptedException` so that it is properly re-thrown (#3632)
- - Remove extraneous output to stdout (#3665)
- - Allow specification of task type for custom objectives and evaluations (#3646)
- - Fix distributed updater check (#3739)
- - Fix issue when spark job execution thread cannot return before we execute `first()` (#3758)
-* Python package
- - Fix accessing `DMatrix.handle` before it is set (#3599)
- - `XGBClassifier.predict()` should return margin scores when `output_margin` is set to true (#3651)
- - Early stopping callback should maximize metric of form `NDCG@n-` (#3685)
- - Preserve feature names when slicing `DMatrix` (#3766)
-* R package
- - Replace `nround` with `nrounds` to match actual parameter (#3592)
- - Amend `xgb.createFolds` to handle classes of a single element (#3630)
- - Fix buggy random generator and make `colsample_bytree` functional (#3781)
-
-### Maintenance: testing, continuous integration, build system
-* Add sanitizers tests to Travis CI (#3557)
-* Add NumPy, Matplotlib, Graphviz as requirements for doc build (#3669)
-* Comply with CRAN submission policy (#3660, #3728)
-* Remove copy-paste error in JVM test suite (#3692)
-* Disable flaky tests in `R-package/tests/testthat/test_update.R` (#3723)
-* Make Python tests compatible with scikit-learn 0.20 release (#3731)
-* Separate out restricted and unrestricted tasks, so that pull requests don't build downloadable artifacts (#3736)
-* Add multi-GPU unit test environment (#3741)
-* Allow plug-ins to be built by CMake (#3752)
-* Test wheel compatibility on CPU containers for pull requests (#3762)
-* Fix broken doc build due to Matplotlib 3.0 release (#3764)
-* Produce `xgboost.so` for XGBoost-R on Mac OSX, so that `make install` works (#3767)
-* Retry Jenkins CI tests up to 3 times to improve reliability (#3769, #3769, #3775, #3776, #3777)
-* Add basic unit tests for `gpu_hist` algorithm (#3785)
-* Fix Python environment for distributed unit tests (#3806)
-* Test wheels on CUDA 10.0 container for compatibility (#3838)
-* Fix JVM doc build (#3853)
-
-### Maintenance: Refactor C++ code for legibility and maintainability
-* Merge generic device helper functions into `GPUSet` class (#3626)
-* Re-factor column sampling logic into `ColumnSampler` class (#3635, #3637)
-* Replace `std::vector` with `HostDeviceVector` in `MetaInfo` and `SparsePage` (#3446)
-* Simplify `DMatrix` class (#3395)
-* De-duplicate CPU/GPU code using `Transform` class (#3643, #3751)
-* Remove obsoleted `QuantileHistMaker` class (#3761)
-* Remove obsoleted `NoConstraint` class (#3792)
-
-### Other Features
-* C++20-compliant Span class for safe pointer indexing (#3548, #3588)
-* Add helper functions to manipulate multiple GPU devices (#3693)
-* XGBoost4J-Spark
- - Allow specifying host ip from the `xgboost-tracker.properties file` (#3833). This comes in handy when `hosts` files doesn't correctly define localhost.
-
-### Usability Improvements
-* Add reference to GitHub repository in `pom.xml` of JVM packages (#3589)
-* Add R demo of multi-class classification (#3695)
-* Document JSON dump functionality (#3600, #3603)
-* Document CUDA requirement and lack of external memory for GPU algorithms (#3624)
-* Document LambdaMART objectives, both pairwise and listwise (#3672)
-* Document `aucpr` evaluation metric (#3687)
-* Document gblinear parameters: `feature_selector` and `top_k` (#3780)
-* Add instructions for using MinGW-built XGBoost with Python. (#3774)
-* Removed nonexistent parameter `use_buffer` from documentation (#3610)
-* Update Python API doc to include all classes and members (#3619, #3682)
-* Fix typos and broken links in documentation (#3618, #3640, #3676, #3713, #3759, #3784, #3843, #3852)
-* Binary classification demo should produce LIBSVM with 0-based indexing (#3652)
-* Process data once for Python and CLI examples of learning to rank (#3666)
-* Include full text of Apache 2.0 license in the repository (#3698)
-* Save predictor parameters in model file (#3856)
-* JVM packages
- - Let users specify feature names when calling `getModelDump` and `getFeatureScore` (#3733)
- - Warn the user about the lack of over-the-wire encryption (#3667)
- - Fix errors in examples (#3719)
- - Document choice of trackers (#3831)
- - Document that vanilla Apache Spark is required (#3854)
-* Python package
- - Document that custom objective can't contain colon (:) (#3601)
- - Show a better error message for failed library loading (#3690)
- - Document that feature importance is unavailable for non-tree learners (#3765)
- - Document behavior of `get_fscore()` for zero-importance features (#3763)
- - Recommend pickling as the way to save `XGBClassifier` / `XGBRegressor` / `XGBRanker` (#3829)
-* R package
- - Enlarge variable importance plot to make it more visible (#3820)
-
-### BREAKING CHANGES
-* External memory page files have changed, breaking backwards compatibility for temporary storage used during external memory training. This only affects external memory users upgrading their xgboost version - we recommend clearing all `*.page` files before resuming training. Model serialization is unaffected.
-
-### Known issues
-* Quantile sketcher fails to produce any quantile for some edge cases (#2943)
-* The `hist` algorithm leaks memory when used with learning rate decay callback (#3579)
-* Using custom evaluation funciton together with early stopping causes assertion failure in XGBoost4J-Spark (#3595)
-* Early stopping doesn't work with `gblinear` learner (#3789)
-* Label and weight vectors are not reshared upon the change in number of GPUs (#3794). To get around this issue, delete the `DMatrix` object and re-load.
-* The `DMatrix` Python objects are initialized with incorrect values when given array slices (#3841)
-* The `gpu_id` parameter is broken and not yet properly supported (#3850)
-
-### Acknowledgement
-**Contributors** (in no particular order): Hyunsu Cho (@hcho3), Jiaming Yuan (@trivialfis), Nan Zhu (@CodingCat), Rory Mitchell (@RAMitchell), Andy Adinets (@canonizer), Vadim Khotilovich (@khotilov), Sergei Lebedev (@superbobry)
-
-**First-time Contributors** (in no particular order): Matthew Tovbin (@tovbinm), Jakob Richter (@jakob-r), Grace Lam (@grace-lam), Grant W Schneider (@grantschneider), Andrew Thia (@BlueTea88), Sergei Chipiga (@schipiga), Joseph Bradley (@jkbradley), Chen Qin (@chenqin), Jerry Lin (@linjer), Dmitriy Rybalko (@rdtft), Michael Mui (@mmui), Takahiro Kojima (@515hikaru), Bruce Zhao (@BruceZhaoR), Wei Tian (@weitian), Saumya Bhatnagar (@Sam1301), Juzer Shakir (@JuzerShakir), Zhao Hang (@cleghom), Jonathan Friedman (@jontonsoup), Bruno Tremblay (@meztez), Boris Filippov (@frenzykryger), @Shiki-H, @mrgutkun, @gorogm, @htgeis, @jakehoare, @zengxy, @KOLANICH
-
-**First-time Reviewers** (in no particular order): Nikita Titov (@StrikerRUS), Xiangrui Meng (@mengxr), Nirmal Borah (@Nirmal-Neel)
-
-
-## v0.80 (2018.08.13)
-* **JVM packages received a major upgrade**: To consolidate the APIs and improve the user experience, we refactored the design of XGBoost4J-Spark in a significant manner. (#3387)
- - Consolidated APIs: It is now much easier to integrate XGBoost models into a Spark ML pipeline. Users can control behaviors like output leaf prediction results by setting corresponding column names. Training is now more consistent with other Estimators in Spark MLLIB: there is now one single method `fit()` to train decision trees.
- - Better user experience: we refactored the parameters relevant modules in XGBoost4J-Spark to provide both camel-case (Spark ML style) and underscore (XGBoost style) parameters
- - A brand-new tutorial is [available](https://xgboost.readthedocs.io/en/release_0.80/jvm/xgboost4j_spark_tutorial.html) for XGBoost4J-Spark.
- - Latest API documentation is now hosted at https://xgboost.readthedocs.io/.
-* XGBoost documentation now keeps track of multiple versions:
- - Latest master: https://xgboost.readthedocs.io/en/latest
- - 0.80 stable: https://xgboost.readthedocs.io/en/release_0.80
- - 0.72 stable: https://xgboost.readthedocs.io/en/release_0.72
-* Support for per-group weights in ranking objective (#3379)
-* Fix inaccurate decimal parsing (#3546)
-* New functionality
- - Query ID column support in LIBSVM data files (#2749). This is convenient for performing ranking task in distributed setting.
- - Hinge loss for binary classification (`binary:hinge`) (#3477)
- - Ability to specify delimiter and instance weight column for CSV files (#3546)
- - Ability to use 1-based indexing instead of 0-based (#3546)
-* GPU support
- - Quantile sketch, binning, and index compression are now performed on GPU, eliminating PCIe transfer for 'gpu_hist' algorithm (#3319, #3393)
- - Upgrade to NCCL2 for multi-GPU training (#3404).
- - Use shared memory atomics for faster training (#3384).
- - Dynamically allocate GPU memory, to prevent large allocations for deep trees (#3519)
- - Fix memory copy bug for large files (#3472)
-* Python package
- - Importing data from Python datatable (#3272)
- - Pre-built binary wheels available for 64-bit Linux and Windows (#3424, #3443)
- - Add new importance measures 'total_gain', 'total_cover' (#3498)
- - Sklearn API now supports saving and loading models (#3192)
- - Arbitrary cross validation fold indices (#3353)
- - `predict()` function in Sklearn API uses `best_ntree_limit` if available, to make early stopping easier to use (#3445)
- - Informational messages are now directed to Python's `print()` rather than standard output (#3438). This way, messages appear inside Jupyter notebooks.
-* R package
- - Oracle Solaris support, per CRAN policy (#3372)
-* JVM packages
- - Single-instance prediction (#3464)
- - Pre-built JARs are now available from Maven Central (#3401)
- - Add NULL pointer check (#3021)
- - Consider `spark.task.cpus` when controlling parallelism (#3530)
- - Handle missing values in prediction (#3529)
- - Eliminate outputs of `System.out` (#3572)
-* Refactored C++ DMatrix class for simplicity and de-duplication (#3301)
-* Refactored C++ histogram facilities (#3564)
-* Refactored constraints / regularization mechanism for split finding (#3335, #3429). Users may specify an elastic net (L2 + L1 regularization) on leaf weights as well as monotonic constraints on test nodes. The refactor will be useful for a future addition of feature interaction constraints.
-* Statically link `libstdc++` for MinGW32 (#3430)
-* Enable loading from `group`, `base_margin` and `weight` (see [here](http://xgboost.readthedocs.io/en/latest/tutorials/input_format.html#auxiliary-files-for-additional-information)) for Python, R, and JVM packages (#3431)
-* Fix model saving for `count:possion` so that `max_delta_step` doesn't get truncated (#3515)
-* Fix loading of sparse CSC matrix (#3553)
-* Fix incorrect handling of `base_score` parameter for Tweedie regression (#3295)
-
-## v0.72.1 (2018.07.08)
-This version is only applicable for the Python package. The content is identical to that of v0.72.
-
-## v0.72 (2018.06.01)
-* Starting with this release, we plan to make a new release every two months. See #3252 for more details.
-* Fix a pathological behavior (near-zero second-order gradients) in multiclass objective (#3304)
-* Tree dumps now use high precision in storing floating-point values (#3298)
-* Submodules `rabit` and `dmlc-core` have been brought up to date, bringing bug fixes (#3330, #3221).
-* GPU support
- - Continuous integration tests for GPU code (#3294, #3309)
- - GPU accelerated coordinate descent algorithm (#3178)
- - Abstract 1D vector class now works with multiple GPUs (#3287)
- - Generate PTX code for most recent architecture (#3316)
- - Fix a memory bug on NVIDIA K80 cards (#3293)
- - Address performance instability for single-GPU, multi-core machines (#3324)
-* Python package
- - FreeBSD support (#3247)
- - Validation of feature names in `Booster.predict()` is now optional (#3323)
-* Updated Sklearn API
- - Validation sets now support instance weights (#2354)
- - `XGBClassifier.predict_proba()` should not support `output_margin` option. (#3343) See BREAKING CHANGES below.
-* R package:
- - Better handling of NULL in `print.xgb.Booster()` (#3338)
- - Comply with CRAN policy by removing compiler warning suppression (#3329)
- - Updated CRAN submission
-* JVM packages
- - JVM packages will now use the same versioning scheme as other packages (#3253)
- - Update Spark to 2.3 (#3254)
- - Add scripts to cross-build and deploy artifacts (#3276, #3307)
- - Fix a compilation error for Scala 2.10 (#3332)
-* BREAKING CHANGES
- - `XGBClassifier.predict_proba()` no longer accepts paramter `output_margin`. The paramater makes no sense for `predict_proba()` because the method is to predict class probabilities, not raw margin scores.
-
-## v0.71 (2018.04.11)
-* This is a minor release, mainly motivated by issues concerning `pip install`, e.g. #2426, #3189, #3118, and #3194.
- With this release, users of Linux and MacOS will be able to run `pip install` for the most part.
-* Refactored linear booster class (`gblinear`), so as to support multiple coordinate descent updaters (#3103, #3134). See BREAKING CHANGES below.
-* Fix slow training for multiclass classification with high number of classes (#3109)
-* Fix a corner case in approximate quantile sketch (#3167). Applicable for 'hist' and 'gpu_hist' algorithms
-* Fix memory leak in DMatrix (#3182)
-* New functionality
- - Better linear booster class (#3103, #3134)
- - Pairwise SHAP interaction effects (#3043)
- - Cox loss (#3043)
- - AUC-PR metric for ranking task (#3172)
- - Monotonic constraints for 'hist' algorithm (#3085)
-* GPU support
- - Create an abtract 1D vector class that moves data seamlessly between the main and GPU memory (#2935, #3116, #3068). This eliminates unnecessary PCIe data transfer during training time.
- - Fix minor bugs (#3051, #3217)
- - Fix compatibility error for CUDA 9.1 (#3218)
-* Python package:
- - Correctly handle parameter `verbose_eval=0` (#3115)
-* R package:
- - Eliminate segmentation fault on 32-bit Windows platform (#2994)
-* JVM packages
- - Fix a memory bug involving double-freeing Booster objects (#3005, #3011)
- - Handle empty partition in predict (#3014)
- - Update docs and unify terminology (#3024)
- - Delete cache files after job finishes (#3022)
- - Compatibility fixes for latest Spark versions (#3062, #3093)
-* BREAKING CHANGES: Updated linear modelling algorithms. In particular L1/L2 regularisation penalties are now normalised to number of training examples. This makes the implementation consistent with sklearn/glmnet. L2 regularisation has also been removed from the intercept. To produce linear models with the old regularisation behaviour, the alpha/lambda regularisation parameters can be manually scaled by dividing them by the number of training examples.
-
-## v0.7 (2017.12.30)
-* **This version represents a major change from the last release (v0.6), which was released one year and half ago.**
-* Updated Sklearn API
- - Add compatibility layer for scikit-learn v0.18: `sklearn.cross_validation` now deprecated
- - Updated to allow use of all XGBoost parameters via `**kwargs`.
- - Updated `nthread` to `n_jobs` and `seed` to `random_state` (as per Sklearn convention); `nthread` and `seed` are now marked as deprecated
- - Updated to allow choice of Booster (`gbtree`, `gblinear`, or `dart`)
- - `XGBRegressor` now supports instance weights (specify `sample_weight` parameter)
- - Pass `n_jobs` parameter to the `DMatrix` constructor
- - Add `xgb_model` parameter to `fit` method, to allow continuation of training
-* Refactored gbm to allow more friendly cache strategy
- - Specialized some prediction routine
-* Robust `DMatrix` construction from a sparse matrix
-* Faster consturction of `DMatrix` from 2D NumPy matrices: elide copies, use of multiple threads
-* Automatically remove nan from input data when it is sparse.
- - This can solve some of user reported problem of istart != hist.size
-* Fix the single-instance prediction function to obtain correct predictions
-* Minor fixes
- - Thread local variable is upgraded so it is automatically freed at thread exit.
- - Fix saving and loading `count::poisson` models
- - Fix CalcDCG to use base-2 logarithm
- - Messages are now written to stderr instead of stdout
- - Keep built-in evaluations while using customized evaluation functions
- - Use `bst_float` consistently to minimize type conversion
- - Copy the base margin when slicing `DMatrix`
- - Evaluation metrics are now saved to the model file
- - Use `int32_t` explicitly when serializing version
- - In distributed training, synchronize the number of features after loading a data matrix.
-* Migrate to C++11
- - The current master version now requires C++11 enabled compiled(g++4.8 or higher)
-* Predictor interface was factored out (in a manner similar to the updater interface).
-* Makefile support for Solaris and ARM
-* Test code coverage using Codecov
-* Add CPP tests
-* Add `Dockerfile` and `Jenkinsfile` to support continuous integration for GPU code
-* New functionality
- - Ability to adjust tree model's statistics to a new dataset without changing tree structures.
- - Ability to extract feature contributions from individual predictions, as described in [here](http://blog.datadive.net/interpreting-random-forests/) and [here](https://arxiv.org/abs/1706.06060).
- - Faster, histogram-based tree algorithm (`tree_method='hist'`) .
- - GPU/CUDA accelerated tree algorithms (`tree_method='gpu_hist'` or `'gpu_exact'`), including the GPU-based predictor.
- - Monotonic constraints: when other features are fixed, force the prediction to be monotonic increasing with respect to a certain specified feature.
- - Faster gradient caculation using AVX SIMD
- - Ability to export models in JSON format
- - Support for Tweedie regression
- - Additional dropout options for DART: binomial+1, epsilon
- - Ability to update an existing model in-place: this is useful for many applications, such as determining feature importance
-* Python package:
- - New parameters:
- - `learning_rates` in `cv()`
- - `shuffle` in `mknfold()`
- - `max_features` and `show_values` in `plot_importance()`
- - `sample_weight` in `XGBRegressor.fit()`
- - Support binary wheel builds
- - Fix `MultiIndex` detection to support Pandas 0.21.0 and higher
- - Support metrics and evaluation sets whose names contain `-`
- - Support feature maps when plotting trees
- - Compatibility fix for Python 2.6
- - Call `print_evaluation` callback at last iteration
- - Use appropriate integer types when calling native code, to prevent truncation and memory error
- - Fix shared library loading on Mac OS X
-* R package:
- - New parameters:
- - `silent` in `xgb.DMatrix()`
- - `use_int_id` in `xgb.model.dt.tree()`
- - `predcontrib` in `predict()`
- - `monotone_constraints` in `xgb.train()`
- - Default value of the `save_period` parameter in `xgboost()` changed to NULL (consistent with `xgb.train()`).
- - It's possible to custom-build the R package with GPU acceleration support.
- - Enable JVM build for Mac OS X and Windows
- - Integration with AppVeyor CI
- - Improved safety for garbage collection
- - Store numeric attributes with higher precision
- - Easier installation for devel version
- - Improved `xgb.plot.tree()`
- - Various minor fixes to improve user experience and robustness
- - Register native code to pass CRAN check
- - Updated CRAN submission
-* JVM packages
- - Add Spark pipeline persistence API
- - Fix data persistence: loss evaluation on test data had wrongly used caches for training data.
- - Clean external cache after training
- - Implement early stopping
- - Enable training of multiple models by distinguishing stage IDs
- - Better Spark integration: support RDD / dataframe / dataset, integrate with Spark ML package
- - XGBoost4j now supports ranking task
- - Support training with missing data
- - Refactor JVM package to separate regression and classification models to be consistent with other machine learning libraries
- - Support XGBoost4j compilation on Windows
- - Parameter tuning tool
- - Publish source code for XGBoost4j to maven local repo
- - Scala implementation of the Rabit tracker (drop-in replacement for the Java implementation)
- - Better exception handling for the Rabit tracker
- - Persist `num_class`, number of classes (for classification task)
- - `XGBoostModel` now holds `BoosterParams`
- - libxgboost4j is now part of CMake build
- - Release `DMatrix` when no longer needed, to conserve memory
- - Expose `baseMargin`, to allow initialization of boosting with predictions from an external model
- - Support instance weights
- - Use `SparkParallelismTracker` to prevent jobs from hanging forever
- - Expose train-time evaluation metrics via `XGBoostModel.summary`
- - Option to specify `host-ip` explicitly in the Rabit tracker
-* Documentation
- - Better math notation for gradient boosting
- - Updated build instructions for Mac OS X
- - Template for GitHub issues
- - Add `CITATION` file for citing XGBoost in scientific writing
- - Fix dropdown menu in xgboost.readthedocs.io
- - Document `updater_seq` parameter
- - Style fixes for Python documentation
- - Links to additional examples and tutorials
- - Clarify installation requirements
-* Changes that break backward compatibility
- - [#1519](https://github.com/dmlc/xgboost/pull/1519) XGBoost-spark no longer contains APIs for DMatrix; use the public booster interface instead.
- - [#2476](https://github.com/dmlc/xgboost/pull/2476) `XGBoostModel.predict()` now has a different signature
-
-
-## v0.6 (2016.07.29)
-* Version 0.5 is skipped due to major improvements in the core
-* Major refactor of core library.
- - Goal: more flexible and modular code as a portable library.
- - Switch to use of c++11 standard code.
- - Random number generator defaults to ```std::mt19937```.
- - Share the data loading pipeline and logging module from dmlc-core.
- - Enable registry pattern to allow optionally plugin of objective, metric, tree constructor, data loader.
- - Future plugin modules can be put into xgboost/plugin and register back to the library.
- - Remove most of the raw pointers to smart ptrs, for RAII safety.
-* Add official option to approximate algorithm `tree_method` to parameter.
- - Change default behavior to switch to prefer faster algorithm.
- - User will get a message when approximate algorithm is chosen.
-* Change library name to libxgboost.so
-* Backward compatiblity
- - The binary buffer file is not backward compatible with previous version.
- - The model file is backward compatible on 64 bit platforms.
-* The model file is compatible between 64/32 bit platforms(not yet tested).
-* External memory version and other advanced features will be exposed to R library as well on linux.
- - Previously some of the features are blocked due to C++11 and threading limits.
- - The windows version is still blocked due to Rtools do not support ```std::thread```.
-* rabit and dmlc-core are maintained through git submodule
- - Anyone can open PR to update these dependencies now.
-* Improvements
- - Rabit and xgboost libs are not thread-safe and use thread local PRNGs
- - This could fix some of the previous problem which runs xgboost on multiple threads.
-* JVM Package
- - Enable xgboost4j for java and scala
- - XGBoost distributed now runs on Flink and Spark.
-* Support model attributes listing for meta data.
- - https://github.com/dmlc/xgboost/pull/1198
- - https://github.com/dmlc/xgboost/pull/1166
-* Support callback API
- - https://github.com/dmlc/xgboost/issues/892
- - https://github.com/dmlc/xgboost/pull/1211
- - https://github.com/dmlc/xgboost/pull/1264
-* Support new booster DART(dropout in tree boosting)
- - https://github.com/dmlc/xgboost/pull/1220
-* Add CMake build system
- - https://github.com/dmlc/xgboost/pull/1314
-
-## v0.47 (2016.01.14)
-
-* Changes in R library
- - fixed possible problem of poisson regression.
- - switched from 0 to NA for missing values.
- - exposed access to additional model parameters.
-* Changes in Python library
- - throws exception instead of crash terminal when a parameter error happens.
- - has importance plot and tree plot functions.
- - accepts different learning rates for each boosting round.
- - allows model training continuation from previously saved model.
- - allows early stopping in CV.
- - allows feval to return a list of tuples.
- - allows eval_metric to handle additional format.
- - improved compatibility in sklearn module.
- - additional parameters added for sklearn wrapper.
- - added pip installation functionality.
- - supports more Pandas DataFrame dtypes.
- - added best_ntree_limit attribute, in addition to best_score and best_iteration.
-* Java api is ready for use
-* Added more test cases and continuous integration to make each build more robust.
-
-## v0.4 (2015.05.11)
-
-* Distributed version of xgboost that runs on YARN, scales to billions of examples
-* Direct save/load data and model from/to S3 and HDFS
-* Feature importance visualization in R module, by Michael Benesty
-* Predict leaf index
-* Poisson regression for counts data
-* Early stopping option in training
-* Native save load support in R and python
- - xgboost models now can be saved using save/load in R
- - xgboost python model is now pickable
-* sklearn wrapper is supported in python module
-* Experimental External memory version
-
-
-## v0.3 (2014.09.07)
-
-* Faster tree construction module
- - Allows subsample columns during tree construction via ```bst:col_samplebytree=ratio```
-* Support for boosting from initial predictions
-* Experimental version of LambdaRank
-* Linear booster is now parallelized, using parallel coordinated descent.
-* Add [Code Guide](src/README.md) for customizing objective function and evaluation
-* Add R module
-
-
-## v0.2x (2014.05.20)
-
-* Python module
-* Weighted samples instances
-* Initial version of pairwise rank
-
-
-## v0.1 (2014.03.26)
-
-* Initial release
diff --git a/ml-xgboost/R-package/.Rbuildignore b/ml-xgboost/R-package/.Rbuildignore
deleted file mode 100644
index b37d627..0000000
--- a/ml-xgboost/R-package/.Rbuildignore
+++ /dev/null
@@ -1,6 +0,0 @@
-\.o$
-\.so$
-\.dll$
-^.*\.Rproj$
-^\.Rproj\.user$
-README.md
diff --git a/ml-xgboost/R-package/CMakeLists.txt b/ml-xgboost/R-package/CMakeLists.txt
deleted file mode 100644
index 96776a0..0000000
--- a/ml-xgboost/R-package/CMakeLists.txt
+++ /dev/null
@@ -1,38 +0,0 @@
-find_package(LibR REQUIRED)
-message(STATUS "LIBR_CORE_LIBRARY " ${LIBR_CORE_LIBRARY})
-
-file(GLOB_RECURSE R_SOURCES
- ${CMAKE_CURRENT_LIST_DIR}/src/*.cc
- ${CMAKE_CURRENT_LIST_DIR}/src/*.c)
-# Use object library to expose symbols
-add_library(xgboost-r OBJECT ${R_SOURCES})
-
-set(R_DEFINITIONS
- -DXGBOOST_STRICT_R_MODE=1
- -DXGBOOST_CUSTOMIZE_GLOBAL_PRNG=1
- -DDMLC_LOG_BEFORE_THROW=0
- -DDMLC_DISABLE_STDIN=1
- -DDMLC_LOG_CUSTOMIZE=1
- -DRABIT_CUSTOMIZE_MSG_
- -DRABIT_STRICT_CXX98_)
-target_compile_definitions(xgboost-r
- PRIVATE ${R_DEFINITIONS})
-target_include_directories(xgboost-r
- PRIVATE
- ${LIBR_INCLUDE_DIRS}
- ${PROJECT_SOURCE_DIR}/include
- ${PROJECT_SOURCE_DIR}/dmlc-core/include
- ${PROJECT_SOURCE_DIR}/rabit/include)
-set_target_properties(
- xgboost-r PROPERTIES
- CXX_STANDARD 14
- CXX_STANDARD_REQUIRED ON
- POSITION_INDEPENDENT_CODE ON)
-
-set(XGBOOST_DEFINITIONS "${XGBOOST_DEFINITIONS};${R_DEFINITIONS}" PARENT_SCOPE)
-set(XGBOOST_OBJ_SOURCES $ PARENT_SCOPE)
-set(LINKED_LIBRARIES_PRIVATE ${LINKED_LIBRARIES_PRIVATE} ${LIBR_CORE_LIBRARY} PARENT_SCOPE)
-
-if (USE_OPENMP)
- target_link_libraries(xgboost-r PRIVATE OpenMP::OpenMP_CXX)
-endif ()
diff --git a/ml-xgboost/R-package/DESCRIPTION b/ml-xgboost/R-package/DESCRIPTION
deleted file mode 100644
index 794abdb..0000000
--- a/ml-xgboost/R-package/DESCRIPTION
+++ /dev/null
@@ -1,67 +0,0 @@
-Package: xgboost
-Type: Package
-Title: Extreme Gradient Boosting
-Version: 1.1.0.1
-Date: 2020-02-21
-Authors@R: c(
- person("Tianqi", "Chen", role = c("aut"),
- email = "tianqi.tchen@gmail.com"),
- person("Tong", "He", role = c("aut", "cre"),
- email = "hetong007@gmail.com"),
- person("Michael", "Benesty", role = c("aut"),
- email = "michael@benesty.fr"),
- person("Vadim", "Khotilovich", role = c("aut"),
- email = "khotilovich@gmail.com"),
- person("Yuan", "Tang", role = c("aut"),
- email = "terrytangyuan@gmail.com",
- comment = c(ORCID = "0000-0001-5243-233X")),
- person("Hyunsu", "Cho", role = c("aut"),
- email = "chohyu01@cs.washington.edu"),
- person("Kailong", "Chen", role = c("aut")),
- person("Rory", "Mitchell", role = c("aut")),
- person("Ignacio", "Cano", role = c("aut")),
- person("Tianyi", "Zhou", role = c("aut")),
- person("Mu", "Li", role = c("aut")),
- person("Junyuan", "Xie", role = c("aut")),
- person("Min", "Lin", role = c("aut")),
- person("Yifeng", "Geng", role = c("aut")),
- person("Yutian", "Li", role = c("aut")),
- person("XGBoost contributors", role = c("cph"),
- comment = "base XGBoost implementation")
- )
-Description: Extreme Gradient Boosting, which is an efficient implementation
- of the gradient boosting framework from Chen & Guestrin (2016) .
- This package is its R interface. The package includes efficient linear
- model solver and tree learning algorithms. The package can automatically
- do parallel computation on a single machine which could be more than 10
- times faster than existing gradient boosting packages. It supports
- various objective functions, including regression, classification and ranking.
- The package is made to be extensible, so that users are also allowed to define
- their own objectives easily.
-License: Apache License (== 2.0) | file LICENSE
-URL: https://github.com/dmlc/xgboost
-BugReports: https://github.com/dmlc/xgboost/issues
-NeedsCompilation: yes
-VignetteBuilder: knitr
-Suggests:
- knitr,
- rmarkdown,
- ggplot2 (>= 1.0.1),
- DiagrammeR (>= 0.9.0),
- Ckmeans.1d.dp (>= 3.3.1),
- vcd (>= 1.3),
- testthat,
- lintr,
- igraph (>= 1.0.1),
- jsonlite,
- float
-Depends:
- R (>= 3.3.0)
-Imports:
- Matrix (>= 1.1-0),
- methods,
- data.table (>= 1.9.6),
- magrittr (>= 1.5),
- stringi (>= 0.5.2)
-RoxygenNote: 7.1.0
-SystemRequirements: GNU make, C++11
diff --git a/ml-xgboost/R-package/LICENSE b/ml-xgboost/R-package/LICENSE
deleted file mode 100644
index b9f38c3..0000000
--- a/ml-xgboost/R-package/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
-Copyright (c) 2014 by Tianqi Chen and Contributors
-
-Licensed 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.
diff --git a/ml-xgboost/R-package/NAMESPACE b/ml-xgboost/R-package/NAMESPACE
deleted file mode 100644
index fb0ac54..0000000
--- a/ml-xgboost/R-package/NAMESPACE
+++ /dev/null
@@ -1,91 +0,0 @@
-# Generated by roxygen2: do not edit by hand
-
-S3method("[",xgb.DMatrix)
-S3method("dimnames<-",xgb.DMatrix)
-S3method(dim,xgb.DMatrix)
-S3method(dimnames,xgb.DMatrix)
-S3method(getinfo,xgb.DMatrix)
-S3method(predict,xgb.Booster)
-S3method(predict,xgb.Booster.handle)
-S3method(print,xgb.Booster)
-S3method(print,xgb.DMatrix)
-S3method(print,xgb.cv.synchronous)
-S3method(setinfo,xgb.DMatrix)
-S3method(slice,xgb.DMatrix)
-export("xgb.attr<-")
-export("xgb.attributes<-")
-export("xgb.config<-")
-export("xgb.parameters<-")
-export(cb.cv.predict)
-export(cb.early.stop)
-export(cb.evaluation.log)
-export(cb.gblinear.history)
-export(cb.print.evaluation)
-export(cb.reset.parameters)
-export(cb.save.model)
-export(getinfo)
-export(setinfo)
-export(slice)
-export(xgb.Booster.complete)
-export(xgb.DMatrix)
-export(xgb.DMatrix.save)
-export(xgb.attr)
-export(xgb.attributes)
-export(xgb.config)
-export(xgb.create.features)
-export(xgb.cv)
-export(xgb.dump)
-export(xgb.gblinear.history)
-export(xgb.ggplot.deepness)
-export(xgb.ggplot.importance)
-export(xgb.importance)
-export(xgb.load)
-export(xgb.load.raw)
-export(xgb.model.dt.tree)
-export(xgb.plot.deepness)
-export(xgb.plot.importance)
-export(xgb.plot.multi.trees)
-export(xgb.plot.shap)
-export(xgb.plot.tree)
-export(xgb.save)
-export(xgb.save.raw)
-export(xgb.serialize)
-export(xgb.train)
-export(xgb.unserialize)
-export(xgboost)
-import(methods)
-importClassesFrom(Matrix,dgCMatrix)
-importClassesFrom(Matrix,dgeMatrix)
-importFrom(Matrix,colSums)
-importFrom(Matrix,sparse.model.matrix)
-importFrom(Matrix,sparseMatrix)
-importFrom(Matrix,sparseVector)
-importFrom(Matrix,t)
-importFrom(data.table,":=")
-importFrom(data.table,as.data.table)
-importFrom(data.table,data.table)
-importFrom(data.table,is.data.table)
-importFrom(data.table,rbindlist)
-importFrom(data.table,setkey)
-importFrom(data.table,setkeyv)
-importFrom(data.table,setnames)
-importFrom(grDevices,rgb)
-importFrom(graphics,barplot)
-importFrom(graphics,grid)
-importFrom(graphics,lines)
-importFrom(graphics,par)
-importFrom(graphics,points)
-importFrom(graphics,title)
-importFrom(magrittr,"%>%")
-importFrom(stats,median)
-importFrom(stats,predict)
-importFrom(stringi,stri_detect_regex)
-importFrom(stringi,stri_match_first_regex)
-importFrom(stringi,stri_replace_all_regex)
-importFrom(stringi,stri_replace_first_regex)
-importFrom(stringi,stri_split_regex)
-importFrom(utils,head)
-importFrom(utils,object.size)
-importFrom(utils,str)
-importFrom(utils,tail)
-useDynLib(xgboost, .registration = TRUE)
diff --git a/ml-xgboost/R-package/R/callbacks.R b/ml-xgboost/R-package/R/callbacks.R
deleted file mode 100644
index e6f9f04..0000000
--- a/ml-xgboost/R-package/R/callbacks.R
+++ /dev/null
@@ -1,831 +0,0 @@
-#' Callback closures for booster training.
-#'
-#' These are used to perform various service tasks either during boosting iterations or at the end.
-#' This approach helps to modularize many of such tasks without bloating the main training methods,
-#' and it offers .
-#'
-#' @details
-#' By default, a callback function is run after each boosting iteration.
-#' An R-attribute \code{is_pre_iteration} could be set for a callback to define a pre-iteration function.
-#'
-#' When a callback function has \code{finalize} parameter, its finalizer part will also be run after
-#' the boosting is completed.
-#'
-#' WARNING: side-effects!!! Be aware that these callback functions access and modify things in
-#' the environment from which they are called from, which is a fairly uncommon thing to do in R.
-#'
-#' To write a custom callback closure, make sure you first understand the main concepts about R environments.
-#' Check either R documentation on \code{\link[base]{environment}} or the
-#' \href{http://adv-r.had.co.nz/Environments.html}{Environments chapter} from the "Advanced R"
-#' book by Hadley Wickham. Further, the best option is to read the code of some of the existing callbacks -
-#' choose ones that do something similar to what you want to achieve. Also, you would need to get familiar
-#' with the objects available inside of the \code{xgb.train} and \code{xgb.cv} internal environments.
-#'
-#' @seealso
-#' \code{\link{cb.print.evaluation}},
-#' \code{\link{cb.evaluation.log}},
-#' \code{\link{cb.reset.parameters}},
-#' \code{\link{cb.early.stop}},
-#' \code{\link{cb.save.model}},
-#' \code{\link{cb.cv.predict}},
-#' \code{\link{xgb.train}},
-#' \code{\link{xgb.cv}}
-#'
-#' @name callbacks
-NULL
-
-#
-# Callbacks -------------------------------------------------------------------
-#
-
-#' Callback closure for printing the result of evaluation
-#'
-#' @param period results would be printed every number of periods
-#' @param showsd whether standard deviations should be printed (when available)
-#'
-#' @details
-#' The callback function prints the result of evaluation at every \code{period} iterations.
-#' The initial and the last iteration's evaluations are always printed.
-#'
-#' Callback function expects the following values to be set in its calling frame:
-#' \code{bst_evaluation} (also \code{bst_evaluation_err} when available),
-#' \code{iteration},
-#' \code{begin_iteration},
-#' \code{end_iteration}.
-#'
-#' @seealso
-#' \code{\link{callbacks}}
-#'
-#' @export
-cb.print.evaluation <- function(period = 1, showsd = TRUE) {
-
- callback <- function(env = parent.frame()) {
- if (length(env$bst_evaluation) == 0 ||
- period == 0 ||
- NVL(env$rank, 0) != 0 )
- return()
-
- i <- env$iteration
- if ((i-1) %% period == 0 ||
- i == env$begin_iteration ||
- i == env$end_iteration) {
- stdev <- if (showsd) env$bst_evaluation_err else NULL
- msg <- format.eval.string(i, env$bst_evaluation, stdev)
- cat(msg, '\n')
- }
- }
- attr(callback, 'call') <- match.call()
- attr(callback, 'name') <- 'cb.print.evaluation'
- callback
-}
-
-
-#' Callback closure for logging the evaluation history
-#'
-#' @details
-#' This callback function appends the current iteration evaluation results \code{bst_evaluation}
-#' available in the calling parent frame to the \code{evaluation_log} list in a calling frame.
-#'
-#' The finalizer callback (called with \code{finalize = TURE} in the end) converts
-#' the \code{evaluation_log} list into a final data.table.
-#'
-#' The iteration evaluation result \code{bst_evaluation} must be a named numeric vector.
-#'
-#' Note: in the column names of the final data.table, the dash '-' character is replaced with
-#' the underscore '_' in order to make the column names more like regular R identifiers.
-#'
-#' Callback function expects the following values to be set in its calling frame:
-#' \code{evaluation_log},
-#' \code{bst_evaluation},
-#' \code{iteration}.
-#'
-#' @seealso
-#' \code{\link{callbacks}}
-#'
-#' @export
-cb.evaluation.log <- function() {
-
- mnames <- NULL
-
- init <- function(env) {
- if (!is.list(env$evaluation_log))
- stop("'evaluation_log' has to be a list")
- mnames <<- names(env$bst_evaluation)
- if (is.null(mnames) || any(mnames == ""))
- stop("bst_evaluation must have non-empty names")
-
- mnames <<- gsub('-', '_', names(env$bst_evaluation))
- if(!is.null(env$bst_evaluation_err))
- mnames <<- c(paste0(mnames, '_mean'), paste0(mnames, '_std'))
- }
-
- finalizer <- function(env) {
- env$evaluation_log <- as.data.table(t(simplify2array(env$evaluation_log)))
- setnames(env$evaluation_log, c('iter', mnames))
-
- if(!is.null(env$bst_evaluation_err)) {
- # rearrange col order from _mean,_mean,...,_std,_std,...
- # to be _mean,_std,_mean,_std,...
- len <- length(mnames)
- means <- mnames[seq_len(len/2)]
- stds <- mnames[(len/2 + 1):len]
- cnames <- numeric(len)
- cnames[c(TRUE, FALSE)] <- means
- cnames[c(FALSE, TRUE)] <- stds
- env$evaluation_log <- env$evaluation_log[, c('iter', cnames), with = FALSE]
- }
- }
-
- callback <- function(env = parent.frame(), finalize = FALSE) {
- if (is.null(mnames))
- init(env)
-
- if (finalize)
- return(finalizer(env))
-
- ev <- env$bst_evaluation
- if(!is.null(env$bst_evaluation_err))
- ev <- c(ev, env$bst_evaluation_err)
- env$evaluation_log <- c(env$evaluation_log,
- list(c(iter = env$iteration, ev)))
- }
- attr(callback, 'call') <- match.call()
- attr(callback, 'name') <- 'cb.evaluation.log'
- callback
-}
-
-#' Callback closure for resetting the booster's parameters at each iteration.
-#'
-#' @param new_params a list where each element corresponds to a parameter that needs to be reset.
-#' Each element's value must be either a vector of values of length \code{nrounds}
-#' to be set at each iteration,
-#' or a function of two parameters \code{learning_rates(iteration, nrounds)}
-#' which returns a new parameter value by using the current iteration number
-#' and the total number of boosting rounds.
-#'
-#' @details
-#' This is a "pre-iteration" callback function used to reset booster's parameters
-#' at the beginning of each iteration.
-#'
-#' Note that when training is resumed from some previous model, and a function is used to
-#' reset a parameter value, the \code{nrounds} argument in this function would be the
-#' the number of boosting rounds in the current training.
-#'
-#' Callback function expects the following values to be set in its calling frame:
-#' \code{bst} or \code{bst_folds},
-#' \code{iteration},
-#' \code{begin_iteration},
-#' \code{end_iteration}.
-#'
-#' @seealso
-#' \code{\link{callbacks}}
-#'
-#' @export
-cb.reset.parameters <- function(new_params) {
-
- if (typeof(new_params) != "list")
- stop("'new_params' must be a list")
- pnames <- gsub("\\.", "_", names(new_params))
- nrounds <- NULL
-
- # run some checks in the begining
- init <- function(env) {
- nrounds <<- env$end_iteration - env$begin_iteration + 1
-
- if (is.null(env$bst) && is.null(env$bst_folds))
- stop("Parent frame has neither 'bst' nor 'bst_folds'")
-
- # Some parameters are not allowed to be changed,
- # since changing them would simply wreck some chaos
- not_allowed <- pnames %in%
- c('num_class', 'num_output_group', 'size_leaf_vector', 'updater_seq')
- if (any(not_allowed))
- stop('Parameters ', paste(pnames[not_allowed]), " cannot be changed during boosting.")
-
- for (n in pnames) {
- p <- new_params[[n]]
- if (is.function(p)) {
- if (length(formals(p)) != 2)
- stop("Parameter '", n, "' is a function but not of two arguments")
- } else if (is.numeric(p) || is.character(p)) {
- if (length(p) != nrounds)
- stop("Length of '", n, "' has to be equal to 'nrounds'")
- } else {
- stop("Parameter '", n, "' is not a function or a vector")
- }
- }
- }
-
- callback <- function(env = parent.frame()) {
- if (is.null(nrounds))
- init(env)
-
- i <- env$iteration
- pars <- lapply(new_params, function(p) {
- if (is.function(p))
- return(p(i, nrounds))
- p[i]
- })
-
- if (!is.null(env$bst)) {
- xgb.parameters(env$bst$handle) <- pars
- } else {
- for (fd in env$bst_folds)
- xgb.parameters(fd$bst) <- pars
- }
- }
- attr(callback, 'is_pre_iteration') <- TRUE
- attr(callback, 'call') <- match.call()
- attr(callback, 'name') <- 'cb.reset.parameters'
- callback
-}
-
-
-#' Callback closure to activate the early stopping.
-#'
-#' @param stopping_rounds The number of rounds with no improvement in
-#' the evaluation metric in order to stop the training.
-#' @param maximize whether to maximize the evaluation metric
-#' @param metric_name the name of an evaluation column to use as a criteria for early
-#' stopping. If not set, the last column would be used.
-#' Let's say the test data in \code{watchlist} was labelled as \code{dtest},
-#' and one wants to use the AUC in test data for early stopping regardless of where
-#' it is in the \code{watchlist}, then one of the following would need to be set:
-#' \code{metric_name='dtest-auc'} or \code{metric_name='dtest_auc'}.
-#' All dash '-' characters in metric names are considered equivalent to '_'.
-#' @param verbose whether to print the early stopping information.
-#'
-#' @details
-#' This callback function determines the condition for early stopping
-#' by setting the \code{stop_condition = TRUE} flag in its calling frame.
-#'
-#' The following additional fields are assigned to the model's R object:
-#' \itemize{
-#' \item \code{best_score} the evaluation score at the best iteration
-#' \item \code{best_iteration} at which boosting iteration the best score has occurred (1-based index)
-#' \item \code{best_ntreelimit} to use with the \code{ntreelimit} parameter in \code{predict}.
-#' It differs from \code{best_iteration} in multiclass or random forest settings.
-#' }
-#'
-#' The Same values are also stored as xgb-attributes:
-#' \itemize{
-#' \item \code{best_iteration} is stored as a 0-based iteration index (for interoperability of binary models)
-#' \item \code{best_msg} message string is also stored.
-#' }
-#'
-#' At least one data element is required in the evaluation watchlist for early stopping to work.
-#'
-#' Callback function expects the following values to be set in its calling frame:
-#' \code{stop_condition},
-#' \code{bst_evaluation},
-#' \code{rank},
-#' \code{bst} (or \code{bst_folds} and \code{basket}),
-#' \code{iteration},
-#' \code{begin_iteration},
-#' \code{end_iteration},
-#' \code{num_parallel_tree}.
-#'
-#' @seealso
-#' \code{\link{callbacks}},
-#' \code{\link{xgb.attr}}
-#'
-#' @export
-cb.early.stop <- function(stopping_rounds, maximize = FALSE,
- metric_name = NULL, verbose = TRUE) {
- # state variables
- best_iteration <- -1
- best_ntreelimit <- -1
- best_score <- Inf
- best_msg <- NULL
- metric_idx <- 1
-
- init <- function(env) {
- if (length(env$bst_evaluation) == 0)
- stop("For early stopping, watchlist must have at least one element")
-
- eval_names <- gsub('-', '_', names(env$bst_evaluation))
- if (!is.null(metric_name)) {
- metric_idx <<- which(gsub('-', '_', metric_name) == eval_names)
- if (length(metric_idx) == 0)
- stop("'metric_name' for early stopping is not one of the following:\n",
- paste(eval_names, collapse = ' '), '\n')
- }
- if (is.null(metric_name) &&
- length(env$bst_evaluation) > 1) {
- metric_idx <<- length(eval_names)
- if (verbose)
- cat('Multiple eval metrics are present. Will use ',
- eval_names[metric_idx], ' for early stopping.\n', sep = '')
- }
-
- metric_name <<- eval_names[metric_idx]
-
- # maximize is usually NULL when not set in xgb.train and built-in metrics
- if (is.null(maximize))
- maximize <<- grepl('(_auc|_map|_ndcg)', metric_name)
-
- if (verbose && NVL(env$rank, 0) == 0)
- cat("Will train until ", metric_name, " hasn't improved in ",
- stopping_rounds, " rounds.\n\n", sep = '')
-
- best_iteration <<- 1
- if (maximize) best_score <<- -Inf
-
- env$stop_condition <- FALSE
-
- if (!is.null(env$bst)) {
- if (!inherits(env$bst, 'xgb.Booster'))
- stop("'bst' in the parent frame must be an 'xgb.Booster'")
- if (!is.null(best_score <- xgb.attr(env$bst$handle, 'best_score'))) {
- best_score <<- as.numeric(best_score)
- best_iteration <<- as.numeric(xgb.attr(env$bst$handle, 'best_iteration')) + 1
- best_msg <<- as.numeric(xgb.attr(env$bst$handle, 'best_msg'))
- } else {
- xgb.attributes(env$bst$handle) <- list(best_iteration = best_iteration - 1,
- best_score = best_score)
- }
- } else if (is.null(env$bst_folds) || is.null(env$basket)) {
- stop("Parent frame has neither 'bst' nor ('bst_folds' and 'basket')")
- }
- }
-
- finalizer <- function(env) {
- if (!is.null(env$bst)) {
- attr_best_score = as.numeric(xgb.attr(env$bst$handle, 'best_score'))
- if (best_score != attr_best_score)
- stop("Inconsistent 'best_score' values between the closure state: ", best_score,
- " and the xgb.attr: ", attr_best_score)
- env$bst$best_iteration = best_iteration
- env$bst$best_ntreelimit = best_ntreelimit
- env$bst$best_score = best_score
- } else {
- env$basket$best_iteration <- best_iteration
- env$basket$best_ntreelimit <- best_ntreelimit
- }
- }
-
- callback <- function(env = parent.frame(), finalize = FALSE) {
- if (best_iteration < 0)
- init(env)
-
- if (finalize)
- return(finalizer(env))
-
- i <- env$iteration
- score = env$bst_evaluation[metric_idx]
-
- if (( maximize && score > best_score) ||
- (!maximize && score < best_score)) {
-
- best_msg <<- format.eval.string(i, env$bst_evaluation, env$bst_evaluation_err)
- best_score <<- score
- best_iteration <<- i
- best_ntreelimit <<- best_iteration * env$num_parallel_tree
- # save the property to attributes, so they will occur in checkpoint
- if (!is.null(env$bst)) {
- xgb.attributes(env$bst) <- list(
- best_iteration = best_iteration - 1, # convert to 0-based index
- best_score = best_score,
- best_msg = best_msg,
- best_ntreelimit = best_ntreelimit)
- }
- } else if (i - best_iteration >= stopping_rounds) {
- env$stop_condition <- TRUE
- env$end_iteration <- i
- if (verbose && NVL(env$rank, 0) == 0)
- cat("Stopping. Best iteration:\n", best_msg, "\n\n", sep = '')
- }
- }
- attr(callback, 'call') <- match.call()
- attr(callback, 'name') <- 'cb.early.stop'
- callback
-}
-
-
-#' Callback closure for saving a model file.
-#'
-#' @param save_period save the model to disk after every
-#' \code{save_period} iterations; 0 means save the model at the end.
-#' @param save_name the name or path for the saved model file.
-#' It can contain a \code{\link[base]{sprintf}} formatting specifier
-#' to include the integer iteration number in the file name.
-#' E.g., with \code{save_name} = 'xgboost_%04d.model',
-#' the file saved at iteration 50 would be named "xgboost_0050.model".
-#'
-#' @details
-#' This callback function allows to save an xgb-model file, either periodically after each \code{save_period}'s or at the end.
-#'
-#' Callback function expects the following values to be set in its calling frame:
-#' \code{bst},
-#' \code{iteration},
-#' \code{begin_iteration},
-#' \code{end_iteration}.
-#'
-#' @seealso
-#' \code{\link{callbacks}}
-#'
-#' @export
-cb.save.model <- function(save_period = 0, save_name = "xgboost.model") {
-
- if (save_period < 0)
- stop("'save_period' cannot be negative")
-
- callback <- function(env = parent.frame()) {
- if (is.null(env$bst))
- stop("'save_model' callback requires the 'bst' booster object in its calling frame")
-
- if ((save_period > 0 && (env$iteration - env$begin_iteration) %% save_period == 0) ||
- (save_period == 0 && env$iteration == env$end_iteration))
- xgb.save(env$bst, sprintf(save_name, env$iteration))
- }
- attr(callback, 'call') <- match.call()
- attr(callback, 'name') <- 'cb.save.model'
- callback
-}
-
-
-#' Callback closure for returning cross-validation based predictions.
-#'
-#' @param save_models a flag for whether to save the folds' models.
-#'
-#' @details
-#' This callback function saves predictions for all of the test folds,
-#' and also allows to save the folds' models.
-#'
-#' It is a "finalizer" callback and it uses early stopping information whenever it is available,
-#' thus it must be run after the early stopping callback if the early stopping is used.
-#'
-#' Callback function expects the following values to be set in its calling frame:
-#' \code{bst_folds},
-#' \code{basket},
-#' \code{data},
-#' \code{end_iteration},
-#' \code{params},
-#' \code{num_parallel_tree},
-#' \code{num_class}.
-#'
-#' @return
-#' Predictions are returned inside of the \code{pred} element, which is either a vector or a matrix,
-#' depending on the number of prediction outputs per data row. The order of predictions corresponds
-#' to the order of rows in the original dataset. Note that when a custom \code{folds} list is
-#' provided in \code{xgb.cv}, the predictions would only be returned properly when this list is a
-#' non-overlapping list of k sets of indices, as in a standard k-fold CV. The predictions would not be
-#' meaningful when user-provided folds have overlapping indices as in, e.g., random sampling splits.
-#' When some of the indices in the training dataset are not included into user-provided \code{folds},
-#' their prediction value would be \code{NA}.
-#'
-#' @seealso
-#' \code{\link{callbacks}}
-#'
-#' @export
-cb.cv.predict <- function(save_models = FALSE) {
-
- finalizer <- function(env) {
- if (is.null(env$basket) || is.null(env$bst_folds))
- stop("'cb.cv.predict' callback requires 'basket' and 'bst_folds' lists in its calling frame")
-
- N <- nrow(env$data)
- pred <-
- if (env$num_class > 1) {
- matrix(NA_real_, N, env$num_class)
- } else {
- rep(NA_real_, N)
- }
-
- ntreelimit <- NVL(env$basket$best_ntreelimit,
- env$end_iteration * env$num_parallel_tree)
- if (NVL(env$params[['booster']], '') == 'gblinear') {
- ntreelimit <- 0 # must be 0 for gblinear
- }
- for (fd in env$bst_folds) {
- pr <- predict(fd$bst, fd$watchlist[[2]], ntreelimit = ntreelimit, reshape = TRUE)
- if (is.matrix(pred)) {
- pred[fd$index,] <- pr
- } else {
- pred[fd$index] <- pr
- }
- }
- env$basket$pred <- pred
- if (save_models) {
- env$basket$models <- lapply(env$bst_folds, function(fd) {
- xgb.attr(fd$bst, 'niter') <- env$end_iteration - 1
- xgb.Booster.complete(xgb.handleToBooster(fd$bst), saveraw = TRUE)
- })
- }
- }
-
- callback <- function(env = parent.frame(), finalize = FALSE) {
- if (finalize)
- return(finalizer(env))
- }
- attr(callback, 'call') <- match.call()
- attr(callback, 'name') <- 'cb.cv.predict'
- callback
-}
-
-
-#' Callback closure for collecting the model coefficients history of a gblinear booster
-#' during its training.
-#'
-#' @param sparse when set to FALSE/TURE, a dense/sparse matrix is used to store the result.
-#' Sparse format is useful when one expects only a subset of coefficients to be non-zero,
-#' when using the "thrifty" feature selector with fairly small number of top features
-#' selected per iteration.
-#'
-#' @details
-#' To keep things fast and simple, gblinear booster does not internally store the history of linear
-#' model coefficients at each boosting iteration. This callback provides a workaround for storing
-#' the coefficients' path, by extracting them after each training iteration.
-#'
-#' Callback function expects the following values to be set in its calling frame:
-#' \code{bst} (or \code{bst_folds}).
-#'
-#' @return
-#' Results are stored in the \code{coefs} element of the closure.
-#' The \code{\link{xgb.gblinear.history}} convenience function provides an easy way to access it.
-#' With \code{xgb.train}, it is either a dense of a sparse matrix.
-#' While with \code{xgb.cv}, it is a list (an element per each fold) of such matrices.
-#'
-#' @seealso
-#' \code{\link{callbacks}}, \code{\link{xgb.gblinear.history}}.
-#'
-#' @examples
-#' #### Binary classification:
-#' #
-#' # In the iris dataset, it is hard to linearly separate Versicolor class from the rest
-#' # without considering the 2nd order interactions:
-#' require(magrittr)
-#' x <- model.matrix(Species ~ .^2, iris)[,-1]
-#' colnames(x)
-#' dtrain <- xgb.DMatrix(scale(x), label = 1*(iris$Species == "versicolor"))
-#' param <- list(booster = "gblinear", objective = "reg:logistic", eval_metric = "auc",
-#' lambda = 0.0003, alpha = 0.0003, nthread = 2)
-#' # For 'shotgun', which is a default linear updater, using high eta values may result in
-#' # unstable behaviour in some datasets. With this simple dataset, however, the high learning
-#' # rate does not break the convergence, but allows us to illustrate the typical pattern of
-#' # "stochastic explosion" behaviour of this lock-free algorithm at early boosting iterations.
-#' bst <- xgb.train(param, dtrain, list(tr=dtrain), nrounds = 200, eta = 1.,
-#' callbacks = list(cb.gblinear.history()))
-#' # Extract the coefficients' path and plot them vs boosting iteration number:
-#' coef_path <- xgb.gblinear.history(bst)
-#' matplot(coef_path, type = 'l')
-#'
-#' # With the deterministic coordinate descent updater, it is safer to use higher learning rates.
-#' # Will try the classical componentwise boosting which selects a single best feature per round:
-#' bst <- xgb.train(param, dtrain, list(tr=dtrain), nrounds = 200, eta = 0.8,
-#' updater = 'coord_descent', feature_selector = 'thrifty', top_k = 1,
-#' callbacks = list(cb.gblinear.history()))
-#' xgb.gblinear.history(bst) %>% matplot(type = 'l')
-#' # Componentwise boosting is known to have similar effect to Lasso regularization.
-#' # Try experimenting with various values of top_k, eta, nrounds,
-#' # as well as different feature_selectors.
-#'
-#' # For xgb.cv:
-#' bst <- xgb.cv(param, dtrain, nfold = 5, nrounds = 100, eta = 0.8,
-#' callbacks = list(cb.gblinear.history()))
-#' # coefficients in the CV fold #3
-#' xgb.gblinear.history(bst)[[3]] %>% matplot(type = 'l')
-#'
-#'
-#' #### Multiclass classification:
-#' #
-#' dtrain <- xgb.DMatrix(scale(x), label = as.numeric(iris$Species) - 1)
-#' param <- list(booster = "gblinear", objective = "multi:softprob", num_class = 3,
-#' lambda = 0.0003, alpha = 0.0003, nthread = 2)
-#' # For the default linear updater 'shotgun' it sometimes is helpful
-#' # to use smaller eta to reduce instability
-#' bst <- xgb.train(param, dtrain, list(tr=dtrain), nrounds = 70, eta = 0.5,
-#' callbacks = list(cb.gblinear.history()))
-#' # Will plot the coefficient paths separately for each class:
-#' xgb.gblinear.history(bst, class_index = 0) %>% matplot(type = 'l')
-#' xgb.gblinear.history(bst, class_index = 1) %>% matplot(type = 'l')
-#' xgb.gblinear.history(bst, class_index = 2) %>% matplot(type = 'l')
-#'
-#' # CV:
-#' bst <- xgb.cv(param, dtrain, nfold = 5, nrounds = 70, eta = 0.5,
-#' callbacks = list(cb.gblinear.history(FALSE)))
-#' # 1st forld of 1st class
-#' xgb.gblinear.history(bst, class_index = 0)[[1]] %>% matplot(type = 'l')
-#'
-#' @export
-cb.gblinear.history <- function(sparse=FALSE) {
- coefs <- NULL
-
- init <- function(env) {
- if (!is.null(env$bst)) { # xgb.train:
- coef_path <- list()
- } else if (!is.null(env$bst_folds)) { # xgb.cv:
- coef_path <- rep(list(), length(env$bst_folds))
- } else stop("Parent frame has neither 'bst' nor 'bst_folds'")
- }
-
- # convert from list to (sparse) matrix
- list2mat <- function(coef_list) {
- if (sparse) {
- coef_mat <- sparseMatrix(x = unlist(lapply(coef_list, slot, "x")),
- i = unlist(lapply(coef_list, slot, "i")),
- p = c(0, cumsum(sapply(coef_list, function(x) length(x@x)))),
- dims = c(length(coef_list[[1]]), length(coef_list)))
- return(t(coef_mat))
- } else {
- return(do.call(rbind, coef_list))
- }
- }
-
- finalizer <- function(env) {
- if (length(coefs) == 0)
- return()
- if (!is.null(env$bst)) { # # xgb.train:
- coefs <<- list2mat(coefs)
- } else { # xgb.cv:
- # first lapply transposes the list
- coefs <<- lapply(seq_along(coefs[[1]]), function(i) lapply(coefs, "[[", i)) %>%
- lapply(function(x) list2mat(x))
- }
- }
-
- extract.coef <- function(env) {
- if (!is.null(env$bst)) { # # xgb.train:
- cf <- as.numeric(grep('(booster|bias|weigh)', xgb.dump(env$bst), invert = TRUE, value = TRUE))
- if (sparse) cf <- as(cf, "sparseVector")
- } else { # xgb.cv:
- cf <- vector("list", length(env$bst_folds))
- for (i in seq_along(env$bst_folds)) {
- dmp <- xgb.dump(xgb.handleToBooster(env$bst_folds[[i]]$bst))
- cf[[i]] <- as.numeric(grep('(booster|bias|weigh)', dmp, invert = TRUE, value = TRUE))
- if (sparse) cf[[i]] <- as(cf[[i]], "sparseVector")
- }
- }
- cf
- }
-
- callback <- function(env = parent.frame(), finalize = FALSE) {
- if (is.null(coefs)) init(env)
- if (finalize) return(finalizer(env))
- cf <- extract.coef(env)
- coefs <<- c(coefs, list(cf))
- }
-
- attr(callback, 'call') <- match.call()
- attr(callback, 'name') <- 'cb.gblinear.history'
- callback
-}
-
-#' Extract gblinear coefficients history.
-#'
-#' A helper function to extract the matrix of linear coefficients' history
-#' from a gblinear model created while using the \code{cb.gblinear.history()}
-#' callback.
-#'
-#' @param model either an \code{xgb.Booster} or a result of \code{xgb.cv()}, trained
-#' using the \code{cb.gblinear.history()} callback.
-#' @param class_index zero-based class index to extract the coefficients for only that
-#' specific class in a multinomial multiclass model. When it is NULL, all the
-#' coefficients are returned. Has no effect in non-multiclass models.
-#'
-#' @return
-#' For an \code{xgb.train} result, a matrix (either dense or sparse) with the columns
-#' corresponding to iteration's coefficients (in the order as \code{xgb.dump()} would
-#' return) and the rows corresponding to boosting iterations.
-#'
-#' For an \code{xgb.cv} result, a list of such matrices is returned with the elements
-#' corresponding to CV folds.
-#'
-#' @export
-xgb.gblinear.history <- function(model, class_index = NULL) {
-
- if (!(inherits(model, "xgb.Booster") ||
- inherits(model, "xgb.cv.synchronous")))
- stop("model must be an object of either xgb.Booster or xgb.cv.synchronous class")
- is_cv <- inherits(model, "xgb.cv.synchronous")
-
- if (is.null(model[["callbacks"]]) || is.null(model$callbacks[["cb.gblinear.history"]]))
- stop("model must be trained while using the cb.gblinear.history() callback")
-
- if (!is_cv) {
- # extract num_class & num_feat from the internal model
- dmp <- xgb.dump(model)
- if(length(dmp) < 2 || dmp[2] != "bias:")
- stop("It does not appear to be a gblinear model")
- dmp <- dmp[-c(1,2)]
- n <- which(dmp == 'weight:')
- if(length(n) != 1)
- stop("It does not appear to be a gblinear model")
- num_class <- n - 1
- num_feat <- (length(dmp) - 4) / num_class
- } else {
- # in case of CV, the object is expected to have this info
- if (model$params$booster != "gblinear")
- stop("It does not appear to be a gblinear model")
- num_class <- NVL(model$params$num_class, 1)
- num_feat <- model$nfeatures
- if (is.null(num_feat))
- stop("This xgb.cv result does not have nfeatures info")
- }
-
- if (!is.null(class_index) &&
- num_class > 1 &&
- (class_index[1] < 0 || class_index[1] >= num_class))
- stop("class_index has to be within [0,", num_class - 1, "]")
-
- coef_path <- environment(model$callbacks$cb.gblinear.history)[["coefs"]]
- if (!is.null(class_index) && num_class > 1) {
- coef_path <- if (is.list(coef_path)) {
- lapply(coef_path,
- function(x) x[, seq(1 + class_index, by=num_class, length.out=num_feat)])
- } else {
- coef_path <- coef_path[, seq(1 + class_index, by=num_class, length.out=num_feat)]
- }
- }
- coef_path
-}
-
-
-#
-# Internal utility functions for callbacks ------------------------------------
-#
-
-# Format the evaluation metric string
-format.eval.string <- function(iter, eval_res, eval_err = NULL) {
- if (length(eval_res) == 0)
- stop('no evaluation results')
- enames <- names(eval_res)
- if (is.null(enames))
- stop('evaluation results must have names')
- iter <- sprintf('[%d]\t', iter)
- if (!is.null(eval_err)) {
- if (length(eval_res) != length(eval_err))
- stop('eval_res & eval_err lengths mismatch')
- res <- paste0(sprintf("%s:%f+%f", enames, eval_res, eval_err), collapse = '\t')
- } else {
- res <- paste0(sprintf("%s:%f", enames, eval_res), collapse = '\t')
- }
- return(paste0(iter, res))
-}
-
-# Extract callback names from the list of callbacks
-callback.names <- function(cb_list) {
- unlist(lapply(cb_list, function(x) attr(x, 'name')))
-}
-
-# Extract callback calls from the list of callbacks
-callback.calls <- function(cb_list) {
- unlist(lapply(cb_list, function(x) attr(x, 'call')))
-}
-
-# Add a callback cb to the list and make sure that
-# cb.early.stop and cb.cv.predict are at the end of the list
-# with cb.cv.predict being the last (when present)
-add.cb <- function(cb_list, cb) {
- cb_list <- c(cb_list, cb)
- names(cb_list) <- callback.names(cb_list)
- if ('cb.early.stop' %in% names(cb_list)) {
- cb_list <- c(cb_list, cb_list['cb.early.stop'])
- # this removes only the first one
- cb_list['cb.early.stop'] <- NULL
- }
- if ('cb.cv.predict' %in% names(cb_list)) {
- cb_list <- c(cb_list, cb_list['cb.cv.predict'])
- cb_list['cb.cv.predict'] <- NULL
- }
- cb_list
-}
-
-# Sort callbacks list into categories
-categorize.callbacks <- function(cb_list) {
- list(
- pre_iter = Filter(function(x) {
- pre <- attr(x, 'is_pre_iteration')
- !is.null(pre) && pre
- }, cb_list),
- post_iter = Filter(function(x) {
- pre <- attr(x, 'is_pre_iteration')
- is.null(pre) || !pre
- }, cb_list),
- finalize = Filter(function(x) {
- 'finalize' %in% names(formals(x))
- }, cb_list)
- )
-}
-
-# Check whether all callback functions with names given by 'query_names' are present in the 'cb_list'.
-has.callbacks <- function(cb_list, query_names) {
- if (length(cb_list) < length(query_names))
- return(FALSE)
- if (!is.list(cb_list) ||
- any(sapply(cb_list, class) != 'function')) {
- stop('`cb_list` must be a list of callback functions')
- }
- cb_names <- callback.names(cb_list)
- if (!is.character(cb_names) ||
- length(cb_names) != length(cb_list) ||
- any(cb_names == "")) {
- stop('All callbacks in the `cb_list` must have a non-empty `name` attribute')
- }
- if (!is.character(query_names) ||
- length(query_names) == 0 ||
- any(query_names == "")) {
- stop('query_names must be a non-empty vector of non-empty character names')
- }
- return(all(query_names %in% cb_names))
-}
diff --git a/ml-xgboost/R-package/R/utils.R b/ml-xgboost/R-package/R/utils.R
deleted file mode 100644
index 0edbf12..0000000
--- a/ml-xgboost/R-package/R/utils.R
+++ /dev/null
@@ -1,352 +0,0 @@
-#
-# This file is for the low level reuseable utility functions
-# that are not supposed to be visibe to a user.
-#
-
-#
-# General helper utilities ----------------------------------------------------
-#
-
-# SQL-style NVL shortcut.
-NVL <- function(x, val) {
- if (is.null(x))
- return(val)
- if (is.vector(x)) {
- x[is.na(x)] <- val
- return(x)
- }
- if (typeof(x) == 'closure')
- return(x)
- stop("typeof(x) == ", typeof(x), " is not supported by NVL")
-}
-
-
-#
-# Low-level functions for boosting --------------------------------------------
-#
-
-# Merges booster params with whatever is provided in ...
-# plus runs some checks
-check.booster.params <- function(params, ...) {
- if (!identical(class(params), "list"))
- stop("params must be a list")
-
- # in R interface, allow for '.' instead of '_' in parameter names
- names(params) <- gsub("\\.", "_", names(params))
-
- # merge parameters from the params and the dots-expansion
- dot_params <- list(...)
- names(dot_params) <- gsub("\\.", "_", names(dot_params))
- if (length(intersect(names(params),
- names(dot_params))) > 0)
- stop("Same parameters in 'params' and in the call are not allowed. Please check your 'params' list.")
- params <- c(params, dot_params)
-
- # providing a parameter multiple times makes sense only for 'eval_metric'
- name_freqs <- table(names(params))
- multi_names <- setdiff(names(name_freqs[name_freqs > 1]), 'eval_metric')
- if (length(multi_names) > 0) {
- warning("The following parameters were provided multiple times:\n\t",
- paste(multi_names, collapse = ', '), "\n Only the last value for each of them will be used.\n")
- # While xgboost internals would choose the last value for a multiple-times parameter,
- # enforce it here in R as well (b/c multi-parameters might be used further in R code,
- # and R takes the 1st value when multiple elements with the same name are present in a list).
- for (n in multi_names) {
- del_idx <- which(n == names(params))
- del_idx <- del_idx[-length(del_idx)]
- params[[del_idx]] <- NULL
- }
- }
-
- # for multiclass, expect num_class to be set
- if (typeof(params[['objective']]) == "character" &&
- substr(NVL(params[['objective']], 'x'), 1, 6) == 'multi:' &&
- as.numeric(NVL(params[['num_class']], 0)) < 2) {
- stop("'num_class' > 1 parameter must be set for multiclass classification")
- }
-
- # monotone_constraints parser
-
- if (!is.null(params[['monotone_constraints']]) &&
- typeof(params[['monotone_constraints']]) != "character") {
- vec2str = paste(params[['monotone_constraints']], collapse = ',')
- vec2str = paste0('(', vec2str, ')')
- params[['monotone_constraints']] = vec2str
- }
-
- # interaction constraints parser (convert from list of column indices to string)
- if (!is.null(params[['interaction_constraints']]) &&
- typeof(params[['interaction_constraints']]) != "character"){
- # check input class
- if (!identical(class(params[['interaction_constraints']]),'list')) stop('interaction_constraints should be class list')
- if (!all(unique(sapply(params[['interaction_constraints']], class)) %in% c('numeric','integer'))) {
- stop('interaction_constraints should be a list of numeric/integer vectors')
- }
-
- # recast parameter as string
- interaction_constraints <- sapply(params[['interaction_constraints']], function(x) paste0('[', paste(x, collapse=','), ']'))
- params[['interaction_constraints']] <- paste0('[', paste(interaction_constraints, collapse=','), ']')
- }
- return(params)
-}
-
-
-# Performs some checks related to custom objective function.
-# WARNING: has side-effects and can modify 'params' and 'obj' in its calling frame
-check.custom.obj <- function(env = parent.frame()) {
- if (!is.null(env$params[['objective']]) && !is.null(env$obj))
- stop("Setting objectives in 'params' and 'obj' at the same time is not allowed")
-
- if (!is.null(env$obj) && typeof(env$obj) != 'closure')
- stop("'obj' must be a function")
-
- # handle the case when custom objective function was provided through params
- if (!is.null(env$params[['objective']]) &&
- typeof(env$params$objective) == 'closure') {
- env$obj <- env$params$objective
- env$params$objective <- NULL
- }
-}
-
-# Performs some checks related to custom evaluation function.
-# WARNING: has side-effects and can modify 'params' and 'feval' in its calling frame
-check.custom.eval <- function(env = parent.frame()) {
- if (!is.null(env$params[['eval_metric']]) && !is.null(env$feval))
- stop("Setting evaluation metrics in 'params' and 'feval' at the same time is not allowed")
-
- if (!is.null(env$feval) && typeof(env$feval) != 'closure')
- stop("'feval' must be a function")
-
- # handle a situation when custom eval function was provided through params
- if (!is.null(env$params[['eval_metric']]) &&
- typeof(env$params$eval_metric) == 'closure') {
- env$feval <- env$params$eval_metric
- env$params$eval_metric <- NULL
- }
-
- # require maximize to be set when custom feval and early stopping are used together
- if (!is.null(env$feval) &&
- is.null(env$maximize) && (
- !is.null(env$early_stopping_rounds) ||
- has.callbacks(env$callbacks, 'cb.early.stop')))
- stop("Please set 'maximize' to indicate whether the evaluation metric needs to be maximized or not")
-}
-
-
-# Update a booster handle for an iteration with dtrain data
-xgb.iter.update <- function(booster_handle, dtrain, iter, obj = NULL) {
- if (!identical(class(booster_handle), "xgb.Booster.handle")) {
- stop("booster_handle must be of xgb.Booster.handle class")
- }
- if (!inherits(dtrain, "xgb.DMatrix")) {
- stop("dtrain must be of xgb.DMatrix class")
- }
-
- if (is.null(obj)) {
- .Call(XGBoosterUpdateOneIter_R, booster_handle, as.integer(iter), dtrain)
- } else {
- pred <- predict(booster_handle, dtrain, outputmargin = TRUE, training = TRUE)
- gpair <- obj(pred, dtrain)
- .Call(XGBoosterBoostOneIter_R, booster_handle, dtrain, gpair$grad, gpair$hess)
- }
- return(TRUE)
-}
-
-
-# Evaluate one iteration.
-# Returns a named vector of evaluation metrics
-# with the names in a 'datasetname-metricname' format.
-xgb.iter.eval <- function(booster_handle, watchlist, iter, feval = NULL) {
- if (!identical(class(booster_handle), "xgb.Booster.handle"))
- stop("class of booster_handle must be xgb.Booster.handle")
-
- if (length(watchlist) == 0)
- return(NULL)
-
- evnames <- names(watchlist)
- if (is.null(feval)) {
- msg <- .Call(XGBoosterEvalOneIter_R, booster_handle, as.integer(iter), watchlist, as.list(evnames))
- msg <- stri_split_regex(msg, '(\\s+|:|\\s+)')[[1]][-1]
- res <- as.numeric(msg[c(FALSE,TRUE)]) # even indices are the values
- names(res) <- msg[c(TRUE,FALSE)] # odds are the names
- } else {
- res <- sapply(seq_along(watchlist), function(j) {
- w <- watchlist[[j]]
- preds <- predict(booster_handle, w) # predict using all trees
- eval_res <- feval(preds, w)
- out <- eval_res$value
- names(out) <- paste0(evnames[j], "-", eval_res$metric)
- out
- })
- }
- return(res)
-}
-
-
-#
-# Helper functions for cross validation ---------------------------------------
-#
-
-# Generates random (stratified if needed) CV folds
-generate.cv.folds <- function(nfold, nrows, stratified, label, params) {
-
- # cannot do it for rank
- if (exists('objective', where = params) &&
- is.character(params$objective) &&
- strtrim(params$objective, 5) == 'rank:') {
- stop("\n\tAutomatic generation of CV-folds is not implemented for ranking!\n",
- "\tConsider providing pre-computed CV-folds through the 'folds=' parameter.\n")
- }
- # shuffle
- rnd_idx <- sample.int(nrows)
- if (stratified &&
- length(label) == length(rnd_idx)) {
- y <- label[rnd_idx]
- # WARNING: some heuristic logic is employed to identify classification setting!
- # - For classification, need to convert y labels to factor before making the folds,
- # and then do stratification by factor levels.
- # - For regression, leave y numeric and do stratification by quantiles.
- if (exists('objective', where = params) &&
- is.character(params$objective)) {
- # If 'objective' provided in params, assume that y is a classification label
- # unless objective is reg:squarederror
- if (params$objective != 'reg:squarederror')
- y <- factor(y)
- } else {
- # If no 'objective' given in params, it means that user either wants to
- # use the default 'reg:squarederror' objective or has provided a custom
- # obj function. Here, assume classification setting when y has 5 or less
- # unique values:
- if (length(unique(y)) <= 5)
- y <- factor(y)
- }
- folds <- xgb.createFolds(y, nfold)
- } else {
- # make simple non-stratified folds
- kstep <- length(rnd_idx) %/% nfold
- folds <- list()
- for (i in seq_len(nfold - 1)) {
- folds[[i]] <- rnd_idx[seq_len(kstep)]
- rnd_idx <- rnd_idx[-seq_len(kstep)]
- }
- folds[[nfold]] <- rnd_idx
- }
- return(folds)
-}
-
-# Creates CV folds stratified by the values of y.
-# It was borrowed from caret::createFolds and simplified
-# by always returning an unnamed list of fold indices.
-xgb.createFolds <- function(y, k = 10)
-{
- if (is.numeric(y)) {
- ## Group the numeric data based on their magnitudes
- ## and sample within those groups.
-
- ## When the number of samples is low, we may have
- ## issues further slicing the numeric data into
- ## groups. The number of groups will depend on the
- ## ratio of the number of folds to the sample size.
- ## At most, we will use quantiles. If the sample
- ## is too small, we just do regular unstratified
- ## CV
- cuts <- floor(length(y) / k)
- if (cuts < 2) cuts <- 2
- if (cuts > 5) cuts <- 5
- y <- cut(y,
- unique(stats::quantile(y, probs = seq(0, 1, length = cuts))),
- include.lowest = TRUE)
- }
-
- if (k < length(y)) {
- ## reset levels so that the possible levels and
- ## the levels in the vector are the same
- y <- factor(as.character(y))
- numInClass <- table(y)
- foldVector <- vector(mode = "integer", length(y))
-
- ## For each class, balance the fold allocation as far
- ## as possible, then resample the remainder.
- ## The final assignment of folds is also randomized.
- for (i in seq_along(numInClass)) {
- ## create a vector of integers from 1:k as many times as possible without
- ## going over the number of samples in the class. Note that if the number
- ## of samples in a class is less than k, nothing is producd here.
- seqVector <- rep(seq_len(k), numInClass[i] %/% k)
- ## add enough random integers to get length(seqVector) == numInClass[i]
- if (numInClass[i] %% k > 0) seqVector <- c(seqVector, sample.int(k, numInClass[i] %% k))
- ## shuffle the integers for fold assignment and assign to this classes's data
- ## seqVector[sample.int(length(seqVector))] is used to handle length(seqVector) == 1
- foldVector[y == dimnames(numInClass)$y[i]] <- seqVector[sample.int(length(seqVector))]
- }
- } else {
- foldVector <- seq(along = y)
- }
-
- out <- split(seq(along = y), foldVector)
- names(out) <- NULL
- out
-}
-
-
-#
-# Deprectaion notice utilities ------------------------------------------------
-#
-
-#' Deprecation notices.
-#'
-#' At this time, some of the parameter names were changed in order to make the code style more uniform.
-#' The deprecated parameters would be removed in the next release.
-#'
-#' To see all the current deprecated and new parameters, check the \code{xgboost:::depr_par_lut} table.
-#'
-#' A deprecation warning is shown when any of the deprecated parameters is used in a call.
-#' An additional warning is shown when there was a partial match to a deprecated parameter
-#' (as R is able to partially match parameter names).
-#'
-#' @name xgboost-deprecated
-NULL
-
-# Lookup table for the deprecated parameters bookkeeping
-depr_par_lut <- matrix(c(
- 'print.every.n', 'print_every_n',
- 'early.stop.round', 'early_stopping_rounds',
- 'training.data', 'data',
- 'with.stats', 'with_stats',
- 'numberOfClusters', 'n_clusters',
- 'features.keep', 'features_keep',
- 'plot.height','plot_height',
- 'plot.width','plot_width',
- 'n_first_tree', 'trees',
- 'dummy', 'DUMMY'
-), ncol = 2, byrow = TRUE)
-colnames(depr_par_lut) <- c('old', 'new')
-
-# Checks the dot-parameters for deprecated names
-# (including partial matching), gives a deprecation warning,
-# and sets new parameters to the old parameters' values within its parent frame.
-# WARNING: has side-effects
-check.deprecation <- function(..., env = parent.frame()) {
- pars <- list(...)
- # exact and partial matches
- all_match <- pmatch(names(pars), depr_par_lut[,1])
- # indices of matched pars' names
- idx_pars <- which(!is.na(all_match))
- if (length(idx_pars) == 0) return()
- # indices of matched LUT rows
- idx_lut <- all_match[idx_pars]
- # which of idx_lut were the exact matches?
- ex_match <- depr_par_lut[idx_lut,1] %in% names(pars)
- for (i in seq_along(idx_pars)) {
- pars_par <- names(pars)[idx_pars[i]]
- old_par <- depr_par_lut[idx_lut[i], 1]
- new_par <- depr_par_lut[idx_lut[i], 2]
- if (!ex_match[i]) {
- warning("'", pars_par, "' was partially matched to '", old_par,"'")
- }
- .Deprecated(new_par, old = old_par, package = 'xgboost')
- if (new_par != 'NULL') {
- eval(parse(text = paste(new_par, '<-', pars[[pars_par]])), envir = env)
- }
- }
-}
diff --git a/ml-xgboost/R-package/R/xgb.Booster.R b/ml-xgboost/R-package/R/xgb.Booster.R
deleted file mode 100644
index dcc4469..0000000
--- a/ml-xgboost/R-package/R/xgb.Booster.R
+++ /dev/null
@@ -1,711 +0,0 @@
-# Construct an internal xgboost Booster and return a handle to it.
-# internal utility function
-xgb.Booster.handle <- function(params = list(), cachelist = list(), modelfile = NULL) {
- if (typeof(cachelist) != "list" ||
- !all(vapply(cachelist, inherits, logical(1), what = 'xgb.DMatrix'))) {
- stop("cachelist must be a list of xgb.DMatrix objects")
- }
- ## Load existing model, dispatch for on disk model file and in memory buffer
- if (!is.null(modelfile)) {
- if (typeof(modelfile) == "character") {
- ## A filename
- handle <- .Call(XGBoosterCreate_R, cachelist)
- .Call(XGBoosterLoadModel_R, handle, modelfile[1])
- class(handle) <- "xgb.Booster.handle"
- if (length(params) > 0) {
- xgb.parameters(handle) <- params
- }
- return(handle)
- } else if (typeof(modelfile) == "raw") {
- ## A memory buffer
- bst <- xgb.unserialize(modelfile)
- xgb.parameters(bst) <- params
- return (bst)
- } else if (inherits(modelfile, "xgb.Booster")) {
- ## A booster object
- bst <- xgb.Booster.complete(modelfile, saveraw = TRUE)
- bst <- xgb.unserialize(bst$raw)
- xgb.parameters(bst) <- params
- return (bst)
- } else {
- stop("modelfile must be either character filename, or raw booster dump, or xgb.Booster object")
- }
- }
- ## Create new model
- handle <- .Call(XGBoosterCreate_R, cachelist)
- class(handle) <- "xgb.Booster.handle"
- if (length(params) > 0) {
- xgb.parameters(handle) <- params
- }
- return(handle)
-}
-
-# Convert xgb.Booster.handle to xgb.Booster
-# internal utility function
-xgb.handleToBooster <- function(handle, raw = NULL) {
- bst <- list(handle = handle, raw = raw)
- class(bst) <- "xgb.Booster"
- return(bst)
-}
-
-# Check whether xgb.Booster.handle is null
-# internal utility function
-is.null.handle <- function(handle) {
- if (is.null(handle)) return(TRUE)
-
- if (!identical(class(handle), "xgb.Booster.handle"))
- stop("argument type must be xgb.Booster.handle")
-
- if (.Call(XGCheckNullPtr_R, handle))
- return(TRUE)
-
- return(FALSE)
-}
-
-# Return a verified to be valid handle out of either xgb.Booster.handle or xgb.Booster
-# internal utility function
-xgb.get.handle <- function(object) {
- if (inherits(object, "xgb.Booster")) {
- handle <- object$handle
- } else if (inherits(object, "xgb.Booster.handle")) {
- handle <- object
- } else {
- stop("argument must be of either xgb.Booster or xgb.Booster.handle class")
- }
- if (is.null.handle(handle)) {
- stop("invalid xgb.Booster.handle")
- }
- handle
-}
-
-#' Restore missing parts of an incomplete xgb.Booster object.
-#'
-#' It attempts to complete an \code{xgb.Booster} object by restoring either its missing
-#' raw model memory dump (when it has no \code{raw} data but its \code{xgb.Booster.handle} is valid)
-#' or its missing internal handle (when its \code{xgb.Booster.handle} is not valid
-#' but it has a raw Booster memory dump).
-#'
-#' @param object object of class \code{xgb.Booster}
-#' @param saveraw a flag indicating whether to append \code{raw} Booster memory dump data
-#' when it doesn't already exist.
-#'
-#' @details
-#'
-#' While this method is primarily for internal use, it might be useful in some practical situations.
-#'
-#' E.g., when an \code{xgb.Booster} model is saved as an R object and then is loaded as an R object,
-#' its handle (pointer) to an internal xgboost model would be invalid. The majority of xgboost methods
-#' should still work for such a model object since those methods would be using
-#' \code{xgb.Booster.complete} internally. However, one might find it to be more efficient to call the
-#' \code{xgb.Booster.complete} function explicitly once after loading a model as an R-object.
-#' That would prevent further repeated implicit reconstruction of an internal booster model.
-#'
-#' @return
-#' An object of \code{xgb.Booster} class.
-#'
-#' @examples
-#'
-#' data(agaricus.train, package='xgboost')
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#' saveRDS(bst, "xgb.model.rds")
-#'
-#' bst1 <- readRDS("xgb.model.rds")
-#' if (file.exists("xgb.model.rds")) file.remove("xgb.model.rds")
-#' # the handle is invalid:
-#' print(bst1$handle)
-#'
-#' bst1 <- xgb.Booster.complete(bst1)
-#' # now the handle points to a valid internal booster model:
-#' print(bst1$handle)
-#'
-#' @export
-xgb.Booster.complete <- function(object, saveraw = TRUE) {
- if (!inherits(object, "xgb.Booster"))
- stop("argument type must be xgb.Booster")
-
- if (is.null.handle(object$handle)) {
- object$handle <- xgb.Booster.handle(modelfile = object$raw)
- } else {
- if (is.null(object$raw) && saveraw) {
- object$raw <- xgb.serialize(object$handle)
- }
- }
-
- attrs <- xgb.attributes(object)
- if (!is.null(attrs$best_ntreelimit)) {
- object$best_ntreelimit <- as.integer(attrs$best_ntreelimit)
- }
- if (!is.null(attrs$best_iteration)) {
- ## Convert from 0 based back to 1 based.
- object$best_iteration <- as.integer(attrs$best_iteration) + 1
- }
- if (!is.null(attrs$best_score)) {
- object$best_score <- as.numeric(attrs$best_score)
- }
- if (!is.null(attrs$best_msg)) {
- object$best_msg <- attrs$best_msg
- }
- if (!is.null(attrs$niter)) {
- object$niter <- as.integer(attrs$niter)
- }
-
- return(object)
-}
-
-#' Predict method for eXtreme Gradient Boosting model
-#'
-#' Predicted values based on either xgboost model or model handle object.
-#'
-#' @param object Object of class \code{xgb.Booster} or \code{xgb.Booster.handle}
-#' @param newdata takes \code{matrix}, \code{dgCMatrix}, local data file or \code{xgb.DMatrix}.
-#' @param missing Missing is only used when input is dense matrix. Pick a float value that represents
-#' missing values in data (e.g., sometimes 0 or some other extreme value is used).
-#' @param outputmargin whether the prediction should be returned in the for of original untransformed
-#' sum of predictions from boosting iterations' results. E.g., setting \code{outputmargin=TRUE} for
-#' logistic regression would result in predictions for log-odds instead of probabilities.
-#' @param ntreelimit limit the number of model's trees or boosting iterations used in prediction (see Details).
-#' It will use all the trees by default (\code{NULL} value).
-#' @param predleaf whether predict leaf index.
-#' @param predcontrib whether to return feature contributions to individual predictions (see Details).
-#' @param approxcontrib whether to use a fast approximation for feature contributions (see Details).
-#' @param predinteraction whether to return contributions of feature interactions to individual predictions (see Details).
-#' @param reshape whether to reshape the vector of predictions to a matrix form when there are several
-#' prediction outputs per case. This option has no effect when either of predleaf, predcontrib,
-#' or predinteraction flags is TRUE.
-#' @param training whether is the prediction result used for training. For dart booster,
-#' training predicting will perform dropout.
-#' @param ... Parameters passed to \code{predict.xgb.Booster}
-#'
-#' @details
-#' Note that \code{ntreelimit} is not necessarily equal to the number of boosting iterations
-#' and it is not necessarily equal to the number of trees in a model.
-#' E.g., in a random forest-like model, \code{ntreelimit} would limit the number of trees.
-#' But for multiclass classification, while there are multiple trees per iteration,
-#' \code{ntreelimit} limits the number of boosting iterations.
-#'
-#' Also note that \code{ntreelimit} would currently do nothing for predictions from gblinear,
-#' since gblinear doesn't keep its boosting history.
-#'
-#' One possible practical applications of the \code{predleaf} option is to use the model
-#' as a generator of new features which capture non-linearity and interactions,
-#' e.g., as implemented in \code{\link{xgb.create.features}}.
-#'
-#' Setting \code{predcontrib = TRUE} allows to calculate contributions of each feature to
-#' individual predictions. For "gblinear" booster, feature contributions are simply linear terms
-#' (feature_beta * feature_value). For "gbtree" booster, feature contributions are SHAP
-#' values (Lundberg 2017) that sum to the difference between the expected output
-#' of the model and the current prediction (where the hessian weights are used to compute the expectations).
-#' Setting \code{approxcontrib = TRUE} approximates these values following the idea explained
-#' in \url{http://blog.datadive.net/interpreting-random-forests/}.
-#'
-#' With \code{predinteraction = TRUE}, SHAP values of contributions of interaction of each pair of features
-#' are computed. Note that this operation might be rather expensive in terms of compute and memory.
-#' Since it quadratically depends on the number of features, it is recommended to perform selection
-#' of the most important features first. See below about the format of the returned results.
-#'
-#' @return
-#' For regression or binary classification, it returns a vector of length \code{nrows(newdata)}.
-#' For multiclass classification, either a \code{num_class * nrows(newdata)} vector or
-#' a \code{(nrows(newdata), num_class)} dimension matrix is returned, depending on
-#' the \code{reshape} value.
-#'
-#' When \code{predleaf = TRUE}, the output is a matrix object with the
-#' number of columns corresponding to the number of trees.
-#'
-#' When \code{predcontrib = TRUE} and it is not a multiclass setting, the output is a matrix object with
-#' \code{num_features + 1} columns. The last "+ 1" column in a matrix corresponds to bias.
-#' For a multiclass case, a list of \code{num_class} elements is returned, where each element is
-#' such a matrix. The contribution values are on the scale of untransformed margin
-#' (e.g., for binary classification would mean that the contributions are log-odds deviations from bias).
-#'
-#' When \code{predinteraction = TRUE} and it is not a multiclass setting, the output is a 3d array with
-#' dimensions \code{c(nrow, num_features + 1, num_features + 1)}. The off-diagonal (in the last two dimensions)
-#' elements represent different features interaction contributions. The array is symmetric WRT the last
-#' two dimensions. The "+ 1" columns corresponds to bias. Summing this array along the last dimension should
-#' produce practically the same result as predict with \code{predcontrib = TRUE}.
-#' For a multiclass case, a list of \code{num_class} elements is returned, where each element is
-#' such an array.
-#'
-#' @seealso
-#' \code{\link{xgb.train}}.
-#'
-#' @references
-#'
-#' Scott M. Lundberg, Su-In Lee, "A Unified Approach to Interpreting Model Predictions", NIPS Proceedings 2017, \url{https://arxiv.org/abs/1705.07874}
-#'
-#' Scott M. Lundberg, Su-In Lee, "Consistent feature attribution for tree ensembles", \url{https://arxiv.org/abs/1706.06060}
-#'
-#' @examples
-#' ## binary classification:
-#'
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#' train <- agaricus.train
-#' test <- agaricus.test
-#'
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 0.5, nthread = 2, nrounds = 5, objective = "binary:logistic")
-#' # use all trees by default
-#' pred <- predict(bst, test$data)
-#' # use only the 1st tree
-#' pred1 <- predict(bst, test$data, ntreelimit = 1)
-#'
-#' # Predicting tree leafs:
-#' # the result is an nsamples X ntrees matrix
-#' pred_leaf <- predict(bst, test$data, predleaf = TRUE)
-#' str(pred_leaf)
-#'
-#' # Predicting feature contributions to predictions:
-#' # the result is an nsamples X (nfeatures + 1) matrix
-#' pred_contr <- predict(bst, test$data, predcontrib = TRUE)
-#' str(pred_contr)
-#' # verify that contributions' sums are equal to log-odds of predictions (up to float precision):
-#' summary(rowSums(pred_contr) - qlogis(pred))
-#' # for the 1st record, let's inspect its features that had non-zero contribution to prediction:
-#' contr1 <- pred_contr[1,]
-#' contr1 <- contr1[-length(contr1)] # drop BIAS
-#' contr1 <- contr1[contr1 != 0] # drop non-contributing features
-#' contr1 <- contr1[order(abs(contr1))] # order by contribution magnitude
-#' old_mar <- par("mar")
-#' par(mar = old_mar + c(0,7,0,0))
-#' barplot(contr1, horiz = TRUE, las = 2, xlab = "contribution to prediction in log-odds")
-#' par(mar = old_mar)
-#'
-#'
-#' ## multiclass classification in iris dataset:
-#'
-#' lb <- as.numeric(iris$Species) - 1
-#' num_class <- 3
-#' set.seed(11)
-#' bst <- xgboost(data = as.matrix(iris[, -5]), label = lb,
-#' max_depth = 4, eta = 0.5, nthread = 2, nrounds = 10, subsample = 0.5,
-#' objective = "multi:softprob", num_class = num_class)
-#' # predict for softmax returns num_class probability numbers per case:
-#' pred <- predict(bst, as.matrix(iris[, -5]))
-#' str(pred)
-#' # reshape it to a num_class-columns matrix
-#' pred <- matrix(pred, ncol=num_class, byrow=TRUE)
-#' # convert the probabilities to softmax labels
-#' pred_labels <- max.col(pred) - 1
-#' # the following should result in the same error as seen in the last iteration
-#' sum(pred_labels != lb)/length(lb)
-#'
-#' # compare that to the predictions from softmax:
-#' set.seed(11)
-#' bst <- xgboost(data = as.matrix(iris[, -5]), label = lb,
-#' max_depth = 4, eta = 0.5, nthread = 2, nrounds = 10, subsample = 0.5,
-#' objective = "multi:softmax", num_class = num_class)
-#' pred <- predict(bst, as.matrix(iris[, -5]))
-#' str(pred)
-#' all.equal(pred, pred_labels)
-#' # prediction from using only 5 iterations should result
-#' # in the same error as seen in iteration 5:
-#' pred5 <- predict(bst, as.matrix(iris[, -5]), ntreelimit=5)
-#' sum(pred5 != lb)/length(lb)
-#'
-#'
-#' ## random forest-like model of 25 trees for binary classification:
-#'
-#' set.seed(11)
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 5,
-#' nthread = 2, nrounds = 1, objective = "binary:logistic",
-#' num_parallel_tree = 25, subsample = 0.6, colsample_bytree = 0.1)
-#' # Inspect the prediction error vs number of trees:
-#' lb <- test$label
-#' dtest <- xgb.DMatrix(test$data, label=lb)
-#' err <- sapply(1:25, function(n) {
-#' pred <- predict(bst, dtest, ntreelimit=n)
-#' sum((pred > 0.5) != lb)/length(lb)
-#' })
-#' plot(err, type='l', ylim=c(0,0.1), xlab='#trees')
-#'
-#' @rdname predict.xgb.Booster
-#' @export
-predict.xgb.Booster <- function(object, newdata, missing = NA, outputmargin = FALSE, ntreelimit = NULL,
- predleaf = FALSE, predcontrib = FALSE, approxcontrib = FALSE, predinteraction = FALSE,
- reshape = FALSE, training = FALSE, ...) {
-
- object <- xgb.Booster.complete(object, saveraw = FALSE)
- if (!inherits(newdata, "xgb.DMatrix"))
- newdata <- xgb.DMatrix(newdata, missing = missing)
- if (!is.null(object[["feature_names"]]) &&
- !is.null(colnames(newdata)) &&
- !identical(object[["feature_names"]], colnames(newdata)))
- stop("Feature names stored in `object` and `newdata` are different!")
- if (is.null(ntreelimit))
- ntreelimit <- NVL(object$best_ntreelimit, 0)
- if (NVL(object$params[['booster']], '') == 'gblinear')
- ntreelimit <- 0
- if (ntreelimit < 0)
- stop("ntreelimit cannot be negative")
-
- option <- 0L + 1L * as.logical(outputmargin) + 2L * as.logical(predleaf) + 4L * as.logical(predcontrib) +
- 8L * as.logical(approxcontrib) + 16L * as.logical(predinteraction)
-
- ret <- .Call(XGBoosterPredict_R, object$handle, newdata, option[1],
- as.integer(ntreelimit), as.integer(training))
-
- n_ret <- length(ret)
- n_row <- nrow(newdata)
- npred_per_case <- n_ret / n_row
-
- if (n_ret %% n_row != 0)
- stop("prediction length ", n_ret, " is not multiple of nrows(newdata) ", n_row)
-
- if (predleaf) {
- ret <- if (n_ret == n_row) {
- matrix(ret, ncol = 1)
- } else {
- matrix(ret, nrow = n_row, byrow = TRUE)
- }
- } else if (predcontrib) {
- n_col1 <- ncol(newdata) + 1
- n_group <- npred_per_case / n_col1
- cnames <- if (!is.null(colnames(newdata))) c(colnames(newdata), "BIAS") else NULL
- ret <- if (n_ret == n_row) {
- matrix(ret, ncol = 1, dimnames = list(NULL, cnames))
- } else if (n_group == 1) {
- matrix(ret, nrow = n_row, byrow = TRUE, dimnames = list(NULL, cnames))
- } else {
- arr <- array(ret, c(n_col1, n_group, n_row),
- dimnames = list(cnames, NULL, NULL)) %>% aperm(c(2,3,1)) # [group, row, col]
- lapply(seq_len(n_group), function(g) arr[g,,])
- }
- } else if (predinteraction) {
- n_col1 <- ncol(newdata) + 1
- n_group <- npred_per_case / n_col1^2
- cnames <- if (!is.null(colnames(newdata))) c(colnames(newdata), "BIAS") else NULL
- ret <- if (n_ret == n_row) {
- matrix(ret, ncol = 1, dimnames = list(NULL, cnames))
- } else if (n_group == 1) {
- array(ret, c(n_col1, n_col1, n_row), dimnames = list(cnames, cnames, NULL)) %>% aperm(c(3,1,2))
- } else {
- arr <- array(ret, c(n_col1, n_col1, n_group, n_row),
- dimnames = list(cnames, cnames, NULL, NULL)) %>% aperm(c(3,4,1,2)) # [group, row, col1, col2]
- lapply(seq_len(n_group), function(g) arr[g,,,])
- }
- } else if (reshape && npred_per_case > 1) {
- ret <- matrix(ret, nrow = n_row, byrow = TRUE)
- }
- return(ret)
-}
-
-#' @rdname predict.xgb.Booster
-#' @export
-predict.xgb.Booster.handle <- function(object, ...) {
-
- bst <- xgb.handleToBooster(object)
-
- ret <- predict(bst, ...)
- return(ret)
-}
-
-
-#' Accessors for serializable attributes of a model.
-#'
-#' These methods allow to manipulate the key-value attribute strings of an xgboost model.
-#'
-#' @param object Object of class \code{xgb.Booster} or \code{xgb.Booster.handle}.
-#' @param name a non-empty character string specifying which attribute is to be accessed.
-#' @param value a value of an attribute for \code{xgb.attr<-}; for \code{xgb.attributes<-}
-#' it's a list (or an object coercible to a list) with the names of attributes to set
-#' and the elements corresponding to attribute values.
-#' Non-character values are converted to character.
-#' When attribute value is not a scalar, only the first index is used.
-#' Use \code{NULL} to remove an attribute.
-#'
-#' @details
-#' The primary purpose of xgboost model attributes is to store some meta-data about the model.
-#' Note that they are a separate concept from the object attributes in R.
-#' Specifically, they refer to key-value strings that can be attached to an xgboost model,
-#' stored together with the model's binary representation, and accessed later
-#' (from R or any other interface).
-#' In contrast, any R-attribute assigned to an R-object of \code{xgb.Booster} class
-#' would not be saved by \code{xgb.save} because an xgboost model is an external memory object
-#' and its serialization is handled externally.
-#' Also, setting an attribute that has the same name as one of xgboost's parameters wouldn't
-#' change the value of that parameter for a model.
-#' Use \code{\link{xgb.parameters<-}} to set or change model parameters.
-#'
-#' The attribute setters would usually work more efficiently for \code{xgb.Booster.handle}
-#' than for \code{xgb.Booster}, since only just a handle (pointer) would need to be copied.
-#' That would only matter if attributes need to be set many times.
-#' Note, however, that when feeding a handle of an \code{xgb.Booster} object to the attribute setters,
-#' the raw model cache of an \code{xgb.Booster} object would not be automatically updated,
-#' and it would be user's responsibility to call \code{xgb.serialize} to update it.
-#'
-#' The \code{xgb.attributes<-} setter either updates the existing or adds one or several attributes,
-#' but it doesn't delete the other existing attributes.
-#'
-#' @return
-#' \code{xgb.attr} returns either a string value of an attribute
-#' or \code{NULL} if an attribute wasn't stored in a model.
-#'
-#' \code{xgb.attributes} returns a list of all attribute stored in a model
-#' or \code{NULL} if a model has no stored attributes.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#'
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#'
-#' xgb.attr(bst, "my_attribute") <- "my attribute value"
-#' print(xgb.attr(bst, "my_attribute"))
-#' xgb.attributes(bst) <- list(a = 123, b = "abc")
-#'
-#' xgb.save(bst, 'xgb.model')
-#' bst1 <- xgb.load('xgb.model')
-#' if (file.exists('xgb.model')) file.remove('xgb.model')
-#' print(xgb.attr(bst1, "my_attribute"))
-#' print(xgb.attributes(bst1))
-#'
-#' # deletion:
-#' xgb.attr(bst1, "my_attribute") <- NULL
-#' print(xgb.attributes(bst1))
-#' xgb.attributes(bst1) <- list(a = NULL, b = NULL)
-#' print(xgb.attributes(bst1))
-#'
-#' @rdname xgb.attr
-#' @export
-xgb.attr <- function(object, name) {
- if (is.null(name) || nchar(as.character(name[1])) == 0) stop("invalid attribute name")
- handle <- xgb.get.handle(object)
- .Call(XGBoosterGetAttr_R, handle, as.character(name[1]))
-}
-
-#' @rdname xgb.attr
-#' @export
-`xgb.attr<-` <- function(object, name, value) {
- if (is.null(name) || nchar(as.character(name[1])) == 0) stop("invalid attribute name")
- handle <- xgb.get.handle(object)
- if (!is.null(value)) {
- # Coerce the elements to be scalar strings.
- # Q: should we warn user about non-scalar elements?
- if (is.numeric(value[1])) {
- value <- format(value[1], digits = 17)
- } else {
- value <- as.character(value[1])
- }
- }
- .Call(XGBoosterSetAttr_R, handle, as.character(name[1]), value)
- if (is(object, 'xgb.Booster') && !is.null(object$raw)) {
- object$raw <- xgb.serialize(object$handle)
- }
- object
-}
-
-#' @rdname xgb.attr
-#' @export
-xgb.attributes <- function(object) {
- handle <- xgb.get.handle(object)
- attr_names <- .Call(XGBoosterGetAttrNames_R, handle)
- if (is.null(attr_names)) return(NULL)
- res <- lapply(attr_names, function(x) {
- .Call(XGBoosterGetAttr_R, handle, x)
- })
- names(res) <- attr_names
- res
-}
-
-#' @rdname xgb.attr
-#' @export
-`xgb.attributes<-` <- function(object, value) {
- a <- as.list(value)
- if (is.null(names(a)) || any(nchar(names(a)) == 0)) {
- stop("attribute names cannot be empty strings")
- }
- # Coerce the elements to be scalar strings.
- # Q: should we warn a user about non-scalar elements?
- a <- lapply(a, function(x) {
- if (is.null(x)) return(NULL)
- if (is.numeric(x[1])) {
- format(x[1], digits = 17)
- } else {
- as.character(x[1])
- }
- })
- handle <- xgb.get.handle(object)
- for (i in seq_along(a)) {
- .Call(XGBoosterSetAttr_R, handle, names(a[i]), a[[i]])
- }
- if (is(object, 'xgb.Booster') && !is.null(object$raw)) {
- object$raw <- xgb.serialize(object$handle)
- }
- object
-}
-
-#' Accessors for model parameters as JSON string.
-#'
-#' @param object Object of class \code{xgb.Booster}
-#' @param value A JSON string.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#'
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#' config <- xgb.config(bst)
-#'
-#' @rdname xgb.config
-#' @export
-xgb.config <- function(object) {
- handle <- xgb.get.handle(object)
- .Call(XGBoosterSaveJsonConfig_R, handle);
-}
-
-#' @rdname xgb.config
-#' @export
-`xgb.config<-` <- function(object, value) {
- handle <- xgb.get.handle(object)
- .Call(XGBoosterLoadJsonConfig_R, handle, value)
- object$raw <- NULL # force renew the raw buffer
- object <- xgb.Booster.complete(object)
- object
-}
-
-#' Accessors for model parameters.
-#'
-#' Only the setter for xgboost parameters is currently implemented.
-#'
-#' @param object Object of class \code{xgb.Booster} or \code{xgb.Booster.handle}.
-#' @param value a list (or an object coercible to a list) with the names of parameters to set
-#' and the elements corresponding to parameter values.
-#'
-#' @details
-#' Note that the setter would usually work more efficiently for \code{xgb.Booster.handle}
-#' than for \code{xgb.Booster}, since only just a handle would need to be copied.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#'
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#'
-#' xgb.parameters(bst) <- list(eta = 0.1)
-#'
-#' @rdname xgb.parameters
-#' @export
-`xgb.parameters<-` <- function(object, value) {
- if (length(value) == 0) return(object)
- p <- as.list(value)
- if (is.null(names(p)) || any(nchar(names(p)) == 0)) {
- stop("parameter names cannot be empty strings")
- }
- names(p) <- gsub("\\.", "_", names(p))
- p <- lapply(p, function(x) as.character(x)[1])
- handle <- xgb.get.handle(object)
- for (i in seq_along(p)) {
- .Call(XGBoosterSetParam_R, handle, names(p[i]), p[[i]])
- }
- if (is(object, 'xgb.Booster') && !is.null(object$raw)) {
- object$raw <- xgb.serialize(object$handle)
- }
- object
-}
-
-# Extract the number of trees in a model.
-# TODO: either add a getter to C-interface, or simply set an 'ntree' attribute after each iteration.
-# internal utility function
-xgb.ntree <- function(bst) {
- length(grep('^booster', xgb.dump(bst)))
-}
-
-
-#' Print xgb.Booster
-#'
-#' Print information about xgb.Booster.
-#'
-#' @param x an xgb.Booster object
-#' @param verbose whether to print detailed data (e.g., attribute values)
-#' @param ... not currently used
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#' attr(bst, 'myattr') <- 'memo'
-#'
-#' print(bst)
-#' print(bst, verbose=TRUE)
-#'
-#' @method print xgb.Booster
-#' @export
-print.xgb.Booster <- function(x, verbose = FALSE, ...) {
- cat('##### xgb.Booster\n')
-
- valid_handle <- !is.null.handle(x$handle)
- if (!valid_handle)
- cat("Handle is invalid! Suggest using xgb.Booster.complete\n")
-
- cat('raw: ')
- if (!is.null(x$raw)) {
- cat(format(object.size(x$raw), units = "auto"), '\n')
- } else {
- cat('NULL\n')
- }
- if (!is.null(x$call)) {
- cat('call:\n ')
- print(x$call)
- }
-
- if (!is.null(x$params)) {
- cat('params (as set within xgb.train):\n')
- cat( ' ',
- paste(names(x$params),
- paste0('"', unlist(x$params), '"'),
- sep = ' = ', collapse = ', '), '\n', sep = '')
- }
- # TODO: need an interface to access all the xgboosts parameters
-
- attrs <- character(0)
- if (valid_handle)
- attrs <- xgb.attributes(x)
- if (length(attrs) > 0) {
- cat('xgb.attributes:\n')
- if (verbose) {
- cat( paste(paste0(' ',names(attrs)),
- paste0('"', unlist(attrs), '"'),
- sep = ' = ', collapse = '\n'), '\n', sep = '')
- } else {
- cat(' ', paste(names(attrs), collapse = ', '), '\n', sep = '')
- }
- }
-
- if (!is.null(x$callbacks) && length(x$callbacks) > 0) {
- cat('callbacks:\n')
- lapply(callback.calls(x$callbacks), function(x) {
- cat(' ')
- print(x)
- })
- }
-
- if (!is.null(x$feature_names))
- cat('# of features:', length(x$feature_names), '\n')
-
- cat('niter: ', x$niter, '\n', sep = '')
- # TODO: uncomment when faster xgb.ntree is implemented
- #cat('ntree: ', xgb.ntree(x), '\n', sep='')
-
- for (n in setdiff(names(x), c('handle', 'raw', 'call', 'params', 'callbacks',
- 'evaluation_log','niter','feature_names'))) {
- if (is.atomic(x[[n]])) {
- cat(n, ':', x[[n]], '\n', sep = ' ')
- } else {
- cat(n, ':\n\t', sep = ' ')
- print(x[[n]])
- }
- }
-
- if (!is.null(x$evaluation_log)) {
- cat('evaluation_log:\n')
- print(x$evaluation_log, row.names = FALSE, topn = 2)
- }
-
- invisible(x)
-}
diff --git a/ml-xgboost/R-package/R/xgb.DMatrix.R b/ml-xgboost/R-package/R/xgb.DMatrix.R
deleted file mode 100644
index 4201a83..0000000
--- a/ml-xgboost/R-package/R/xgb.DMatrix.R
+++ /dev/null
@@ -1,380 +0,0 @@
-#' Construct xgb.DMatrix object
-#'
-#' Construct xgb.DMatrix object from either a dense matrix, a sparse matrix, or a local file.
-#' Supported input file formats are either a libsvm text file or a binary file that was created previously by
-#' \code{\link{xgb.DMatrix.save}}).
-#'
-#' @param data a \code{matrix} object (either numeric or integer), a \code{dgCMatrix} object, or a character
-#' string representing a filename.
-#' @param info a named list of additional information to store in the \code{xgb.DMatrix} object.
-#' See \code{\link{setinfo}} for the specific allowed kinds of
-#' @param missing a float value to represents missing values in data (used only when input is a dense matrix).
-#' It is useful when a 0 or some other extreme value represents missing values in data.
-#' @param silent whether to suppress printing an informational message after loading from a file.
-#' @param ... the \code{info} data could be passed directly as parameters, without creating an \code{info} list.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#' xgb.DMatrix.save(dtrain, 'xgb.DMatrix.data')
-#' dtrain <- xgb.DMatrix('xgb.DMatrix.data')
-#' if (file.exists('xgb.DMatrix.data')) file.remove('xgb.DMatrix.data')
-#' @export
-xgb.DMatrix <- function(data, info = list(), missing = NA, silent = FALSE, ...) {
- cnames <- NULL
- if (typeof(data) == "character") {
- if (length(data) > 1)
- stop("'data' has class 'character' and length ", length(data),
- ".\n 'data' accepts either a numeric matrix or a single filename.")
- handle <- .Call(XGDMatrixCreateFromFile_R, data, as.integer(silent))
- } else if (is.matrix(data)) {
- handle <- .Call(XGDMatrixCreateFromMat_R, data, missing)
- cnames <- colnames(data)
- } else if (inherits(data, "dgCMatrix")) {
- handle <- .Call(XGDMatrixCreateFromCSC_R, data@p, data@i, data@x, nrow(data))
- cnames <- colnames(data)
- } else {
- stop("xgb.DMatrix does not support construction from ", typeof(data))
- }
- dmat <- handle
- attributes(dmat) <- list(.Dimnames = list(NULL, cnames), class = "xgb.DMatrix")
-
- info <- append(info, list(...))
- for (i in seq_along(info)) {
- p <- info[i]
- setinfo(dmat, names(p), p[[1]])
- }
- return(dmat)
-}
-
-
-# get dmatrix from data, label
-# internal helper method
-xgb.get.DMatrix <- function(data, label = NULL, missing = NA, weight = NULL) {
- if (inherits(data, "dgCMatrix") || is.matrix(data)) {
- if (is.null(label)) {
- stop("label must be provided when data is a matrix")
- }
- dtrain <- xgb.DMatrix(data, label = label, missing = missing)
- if (!is.null(weight)){
- setinfo(dtrain, "weight", weight)
- }
- } else {
- if (!is.null(label)) {
- warning("xgboost: label will be ignored.")
- }
- if (is.character(data)) {
- dtrain <- xgb.DMatrix(data[1])
- } else if (inherits(data, "xgb.DMatrix")) {
- dtrain <- data
- } else if (inherits(data, "data.frame")) {
- stop("xgboost doesn't support data.frame as input. Convert it to matrix first.")
- } else {
- stop("xgboost: invalid input data")
- }
- }
- return (dtrain)
-}
-
-
-#' Dimensions of xgb.DMatrix
-#'
-#' Returns a vector of numbers of rows and of columns in an \code{xgb.DMatrix}.
-#' @param x Object of class \code{xgb.DMatrix}
-#'
-#' @details
-#' Note: since \code{nrow} and \code{ncol} internally use \code{dim}, they can also
-#' be directly used with an \code{xgb.DMatrix} object.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#'
-#' stopifnot(nrow(dtrain) == nrow(train$data))
-#' stopifnot(ncol(dtrain) == ncol(train$data))
-#' stopifnot(all(dim(dtrain) == dim(train$data)))
-#'
-#' @export
-dim.xgb.DMatrix <- function(x) {
- c(.Call(XGDMatrixNumRow_R, x), .Call(XGDMatrixNumCol_R, x))
-}
-
-
-#' Handling of column names of \code{xgb.DMatrix}
-#'
-#' Only column names are supported for \code{xgb.DMatrix}, thus setting of
-#' row names would have no effect and returned row names would be NULL.
-#'
-#' @param x object of class \code{xgb.DMatrix}
-#' @param value a list of two elements: the first one is ignored
-#' and the second one is column names
-#'
-#' @details
-#' Generic \code{dimnames} methods are used by \code{colnames}.
-#' Since row names are irrelevant, it is recommended to use \code{colnames} directly.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#' dimnames(dtrain)
-#' colnames(dtrain)
-#' colnames(dtrain) <- make.names(1:ncol(train$data))
-#' print(dtrain, verbose=TRUE)
-#'
-#' @rdname dimnames.xgb.DMatrix
-#' @export
-dimnames.xgb.DMatrix <- function(x) {
- attr(x, '.Dimnames')
-}
-
-#' @rdname dimnames.xgb.DMatrix
-#' @export
-`dimnames<-.xgb.DMatrix` <- function(x, value) {
- if (!is.list(value) || length(value) != 2L)
- stop("invalid 'dimnames' given: must be a list of two elements")
- if (!is.null(value[[1L]]))
- stop("xgb.DMatrix does not have rownames")
- if (is.null(value[[2]])) {
- attr(x, '.Dimnames') <- NULL
- return(x)
- }
- if (ncol(x) != length(value[[2]]))
- stop("can't assign ", length(value[[2]]), " colnames to a ",
- ncol(x), " column xgb.DMatrix")
- attr(x, '.Dimnames') <- value
- x
-}
-
-
-#' Get information of an xgb.DMatrix object
-#'
-#' Get information of an xgb.DMatrix object
-#' @param object Object of class \code{xgb.DMatrix}
-#' @param name the name of the information field to get (see details)
-#' @param ... other parameters
-#'
-#' @details
-#' The \code{name} field can be one of the following:
-#'
-#' \itemize{
-#' \item \code{label}: label Xgboost learn from ;
-#' \item \code{weight}: to do a weight rescale ;
-#' \item \code{base_margin}: base margin is the base prediction Xgboost will boost from ;
-#' \item \code{nrow}: number of rows of the \code{xgb.DMatrix}.
-#'
-#' }
-#'
-#' \code{group} can be setup by \code{setinfo} but can't be retrieved by \code{getinfo}.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#'
-#' labels <- getinfo(dtrain, 'label')
-#' setinfo(dtrain, 'label', 1-labels)
-#'
-#' labels2 <- getinfo(dtrain, 'label')
-#' stopifnot(all(labels2 == 1-labels))
-#' @rdname getinfo
-#' @export
-getinfo <- function(object, ...) UseMethod("getinfo")
-
-#' @rdname getinfo
-#' @export
-getinfo.xgb.DMatrix <- function(object, name, ...) {
- if (typeof(name) != "character" ||
- length(name) != 1 ||
- !name %in% c('label', 'weight', 'base_margin', 'nrow',
- 'label_lower_bound', 'label_upper_bound')) {
- stop("getinfo: name must be one of the following\n",
- " 'label', 'weight', 'base_margin', 'nrow', 'label_lower_bound', 'label_upper_bound'")
- }
- if (name != "nrow"){
- ret <- .Call(XGDMatrixGetInfo_R, object, name)
- } else {
- ret <- nrow(object)
- }
- if (length(ret) == 0) return(NULL)
- return(ret)
-}
-
-
-#' Set information of an xgb.DMatrix object
-#'
-#' Set information of an xgb.DMatrix object
-#'
-#' @param object Object of class "xgb.DMatrix"
-#' @param name the name of the field to get
-#' @param info the specific field of information to set
-#' @param ... other parameters
-#'
-#' @details
-#' The \code{name} field can be one of the following:
-#'
-#' \itemize{
-#' \item \code{label}: label Xgboost learn from ;
-#' \item \code{weight}: to do a weight rescale ;
-#' \item \code{base_margin}: base margin is the base prediction Xgboost will boost from ;
-#' \item \code{group}: number of rows in each group (to use with \code{rank:pairwise} objective).
-#' }
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#'
-#' labels <- getinfo(dtrain, 'label')
-#' setinfo(dtrain, 'label', 1-labels)
-#' labels2 <- getinfo(dtrain, 'label')
-#' stopifnot(all.equal(labels2, 1-labels))
-#' @rdname setinfo
-#' @export
-setinfo <- function(object, ...) UseMethod("setinfo")
-
-#' @rdname setinfo
-#' @export
-setinfo.xgb.DMatrix <- function(object, name, info, ...) {
- if (name == "label") {
- if (length(info) != nrow(object))
- stop("The length of labels must equal to the number of rows in the input data")
- .Call(XGDMatrixSetInfo_R, object, name, as.numeric(info))
- return(TRUE)
- }
- if (name == "label_lower_bound") {
- if (length(info) != nrow(object))
- stop("The length of lower-bound labels must equal to the number of rows in the input data")
- .Call(XGDMatrixSetInfo_R, object, name, as.numeric(info))
- return(TRUE)
- }
- if (name == "label_upper_bound") {
- if (length(info) != nrow(object))
- stop("The length of upper-bound labels must equal to the number of rows in the input data")
- .Call(XGDMatrixSetInfo_R, object, name, as.numeric(info))
- return(TRUE)
- }
- if (name == "weight") {
- if (length(info) != nrow(object))
- stop("The length of weights must equal to the number of rows in the input data")
- .Call(XGDMatrixSetInfo_R, object, name, as.numeric(info))
- return(TRUE)
- }
- if (name == "base_margin") {
- # if (length(info)!=nrow(object))
- # stop("The length of base margin must equal to the number of rows in the input data")
- .Call(XGDMatrixSetInfo_R, object, name, as.numeric(info))
- return(TRUE)
- }
- if (name == "group") {
- if (sum(info) != nrow(object))
- stop("The sum of groups must equal to the number of rows in the input data")
- .Call(XGDMatrixSetInfo_R, object, name, as.integer(info))
- return(TRUE)
- }
- stop("setinfo: unknown info name ", name)
- return(FALSE)
-}
-
-
-#' Get a new DMatrix containing the specified rows of
-#' original xgb.DMatrix object
-#'
-#' Get a new DMatrix containing the specified rows of
-#' original xgb.DMatrix object
-#'
-#' @param object Object of class "xgb.DMatrix"
-#' @param idxset a integer vector of indices of rows needed
-#' @param colset currently not used (columns subsetting is not available)
-#' @param ... other parameters (currently not used)
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#'
-#' dsub <- slice(dtrain, 1:42)
-#' labels1 <- getinfo(dsub, 'label')
-#' dsub <- dtrain[1:42, ]
-#' labels2 <- getinfo(dsub, 'label')
-#' all.equal(labels1, labels2)
-#'
-#' @rdname slice.xgb.DMatrix
-#' @export
-slice <- function(object, ...) UseMethod("slice")
-
-#' @rdname slice.xgb.DMatrix
-#' @export
-slice.xgb.DMatrix <- function(object, idxset, ...) {
- if (!inherits(object, "xgb.DMatrix")) {
- stop("object must be xgb.DMatrix")
- }
- ret <- .Call(XGDMatrixSliceDMatrix_R, object, idxset)
-
- attr_list <- attributes(object)
- nr <- nrow(object)
- len <- sapply(attr_list, NROW)
- ind <- which(len == nr)
- if (length(ind) > 0) {
- nms <- names(attr_list)[ind]
- for (i in seq_along(ind)) {
- obj_attr <- attr(object, nms[i])
- if (NCOL(obj_attr) > 1) {
- attr(ret, nms[i]) <- obj_attr[idxset,]
- } else {
- attr(ret, nms[i]) <- obj_attr[idxset]
- }
- }
- }
- return(structure(ret, class = "xgb.DMatrix"))
-}
-
-#' @rdname slice.xgb.DMatrix
-#' @export
-`[.xgb.DMatrix` <- function(object, idxset, colset = NULL) {
- slice(object, idxset)
-}
-
-
-#' Print xgb.DMatrix
-#'
-#' Print information about xgb.DMatrix.
-#' Currently it displays dimensions and presence of info-fields and colnames.
-#'
-#' @param x an xgb.DMatrix object
-#' @param verbose whether to print colnames (when present)
-#' @param ... not currently used
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#'
-#' dtrain
-#' print(dtrain, verbose=TRUE)
-#'
-#' @method print xgb.DMatrix
-#' @export
-print.xgb.DMatrix <- function(x, verbose = FALSE, ...) {
- cat('xgb.DMatrix dim:', nrow(x), 'x', ncol(x), ' info: ')
- infos <- c()
- if(length(getinfo(x, 'label')) > 0) infos <- 'label'
- if(length(getinfo(x, 'weight')) > 0) infos <- c(infos, 'weight')
- if(length(getinfo(x, 'base_margin')) > 0) infos <- c(infos, 'base_margin')
- if (length(infos) == 0) infos <- 'NA'
- cat(infos)
- cnames <- colnames(x)
- cat(' colnames:')
- if (verbose & !is.null(cnames)) {
- cat("\n'")
- cat(cnames, sep = "','")
- cat("'")
- } else {
- if (is.null(cnames)) cat(' no')
- else cat(' yes')
- }
- cat("\n")
- invisible(x)
-}
diff --git a/ml-xgboost/R-package/R/xgb.DMatrix.save.R b/ml-xgboost/R-package/R/xgb.DMatrix.save.R
deleted file mode 100644
index 1c659e5..0000000
--- a/ml-xgboost/R-package/R/xgb.DMatrix.save.R
+++ /dev/null
@@ -1,24 +0,0 @@
-#' Save xgb.DMatrix object to binary file
-#'
-#' Save xgb.DMatrix object to binary file
-#'
-#' @param dmatrix the \code{xgb.DMatrix} object
-#' @param fname the name of the file to write.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' dtrain <- xgb.DMatrix(train$data, label=train$label)
-#' xgb.DMatrix.save(dtrain, 'xgb.DMatrix.data')
-#' dtrain <- xgb.DMatrix('xgb.DMatrix.data')
-#' if (file.exists('xgb.DMatrix.data')) file.remove('xgb.DMatrix.data')
-#' @export
-xgb.DMatrix.save <- function(dmatrix, fname) {
- if (typeof(fname) != "character")
- stop("fname must be character")
- if (!inherits(dmatrix, "xgb.DMatrix"))
- stop("dmatrix must be xgb.DMatrix")
-
- .Call(XGDMatrixSaveBinary_R, dmatrix, fname[1], 0L)
- return(TRUE)
-}
diff --git a/ml-xgboost/R-package/R/xgb.create.features.R b/ml-xgboost/R-package/R/xgb.create.features.R
deleted file mode 100644
index b8be649..0000000
--- a/ml-xgboost/R-package/R/xgb.create.features.R
+++ /dev/null
@@ -1,87 +0,0 @@
-#' Create new features from a previously learned model
-#'
-#' May improve the learning by adding new features to the training data based on the decision trees from a previously learned model.
-#'
-#' @param model decision tree boosting model learned on the original data
-#' @param data original data (usually provided as a \code{dgCMatrix} matrix)
-#' @param ... currently not used
-#'
-#' @return \code{dgCMatrix} matrix including both the original data and the new features.
-#'
-#' @details
-#' This is the function inspired from the paragraph 3.1 of the paper:
-#'
-#' \strong{Practical Lessons from Predicting Clicks on Ads at Facebook}
-#'
-#' \emph{(Xinran He, Junfeng Pan, Ou Jin, Tianbing Xu, Bo Liu, Tao Xu, Yan, xin Shi, Antoine Atallah, Ralf Herbrich, Stuart Bowers,
-#' Joaquin Quinonero Candela)}
-#'
-#' International Workshop on Data Mining for Online Advertising (ADKDD) - August 24, 2014
-#'
-#' \url{https://research.fb.com/publications/practical-lessons-from-predicting-clicks-on-ads-at-facebook/}.
-#'
-#' Extract explaining the method:
-#'
-#' "We found that boosted decision trees are a powerful and very
-#' convenient way to implement non-linear and tuple transformations
-#' of the kind we just described. We treat each individual
-#' tree as a categorical feature that takes as value the
-#' index of the leaf an instance ends up falling in. We use
-#' 1-of-K coding of this type of features.
-#'
-#' For example, consider the boosted tree model in Figure 1 with 2 subtrees,
-#' where the first subtree has 3 leafs and the second 2 leafs. If an
-#' instance ends up in leaf 2 in the first subtree and leaf 1 in
-#' second subtree, the overall input to the linear classifier will
-#' be the binary vector \code{[0, 1, 0, 1, 0]}, where the first 3 entries
-#' correspond to the leaves of the first subtree and last 2 to
-#' those of the second subtree.
-#'
-#' [...]
-#'
-#' We can understand boosted decision tree
-#' based transformation as a supervised feature encoding that
-#' converts a real-valued vector into a compact binary-valued
-#' vector. A traversal from root node to a leaf node represents
-#' a rule on certain features."
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#' dtrain <- xgb.DMatrix(data = agaricus.train$data, label = agaricus.train$label)
-#' dtest <- xgb.DMatrix(data = agaricus.test$data, label = agaricus.test$label)
-#'
-#' param <- list(max_depth=2, eta=1, silent=1, objective='binary:logistic')
-#' nrounds = 4
-#'
-#' bst = xgb.train(params = param, data = dtrain, nrounds = nrounds, nthread = 2)
-#'
-#' # Model accuracy without new features
-#' accuracy.before <- sum((predict(bst, agaricus.test$data) >= 0.5) == agaricus.test$label) /
-#' length(agaricus.test$label)
-#'
-#' # Convert previous features to one hot encoding
-#' new.features.train <- xgb.create.features(model = bst, agaricus.train$data)
-#' new.features.test <- xgb.create.features(model = bst, agaricus.test$data)
-#'
-#' # learning with new features
-#' new.dtrain <- xgb.DMatrix(data = new.features.train, label = agaricus.train$label)
-#' new.dtest <- xgb.DMatrix(data = new.features.test, label = agaricus.test$label)
-#' watchlist <- list(train = new.dtrain)
-#' bst <- xgb.train(params = param, data = new.dtrain, nrounds = nrounds, nthread = 2)
-#'
-#' # Model accuracy with new features
-#' accuracy.after <- sum((predict(bst, new.dtest) >= 0.5) == agaricus.test$label) /
-#' length(agaricus.test$label)
-#'
-#' # Here the accuracy was already good and is now perfect.
-#' cat(paste("The accuracy was", accuracy.before, "before adding leaf features and it is now",
-#' accuracy.after, "!\n"))
-#'
-#' @export
-xgb.create.features <- function(model, data, ...){
- check.deprecation(...)
- pred_with_leaf <- predict(model, data, predleaf = TRUE)
- cols <- lapply(as.data.frame(pred_with_leaf), factor)
- cbind(data, sparse.model.matrix( ~ . -1, cols))
-}
diff --git a/ml-xgboost/R-package/R/xgb.cv.R b/ml-xgboost/R-package/R/xgb.cv.R
deleted file mode 100644
index fdfcb59..0000000
--- a/ml-xgboost/R-package/R/xgb.cv.R
+++ /dev/null
@@ -1,319 +0,0 @@
-#' Cross Validation
-#'
-#' The cross validation function of xgboost
-#'
-#' @param params the list of parameters. Commonly used ones are:
-#' \itemize{
-#' \item \code{objective} objective function, common ones are
-#' \itemize{
-#' \item \code{reg:squarederror} Regression with squared loss
-#' \item \code{binary:logistic} logistic regression for classification
-#' }
-#' \item \code{eta} step size of each boosting step
-#' \item \code{max_depth} maximum depth of the tree
-#' \item \code{nthread} number of thread used in training, if not set, all threads are used
-#' }
-#'
-#' See \code{\link{xgb.train}} for further details.
-#' See also demo/ for walkthrough example in R.
-#' @param data takes an \code{xgb.DMatrix}, \code{matrix}, or \code{dgCMatrix} as the input.
-#' @param nrounds the max number of iterations
-#' @param nfold the original dataset is randomly partitioned into \code{nfold} equal size subsamples.
-#' @param label vector of response values. Should be provided only when data is an R-matrix.
-#' @param missing is only used when input is a dense matrix. By default is set to NA, which means
-#' that NA values should be considered as 'missing' by the algorithm.
-#' Sometimes, 0 or other extreme value might be used to represent missing values.
-#' @param prediction A logical value indicating whether to return the test fold predictions
-#' from each CV model. This parameter engages the \code{\link{cb.cv.predict}} callback.
-#' @param showsd \code{boolean}, whether to show standard deviation of cross validation
-#' @param metrics, list of evaluation metrics to be used in cross validation,
-#' when it is not specified, the evaluation metric is chosen according to objective function.
-#' Possible options are:
-#' \itemize{
-#' \item \code{error} binary classification error rate
-#' \item \code{rmse} Rooted mean square error
-#' \item \code{logloss} negative log-likelihood function
-#' \item \code{auc} Area under curve
-#' \item \code{aucpr} Area under PR curve
-#' \item \code{merror} Exact matching error, used to evaluate multi-class classification
-#' }
-#' @param obj customized objective function. Returns gradient and second order
-#' gradient with given prediction and dtrain.
-#' @param feval customized evaluation function. Returns
-#' \code{list(metric='metric-name', value='metric-value')} with given
-#' prediction and dtrain.
-#' @param stratified a \code{boolean} indicating whether sampling of folds should be stratified
-#' by the values of outcome labels.
-#' @param folds \code{list} provides a possibility to use a list of pre-defined CV folds
-#' (each element must be a vector of test fold's indices). When folds are supplied,
-#' the \code{nfold} and \code{stratified} parameters are ignored.
-#' @param train_folds \code{list} list specifying which indicies to use for training. If \code{NULL}
-#' (the default) all indices not specified in \code{folds} will be used for training.
-#' @param verbose \code{boolean}, print the statistics during the process
-#' @param print_every_n Print each n-th iteration evaluation messages when \code{verbose>0}.
-#' Default is 1 which means all messages are printed. This parameter is passed to the
-#' \code{\link{cb.print.evaluation}} callback.
-#' @param early_stopping_rounds If \code{NULL}, the early stopping function is not triggered.
-#' If set to an integer \code{k}, training with a validation set will stop if the performance
-#' doesn't improve for \code{k} rounds.
-#' Setting this parameter engages the \code{\link{cb.early.stop}} callback.
-#' @param maximize If \code{feval} and \code{early_stopping_rounds} are set,
-#' then this parameter must be set as well.
-#' When it is \code{TRUE}, it means the larger the evaluation score the better.
-#' This parameter is passed to the \code{\link{cb.early.stop}} callback.
-#' @param callbacks a list of callback functions to perform various task during boosting.
-#' See \code{\link{callbacks}}. Some of the callbacks are automatically created depending on the
-#' parameters' values. User can provide either existing or their own callback methods in order
-#' to customize the training process.
-#' @param ... other parameters to pass to \code{params}.
-#'
-#' @details
-#' The original sample is randomly partitioned into \code{nfold} equal size subsamples.
-#'
-#' Of the \code{nfold} subsamples, a single subsample is retained as the validation data for testing the model, and the remaining \code{nfold - 1} subsamples are used as training data.
-#'
-#' The cross-validation process is then repeated \code{nrounds} times, with each of the \code{nfold} subsamples used exactly once as the validation data.
-#'
-#' All observations are used for both training and validation.
-#'
-#' Adapted from \url{http://en.wikipedia.org/wiki/Cross-validation_\%28statistics\%29#k-fold_cross-validation}
-#'
-#' @return
-#' An object of class \code{xgb.cv.synchronous} with the following elements:
-#' \itemize{
-#' \item \code{call} a function call.
-#' \item \code{params} parameters that were passed to the xgboost library. Note that it does not
-#' capture parameters changed by the \code{\link{cb.reset.parameters}} callback.
-#' \item \code{callbacks} callback functions that were either automatically assigned or
-#' explicitly passed.
-#' \item \code{evaluation_log} evaluation history stored as a \code{data.table} with the
-#' first column corresponding to iteration number and the rest corresponding to the
-#' CV-based evaluation means and standard deviations for the training and test CV-sets.
-#' It is created by the \code{\link{cb.evaluation.log}} callback.
-#' \item \code{niter} number of boosting iterations.
-#' \item \code{nfeatures} number of features in training data.
-#' \item \code{folds} the list of CV folds' indices - either those passed through the \code{folds}
-#' parameter or randomly generated.
-#' \item \code{best_iteration} iteration number with the best evaluation metric value
-#' (only available with early stopping).
-#' \item \code{best_ntreelimit} the \code{ntreelimit} value corresponding to the best iteration,
-#' which could further be used in \code{predict} method
-#' (only available with early stopping).
-#' \item \code{pred} CV prediction values available when \code{prediction} is set.
-#' It is either vector or matrix (see \code{\link{cb.cv.predict}}).
-#' \item \code{models} a list of the CV folds' models. It is only available with the explicit
-#' setting of the \code{cb.cv.predict(save_models = TRUE)} callback.
-#' }
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-#' cv <- xgb.cv(data = dtrain, nrounds = 3, nthread = 2, nfold = 5, metrics = list("rmse","auc"),
-#' max_depth = 3, eta = 1, objective = "binary:logistic")
-#' print(cv)
-#' print(cv, verbose=TRUE)
-#'
-#' @export
-xgb.cv <- function(params=list(), data, nrounds, nfold, label = NULL, missing = NA,
- prediction = FALSE, showsd = TRUE, metrics=list(),
- obj = NULL, feval = NULL, stratified = TRUE, folds = NULL, train_folds = NULL,
- verbose = TRUE, print_every_n=1L,
- early_stopping_rounds = NULL, maximize = NULL, callbacks = list(), ...) {
-
- check.deprecation(...)
-
- params <- check.booster.params(params, ...)
- # TODO: should we deprecate the redundant 'metrics' parameter?
- for (m in metrics)
- params <- c(params, list("eval_metric" = m))
-
- check.custom.obj()
- check.custom.eval()
-
- #if (is.null(params[['eval_metric']]) && is.null(feval))
- # stop("Either 'eval_metric' or 'feval' must be provided for CV")
-
- # Check the labels
- if ( (inherits(data, 'xgb.DMatrix') && is.null(getinfo(data, 'label'))) ||
- (!inherits(data, 'xgb.DMatrix') && is.null(label))) {
- stop("Labels must be provided for CV either through xgb.DMatrix, or through 'label=' when 'data' is matrix")
- } else if (inherits(data, 'xgb.DMatrix')) {
- if (!is.null(label))
- warning("xgb.cv: label will be ignored, since data is of type xgb.DMatrix")
- cv_label = getinfo(data, 'label')
- } else {
- cv_label = label
- }
-
- # CV folds
- if(!is.null(folds)) {
- if(!is.list(folds) || length(folds) < 2)
- stop("'folds' must be a list with 2 or more elements that are vectors of indices for each CV-fold")
- nfold <- length(folds)
- } else {
- if (nfold <= 1)
- stop("'nfold' must be > 1")
- folds <- generate.cv.folds(nfold, nrow(data), stratified, cv_label, params)
- }
-
- # Potential TODO: sequential CV
- #if (strategy == 'sequential')
- # stop('Sequential CV strategy is not yet implemented')
-
- # verbosity & evaluation printing callback:
- params <- c(params, list(silent = 1))
- print_every_n <- max( as.integer(print_every_n), 1L)
- if (!has.callbacks(callbacks, 'cb.print.evaluation') && verbose) {
- callbacks <- add.cb(callbacks, cb.print.evaluation(print_every_n, showsd = showsd))
- }
- # evaluation log callback: always is on in CV
- evaluation_log <- list()
- if (!has.callbacks(callbacks, 'cb.evaluation.log')) {
- callbacks <- add.cb(callbacks, cb.evaluation.log())
- }
- # Early stopping callback
- stop_condition <- FALSE
- if (!is.null(early_stopping_rounds) &&
- !has.callbacks(callbacks, 'cb.early.stop')) {
- callbacks <- add.cb(callbacks, cb.early.stop(early_stopping_rounds,
- maximize = maximize, verbose = verbose))
- }
- # CV-predictions callback
- if (prediction &&
- !has.callbacks(callbacks, 'cb.cv.predict')) {
- callbacks <- add.cb(callbacks, cb.cv.predict(save_models = FALSE))
- }
- # Sort the callbacks into categories
- cb <- categorize.callbacks(callbacks)
-
-
- # create the booster-folds
- # train_folds
- dall <- xgb.get.DMatrix(data, label, missing)
- bst_folds <- lapply(seq_along(folds), function(k) {
- dtest <- slice(dall, folds[[k]])
- # code originally contributed by @RolandASc on stackoverflow
- if(is.null(train_folds))
- dtrain <- slice(dall, unlist(folds[-k]))
- else
- dtrain <- slice(dall, train_folds[[k]])
- handle <- xgb.Booster.handle(params, list(dtrain, dtest))
- list(dtrain = dtrain, bst = handle, watchlist = list(train = dtrain, test=dtest), index = folds[[k]])
- })
- rm(dall)
- # a "basket" to collect some results from callbacks
- basket <- list()
-
- # extract parameters that can affect the relationship b/w #trees and #iterations
- num_class <- max(as.numeric(NVL(params[['num_class']], 1)), 1)
- num_parallel_tree <- max(as.numeric(NVL(params[['num_parallel_tree']], 1)), 1)
-
- # those are fixed for CV (no training continuation)
- begin_iteration <- 1
- end_iteration <- nrounds
-
- # synchronous CV boosting: run CV folds' models within each iteration
- for (iteration in begin_iteration:end_iteration) {
-
- for (f in cb$pre_iter) f()
-
- msg <- lapply(bst_folds, function(fd) {
- xgb.iter.update(fd$bst, fd$dtrain, iteration - 1, obj)
- xgb.iter.eval(fd$bst, fd$watchlist, iteration - 1, feval)
- })
- msg <- simplify2array(msg)
- bst_evaluation <- rowMeans(msg)
- bst_evaluation_err <- sqrt(rowMeans(msg^2) - bst_evaluation^2)
-
- for (f in cb$post_iter) f()
-
- if (stop_condition) break
- }
- for (f in cb$finalize) f(finalize = TRUE)
-
- # the CV result
- ret <- list(
- call = match.call(),
- params = params,
- callbacks = callbacks,
- evaluation_log = evaluation_log,
- niter = end_iteration,
- nfeatures = ncol(data),
- folds = folds
- )
- ret <- c(ret, basket)
-
- class(ret) <- 'xgb.cv.synchronous'
- invisible(ret)
-}
-
-
-
-#' Print xgb.cv result
-#'
-#' Prints formatted results of \code{xgb.cv}.
-#'
-#' @param x an \code{xgb.cv.synchronous} object
-#' @param verbose whether to print detailed data
-#' @param ... passed to \code{data.table.print}
-#'
-#' @details
-#' When not verbose, it would only print the evaluation results,
-#' including the best iteration (when available).
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' train <- agaricus.train
-#' cv <- xgb.cv(data = train$data, label = train$label, nfold = 5, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#' print(cv)
-#' print(cv, verbose=TRUE)
-#'
-#' @rdname print.xgb.cv
-#' @method print xgb.cv.synchronous
-#' @export
-print.xgb.cv.synchronous <- function(x, verbose = FALSE, ...) {
- cat('##### xgb.cv ', length(x$folds), '-folds\n', sep = '')
-
- if (verbose) {
- if (!is.null(x$call)) {
- cat('call:\n ')
- print(x$call)
- }
- if (!is.null(x$params)) {
- cat('params (as set within xgb.cv):\n')
- cat( ' ',
- paste(names(x$params),
- paste0('"', unlist(x$params), '"'),
- sep = ' = ', collapse = ', '), '\n', sep = '')
- }
- if (!is.null(x$callbacks) && length(x$callbacks) > 0) {
- cat('callbacks:\n')
- lapply(callback.calls(x$callbacks), function(x) {
- cat(' ')
- print(x)
- })
- }
-
- for (n in c('niter', 'best_iteration', 'best_ntreelimit')) {
- if (is.null(x[[n]]))
- next
- cat(n, ': ', x[[n]], '\n', sep = '')
- }
-
- if (!is.null(x$pred)) {
- cat('pred:\n')
- str(x$pred)
- }
- }
-
- if (verbose)
- cat('evaluation_log:\n')
- print(x$evaluation_log, row.names = FALSE, ...)
-
- if (!is.null(x$best_iteration)) {
- cat('Best iteration:\n')
- print(x$evaluation_log[x$best_iteration], row.names = FALSE, ...)
- }
- invisible(x)
-}
diff --git a/ml-xgboost/R-package/R/xgb.dump.R b/ml-xgboost/R-package/R/xgb.dump.R
deleted file mode 100644
index ffa3cbc..0000000
--- a/ml-xgboost/R-package/R/xgb.dump.R
+++ /dev/null
@@ -1,72 +0,0 @@
-#' Dump an xgboost model in text format.
-#'
-#' Dump an xgboost model in text format.
-#'
-#' @param model the model object.
-#' @param fname the name of the text file where to save the model text dump.
-#' If not provided or set to \code{NULL}, the model is returned as a \code{character} vector.
-#' @param fmap feature map file representing feature types.
-#' Detailed description could be found at
-#' \url{https://github.com/dmlc/xgboost/wiki/Binary-Classification#dump-model}.
-#' See demo/ for walkthrough example in R, and
-#' \url{https://github.com/dmlc/xgboost/blob/master/demo/data/featmap.txt}
-#' for example Format.
-#' @param with_stats whether to dump some additional statistics about the splits.
-#' When this option is on, the model dump contains two additional values:
-#' gain is the approximate loss function gain we get in each split;
-#' cover is the sum of second order gradient in each node.
-#' @param dump_format either 'text' or 'json' format could be specified.
-#' @param ... currently not used
-#'
-#' @return
-#' If fname is not provided or set to \code{NULL} the function will return the model
-#' as a \code{character} vector. Otherwise it will return \code{TRUE}.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#' train <- agaricus.train
-#' test <- agaricus.test
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#' # save the model in file 'xgb.model.dump'
-#' dump_path = file.path(tempdir(), 'model.dump')
-#' xgb.dump(bst, dump_path, with_stats = TRUE)
-#'
-#' # print the model without saving it to a file
-#' print(xgb.dump(bst, with_stats = TRUE))
-#'
-#' # print in JSON format:
-#' cat(xgb.dump(bst, with_stats = TRUE, dump_format='json'))
-#'
-#' @export
-xgb.dump <- function(model, fname = NULL, fmap = "", with_stats=FALSE,
- dump_format = c("text", "json"), ...) {
- check.deprecation(...)
- dump_format <- match.arg(dump_format)
- if (!inherits(model, "xgb.Booster"))
- stop("model: argument must be of type xgb.Booster")
- if (!(is.null(fname) || is.character(fname)))
- stop("fname: argument must be a character string (when provided)")
- if (!(is.null(fmap) || is.character(fmap)))
- stop("fmap: argument must be a character string (when provided)")
-
- model <- xgb.Booster.complete(model)
- model_dump <- .Call(XGBoosterDumpModel_R, model$handle, NVL(fmap, "")[1], as.integer(with_stats),
- as.character(dump_format))
-
- if (is.null(fname))
- model_dump <- stri_replace_all_regex(model_dump, '\t', '')
-
- if (dump_format == "text")
- model_dump <- unlist(stri_split_regex(model_dump, '\n'))
-
- model_dump <- grep('^\\s*$', model_dump, invert = TRUE, value = TRUE)
-
- if (is.null(fname)) {
- return(model_dump)
- } else {
- writeLines(model_dump, fname[1])
- return(TRUE)
- }
-}
diff --git a/ml-xgboost/R-package/R/xgb.ggplot.R b/ml-xgboost/R-package/R/xgb.ggplot.R
deleted file mode 100644
index eceb5c4..0000000
--- a/ml-xgboost/R-package/R/xgb.ggplot.R
+++ /dev/null
@@ -1,135 +0,0 @@
-# ggplot backend for the xgboost plotting facilities
-
-
-#' @rdname xgb.plot.importance
-#' @export
-xgb.ggplot.importance <- function(importance_matrix = NULL, top_n = NULL, measure = NULL,
- rel_to_first = FALSE, n_clusters = c(1:10), ...) {
-
- importance_matrix <- xgb.plot.importance(importance_matrix, top_n = top_n, measure = measure,
- rel_to_first = rel_to_first, plot = FALSE, ...)
- if (!requireNamespace("ggplot2", quietly = TRUE)) {
- stop("ggplot2 package is required", call. = FALSE)
- }
- if (!requireNamespace("Ckmeans.1d.dp", quietly = TRUE)) {
- stop("Ckmeans.1d.dp package is required", call. = FALSE)
- }
-
- clusters <- suppressWarnings(
- Ckmeans.1d.dp::Ckmeans.1d.dp(importance_matrix$Importance, n_clusters)
- )
- importance_matrix[, Cluster := as.character(clusters$cluster)]
-
- plot <-
- ggplot2::ggplot(importance_matrix,
- ggplot2::aes(x = factor(Feature, levels = rev(Feature)), y = Importance, width = 0.5),
- environment = environment()) +
- ggplot2::geom_bar(ggplot2::aes(fill = Cluster), stat = "identity", position = "identity") +
- ggplot2::coord_flip() +
- ggplot2::xlab("Features") +
- ggplot2::ggtitle("Feature importance") +
- ggplot2::theme(plot.title = ggplot2::element_text(lineheight = .9, face = "bold"),
- panel.grid.major.y = ggplot2::element_blank())
- return(plot)
-}
-
-
-#' @rdname xgb.plot.deepness
-#' @export
-xgb.ggplot.deepness <- function(model = NULL, which = c("2x1", "max.depth", "med.depth", "med.weight")) {
-
- if (!requireNamespace("ggplot2", quietly = TRUE))
- stop("ggplot2 package is required for plotting the graph deepness.", call. = FALSE)
-
- which <- match.arg(which)
-
- dt_depths <- xgb.plot.deepness(model = model, plot = FALSE)
- dt_summaries <- dt_depths[, .(.N, Cover = mean(Cover)), Depth]
- setkey(dt_summaries, 'Depth')
-
- if (which == "2x1") {
- p1 <-
- ggplot2::ggplot(dt_summaries) +
- ggplot2::geom_bar(ggplot2::aes(x = Depth, y = N), stat = "Identity") +
- ggplot2::xlab("") +
- ggplot2::ylab("Number of leafs") +
- ggplot2::ggtitle("Model complexity") +
- ggplot2::theme(
- plot.title = ggplot2::element_text(lineheight = 0.9, face = "bold"),
- panel.grid.major.y = ggplot2::element_blank(),
- axis.ticks = ggplot2::element_blank(),
- axis.text.x = ggplot2::element_blank()
- )
-
- p2 <-
- ggplot2::ggplot(dt_summaries) +
- ggplot2::geom_bar(ggplot2::aes(x = Depth, y = Cover), stat = "Identity") +
- ggplot2::xlab("Leaf depth") +
- ggplot2::ylab("Weighted cover")
-
- multiplot(p1, p2, cols = 1)
- return(invisible(list(p1, p2)))
-
- } else if (which == "max.depth") {
- p <-
- ggplot2::ggplot(dt_depths[, max(Depth), Tree]) +
- ggplot2::geom_jitter(ggplot2::aes(x = Tree, y = V1),
- height = 0.15, alpha=0.4, size=3, stroke=0) +
- ggplot2::xlab("tree #") +
- ggplot2::ylab("Max tree leaf depth")
- return(p)
-
- } else if (which == "med.depth") {
- p <-
- ggplot2::ggplot(dt_depths[, median(as.numeric(Depth)), Tree]) +
- ggplot2::geom_jitter(ggplot2::aes(x = Tree, y = V1),
- height = 0.15, alpha=0.4, size=3, stroke=0) +
- ggplot2::xlab("tree #") +
- ggplot2::ylab("Median tree leaf depth")
- return(p)
-
- } else if (which == "med.weight") {
- p <-
- ggplot2::ggplot(dt_depths[, median(abs(Weight)), Tree]) +
- ggplot2::geom_point(ggplot2::aes(x = Tree, y = V1),
- alpha=0.4, size=3, stroke=0) +
- ggplot2::xlab("tree #") +
- ggplot2::ylab("Median absolute leaf weight")
- return(p)
- }
-}
-
-# Plot multiple ggplot graph aligned by rows and columns.
-# ... the plots
-# cols number of columns
-# internal utility function
-multiplot <- function(..., cols = 1) {
- plots <- list(...)
- num_plots = length(plots)
-
- layout <- matrix(seq(1, cols * ceiling(num_plots / cols)),
- ncol = cols, nrow = ceiling(num_plots / cols))
-
- if (num_plots == 1) {
- print(plots[[1]])
- } else {
- grid::grid.newpage()
- grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout))))
- for (i in 1:num_plots) {
- # Get the i,j matrix positions of the regions that contain this subplot
- matchidx <- as.data.table(which(layout == i, arr.ind = TRUE))
-
- print(
- plots[[i]], vp = grid::viewport(
- layout.pos.row = matchidx$row,
- layout.pos.col = matchidx$col
- )
- )
- }
- }
-}
-
-globalVariables(c(
- "Cluster", "ggplot", "aes", "geom_bar", "coord_flip", "xlab", "ylab", "ggtitle", "theme",
- "element_blank", "element_text", "V1", "Weight"
-))
diff --git a/ml-xgboost/R-package/R/xgb.importance.R b/ml-xgboost/R-package/R/xgb.importance.R
deleted file mode 100644
index 62e37e8..0000000
--- a/ml-xgboost/R-package/R/xgb.importance.R
+++ /dev/null
@@ -1,139 +0,0 @@
-#' Importance of features in a model.
-#'
-#' Creates a \code{data.table} of feature importances in a model.
-#'
-#' @param feature_names character vector of feature names. If the model already
-#' contains feature names, those would be used when \code{feature_names=NULL} (default value).
-#' Non-null \code{feature_names} could be provided to override those in the model.
-#' @param model object of class \code{xgb.Booster}.
-#' @param trees (only for the gbtree booster) an integer vector of tree indices that should be included
-#' into the importance calculation. If set to \code{NULL}, all trees of the model are parsed.
-#' It could be useful, e.g., in multiclass classification to get feature importances
-#' for each class separately. IMPORTANT: the tree index in xgboost models
-#' is zero-based (e.g., use \code{trees = 0:4} for first 5 trees).
-#' @param data deprecated.
-#' @param label deprecated.
-#' @param target deprecated.
-#'
-#' @details
-#'
-#' This function works for both linear and tree models.
-#'
-#' For linear models, the importance is the absolute magnitude of linear coefficients.
-#' For that reason, in order to obtain a meaningful ranking by importance for a linear model,
-#' the features need to be on the same scale (which you also would want to do when using either
-#' L1 or L2 regularization).
-#'
-#' @return
-#'
-#' For a tree model, a \code{data.table} with the following columns:
-#' \itemize{
-#' \item \code{Features} names of the features used in the model;
-#' \item \code{Gain} represents fractional contribution of each feature to the model based on
-#' the total gain of this feature's splits. Higher percentage means a more important
-#' predictive feature.
-#' \item \code{Cover} metric of the number of observation related to this feature;
-#' \item \code{Frequency} percentage representing the relative number of times
-#' a feature have been used in trees.
-#' }
-#'
-#' A linear model's importance \code{data.table} has the following columns:
-#' \itemize{
-#' \item \code{Features} names of the features used in the model;
-#' \item \code{Weight} the linear coefficient of this feature;
-#' \item \code{Class} (only for multiclass models) class label.
-#' }
-#'
-#' If \code{feature_names} is not provided and \code{model} doesn't have \code{feature_names},
-#' index of the features will be used instead. Because the index is extracted from the model dump
-#' (based on C++ code), it starts at 0 (as in C/C++ or Python) instead of 1 (usual in R).
-#'
-#' @examples
-#'
-#' # binomial classification using gbtree:
-#' data(agaricus.train, package='xgboost')
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#' xgb.importance(model = bst)
-#'
-#' # binomial classification using gblinear:
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, booster = "gblinear",
-#' eta = 0.3, nthread = 1, nrounds = 20, objective = "binary:logistic")
-#' xgb.importance(model = bst)
-#'
-#' # multiclass classification using gbtree:
-#' nclass <- 3
-#' nrounds <- 10
-#' mbst <- xgboost(data = as.matrix(iris[, -5]), label = as.numeric(iris$Species) - 1,
-#' max_depth = 3, eta = 0.2, nthread = 2, nrounds = nrounds,
-#' objective = "multi:softprob", num_class = nclass)
-#' # all classes clumped together:
-#' xgb.importance(model = mbst)
-#' # inspect importances separately for each class:
-#' xgb.importance(model = mbst, trees = seq(from=0, by=nclass, length.out=nrounds))
-#' xgb.importance(model = mbst, trees = seq(from=1, by=nclass, length.out=nrounds))
-#' xgb.importance(model = mbst, trees = seq(from=2, by=nclass, length.out=nrounds))
-#'
-#' # multiclass classification using gblinear:
-#' mbst <- xgboost(data = scale(as.matrix(iris[, -5])), label = as.numeric(iris$Species) - 1,
-#' booster = "gblinear", eta = 0.2, nthread = 1, nrounds = 15,
-#' objective = "multi:softprob", num_class = nclass)
-#' xgb.importance(model = mbst)
-#'
-#' @export
-xgb.importance <- function(feature_names = NULL, model = NULL, trees = NULL,
- data = NULL, label = NULL, target = NULL){
-
- if (!(is.null(data) && is.null(label) && is.null(target)))
- warning("xgb.importance: parameters 'data', 'label' and 'target' are deprecated")
-
- if (!inherits(model, "xgb.Booster"))
- stop("model: must be an object of class xgb.Booster")
-
- if (is.null(feature_names) && !is.null(model$feature_names))
- feature_names <- model$feature_names
-
- if (!(is.null(feature_names) || is.character(feature_names)))
- stop("feature_names: Has to be a character vector")
-
- model_text_dump <- xgb.dump(model = model, with_stats = TRUE)
-
- # linear model
- if(model_text_dump[2] == "bias:"){
- weights <- which(model_text_dump == "weight:") %>%
- {model_text_dump[(. + 1):length(model_text_dump)]} %>%
- as.numeric
-
- num_class <- NVL(model$params$num_class, 1)
- if(is.null(feature_names))
- feature_names <- seq(to = length(weights) / num_class) - 1
- if (length(feature_names) * num_class != length(weights))
- stop("feature_names length does not match the number of features used in the model")
-
- result <- if (num_class == 1) {
- data.table(Feature = feature_names, Weight = weights)[order(-abs(Weight))]
- } else {
- data.table(Feature = rep(feature_names, each = num_class),
- Weight = weights,
- Class = seq_len(num_class) - 1)[order(Class, -abs(Weight))]
- }
- } else {
- # tree model
- result <- xgb.model.dt.tree(feature_names = feature_names,
- text = model_text_dump,
- trees = trees)[
- Feature != "Leaf", .(Gain = sum(Quality),
- Cover = sum(Cover),
- Frequency = .N), by = Feature][
- ,`:=`(Gain = Gain / sum(Gain),
- Cover = Cover / sum(Cover),
- Frequency = Frequency / sum(Frequency))][
- order(Gain, decreasing = TRUE)]
- }
- result
-}
-
-# Avoid error messages during CRAN check.
-# The reason is that these variables are never declared
-# They are mainly column names inferred by Data.table...
-globalVariables(c(".", ".N", "Gain", "Cover", "Frequency", "Feature", "Class"))
diff --git a/ml-xgboost/R-package/R/xgb.load.R b/ml-xgboost/R-package/R/xgb.load.R
deleted file mode 100644
index bda4e7e..0000000
--- a/ml-xgboost/R-package/R/xgb.load.R
+++ /dev/null
@@ -1,47 +0,0 @@
-#' Load xgboost model from binary file
-#'
-#' Load xgboost model from the binary model file.
-#'
-#' @param modelfile the name of the binary input file.
-#'
-#' @details
-#' The input file is expected to contain a model saved in an xgboost-internal binary format
-#' using either \code{\link{xgb.save}} or \code{\link{cb.save.model}} in R, or using some
-#' appropriate methods from other xgboost interfaces. E.g., a model trained in Python and
-#' saved from there in xgboost format, could be loaded from R.
-#'
-#' Note: a model saved as an R-object, has to be loaded using corresponding R-methods,
-#' not \code{xgb.load}.
-#'
-#' @return
-#' An object of \code{xgb.Booster} class.
-#'
-#' @seealso
-#' \code{\link{xgb.save}}, \code{\link{xgb.Booster.complete}}.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#' train <- agaricus.train
-#' test <- agaricus.test
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-#' xgb.save(bst, 'xgb.model')
-#' bst <- xgb.load('xgb.model')
-#' if (file.exists('xgb.model')) file.remove('xgb.model')
-#' pred <- predict(bst, test$data)
-#' @export
-xgb.load <- function(modelfile) {
- if (is.null(modelfile))
- stop("xgb.load: modelfile cannot be NULL")
-
- handle <- xgb.Booster.handle(modelfile = modelfile)
- # re-use modelfile if it is raw so we do not need to serialize
- if (typeof(modelfile) == "raw") {
- bst <- xgb.handleToBooster(handle, modelfile)
- } else {
- bst <- xgb.handleToBooster(handle, NULL)
- }
- bst <- xgb.Booster.complete(bst, saveraw = TRUE)
- return(bst)
-}
diff --git a/ml-xgboost/R-package/R/xgb.load.raw.R b/ml-xgboost/R-package/R/xgb.load.raw.R
deleted file mode 100644
index 2a7d375..0000000
--- a/ml-xgboost/R-package/R/xgb.load.raw.R
+++ /dev/null
@@ -1,14 +0,0 @@
-#' Load serialised xgboost model from R's raw vector
-#'
-#' User can generate raw memory buffer by calling xgb.save.raw
-#'
-#' @param buffer the buffer returned by xgb.save.raw
-#'
-#' @export
-xgb.load.raw <- function(buffer) {
- cachelist <- list()
- handle <- .Call(XGBoosterCreate_R, cachelist)
- .Call(XGBoosterLoadModelFromRaw_R, handle, buffer)
- class(handle) <- "xgb.Booster.handle"
- return (handle)
-}
diff --git a/ml-xgboost/R-package/R/xgb.model.dt.tree.R b/ml-xgboost/R-package/R/xgb.model.dt.tree.R
deleted file mode 100644
index 6a00797..0000000
--- a/ml-xgboost/R-package/R/xgb.model.dt.tree.R
+++ /dev/null
@@ -1,159 +0,0 @@
-#' Parse a boosted tree model text dump
-#'
-#' Parse a boosted tree model text dump into a \code{data.table} structure.
-#'
-#' @param feature_names character vector of feature names. If the model already
-#' contains feature names, those would be used when \code{feature_names=NULL} (default value).
-#' Non-null \code{feature_names} could be provided to override those in the model.
-#' @param model object of class \code{xgb.Booster}
-#' @param text \code{character} vector previously generated by the \code{xgb.dump}
-#' function (where parameter \code{with_stats = TRUE} should have been set).
-#' \code{text} takes precedence over \code{model}.
-#' @param trees an integer vector of tree indices that should be parsed.
-#' If set to \code{NULL}, all trees of the model are parsed.
-#' It could be useful, e.g., in multiclass classification to get only
-#' the trees of one certain class. IMPORTANT: the tree index in xgboost models
-#' is zero-based (e.g., use \code{trees = 0:4} for first 5 trees).
-#' @param use_int_id a logical flag indicating whether nodes in columns "Yes", "No", "Missing" should be
-#' represented as integers (when FALSE) or as "Tree-Node" character strings (when FALSE).
-#' @param ... currently not used.
-#'
-#' @return
-#' A \code{data.table} with detailed information about model trees' nodes.
-#'
-#' The columns of the \code{data.table} are:
-#'
-#' \itemize{
-#' \item \code{Tree}: integer ID of a tree in a model (zero-based index)
-#' \item \code{Node}: integer ID of a node in a tree (zero-based index)
-#' \item \code{ID}: character identifier of a node in a model (only when \code{use_int_id=FALSE})
-#' \item \code{Feature}: for a branch node, it's a feature id or name (when available);
-#' for a leaf note, it simply labels it as \code{'Leaf'}
-#' \item \code{Split}: location of the split for a branch node (split condition is always "less than")
-#' \item \code{Yes}: ID of the next node when the split condition is met
-#' \item \code{No}: ID of the next node when the split condition is not met
-#' \item \code{Missing}: ID of the next node when branch value is missing
-#' \item \code{Quality}: either the split gain (change in loss) or the leaf value
-#' \item \code{Cover}: metric related to the number of observation either seen by a split
-#' or collected by a leaf during training.
-#' }
-#'
-#' When \code{use_int_id=FALSE}, columns "Yes", "No", and "Missing" point to model-wide node identifiers
-#' in the "ID" column. When \code{use_int_id=TRUE}, those columns point to node identifiers from
-#' the corresponding trees in the "Node" column.
-#'
-#' @examples
-#' # Basic use:
-#'
-#' data(agaricus.train, package='xgboost')
-#'
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-#'
-#' (dt <- xgb.model.dt.tree(colnames(agaricus.train$data), bst))
-#'
-#' # This bst model already has feature_names stored with it, so those would be used when
-#' # feature_names is not set:
-#' (dt <- xgb.model.dt.tree(model = bst))
-#'
-#' # How to match feature names of splits that are following a current 'Yes' branch:
-#'
-#' merge(dt, dt[, .(ID, Y.Feature=Feature)], by.x='Yes', by.y='ID', all.x=TRUE)[order(Tree,Node)]
-#'
-#' @export
-xgb.model.dt.tree <- function(feature_names = NULL, model = NULL, text = NULL,
- trees = NULL, use_int_id = FALSE, ...){
- check.deprecation(...)
-
- if (!inherits(model, "xgb.Booster") && !is.character(text)) {
- stop("Either 'model' must be an object of class xgb.Booster\n",
- " or 'text' must be a character vector with the result of xgb.dump\n",
- " (or NULL if 'model' was provided).")
- }
-
- if (is.null(feature_names) && !is.null(model) && !is.null(model$feature_names))
- feature_names <- model$feature_names
-
- if (!(is.null(feature_names) || is.character(feature_names))) {
- stop("feature_names: must be a character vector")
- }
-
- if (!(is.null(trees) || is.numeric(trees))) {
- stop("trees: must be a vector of integers.")
- }
-
- if (is.null(text)){
- text <- xgb.dump(model = model, with_stats = TRUE)
- }
-
- if (length(text) < 2 ||
- sum(stri_detect_regex(text, 'yes=(\\d+),no=(\\d+)')) < 1) {
- stop("Non-tree model detected! This function can only be used with tree models.")
- }
-
- position <- which(!is.na(stri_match_first_regex(text, "booster")))
-
- add.tree.id <- function(node, tree) if (use_int_id) node else paste(tree, node, sep = "-")
-
- anynumber_regex <- "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"
-
- td <- data.table(t = text)
- td[position, Tree := 1L]
- td[, Tree := cumsum(ifelse(is.na(Tree), 0L, Tree)) - 1L]
-
- if (is.null(trees)) {
- trees <- 0:max(td$Tree)
- } else {
- trees <- trees[trees >= 0 & trees <= max(td$Tree)]
- }
- td <- td[Tree %in% trees & !grepl('^booster', t)]
-
- td[, Node := stri_match_first_regex(t, "(\\d+):")[,2] %>% as.integer ]
- if (!use_int_id) td[, ID := add.tree.id(Node, Tree)]
- td[, isLeaf := !is.na(stri_match_first_regex(t, "leaf"))]
-
- # parse branch lines
- branch_rx <- paste0("f(\\d+)<(", anynumber_regex, ")\\] yes=(\\d+),no=(\\d+),missing=(\\d+),",
- "gain=(", anynumber_regex, "),cover=(", anynumber_regex, ")")
- branch_cols <- c("Feature", "Split", "Yes", "No", "Missing", "Quality", "Cover")
- td[isLeaf == FALSE,
- (branch_cols) := {
- # skip some indices with spurious capture groups from anynumber_regex
- xtr <- stri_match_first_regex(t, branch_rx)[, c(2,3,5,6,7,8,10), drop = FALSE]
- xtr[, 3:5] <- add.tree.id(xtr[, 3:5], Tree)
- lapply(seq_len(ncol(xtr)), function(i) xtr[,i])
- }]
- # assign feature_names when available
- if (!is.null(feature_names)) {
- if (length(feature_names) <= max(as.numeric(td$Feature), na.rm = TRUE))
- stop("feature_names has less elements than there are features used in the model")
- td[isLeaf == FALSE, Feature := feature_names[as.numeric(Feature) + 1] ]
- }
-
- # parse leaf lines
- leaf_rx <- paste0("leaf=(", anynumber_regex, "),cover=(", anynumber_regex, ")")
- leaf_cols <- c("Feature", "Quality", "Cover")
- td[isLeaf == TRUE,
- (leaf_cols) := {
- xtr <- stri_match_first_regex(t, leaf_rx)[, c(2,4)]
- c("Leaf", lapply(seq_len(ncol(xtr)), function(i) xtr[,i]))
- }]
-
- # convert some columns to numeric
- numeric_cols <- c("Split", "Quality", "Cover")
- td[, (numeric_cols) := lapply(.SD, as.numeric), .SDcols = numeric_cols]
- if (use_int_id) {
- int_cols <- c("Yes", "No", "Missing")
- td[, (int_cols) := lapply(.SD, as.integer), .SDcols = int_cols]
- }
-
- td[, t := NULL]
- td[, isLeaf := NULL]
-
- td[order(Tree, Node)]
-}
-
-# Avoid error messages during CRAN check.
-# The reason is that these variables are never declared
-# They are mainly column names inferred by Data.table...
-globalVariables(c("Tree", "Node", "ID", "Feature", "t", "isLeaf",".SD", ".SDcols"))
diff --git a/ml-xgboost/R-package/R/xgb.plot.deepness.R b/ml-xgboost/R-package/R/xgb.plot.deepness.R
deleted file mode 100644
index 87d632a..0000000
--- a/ml-xgboost/R-package/R/xgb.plot.deepness.R
+++ /dev/null
@@ -1,150 +0,0 @@
-#' Plot model trees deepness
-#'
-#' Visualizes distributions related to depth of tree leafs.
-#' \code{xgb.plot.deepness} uses base R graphics, while \code{xgb.ggplot.deepness} uses the ggplot backend.
-#'
-#' @param model either an \code{xgb.Booster} model generated by the \code{xgb.train} function
-#' or a data.table result of the \code{xgb.model.dt.tree} function.
-#' @param plot (base R barplot) whether a barplot should be produced.
-#' If FALSE, only a data.table is returned.
-#' @param which which distribution to plot (see details).
-#' @param ... other parameters passed to \code{barplot} or \code{plot}.
-#'
-#' @details
-#'
-#' When \code{which="2x1"}, two distributions with respect to the leaf depth
-#' are plotted on top of each other:
-#' \itemize{
-#' \item the distribution of the number of leafs in a tree model at a certain depth;
-#' \item the distribution of average weighted number of observations ("cover")
-#' ending up in leafs at certain depth.
-#' }
-#' Those could be helpful in determining sensible ranges of the \code{max_depth}
-#' and \code{min_child_weight} parameters.
-#'
-#' When \code{which="max.depth"} or \code{which="med.depth"}, plots of either maximum or median depth
-#' per tree with respect to tree number are created. And \code{which="med.weight"} allows to see how
-#' a tree's median absolute leaf weight changes through the iterations.
-#'
-#' This function was inspired by the blog post
-#' \url{https://github.com/aysent/random-forest-leaf-visualization}.
-#'
-#' @return
-#'
-#' Other than producing plots (when \code{plot=TRUE}), the \code{xgb.plot.deepness} function
-#' silently returns a processed data.table where each row corresponds to a terminal leaf in a tree model,
-#' and contains information about leaf's depth, cover, and weight (which is used in calculating predictions).
-#'
-#' The \code{xgb.ggplot.deepness} silently returns either a list of two ggplot graphs when \code{which="2x1"}
-#' or a single ggplot graph for the other \code{which} options.
-#'
-#' @seealso
-#'
-#' \code{\link{xgb.train}}, \code{\link{xgb.model.dt.tree}}.
-#'
-#' @examples
-#'
-#' data(agaricus.train, package='xgboost')
-#'
-#' # Change max_depth to a higher number to get a more significant result
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 6,
-#' eta = 0.1, nthread = 2, nrounds = 50, objective = "binary:logistic",
-#' subsample = 0.5, min_child_weight = 2)
-#'
-#' xgb.plot.deepness(bst)
-#' xgb.ggplot.deepness(bst)
-#'
-#' xgb.plot.deepness(bst, which='max.depth', pch=16, col=rgb(0,0,1,0.3), cex=2)
-#'
-#' xgb.plot.deepness(bst, which='med.weight', pch=16, col=rgb(0,0,1,0.3), cex=2)
-#'
-#' @rdname xgb.plot.deepness
-#' @export
-xgb.plot.deepness <- function(model = NULL, which = c("2x1", "max.depth", "med.depth", "med.weight"),
- plot = TRUE, ...) {
-
- if (!(inherits(model, "xgb.Booster") || is.data.table(model)))
- stop("model: Has to be either an xgb.Booster model generaged by the xgb.train function\n",
- "or a data.table result of the xgb.importance function")
-
- if (!requireNamespace("igraph", quietly = TRUE))
- stop("igraph package is required for plotting the graph deepness.", call. = FALSE)
-
- which <- match.arg(which)
-
- dt_tree <- model
- if (inherits(model, "xgb.Booster"))
- dt_tree <- xgb.model.dt.tree(model = model)
-
- if (!all(c("Feature", "Tree", "ID", "Yes", "No", "Cover") %in% colnames(dt_tree)))
- stop("Model tree columns are not as expected!\n",
- " Note that this function works only for tree models.")
-
- dt_depths <- merge(get.leaf.depth(dt_tree), dt_tree[, .(ID, Cover, Weight = Quality)], by = "ID")
- setkeyv(dt_depths, c("Tree", "ID"))
- # count by depth levels, and also calculate average cover at a depth
- dt_summaries <- dt_depths[, .(.N, Cover = mean(Cover)), Depth]
- setkey(dt_summaries, "Depth")
-
- if (plot) {
- if (which == "2x1") {
- op <- par(no.readonly = TRUE)
- par(mfrow = c(2,1),
- oma = c(3,1,3,1) + 0.1,
- mar = c(1,4,1,0) + 0.1)
-
- dt_summaries[, barplot(N, border = NA, ylab = 'Number of leafs', ...)]
-
- dt_summaries[, barplot(Cover, border = NA, ylab = "Weighted cover", names.arg = Depth, ...)]
-
- title("Model complexity", xlab = "Leaf depth", outer = TRUE, line = 1)
- par(op)
- } else if (which == "max.depth") {
- dt_depths[, max(Depth), Tree][
- , plot(jitter(V1, amount = 0.1) ~ Tree, ylab = 'Max tree leaf depth', xlab = "tree #", ...)]
- } else if (which == "med.depth") {
- dt_depths[, median(as.numeric(Depth)), Tree][
- , plot(jitter(V1, amount = 0.1) ~ Tree, ylab = 'Median tree leaf depth', xlab = "tree #", ...)]
- } else if (which == "med.weight") {
- dt_depths[, median(abs(Weight)), Tree][
- , plot(V1 ~ Tree, ylab = 'Median absolute leaf weight', xlab = "tree #", ...)]
- }
- }
- invisible(dt_depths)
-}
-
-# Extract path depths from root to leaf
-# from data.table containing the nodes and edges of the trees.
-# internal utility function
-get.leaf.depth <- function(dt_tree) {
- # extract tree graph's edges
- dt_edges <- rbindlist(list(
- dt_tree[Feature != "Leaf", .(ID, To = Yes, Tree)],
- dt_tree[Feature != "Leaf", .(ID, To = No, Tree)]
- ))
- # whether "To" is a leaf:
- dt_edges <-
- merge(dt_edges,
- dt_tree[Feature == "Leaf", .(ID, Leaf = TRUE)],
- all.x = TRUE, by.x = "To", by.y = "ID")
- dt_edges[is.na(Leaf), Leaf := FALSE]
-
- dt_edges[, {
- graph <- igraph::graph_from_data_frame(.SD[,.(ID, To)])
- # min(ID) in a tree is a root node
- paths_tmp <- igraph::shortest_paths(graph, from = min(ID), to = To[Leaf == TRUE])
- # list of paths to each leaf in a tree
- paths <- lapply(paths_tmp$vpath, names)
- # combine into a resulting path lengths table for a tree
- data.table(Depth = sapply(paths, length), ID = To[Leaf == TRUE])
- }, by = Tree]
-}
-
-# Avoid error messages during CRAN check.
-# The reason is that these variables are never declared
-# They are mainly column names inferred by Data.table...
-globalVariables(
- c(
- ".N", "N", "Depth", "Quality", "Cover", "Tree", "ID", "Yes", "No", "Feature", "Leaf", "Weight"
- )
-)
diff --git a/ml-xgboost/R-package/R/xgb.plot.importance.R b/ml-xgboost/R-package/R/xgb.plot.importance.R
deleted file mode 100644
index 598bd3b..0000000
--- a/ml-xgboost/R-package/R/xgb.plot.importance.R
+++ /dev/null
@@ -1,125 +0,0 @@
-#' Plot feature importance as a bar graph
-#'
-#' Represents previously calculated feature importance as a bar graph.
-#' \code{xgb.plot.importance} uses base R graphics, while \code{xgb.ggplot.importance} uses the ggplot backend.
-#'
-#' @param importance_matrix a \code{data.table} returned by \code{\link{xgb.importance}}.
-#' @param top_n maximal number of top features to include into the plot.
-#' @param measure the name of importance measure to plot.
-#' When \code{NULL}, 'Gain' would be used for trees and 'Weight' would be used for gblinear.
-#' @param rel_to_first whether importance values should be represented as relative to the highest ranked feature.
-#' See Details.
-#' @param left_margin (base R barplot) allows to adjust the left margin size to fit feature names.
-#' When it is NULL, the existing \code{par('mar')} is used.
-#' @param cex (base R barplot) passed as \code{cex.names} parameter to \code{barplot}.
-#' @param plot (base R barplot) whether a barplot should be produced.
-#' If FALSE, only a data.table is returned.
-#' @param n_clusters (ggplot only) a \code{numeric} vector containing the min and the max range
-#' of the possible number of clusters of bars.
-#' @param ... other parameters passed to \code{barplot} (except horiz, border, cex.names, names.arg, and las).
-#'
-#' @details
-#' The graph represents each feature as a horizontal bar of length proportional to the importance of a feature.
-#' Features are shown ranked in a decreasing importance order.
-#' It works for importances from both \code{gblinear} and \code{gbtree} models.
-#'
-#' When \code{rel_to_first = FALSE}, the values would be plotted as they were in \code{importance_matrix}.
-#' For gbtree model, that would mean being normalized to the total of 1
-#' ("what is feature's importance contribution relative to the whole model?").
-#' For linear models, \code{rel_to_first = FALSE} would show actual values of the coefficients.
-#' Setting \code{rel_to_first = TRUE} allows to see the picture from the perspective of
-#' "what is feature's importance contribution relative to the most important feature?"
-#'
-#' The ggplot-backend method also performs 1-D clustering of the importance values,
-#' with bar colors corresponding to different clusters that have somewhat similar importance values.
-#'
-#' @return
-#' The \code{xgb.plot.importance} function creates a \code{barplot} (when \code{plot=TRUE})
-#' and silently returns a processed data.table with \code{n_top} features sorted by importance.
-#'
-#' The \code{xgb.ggplot.importance} function returns a ggplot graph which could be customized afterwards.
-#' E.g., to change the title of the graph, add \code{+ ggtitle("A GRAPH NAME")} to the result.
-#'
-#' @seealso
-#' \code{\link[graphics]{barplot}}.
-#'
-#' @examples
-#' data(agaricus.train)
-#'
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 3,
-#' eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-#'
-#' importance_matrix <- xgb.importance(colnames(agaricus.train$data), model = bst)
-#'
-#' xgb.plot.importance(importance_matrix, rel_to_first = TRUE, xlab = "Relative importance")
-#'
-#' (gg <- xgb.ggplot.importance(importance_matrix, measure = "Frequency", rel_to_first = TRUE))
-#' gg + ggplot2::ylab("Frequency")
-#'
-#' @rdname xgb.plot.importance
-#' @export
-xgb.plot.importance <- function(importance_matrix = NULL, top_n = NULL, measure = NULL,
- rel_to_first = FALSE, left_margin = 10, cex = NULL, plot = TRUE, ...) {
- check.deprecation(...)
- if (!is.data.table(importance_matrix)) {
- stop("importance_matrix: must be a data.table")
- }
-
- imp_names <- colnames(importance_matrix)
- if (is.null(measure)) {
- if (all(c("Feature", "Gain") %in% imp_names)) {
- measure <- "Gain"
- } else if (all(c("Feature", "Weight") %in% imp_names)) {
- measure <- "Weight"
- } else {
- stop("Importance matrix column names are not as expected!")
- }
- } else {
- if (!measure %in% imp_names)
- stop("Invalid `measure`")
- if (!"Feature" %in% imp_names)
- stop("Importance matrix column names are not as expected!")
- }
-
- # also aggregate, just in case when the values were not yet summed up by feature
- importance_matrix <- importance_matrix[, Importance := sum(get(measure)), by = Feature]
-
- # make sure it's ordered
- importance_matrix <- importance_matrix[order(-abs(Importance))]
-
- if (!is.null(top_n)) {
- top_n <- min(top_n, nrow(importance_matrix))
- importance_matrix <- head(importance_matrix, top_n)
- }
- if (rel_to_first) {
- importance_matrix[, Importance := Importance/max(abs(Importance))]
- }
- if (is.null(cex)) {
- cex <- 2.5/log2(1 + nrow(importance_matrix))
- }
-
- if (plot) {
- op <- par(no.readonly = TRUE)
- mar <- op$mar
- if (!is.null(left_margin))
- mar[2] <- left_margin
- par(mar = mar)
-
- # reverse the order of rows to have the highest ranked at the top
- importance_matrix[nrow(importance_matrix):1,
- barplot(Importance, horiz = TRUE, border = NA, cex.names = cex,
- names.arg = Feature, las = 1, ...)]
- grid(NULL, NA)
- # redraw over the grid
- importance_matrix[nrow(importance_matrix):1,
- barplot(Importance, horiz = TRUE, border = NA, add = TRUE)]
- par(op)
- }
-
- invisible(importance_matrix)
-}
-
-# Avoid error messages during CRAN check.
-# The reason is that these variables are never declared
-# They are mainly column names inferred by Data.table...
-globalVariables(c("Feature", "Importance"))
diff --git a/ml-xgboost/R-package/R/xgb.plot.multi.trees.R b/ml-xgboost/R-package/R/xgb.plot.multi.trees.R
deleted file mode 100644
index 3e7b04b..0000000
--- a/ml-xgboost/R-package/R/xgb.plot.multi.trees.R
+++ /dev/null
@@ -1,148 +0,0 @@
-#' Project all trees on one tree and plot it
-#'
-#' Visualization of the ensemble of trees as a single collective unit.
-#'
-#' @param model produced by the \code{xgb.train} function.
-#' @param feature_names names of each feature as a \code{character} vector.
-#' @param features_keep number of features to keep in each position of the multi trees.
-#' @param plot_width width in pixels of the graph to produce
-#' @param plot_height height in pixels of the graph to produce
-#' @param render a logical flag for whether the graph should be rendered (see Value).
-#' @param ... currently not used
-#'
-#' @details
-#'
-#' This function tries to capture the complexity of a gradient boosted tree model
-#' in a cohesive way by compressing an ensemble of trees into a single tree-graph representation.
-#' The goal is to improve the interpretability of a model generally seen as black box.
-#'
-#' Note: this function is applicable to tree booster-based models only.
-#'
-#' It takes advantage of the fact that the shape of a binary tree is only defined by
-#' its depth (therefore, in a boosting model, all trees have similar shape).
-#'
-#' Moreover, the trees tend to reuse the same features.
-#'
-#' The function projects each tree onto one, and keeps for each position the
-#' \code{features_keep} first features (based on the Gain per feature measure).
-#'
-#' This function is inspired by this blog post:
-#' \url{https://wellecks.wordpress.com/2015/02/21/peering-into-the-black-box-visualizing-lambdamart/}
-#'
-#' @return
-#'
-#' When \code{render = TRUE}:
-#' returns a rendered graph object which is an \code{htmlwidget} of class \code{grViz}.
-#' Similar to ggplot objects, it needs to be printed to see it when not running from command line.
-#'
-#' When \code{render = FALSE}:
-#' silently returns a graph object which is of DiagrammeR's class \code{dgr_graph}.
-#' This could be useful if one wants to modify some of the graph attributes
-#' before rendering the graph with \code{\link[DiagrammeR]{render_graph}}.
-#'
-#' @examples
-#'
-#' data(agaricus.train, package='xgboost')
-#'
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 15,
-#' eta = 1, nthread = 2, nrounds = 30, objective = "binary:logistic",
-#' min_child_weight = 50, verbose = 0)
-#'
-#' p <- xgb.plot.multi.trees(model = bst, features_keep = 3)
-#' print(p)
-#'
-#' \dontrun{
-#' # Below is an example of how to save this plot to a file.
-#' # Note that for `export_graph` to work, the DiagrammeRsvg and rsvg packages must also be installed.
-#' library(DiagrammeR)
-#' gr <- xgb.plot.multi.trees(model=bst, features_keep = 3, render=FALSE)
-#' export_graph(gr, 'tree.pdf', width=1500, height=600)
-#' }
-#'
-#' @export
-xgb.plot.multi.trees <- function(model, feature_names = NULL, features_keep = 5, plot_width = NULL, plot_height = NULL,
- render = TRUE, ...){
- check.deprecation(...)
- tree.matrix <- xgb.model.dt.tree(feature_names = feature_names, model = model)
-
- # first number of the path represents the tree, then the following numbers are related to the path to follow
- # root init
- root.nodes <- tree.matrix[stri_detect_regex(ID, "\\d+-0"), ID]
- tree.matrix[ID %in% root.nodes, abs.node.position := root.nodes]
-
- precedent.nodes <- root.nodes
-
- while(tree.matrix[,sum(is.na(abs.node.position))] > 0) {
- yes.row.nodes <- tree.matrix[abs.node.position %in% precedent.nodes & !is.na(Yes)]
- no.row.nodes <- tree.matrix[abs.node.position %in% precedent.nodes & !is.na(No)]
- yes.nodes.abs.pos <- yes.row.nodes[, abs.node.position] %>% paste0("_0")
- no.nodes.abs.pos <- no.row.nodes[, abs.node.position] %>% paste0("_1")
-
- tree.matrix[ID %in% yes.row.nodes[, Yes], abs.node.position := yes.nodes.abs.pos]
- tree.matrix[ID %in% no.row.nodes[, No], abs.node.position := no.nodes.abs.pos]
- precedent.nodes <- c(yes.nodes.abs.pos, no.nodes.abs.pos)
- }
-
- tree.matrix[!is.na(Yes), Yes := paste0(abs.node.position, "_0")]
- tree.matrix[!is.na(No), No := paste0(abs.node.position, "_1")]
-
- remove.tree <- . %>% stri_replace_first_regex(pattern = "^\\d+-", replacement = "")
-
- tree.matrix[,`:=`(abs.node.position = remove.tree(abs.node.position),
- Yes = remove.tree(Yes),
- No = remove.tree(No))]
-
- nodes.dt <- tree.matrix[
- , .(Quality = sum(Quality))
- , by = .(abs.node.position, Feature)
- ][, .(Text = paste0(Feature[1:min(length(Feature), features_keep)],
- " (",
- format(Quality[1:min(length(Quality), features_keep)], digits=5),
- ")") %>%
- paste0(collapse = "\n"))
- , by = abs.node.position]
-
- edges.dt <- tree.matrix[Feature != "Leaf", .(abs.node.position, Yes)] %>%
- list(tree.matrix[Feature != "Leaf",.(abs.node.position, No)]) %>%
- rbindlist() %>%
- setnames(c("From", "To")) %>%
- .[, .N, .(From, To)] %>%
- .[, N:=NULL]
-
- nodes <- DiagrammeR::create_node_df(
- n = nrow(nodes.dt),
- label = nodes.dt[,Text]
- )
-
- edges <- DiagrammeR::create_edge_df(
- from = match(edges.dt[,From], nodes.dt[,abs.node.position]),
- to = match(edges.dt[,To], nodes.dt[,abs.node.position]),
- rel = "leading_to")
-
- graph <- DiagrammeR::create_graph(
- nodes_df = nodes,
- edges_df = edges,
- attr_theme = NULL
- ) %>%
- DiagrammeR::add_global_graph_attrs(
- attr_type = "graph",
- attr = c("layout", "rankdir"),
- value = c("dot", "LR")
- ) %>%
- DiagrammeR::add_global_graph_attrs(
- attr_type = "node",
- attr = c("color", "fillcolor", "style", "shape", "fontname"),
- value = c("DimGray", "beige", "filled", "rectangle", "Helvetica")
- ) %>%
- DiagrammeR::add_global_graph_attrs(
- attr_type = "edge",
- attr = c("color", "arrowsize", "arrowhead", "fontname"),
- value = c("DimGray", "1.5", "vee", "Helvetica"))
-
- if (!render) return(invisible(graph))
-
- DiagrammeR::render_graph(graph, width = plot_width, height = plot_height)
-}
-
-globalVariables(c(".N", "N", "From", "To", "Text", "Feature", "no.nodes.abs.pos",
- "ID", "Yes", "No", "Tree", "yes.nodes.abs.pos", "abs.node.position"))
diff --git a/ml-xgboost/R-package/R/xgb.plot.shap.R b/ml-xgboost/R-package/R/xgb.plot.shap.R
deleted file mode 100644
index 18f6aaa..0000000
--- a/ml-xgboost/R-package/R/xgb.plot.shap.R
+++ /dev/null
@@ -1,218 +0,0 @@
-#' SHAP contribution dependency plots
-#'
-#' Visualizing the SHAP feature contribution to prediction dependencies on feature value.
-#'
-#' @param data data as a \code{matrix} or \code{dgCMatrix}.
-#' @param shap_contrib a matrix of SHAP contributions that was computed earlier for the above
-#' \code{data}. When it is NULL, it is computed internally using \code{model} and \code{data}.
-#' @param features a vector of either column indices or of feature names to plot. When it is NULL,
-#' feature importance is calculated, and \code{top_n} high ranked features are taken.
-#' @param top_n when \code{features} is NULL, top_n [1, 100] most important features in a model are taken.
-#' @param model an \code{xgb.Booster} model. It has to be provided when either \code{shap_contrib}
-#' or \code{features} is missing.
-#' @param trees passed to \code{\link{xgb.importance}} when \code{features = NULL}.
-#' @param target_class is only relevant for multiclass models. When it is set to a 0-based class index,
-#' only SHAP contributions for that specific class are used.
-#' If it is not set, SHAP importances are averaged over all classes.
-#' @param approxcontrib passed to \code{\link{predict.xgb.Booster}} when \code{shap_contrib = NULL}.
-#' @param subsample a random fraction of data points to use for plotting. When it is NULL,
-#' it is set so that up to 100K data points are used.
-#' @param n_col a number of columns in a grid of plots.
-#' @param col color of the scatterplot markers.
-#' @param pch scatterplot marker.
-#' @param discrete_n_uniq a maximal number of unique values in a feature to consider it as discrete.
-#' @param discrete_jitter an \code{amount} parameter of jitter added to discrete features' positions.
-#' @param ylab a y-axis label in 1D plots.
-#' @param plot_NA whether the contributions of cases with missing values should also be plotted.
-#' @param col_NA a color of marker for missing value contributions.
-#' @param pch_NA a marker type for NA values.
-#' @param pos_NA a relative position of the x-location where NA values are shown:
-#' \code{min(x) + (max(x) - min(x)) * pos_NA}.
-#' @param plot_loess whether to plot loess-smoothed curves. The smoothing is only done for features with
-#' more than 5 distinct values.
-#' @param col_loess a color to use for the loess curves.
-#' @param span_loess the \code{span} parameter in \code{\link[stats]{loess}}'s call.
-#' @param which whether to do univariate or bivariate plotting. NOTE: only 1D is implemented so far.
-#' @param plot whether a plot should be drawn. If FALSE, only a lits of matrices is returned.
-#' @param ... other parameters passed to \code{plot}.
-#'
-#' @details
-#'
-#' These scatterplots represent how SHAP feature contributions depend of feature values.
-#' The similarity to partial dependency plots is that they also give an idea for how feature values
-#' affect predictions. However, in partial dependency plots, we usually see marginal dependencies
-#' of model prediction on feature value, while SHAP contribution dependency plots display the estimated
-#' contributions of a feature to model prediction for each individual case.
-#'
-#' When \code{plot_loess = TRUE} is set, feature values are rounded to 3 significant digits and
-#' weighted LOESS is computed and plotted, where weights are the numbers of data points
-#' at each rounded value.
-#'
-#' Note: SHAP contributions are shown on the scale of model margin. E.g., for a logistic binomial objective,
-#' the margin is prediction before a sigmoidal transform into probability-like values.
-#' Also, since SHAP stands for "SHapley Additive exPlanation" (model prediction = sum of SHAP
-#' contributions for all features + bias), depending on the objective used, transforming SHAP
-#' contributions for a feature from the marginal to the prediction space is not necessarily
-#' a meaningful thing to do.
-#'
-#' @return
-#'
-#' In addition to producing plots (when \code{plot=TRUE}), it silently returns a list of two matrices:
-#' \itemize{
-#' \item \code{data} the values of selected features;
-#' \item \code{shap_contrib} the contributions of selected features.
-#' }
-#'
-#' @references
-#'
-#' Scott M. Lundberg, Su-In Lee, "A Unified Approach to Interpreting Model Predictions", NIPS Proceedings 2017, \url{https://arxiv.org/abs/1705.07874}
-#'
-#' Scott M. Lundberg, Su-In Lee, "Consistent feature attribution for tree ensembles", \url{https://arxiv.org/abs/1706.06060}
-#'
-#' @examples
-#'
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#'
-#' bst <- xgboost(agaricus.train$data, agaricus.train$label, nrounds = 50,
-#' eta = 0.1, max_depth = 3, subsample = .5,
-#' method = "hist", objective = "binary:logistic", nthread = 2, verbose = 0)
-#'
-#' xgb.plot.shap(agaricus.test$data, model = bst, features = "odor=none")
-#' contr <- predict(bst, agaricus.test$data, predcontrib = TRUE)
-#' xgb.plot.shap(agaricus.test$data, contr, model = bst, top_n = 12, n_col = 3)
-#'
-#' # multiclass example - plots for each class separately:
-#' nclass <- 3
-#' nrounds <- 20
-#' x <- as.matrix(iris[, -5])
-#' set.seed(123)
-#' is.na(x[sample(nrow(x) * 4, 30)]) <- TRUE # introduce some missing values
-#' mbst <- xgboost(data = x, label = as.numeric(iris$Species) - 1, nrounds = nrounds,
-#' max_depth = 2, eta = 0.3, subsample = .5, nthread = 2,
-#' objective = "multi:softprob", num_class = nclass, verbose = 0)
-#' trees0 <- seq(from=0, by=nclass, length.out=nrounds)
-#' col <- rgb(0, 0, 1, 0.5)
-#' xgb.plot.shap(x, model = mbst, trees = trees0, target_class = 0, top_n = 4,
-#' n_col = 2, col = col, pch = 16, pch_NA = 17)
-#' xgb.plot.shap(x, model = mbst, trees = trees0 + 1, target_class = 1, top_n = 4,
-#' n_col = 2, col = col, pch = 16, pch_NA = 17)
-#' xgb.plot.shap(x, model = mbst, trees = trees0 + 2, target_class = 2, top_n = 4,
-#' n_col = 2, col = col, pch = 16, pch_NA = 17)
-#'
-#' @rdname xgb.plot.shap
-#' @export
-xgb.plot.shap <- function(data, shap_contrib = NULL, features = NULL, top_n = 1, model = NULL,
- trees = NULL, target_class = NULL, approxcontrib = FALSE,
- subsample = NULL, n_col = 1, col = rgb(0, 0, 1, 0.2), pch = '.',
- discrete_n_uniq = 5, discrete_jitter = 0.01, ylab = "SHAP",
- plot_NA = TRUE, col_NA = rgb(0.7, 0, 1, 0.6), pch_NA = '.', pos_NA = 1.07,
- plot_loess = TRUE, col_loess = 2, span_loess = 0.5,
- which = c("1d", "2d"), plot = TRUE, ...) {
-
- if (!is.matrix(data) && !inherits(data, "dgCMatrix"))
- stop("data: must be either matrix or dgCMatrix")
-
- if (is.null(shap_contrib) && (is.null(model) || !inherits(model, "xgb.Booster")))
- stop("when shap_contrib is not provided, one must provide an xgb.Booster model")
-
- if (is.null(features) && (is.null(model) || !inherits(model, "xgb.Booster")))
- stop("when features are not provided, one must provide an xgb.Booster model to rank the features")
-
- if (!is.null(shap_contrib) &&
- (!is.matrix(shap_contrib) || nrow(shap_contrib) != nrow(data) || ncol(shap_contrib) != ncol(data) + 1))
- stop("shap_contrib is not compatible with the provided data")
-
- nsample <- if (is.null(subsample)) min(100000, nrow(data)) else as.integer(subsample * nrow(data))
- idx <- sample(1:nrow(data), nsample)
- data <- data[idx,]
-
- if (is.null(shap_contrib)) {
- shap_contrib <- predict(model, data, predcontrib = TRUE, approxcontrib = approxcontrib)
- } else {
- shap_contrib <- shap_contrib[idx,]
- }
-
- which <- match.arg(which)
- if (which == "2d")
- stop("2D plots are not implemented yet")
-
- if (is.null(features)) {
- imp <- xgb.importance(model = model, trees = trees)
- top_n <- as.integer(top_n[1])
- if (top_n < 1 && top_n > 100)
- stop("top_n: must be an integer within [1, 100]")
- features <- imp$Feature[1:min(top_n, NROW(imp))]
- }
-
- if (is.character(features)) {
- if (is.null(colnames(data)))
- stop("Either provide `data` with column names or provide `features` as column indices")
- features <- match(features, colnames(data))
- }
-
- if (n_col > length(features)) n_col <- length(features)
-
- if (is.list(shap_contrib)) { # multiclass: either choose a class or merge
- shap_contrib <- if (!is.null(target_class)) shap_contrib[[target_class + 1]]
- else Reduce("+", lapply(shap_contrib, abs))
- }
-
- shap_contrib <- shap_contrib[, features, drop = FALSE]
- data <- data[, features, drop = FALSE]
- cols <- colnames(data)
- if (is.null(cols)) cols <- colnames(shap_contrib)
- if (is.null(cols)) cols <- paste0('X', 1:ncol(data))
- colnames(data) <- cols
- colnames(shap_contrib) <- cols
-
- if (plot && which == "1d") {
- op <- par(mfrow = c(ceiling(length(features) / n_col), n_col),
- oma = c(0,0,0,0) + 0.2,
- mar = c(3.5,3.5,0,0) + 0.1,
- mgp = c(1.7, 0.6, 0))
- for (f in cols) {
- ord <- order(data[, f])
- x <- data[, f][ord]
- y <- shap_contrib[, f][ord]
- x_lim <- range(x, na.rm = TRUE)
- y_lim <- range(y, na.rm = TRUE)
- do_na <- plot_NA && any(is.na(x))
- if (do_na) {
- x_range <- diff(x_lim)
- loc_na <- min(x, na.rm = TRUE) + x_range * pos_NA
- x_lim <- range(c(x_lim, loc_na))
- }
- x_uniq <- unique(x)
- x2plot <- x
- # add small jitter for discrete features with <= 5 distinct values
- if (length(x_uniq) <= discrete_n_uniq)
- x2plot <- jitter(x, amount = discrete_jitter * min(diff(x_uniq), na.rm = TRUE))
- plot(x2plot, y, pch = pch, xlab = f, col = col, xlim = x_lim, ylim = y_lim, ylab = ylab, ...)
- grid()
- if (plot_loess) {
- # compress x to 3 digits, and mean-aggredate y
- zz <- data.table(x = signif(x, 3), y)[, .(.N, y=mean(y)), x]
- if (nrow(zz) <= 5) {
- lines(zz$x, zz$y, col = col_loess)
- } else {
- lo <- stats::loess(y ~ x, data = zz, weights = zz$N, span = span_loess)
- zz$y_lo <- predict(lo, zz, type = "link")
- lines(zz$x, zz$y_lo, col = col_loess)
- }
- }
- if (do_na) {
- i_na <- which(is.na(x))
- x_na <- rep(loc_na, length(i_na))
- x_na <- jitter(x_na, amount = x_range * 0.01)
- points(x_na, y[i_na], pch = pch_NA, col = col_NA)
- }
- }
- par(op)
- }
- if (plot && which == "2d") {
- # TODO
- warning("Bivariate plotting is currently not available.")
- }
- invisible(list(data = data, shap_contrib = shap_contrib))
-}
diff --git a/ml-xgboost/R-package/R/xgb.plot.tree.R b/ml-xgboost/R-package/R/xgb.plot.tree.R
deleted file mode 100644
index 29c37d6..0000000
--- a/ml-xgboost/R-package/R/xgb.plot.tree.R
+++ /dev/null
@@ -1,138 +0,0 @@
-#' Plot a boosted tree model
-#'
-#' Read a tree model text dump and plot the model.
-#'
-#' @param feature_names names of each feature as a \code{character} vector.
-#' @param model produced by the \code{xgb.train} function.
-#' @param trees an integer vector of tree indices that should be visualized.
-#' If set to \code{NULL}, all trees of the model are included.
-#' IMPORTANT: the tree index in xgboost model is zero-based
-#' (e.g., use \code{trees = 0:2} for the first 3 trees in a model).
-#' @param plot_width the width of the diagram in pixels.
-#' @param plot_height the height of the diagram in pixels.
-#' @param render a logical flag for whether the graph should be rendered (see Value).
-#' @param show_node_id a logical flag for whether to show node id's in the graph.
-#' @param ... currently not used.
-#'
-#' @details
-#'
-#' The content of each node is organised that way:
-#'
-#' \itemize{
-#' \item Feature name.
-#' \item \code{Cover}: The sum of second order gradient of training data classified to the leaf.
-#' If it is square loss, this simply corresponds to the number of instances seen by a split
-#' or collected by a leaf during training.
-#' The deeper in the tree a node is, the lower this metric will be.
-#' \item \code{Gain} (for split nodes): the information gain metric of a split
-#' (corresponds to the importance of the node in the model).
-#' \item \code{Value} (for leafs): the margin value that the leaf may contribute to prediction.
-#' }
-#' The tree root nodes also indicate the Tree index (0-based).
-#'
-#' The "Yes" branches are marked by the "< split_value" label.
-#' The branches that also used for missing values are marked as bold
-#' (as in "carrying extra capacity").
-#'
-#' This function uses \href{http://www.graphviz.org/}{GraphViz} as a backend of DiagrammeR.
-#'
-#' @return
-#'
-#' When \code{render = TRUE}:
-#' returns a rendered graph object which is an \code{htmlwidget} of class \code{grViz}.
-#' Similar to ggplot objects, it needs to be printed to see it when not running from command line.
-#'
-#' When \code{render = FALSE}:
-#' silently returns a graph object which is of DiagrammeR's class \code{dgr_graph}.
-#' This could be useful if one wants to modify some of the graph attributes
-#' before rendering the graph with \code{\link[DiagrammeR]{render_graph}}.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#'
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 3,
-#' eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-#' # plot all the trees
-#' xgb.plot.tree(model = bst)
-#' # plot only the first tree and display the node ID:
-#' xgb.plot.tree(model = bst, trees = 0, show_node_id = TRUE)
-#'
-#' \dontrun{
-#' # Below is an example of how to save this plot to a file.
-#' # Note that for `export_graph` to work, the DiagrammeRsvg and rsvg packages must also be installed.
-#' library(DiagrammeR)
-#' gr <- xgb.plot.tree(model=bst, trees=0:1, render=FALSE)
-#' export_graph(gr, 'tree.pdf', width=1500, height=1900)
-#' export_graph(gr, 'tree.png', width=1500, height=1900)
-#' }
-#'
-#' @export
-xgb.plot.tree <- function(feature_names = NULL, model = NULL, trees = NULL, plot_width = NULL, plot_height = NULL,
- render = TRUE, show_node_id = FALSE, ...){
- check.deprecation(...)
- if (!inherits(model, "xgb.Booster")) {
- stop("model: Has to be an object of class xgb.Booster")
- }
-
- if (!requireNamespace("DiagrammeR", quietly = TRUE)) {
- stop("DiagrammeR package is required for xgb.plot.tree", call. = FALSE)
- }
-
- dt <- xgb.model.dt.tree(feature_names = feature_names, model = model, trees = trees)
-
- dt[, label:= paste0(Feature, "\nCover: ", Cover, ifelse(Feature == "Leaf", "\nValue: ", "\nGain: "), Quality)]
- if (show_node_id)
- dt[, label := paste0(ID, ": ", label)]
- dt[Node == 0, label := paste0("Tree ", Tree, "\n", label)]
- dt[, shape:= "rectangle"][Feature == "Leaf", shape:= "oval"]
- dt[, filledcolor:= "Beige"][Feature == "Leaf", filledcolor:= "Khaki"]
- # in order to draw the first tree on top:
- dt <- dt[order(-Tree)]
-
- nodes <- DiagrammeR::create_node_df(
- n = nrow(dt),
- ID = dt$ID,
- label = dt$label,
- fillcolor = dt$filledcolor,
- shape = dt$shape,
- data = dt$Feature,
- fontcolor = "black")
-
- edges <- DiagrammeR::create_edge_df(
- from = match(dt[Feature != "Leaf", c(ID)] %>% rep(2), dt$ID),
- to = match(dt[Feature != "Leaf", c(Yes, No)], dt$ID),
- label = dt[Feature != "Leaf", paste("<", Split)] %>%
- c(rep("", nrow(dt[Feature != "Leaf"]))),
- style = dt[Feature != "Leaf", ifelse(Missing == Yes, "bold", "solid")] %>%
- c(dt[Feature != "Leaf", ifelse(Missing == No, "bold", "solid")]),
- rel = "leading_to")
-
- graph <- DiagrammeR::create_graph(
- nodes_df = nodes,
- edges_df = edges,
- attr_theme = NULL
- ) %>%
- DiagrammeR::add_global_graph_attrs(
- attr_type = "graph",
- attr = c("layout", "rankdir"),
- value = c("dot", "LR")
- ) %>%
- DiagrammeR::add_global_graph_attrs(
- attr_type = "node",
- attr = c("color", "style", "fontname"),
- value = c("DimGray", "filled", "Helvetica")
- ) %>%
- DiagrammeR::add_global_graph_attrs(
- attr_type = "edge",
- attr = c("color", "arrowsize", "arrowhead", "fontname"),
- value = c("DimGray", "1.5", "vee", "Helvetica"))
-
- if (!render) return(invisible(graph))
-
- DiagrammeR::render_graph(graph, width = plot_width, height = plot_height)
-}
-
-# Avoid error messages during CRAN check.
-# The reason is that these variables are never declared
-# They are mainly column names inferred by Data.table...
-globalVariables(c("Feature", "ID", "Cover", "Quality", "Split", "Yes", "No", "Missing", ".", "shape", "filledcolor", "label"))
diff --git a/ml-xgboost/R-package/R/xgb.save.R b/ml-xgboost/R-package/R/xgb.save.R
deleted file mode 100644
index d969dae..0000000
--- a/ml-xgboost/R-package/R/xgb.save.R
+++ /dev/null
@@ -1,43 +0,0 @@
-#' Save xgboost model to binary file
-#'
-#' Save xgboost model to a file in binary format.
-#'
-#' @param model model object of \code{xgb.Booster} class.
-#' @param fname name of the file to write.
-#'
-#' @details
-#' This methods allows to save a model in an xgboost-internal binary format which is universal
-#' among the various xgboost interfaces. In R, the saved model file could be read-in later
-#' using either the \code{\link{xgb.load}} function or the \code{xgb_model} parameter
-#' of \code{\link{xgb.train}}.
-#'
-#' Note: a model can also be saved as an R-object (e.g., by using \code{\link[base]{readRDS}}
-#' or \code{\link[base]{save}}). However, it would then only be compatible with R, and
-#' corresponding R-methods would need to be used to load it.
-#'
-#' @seealso
-#' \code{\link{xgb.load}}, \code{\link{xgb.Booster.complete}}.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#' train <- agaricus.train
-#' test <- agaricus.test
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-#' xgb.save(bst, 'xgb.model')
-#' bst <- xgb.load('xgb.model')
-#' if (file.exists('xgb.model')) file.remove('xgb.model')
-#' pred <- predict(bst, test$data)
-#' @export
-xgb.save <- function(model, fname) {
- if (typeof(fname) != "character")
- stop("fname must be character")
- if (!inherits(model, "xgb.Booster")) {
- stop("model must be xgb.Booster.",
- if (inherits(model, "xgb.DMatrix")) " Use xgb.DMatrix.save to save an xgb.DMatrix object." else "")
- }
- model <- xgb.Booster.complete(model, saveraw = FALSE)
- .Call(XGBoosterSaveModel_R, model$handle, fname[1])
- return(TRUE)
-}
diff --git a/ml-xgboost/R-package/R/xgb.save.raw.R b/ml-xgboost/R-package/R/xgb.save.raw.R
deleted file mode 100644
index 967a314..0000000
--- a/ml-xgboost/R-package/R/xgb.save.raw.R
+++ /dev/null
@@ -1,23 +0,0 @@
-#' Save xgboost model to R's raw vector,
-#' user can call xgb.load.raw to load the model back from raw vector
-#'
-#' Save xgboost model from xgboost or xgb.train
-#'
-#' @param model the model object.
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#' train <- agaricus.train
-#' test <- agaricus.test
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-#' raw <- xgb.save.raw(bst)
-#' bst <- xgb.load.raw(raw)
-#' pred <- predict(bst, test$data)
-#'
-#' @export
-xgb.save.raw <- function(model) {
- handle <- xgb.get.handle(model)
- .Call(XGBoosterModelToRaw_R, handle)
-}
diff --git a/ml-xgboost/R-package/R/xgb.serialize.R b/ml-xgboost/R-package/R/xgb.serialize.R
deleted file mode 100644
index 00bbb42..0000000
--- a/ml-xgboost/R-package/R/xgb.serialize.R
+++ /dev/null
@@ -1,21 +0,0 @@
-#' Serialize the booster instance into R's raw vector. The serialization method differs
-#' from \code{\link{xgb.save.raw}} as the latter one saves only the model but not
-#' parameters. This serialization format is not stable across different xgboost versions.
-#'
-#' @param booster the booster instance
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#' train <- agaricus.train
-#' test <- agaricus.test
-#' bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
-#' eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-#' raw <- xgb.serialize(bst)
-#' bst <- xgb.unserialize(raw)
-#'
-#' @export
-xgb.serialize <- function(booster) {
- handle <- xgb.get.handle(booster)
- .Call(XGBoosterSerializeToBuffer_R, handle)
-}
diff --git a/ml-xgboost/R-package/R/xgb.train.R b/ml-xgboost/R-package/R/xgb.train.R
deleted file mode 100644
index 8733bcc..0000000
--- a/ml-xgboost/R-package/R/xgb.train.R
+++ /dev/null
@@ -1,377 +0,0 @@
-#' eXtreme Gradient Boosting Training
-#'
-#' \code{xgb.train} is an advanced interface for training an xgboost model.
-#' The \code{xgboost} function is a simpler wrapper for \code{xgb.train}.
-#'
-#' @param params the list of parameters.
-#' The complete list of parameters is available at \url{http://xgboost.readthedocs.io/en/latest/parameter.html}.
-#' Below is a shorter summary:
-#'
-#' 1. General Parameters
-#'
-#' \itemize{
-#' \item \code{booster} which booster to use, can be \code{gbtree} or \code{gblinear}. Default: \code{gbtree}.
-#' }
-#'
-#' 2. Booster Parameters
-#'
-#' 2.1. Parameter for Tree Booster
-#'
-#' \itemize{
-#' \item \code{eta} control the learning rate: scale the contribution of each tree by a factor of \code{0 < eta < 1} when it is added to the current approximation. Used to prevent overfitting by making the boosting process more conservative. Lower value for \code{eta} implies larger value for \code{nrounds}: low \code{eta} value means model more robust to overfitting but slower to compute. Default: 0.3
-#' \item \code{gamma} minimum loss reduction required to make a further partition on a leaf node of the tree. the larger, the more conservative the algorithm will be.
-#' \item \code{max_depth} maximum depth of a tree. Default: 6
-#' \item \code{min_child_weight} minimum sum of instance weight (hessian) needed in a child. If the tree partition step results in a leaf node with the sum of instance weight less than min_child_weight, then the building process will give up further partitioning. In linear regression mode, this simply corresponds to minimum number of instances needed to be in each node. The larger, the more conservative the algorithm will be. Default: 1
-#' \item \code{subsample} subsample ratio of the training instance. Setting it to 0.5 means that xgboost randomly collected half of the data instances to grow trees and this will prevent overfitting. It makes computation shorter (because less data to analyse). It is advised to use this parameter with \code{eta} and increase \code{nrounds}. Default: 1
-#' \item \code{colsample_bytree} subsample ratio of columns when constructing each tree. Default: 1
-#' \item \code{num_parallel_tree} Experimental parameter. number of trees to grow per round. Useful to test Random Forest through Xgboost (set \code{colsample_bytree < 1}, \code{subsample < 1} and \code{round = 1}) accordingly. Default: 1
-#' \item \code{monotone_constraints} A numerical vector consists of \code{1}, \code{0} and \code{-1} with its length equals to the number of features in the training data. \code{1} is increasing, \code{-1} is decreasing and \code{0} is no constraint.
-#' \item \code{interaction_constraints} A list of vectors specifying feature indices of permitted interactions. Each item of the list represents one permitted interaction where specified features are allowed to interact with each other. Feature index values should start from \code{0} (\code{0} references the first column). Leave argument unspecified for no interaction constraints.
-#' }
-#'
-#' 2.2. Parameter for Linear Booster
-#'
-#' \itemize{
-#' \item \code{lambda} L2 regularization term on weights. Default: 0
-#' \item \code{lambda_bias} L2 regularization term on bias. Default: 0
-#' \item \code{alpha} L1 regularization term on weights. (there is no L1 reg on bias because it is not important). Default: 0
-#' }
-#'
-#' 3. Task Parameters
-#'
-#' \itemize{
-#' \item \code{objective} specify the learning task and the corresponding learning objective, users can pass a self-defined function to it. The default objective options are below:
-#' \itemize{
-#' \item \code{reg:squarederror} Regression with squared loss (Default).
-#' \item \code{reg:logistic} logistic regression.
-#' \item \code{binary:logistic} logistic regression for binary classification. Output probability.
-#' \item \code{binary:logitraw} logistic regression for binary classification, output score before logistic transformation.
-#' \item \code{num_class} set the number of classes. To use only with multiclass objectives.
-#' \item \code{multi:softmax} set xgboost to do multiclass classification using the softmax objective. Class is represented by a number and should be from 0 to \code{num_class - 1}.
-#' \item \code{multi:softprob} same as softmax, but prediction outputs a vector of ndata * nclass elements, which can be further reshaped to ndata, nclass matrix. The result contains predicted probabilities of each data point belonging to each class.
-#' \item \code{rank:pairwise} set xgboost to do ranking task by minimizing the pairwise loss.
-#' }
-#' \item \code{base_score} the initial prediction score of all instances, global bias. Default: 0.5
-#' \item \code{eval_metric} evaluation metrics for validation data. Users can pass a self-defined function to it. Default: metric will be assigned according to objective(rmse for regression, and error for classification, mean average precision for ranking). List is provided in detail section.
-#' }
-#'
-#' @param data training dataset. \code{xgb.train} accepts only an \code{xgb.DMatrix} as the input.
-#' \code{xgboost}, in addition, also accepts \code{matrix}, \code{dgCMatrix}, or name of a local data file.
-#' @param nrounds max number of boosting iterations.
-#' @param watchlist named list of xgb.DMatrix datasets to use for evaluating model performance.
-#' Metrics specified in either \code{eval_metric} or \code{feval} will be computed for each
-#' of these datasets during each boosting iteration, and stored in the end as a field named
-#' \code{evaluation_log} in the resulting object. When either \code{verbose>=1} or
-#' \code{\link{cb.print.evaluation}} callback is engaged, the performance results are continuously
-#' printed out during the training.
-#' E.g., specifying \code{watchlist=list(validation1=mat1, validation2=mat2)} allows to track
-#' the performance of each round's model on mat1 and mat2.
-#' @param obj customized objective function. Returns gradient and second order
-#' gradient with given prediction and dtrain.
-#' @param feval customized evaluation function. Returns
-#' \code{list(metric='metric-name', value='metric-value')} with given
-#' prediction and dtrain.
-#' @param verbose If 0, xgboost will stay silent. If 1, it will print information about performance.
-#' If 2, some additional information will be printed out.
-#' Note that setting \code{verbose > 0} automatically engages the
-#' \code{cb.print.evaluation(period=1)} callback function.
-#' @param print_every_n Print each n-th iteration evaluation messages when \code{verbose>0}.
-#' Default is 1 which means all messages are printed. This parameter is passed to the
-#' \code{\link{cb.print.evaluation}} callback.
-#' @param early_stopping_rounds If \code{NULL}, the early stopping function is not triggered.
-#' If set to an integer \code{k}, training with a validation set will stop if the performance
-#' doesn't improve for \code{k} rounds.
-#' Setting this parameter engages the \code{\link{cb.early.stop}} callback.
-#' @param maximize If \code{feval} and \code{early_stopping_rounds} are set,
-#' then this parameter must be set as well.
-#' When it is \code{TRUE}, it means the larger the evaluation score the better.
-#' This parameter is passed to the \code{\link{cb.early.stop}} callback.
-#' @param save_period when it is non-NULL, model is saved to disk after every \code{save_period} rounds,
-#' 0 means save at the end. The saving is handled by the \code{\link{cb.save.model}} callback.
-#' @param save_name the name or path for periodically saved model file.
-#' @param xgb_model a previously built model to continue the training from.
-#' Could be either an object of class \code{xgb.Booster}, or its raw data, or the name of a
-#' file with a previously saved model.
-#' @param callbacks a list of callback functions to perform various task during boosting.
-#' See \code{\link{callbacks}}. Some of the callbacks are automatically created depending on the
-#' parameters' values. User can provide either existing or their own callback methods in order
-#' to customize the training process.
-#' @param ... other parameters to pass to \code{params}.
-#' @param label vector of response values. Should not be provided when data is
-#' a local data file name or an \code{xgb.DMatrix}.
-#' @param missing by default is set to NA, which means that NA values should be considered as 'missing'
-#' by the algorithm. Sometimes, 0 or other extreme value might be used to represent missing values.
-#' This parameter is only used when input is a dense matrix.
-#' @param weight a vector indicating the weight for each row of the input.
-#'
-#' @details
-#' These are the training functions for \code{xgboost}.
-#'
-#' The \code{xgb.train} interface supports advanced features such as \code{watchlist},
-#' customized objective and evaluation metric functions, therefore it is more flexible
-#' than the \code{xgboost} interface.
-#'
-#' Parallelization is automatically enabled if \code{OpenMP} is present.
-#' Number of threads can also be manually specified via \code{nthread} parameter.
-#'
-#' The evaluation metric is chosen automatically by Xgboost (according to the objective)
-#' when the \code{eval_metric} parameter is not provided.
-#' User may set one or several \code{eval_metric} parameters.
-#' Note that when using a customized metric, only this single metric can be used.
-#' The following is the list of built-in metrics for which Xgboost provides optimized implementation:
-#' \itemize{
-#' \item \code{rmse} root mean square error. \url{http://en.wikipedia.org/wiki/Root_mean_square_error}
-#' \item \code{logloss} negative log-likelihood. \url{http://en.wikipedia.org/wiki/Log-likelihood}
-#' \item \code{mlogloss} multiclass logloss. \url{http://wiki.fast.ai/index.php/Log_Loss}
-#' \item \code{error} Binary classification error rate. It is calculated as \code{(# wrong cases) / (# all cases)}.
-#' By default, it uses the 0.5 threshold for predicted values to define negative and positive instances.
-#' Different threshold (e.g., 0.) could be specified as "error@0."
-#' \item \code{merror} Multiclass classification error rate. It is calculated as \code{(# wrong cases) / (# all cases)}.
-#' \item \code{auc} Area under the curve. \url{http://en.wikipedia.org/wiki/Receiver_operating_characteristic#'Area_under_curve} for ranking evaluation.
-#' \item \code{aucpr} Area under the PR curve. \url{https://en.wikipedia.org/wiki/Precision_and_recall} for ranking evaluation.
-#' \item \code{ndcg} Normalized Discounted Cumulative Gain (for ranking task). \url{http://en.wikipedia.org/wiki/NDCG}
-#' }
-#'
-#' The following callbacks are automatically created when certain parameters are set:
-#' \itemize{
-#' \item \code{cb.print.evaluation} is turned on when \code{verbose > 0};
-#' and the \code{print_every_n} parameter is passed to it.
-#' \item \code{cb.evaluation.log} is on when \code{watchlist} is present.
-#' \item \code{cb.early.stop}: when \code{early_stopping_rounds} is set.
-#' \item \code{cb.save.model}: when \code{save_period > 0} is set.
-#' }
-#'
-#' @return
-#' An object of class \code{xgb.Booster} with the following elements:
-#' \itemize{
-#' \item \code{handle} a handle (pointer) to the xgboost model in memory.
-#' \item \code{raw} a cached memory dump of the xgboost model saved as R's \code{raw} type.
-#' \item \code{niter} number of boosting iterations.
-#' \item \code{evaluation_log} evaluation history stored as a \code{data.table} with the
-#' first column corresponding to iteration number and the rest corresponding to evaluation
-#' metrics' values. It is created by the \code{\link{cb.evaluation.log}} callback.
-#' \item \code{call} a function call.
-#' \item \code{params} parameters that were passed to the xgboost library. Note that it does not
-#' capture parameters changed by the \code{\link{cb.reset.parameters}} callback.
-#' \item \code{callbacks} callback functions that were either automatically assigned or
-#' explicitly passed.
-#' \item \code{best_iteration} iteration number with the best evaluation metric value
-#' (only available with early stopping).
-#' \item \code{best_ntreelimit} the \code{ntreelimit} value corresponding to the best iteration,
-#' which could further be used in \code{predict} method
-#' (only available with early stopping).
-#' \item \code{best_score} the best evaluation metric value during early stopping.
-#' (only available with early stopping).
-#' \item \code{feature_names} names of the training dataset features
-#' (only when column names were defined in training data).
-#' \item \code{nfeatures} number of features in training data.
-#' }
-#'
-#' @seealso
-#' \code{\link{callbacks}},
-#' \code{\link{predict.xgb.Booster}},
-#' \code{\link{xgb.cv}}
-#'
-#' @references
-#'
-#' Tianqi Chen and Carlos Guestrin, "XGBoost: A Scalable Tree Boosting System",
-#' 22nd SIGKDD Conference on Knowledge Discovery and Data Mining, 2016, \url{https://arxiv.org/abs/1603.02754}
-#'
-#' @examples
-#' data(agaricus.train, package='xgboost')
-#' data(agaricus.test, package='xgboost')
-#'
-#' dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-#' dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-#' watchlist <- list(train = dtrain, eval = dtest)
-#'
-#' ## A simple xgb.train example:
-#' param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2,
-#' objective = "binary:logistic", eval_metric = "auc")
-#' bst <- xgb.train(param, dtrain, nrounds = 2, watchlist)
-#'
-#'
-#' ## An xgb.train example where custom objective and evaluation metric are used:
-#' logregobj <- function(preds, dtrain) {
-#' labels <- getinfo(dtrain, "label")
-#' preds <- 1/(1 + exp(-preds))
-#' grad <- preds - labels
-#' hess <- preds * (1 - preds)
-#' return(list(grad = grad, hess = hess))
-#' }
-#' evalerror <- function(preds, dtrain) {
-#' labels <- getinfo(dtrain, "label")
-#' err <- as.numeric(sum(labels != (preds > 0)))/length(labels)
-#' return(list(metric = "error", value = err))
-#' }
-#'
-#' # These functions could be used by passing them either:
-#' # as 'objective' and 'eval_metric' parameters in the params list:
-#' param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2,
-#' objective = logregobj, eval_metric = evalerror)
-#' bst <- xgb.train(param, dtrain, nrounds = 2, watchlist)
-#'
-#' # or through the ... arguments:
-#' param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2)
-#' bst <- xgb.train(param, dtrain, nrounds = 2, watchlist,
-#' objective = logregobj, eval_metric = evalerror)
-#'
-#' # or as dedicated 'obj' and 'feval' parameters of xgb.train:
-#' bst <- xgb.train(param, dtrain, nrounds = 2, watchlist,
-#' obj = logregobj, feval = evalerror)
-#'
-#'
-#' ## An xgb.train example of using variable learning rates at each iteration:
-#' param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2,
-#' objective = "binary:logistic", eval_metric = "auc")
-#' my_etas <- list(eta = c(0.5, 0.1))
-#' bst <- xgb.train(param, dtrain, nrounds = 2, watchlist,
-#' callbacks = list(cb.reset.parameters(my_etas)))
-#'
-#' ## Early stopping:
-#' bst <- xgb.train(param, dtrain, nrounds = 25, watchlist,
-#' early_stopping_rounds = 3)
-#'
-#' ## An 'xgboost' interface example:
-#' bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label,
-#' max_depth = 2, eta = 1, nthread = 2, nrounds = 2,
-#' objective = "binary:logistic")
-#' pred <- predict(bst, agaricus.test$data)
-#'
-#' @rdname xgb.train
-#' @export
-xgb.train <- function(params = list(), data, nrounds, watchlist = list(),
- obj = NULL, feval = NULL, verbose = 1, print_every_n = 1L,
- early_stopping_rounds = NULL, maximize = NULL,
- save_period = NULL, save_name = "xgboost.model",
- xgb_model = NULL, callbacks = list(), ...) {
-
- check.deprecation(...)
-
- params <- check.booster.params(params, ...)
-
- check.custom.obj()
- check.custom.eval()
-
- # data & watchlist checks
- dtrain <- data
- if (!inherits(dtrain, "xgb.DMatrix"))
- stop("second argument dtrain must be xgb.DMatrix")
- if (length(watchlist) > 0) {
- if (typeof(watchlist) != "list" ||
- !all(vapply(watchlist, inherits, logical(1), what = 'xgb.DMatrix')))
- stop("watchlist must be a list of xgb.DMatrix elements")
- evnames <- names(watchlist)
- if (is.null(evnames) || any(evnames == ""))
- stop("each element of the watchlist must have a name tag")
- }
-
- # evaluation printing callback
- params <- c(params)
- print_every_n <- max( as.integer(print_every_n), 1L)
- if (!has.callbacks(callbacks, 'cb.print.evaluation') &&
- verbose) {
- callbacks <- add.cb(callbacks, cb.print.evaluation(print_every_n))
- }
- # evaluation log callback: it is automatically enabled when watchlist is provided
- evaluation_log <- list()
- if (!has.callbacks(callbacks, 'cb.evaluation.log') &&
- length(watchlist) > 0) {
- callbacks <- add.cb(callbacks, cb.evaluation.log())
- }
- # Model saving callback
- if (!is.null(save_period) &&
- !has.callbacks(callbacks, 'cb.save.model')) {
- callbacks <- add.cb(callbacks, cb.save.model(save_period, save_name))
- }
- # Early stopping callback
- stop_condition <- FALSE
- if (!is.null(early_stopping_rounds) &&
- !has.callbacks(callbacks, 'cb.early.stop')) {
- callbacks <- add.cb(callbacks, cb.early.stop(early_stopping_rounds,
- maximize = maximize, verbose = verbose))
- }
-
- # Sort the callbacks into categories
- cb <- categorize.callbacks(callbacks)
- params['validate_parameters'] <- TRUE
- if (!is.null(params[['seed']])) {
- warning("xgb.train: `seed` is ignored in R package. Use `set.seed()` instead.")
- }
-
- # The tree updating process would need slightly different handling
- is_update <- NVL(params[['process_type']], '.') == 'update'
-
- # Construct a booster (either a new one or load from xgb_model)
- handle <- xgb.Booster.handle(params, append(watchlist, dtrain), xgb_model)
- bst <- xgb.handleToBooster(handle)
-
- # extract parameters that can affect the relationship b/w #trees and #iterations
- num_class <- max(as.numeric(NVL(params[['num_class']], 1)), 1)
- num_parallel_tree <- max(as.numeric(NVL(params[['num_parallel_tree']], 1)), 1)
-
- # When the 'xgb_model' was set, find out how many boosting iterations it has
- niter_init <- 0
- if (!is.null(xgb_model)) {
- niter_init <- as.numeric(xgb.attr(bst, 'niter')) + 1
- if (length(niter_init) == 0) {
- niter_init <- xgb.ntree(bst) %/% (num_parallel_tree * num_class)
- }
- }
- if(is_update && nrounds > niter_init)
- stop("nrounds cannot be larger than ", niter_init, " (nrounds of xgb_model)")
-
- # TODO: distributed code
- rank <- 0
-
- niter_skip <- ifelse(is_update, 0, niter_init)
- begin_iteration <- niter_skip + 1
- end_iteration <- niter_skip + nrounds
-
- # the main loop for boosting iterations
- for (iteration in begin_iteration:end_iteration) {
-
- for (f in cb$pre_iter) f()
-
- xgb.iter.update(bst$handle, dtrain, iteration - 1, obj)
-
- bst_evaluation <- numeric(0)
- if (length(watchlist) > 0)
- bst_evaluation <- xgb.iter.eval(bst$handle, watchlist, iteration - 1, feval)
-
- xgb.attr(bst$handle, 'niter') <- iteration - 1
-
- for (f in cb$post_iter) f()
-
- if (stop_condition) break
- }
- for (f in cb$finalize) f(finalize = TRUE)
-
- bst <- xgb.Booster.complete(bst, saveraw = TRUE)
-
- # store the total number of boosting iterations
- bst$niter = end_iteration
-
- # store the evaluation results
- if (length(evaluation_log) > 0 &&
- nrow(evaluation_log) > 0) {
- # include the previous compatible history when available
- if (inherits(xgb_model, 'xgb.Booster') &&
- !is_update &&
- !is.null(xgb_model$evaluation_log) &&
- isTRUE(all.equal(colnames(evaluation_log),
- colnames(xgb_model$evaluation_log)))) {
- evaluation_log <- rbindlist(list(xgb_model$evaluation_log, evaluation_log))
- }
- bst$evaluation_log <- evaluation_log
- }
-
- bst$call <- match.call()
- bst$params <- params
- bst$callbacks <- callbacks
- if (!is.null(colnames(dtrain)))
- bst$feature_names <- colnames(dtrain)
- bst$nfeatures <- ncol(dtrain)
-
- return(bst)
-}
diff --git a/ml-xgboost/R-package/R/xgb.unserialize.R b/ml-xgboost/R-package/R/xgb.unserialize.R
deleted file mode 100644
index 1a62e4c..0000000
--- a/ml-xgboost/R-package/R/xgb.unserialize.R
+++ /dev/null
@@ -1,12 +0,0 @@
-#' Load the instance back from \code{\link{xgb.serialize}}
-#'
-#' @param buffer the buffer containing booster instance saved by \code{\link{xgb.serialize}}
-#'
-#' @export
-xgb.unserialize <- function(buffer) {
- cachelist <- list()
- handle <- .Call(XGBoosterCreate_R, cachelist)
- .Call(XGBoosterUnserializeFromBuffer_R, handle, buffer)
- class(handle) <- "xgb.Booster.handle"
- return (handle)
-}
diff --git a/ml-xgboost/R-package/R/xgboost.R b/ml-xgboost/R-package/R/xgboost.R
deleted file mode 100644
index 2fddfa4..0000000
--- a/ml-xgboost/R-package/R/xgboost.R
+++ /dev/null
@@ -1,113 +0,0 @@
-# Simple interface for training an xgboost model that wraps \code{xgb.train}.
-# Its documentation is combined with xgb.train.
-#
-#' @rdname xgb.train
-#' @export
-xgboost <- function(data = NULL, label = NULL, missing = NA, weight = NULL,
- params = list(), nrounds,
- verbose = 1, print_every_n = 1L,
- early_stopping_rounds = NULL, maximize = NULL,
- save_period = NULL, save_name = "xgboost.model",
- xgb_model = NULL, callbacks = list(), ...) {
-
- dtrain <- xgb.get.DMatrix(data, label, missing, weight)
-
- watchlist <- list(train = dtrain)
-
- bst <- xgb.train(params, dtrain, nrounds, watchlist, verbose = verbose, print_every_n = print_every_n,
- early_stopping_rounds = early_stopping_rounds, maximize = maximize,
- save_period = save_period, save_name = save_name,
- xgb_model = xgb_model, callbacks = callbacks, ...)
- return (bst)
-}
-
-#' Training part from Mushroom Data Set
-#'
-#' This data set is originally from the Mushroom data set,
-#' UCI Machine Learning Repository.
-#'
-#' This data set includes the following fields:
-#'
-#' \itemize{
-#' \item \code{label} the label for each record
-#' \item \code{data} a sparse Matrix of \code{dgCMatrix} class, with 126 columns.
-#' }
-#'
-#' @references
-#' https://archive.ics.uci.edu/ml/datasets/Mushroom
-#'
-#' Bache, K. & Lichman, M. (2013). UCI Machine Learning Repository
-#' [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California,
-#' School of Information and Computer Science.
-#'
-#' @docType data
-#' @keywords datasets
-#' @name agaricus.train
-#' @usage data(agaricus.train)
-#' @format A list containing a label vector, and a dgCMatrix object with 6513
-#' rows and 127 variables
-NULL
-
-#' Test part from Mushroom Data Set
-#'
-#' This data set is originally from the Mushroom data set,
-#' UCI Machine Learning Repository.
-#'
-#' This data set includes the following fields:
-#'
-#' \itemize{
-#' \item \code{label} the label for each record
-#' \item \code{data} a sparse Matrix of \code{dgCMatrix} class, with 126 columns.
-#' }
-#'
-#' @references
-#' https://archive.ics.uci.edu/ml/datasets/Mushroom
-#'
-#' Bache, K. & Lichman, M. (2013). UCI Machine Learning Repository
-#' [http://archive.ics.uci.edu/ml]. Irvine, CA: University of California,
-#' School of Information and Computer Science.
-#'
-#' @docType data
-#' @keywords datasets
-#' @name agaricus.test
-#' @usage data(agaricus.test)
-#' @format A list containing a label vector, and a dgCMatrix object with 1611
-#' rows and 126 variables
-NULL
-
-# Various imports
-#' @importClassesFrom Matrix dgCMatrix dgeMatrix
-#' @importFrom Matrix colSums
-#' @importFrom Matrix sparse.model.matrix
-#' @importFrom Matrix sparseVector
-#' @importFrom Matrix sparseMatrix
-#' @importFrom Matrix t
-#' @importFrom data.table data.table
-#' @importFrom data.table is.data.table
-#' @importFrom data.table as.data.table
-#' @importFrom data.table :=
-#' @importFrom data.table rbindlist
-#' @importFrom data.table setkey
-#' @importFrom data.table setkeyv
-#' @importFrom data.table setnames
-#' @importFrom magrittr %>%
-#' @importFrom stringi stri_detect_regex
-#' @importFrom stringi stri_match_first_regex
-#' @importFrom stringi stri_replace_first_regex
-#' @importFrom stringi stri_replace_all_regex
-#' @importFrom stringi stri_split_regex
-#' @importFrom utils object.size str tail
-#' @importFrom stats predict
-#' @importFrom stats median
-#' @importFrom utils head
-#' @importFrom graphics barplot
-#' @importFrom graphics lines
-#' @importFrom graphics points
-#' @importFrom graphics grid
-#' @importFrom graphics par
-#' @importFrom graphics title
-#' @importFrom grDevices rgb
-#'
-#' @import methods
-#' @useDynLib xgboost, .registration = TRUE
-NULL
diff --git a/ml-xgboost/R-package/README.md b/ml-xgboost/R-package/README.md
deleted file mode 100644
index c548731..0000000
--- a/ml-xgboost/R-package/README.md
+++ /dev/null
@@ -1,33 +0,0 @@
-XGBoost R Package for Scalable GBM
-==================================
-
-[![CRAN Status Badge](http://www.r-pkg.org/badges/version/xgboost)](https://cran.r-project.org/web/packages/xgboost)
-[![CRAN Downloads](http://cranlogs.r-pkg.org/badges/xgboost)](https://cran.rstudio.com/web/packages/xgboost/index.html)
-[![Documentation Status](https://readthedocs.org/projects/xgboost/badge/?version=latest)](http://xgboost.readthedocs.org/en/latest/R-package/index.html)
-
-Resources
----------
-* [XGBoost R Package Online Documentation](http://xgboost.readthedocs.org/en/latest/R-package/index.html)
- - Check this out for detailed documents, examples and tutorials.
-
-Installation
-------------
-
-We are [on CRAN](https://cran.r-project.org/web/packages/xgboost/index.html) now. For stable/pre-compiled(for Windows and OS X) version, please install from CRAN:
-
-```r
-install.packages('xgboost')
-```
-
-For more detailed installation instructions, please see [here](http://xgboost.readthedocs.org/en/latest/build.html#r-package-installation).
-
-Examples
---------
-
-* Please visit [walk through example](demo).
-* See also the [example scripts](../demo/kaggle-higgs) for Kaggle Higgs Challenge, including [speedtest script](../demo/kaggle-higgs/speedtest.R) on this dataset and the one related to [Otto challenge](../demo/kaggle-otto), including a [RMarkdown documentation](../demo/kaggle-otto/understandingXGBoostModel.Rmd).
-
-Development
------------
-
-* See the [R Package section](https://xgboost.readthedocs.io/en/latest/contribute.html#r-package) of the contributors guide.
diff --git a/ml-xgboost/R-package/cleanup b/ml-xgboost/R-package/cleanup
deleted file mode 100644
index eb86699..0000000
--- a/ml-xgboost/R-package/cleanup
+++ /dev/null
@@ -1,4 +0,0 @@
-#!/bin/sh
-
-rm -f src/Makevars
-rm -f CMakeLists.txt
diff --git a/ml-xgboost/R-package/configure b/ml-xgboost/R-package/configure
deleted file mode 100644
index 8dab660..0000000
--- a/ml-xgboost/R-package/configure
+++ /dev/null
@@ -1,3891 +0,0 @@
-#! /bin/sh
-# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for xgboost 0.6-3.
-#
-#
-# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
-#
-#
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
- emulate sh
- NULLCMD=:
- # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
- # is contrary to our usage. Disable this feature.
- alias -g '${1+"$@"}'='"$@"'
- setopt NO_GLOB_SUBST
-else
- case `(set -o) 2>/dev/null` in #(
- *posix*) :
- set -o posix ;; #(
- *) :
- ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
- && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='print -r --'
- as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='printf %s\n'
- as_echo_n='printf %s'
-else
- if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
- as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
- as_echo_n='/usr/ucb/echo -n'
- else
- as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
- as_echo_n_body='eval
- arg=$1;
- case $arg in #(
- *"$as_nl"*)
- expr "X$arg" : "X\\(.*\\)$as_nl";
- arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
- esac;
- expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
- '
- export as_echo_n_body
- as_echo_n='sh -c $as_echo_n_body as_echo'
- fi
- export as_echo_body
- as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
- PATH_SEPARATOR=:
- (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
- (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
- PATH_SEPARATOR=';'
- }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order. Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" "" $as_nl"
-
-# Find who we are. Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
- *[\\/]* ) as_myself=$0 ;;
- *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
- done
-IFS=$as_save_IFS
-
- ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
- as_myself=$0
-fi
-if test ! -f "$as_myself"; then
- $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
- exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there. '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
- && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-# Use a proper internal environment variable to ensure we don't fall
- # into an infinite loop, continuously re-executing ourselves.
- if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
- _as_can_reexec=no; export _as_can_reexec;
- # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
- *v*x* | *x*v* ) as_opts=-vx ;;
- *v* ) as_opts=-v ;;
- *x* ) as_opts=-x ;;
- * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-as_fn_exit 255
- fi
- # We don't want this to propagate to other subprocesses.
- { _as_can_reexec=; unset _as_can_reexec;}
-if test "x$CONFIG_SHELL" = x; then
- as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
- emulate sh
- NULLCMD=:
- # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
- # is contrary to our usage. Disable this feature.
- alias -g '\${1+\"\$@\"}'='\"\$@\"'
- setopt NO_GLOB_SUBST
-else
- case \`(set -o) 2>/dev/null\` in #(
- *posix*) :
- set -o posix ;; #(
- *) :
- ;;
-esac
-fi
-"
- as_required="as_fn_return () { (exit \$1); }
-as_fn_success () { as_fn_return 0; }
-as_fn_failure () { as_fn_return 1; }
-as_fn_ret_success () { return 0; }
-as_fn_ret_failure () { return 1; }
-
-exitcode=0
-as_fn_success || { exitcode=1; echo as_fn_success failed.; }
-as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
-as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
-as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
-if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
-
-else
- exitcode=1; echo positional parameters were not saved.
-fi
-test x\$exitcode = x0 || exit 1
-test -x / || exit 1"
- as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
- as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
- eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
- test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1"
- if (eval "$as_required") 2>/dev/null; then :
- as_have_required=yes
-else
- as_have_required=no
-fi
- if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
-
-else
- as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-as_found=false
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- as_found=:
- case $as_dir in #(
- /*)
- for as_base in sh bash ksh sh5; do
- # Try only shells that exist, to save several forks.
- as_shell=$as_dir/$as_base
- if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
- { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
- CONFIG_SHELL=$as_shell as_have_required=yes
- if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
- break 2
-fi
-fi
- done;;
- esac
- as_found=false
-done
-$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
- { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
- CONFIG_SHELL=$SHELL as_have_required=yes
-fi; }
-IFS=$as_save_IFS
-
-
- if test "x$CONFIG_SHELL" != x; then :
- export CONFIG_SHELL
- # We cannot yet assume a decent shell, so we have to provide a
-# neutralization value for shells without unset; and this also
-# works around shells that cannot unset nonexistent variables.
-# Preserve -v and -x to the replacement shell.
-BASH_ENV=/dev/null
-ENV=/dev/null
-(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-case $- in # ((((
- *v*x* | *x*v* ) as_opts=-vx ;;
- *v* ) as_opts=-v ;;
- *x* ) as_opts=-x ;;
- * ) as_opts= ;;
-esac
-exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
-# Admittedly, this is quite paranoid, since all the known shells bail
-# out after a failed `exec'.
-$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
-exit 255
-fi
-
- if test x$as_have_required = xno; then :
- $as_echo "$0: This script requires a shell more modern than all"
- $as_echo "$0: the shells that I found on your system."
- if test x${ZSH_VERSION+set} = xset ; then
- $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
- $as_echo "$0: be upgraded to zsh 4.3.4 or later."
- else
- $as_echo "$0: Please tell bug-autoconf@gnu.org about your system,
-$0: including any error possibly output before this
-$0: message. Then install a modern shell, or manually run
-$0: the script under such a shell if you do have one."
- fi
- exit 1
-fi
-fi
-fi
-SHELL=${CONFIG_SHELL-/bin/sh}
-export SHELL
-# Unset more variables known to interfere with behavior of common tools.
-CLICOLOR_FORCE= GREP_OPTIONS=
-unset CLICOLOR_FORCE GREP_OPTIONS
-
-## --------------------- ##
-## M4sh Shell Functions. ##
-## --------------------- ##
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
- { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
- return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
- set +e
- as_fn_set_status $1
- exit $1
-} # as_fn_exit
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
- case $as_dir in #(
- -*) as_dir=./$as_dir;;
- esac
- test -d "$as_dir" || eval $as_mkdir_p || {
- as_dirs=
- while :; do
- case $as_dir in #(
- *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
- *) as_qdir=$as_dir;;
- esac
- as_dirs="'$as_qdir' $as_dirs"
- as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_dir" : 'X\(//\)[^/]' \| \
- X"$as_dir" : 'X\(//\)$' \| \
- X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- test -d "$as_dir" && break
- done
- test -z "$as_dirs" || eval "mkdir $as_dirs"
- } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
- test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
- eval 'as_fn_append ()
- {
- eval $1+=\$2
- }'
-else
- as_fn_append ()
- {
- eval $1=\$$1\$2
- }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
- eval 'as_fn_arith ()
- {
- as_val=$(( $* ))
- }'
-else
- as_fn_arith ()
- {
- as_val=`expr "$@" || test $? -eq 1`
- }
-fi # as_fn_arith
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
- as_status=$1; test $as_status -eq 0 && as_status=1
- if test "$4"; then
- as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
- fi
- $as_echo "$as_me: error: $2" >&2
- as_fn_exit $as_status
-} # as_fn_error
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
- test "X`expr 00001 : '.*\(...\)'`" = X001; then
- as_expr=expr
-else
- as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
- as_basename=basename
-else
- as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
- as_dirname=dirname
-else
- as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
- X"$0" : 'X\(//\)$' \| \
- X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
- sed '/^.*\/\([^/][^/]*\)\/*$/{
- s//\1/
- q
- }
- /^X\/\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\/\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-
- as_lineno_1=$LINENO as_lineno_1a=$LINENO
- as_lineno_2=$LINENO as_lineno_2a=$LINENO
- eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
- test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
- # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-)
- sed -n '
- p
- /[$]LINENO/=
- ' <$as_myself |
- sed '
- s/[$]LINENO.*/&-/
- t lineno
- b
- :lineno
- N
- :loop
- s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
- t loop
- s/-\n.*//
- ' >$as_me.lineno &&
- chmod +x "$as_me.lineno" ||
- { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
-
- # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
- # already done that, so ensure we don't try to do so again and fall
- # in an infinite loop. This has already happened in practice.
- _as_can_reexec=no; export _as_can_reexec
- # Don't try to exec as it changes $[0], causing all sort of problems
- # (the dirname of $[0] is not the place where we might find the
- # original and so on. Autoconf is especially sensitive to this).
- . "./$as_me.lineno"
- # Exit status is that of the last command.
- exit
-}
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
- case `echo 'xy\c'` in
- *c*) ECHO_T=' ';; # ECHO_T is single tab character.
- xy) ECHO_C='\c';;
- *) echo `echo ksh88 bug on AIX 6.1` > /dev/null
- ECHO_T=' ';;
- esac;;
-*)
- ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
- rm -f conf$$.dir/conf$$.file
-else
- rm -f conf$$.dir
- mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
- if ln -s conf$$.file conf$$ 2>/dev/null; then
- as_ln_s='ln -s'
- # ... but there are two gotchas:
- # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
- # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
- # In both cases, we have to default to `cp -pR'.
- ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
- as_ln_s='cp -pR'
- elif ln conf$$.file conf$$ 2>/dev/null; then
- as_ln_s=ln
- else
- as_ln_s='cp -pR'
- fi
-else
- as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
- as_mkdir_p='mkdir -p "$as_dir"'
-else
- test -d ./-p && rmdir ./-p
- as_mkdir_p=false
-fi
-
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-test -n "$DJDIR" || exec 7<&0 &1
-
-# Name of the host.
-# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
-# so uname gets run too.
-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
-
-#
-# Initializations.
-#
-ac_default_prefix=/usr/local
-ac_clean_files=
-ac_config_libobj_dir=.
-LIBOBJS=
-cross_compiling=no
-subdirs=
-MFLAGS=
-MAKEFLAGS=
-
-# Identity of this package.
-PACKAGE_NAME='xgboost'
-PACKAGE_TARNAME='xgboost'
-PACKAGE_VERSION='0.6-3'
-PACKAGE_STRING='xgboost 0.6-3'
-PACKAGE_BUGREPORT=''
-PACKAGE_URL=''
-
-ac_subst_vars='LTLIBOBJS
-LIBOBJS
-BACKTRACE_LIB
-ENDIAN_FLAG
-OPENMP_LIB
-OPENMP_CXXFLAGS
-OBJEXT
-EXEEXT
-ac_ct_CC
-CPPFLAGS
-LDFLAGS
-CFLAGS
-CC
-target_alias
-host_alias
-build_alias
-LIBS
-ECHO_T
-ECHO_N
-ECHO_C
-DEFS
-mandir
-localedir
-libdir
-psdir
-pdfdir
-dvidir
-htmldir
-infodir
-docdir
-oldincludedir
-includedir
-localstatedir
-sharedstatedir
-sysconfdir
-datadir
-datarootdir
-libexecdir
-sbindir
-bindir
-program_transform_name
-prefix
-exec_prefix
-PACKAGE_URL
-PACKAGE_BUGREPORT
-PACKAGE_STRING
-PACKAGE_VERSION
-PACKAGE_TARNAME
-PACKAGE_NAME
-PATH_SEPARATOR
-SHELL'
-ac_subst_files=''
-ac_user_opts='
-enable_option_checking
-'
- ac_precious_vars='build_alias
-host_alias
-target_alias
-CC
-CFLAGS
-LDFLAGS
-LIBS
-CPPFLAGS'
-
-
-# Initialize some variables set by options.
-ac_init_help=
-ac_init_version=false
-ac_unrecognized_opts=
-ac_unrecognized_sep=
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-cache_file=/dev/null
-exec_prefix=NONE
-no_create=
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-verbose=
-x_includes=NONE
-x_libraries=NONE
-
-# Installation directory options.
-# These are left unexpanded so users can "make install exec_prefix=/foo"
-# and all the variables that are supposed to be based on exec_prefix
-# by default will actually change.
-# Use braces instead of parens because sh, perl, etc. also accept them.
-# (The list follows the same order as the GNU Coding Standards.)
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datarootdir='${prefix}/share'
-datadir='${datarootdir}'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
-infodir='${datarootdir}/info'
-htmldir='${docdir}'
-dvidir='${docdir}'
-pdfdir='${docdir}'
-psdir='${docdir}'
-libdir='${exec_prefix}/lib'
-localedir='${datarootdir}/locale'
-mandir='${datarootdir}/man'
-
-ac_prev=
-ac_dashdash=
-for ac_option
-do
- # If the previous option needs an argument, assign it.
- if test -n "$ac_prev"; then
- eval $ac_prev=\$ac_option
- ac_prev=
- continue
- fi
-
- case $ac_option in
- *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
- *=) ac_optarg= ;;
- *) ac_optarg=yes ;;
- esac
-
- # Accept the important Cygnus configure options, so we can diagnose typos.
-
- case $ac_dashdash$ac_option in
- --)
- ac_dashdash=yes ;;
-
- -bindir | --bindir | --bindi | --bind | --bin | --bi)
- ac_prev=bindir ;;
- -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
- bindir=$ac_optarg ;;
-
- -build | --build | --buil | --bui | --bu)
- ac_prev=build_alias ;;
- -build=* | --build=* | --buil=* | --bui=* | --bu=*)
- build_alias=$ac_optarg ;;
-
- -cache-file | --cache-file | --cache-fil | --cache-fi \
- | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
- ac_prev=cache_file ;;
- -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
- | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
- cache_file=$ac_optarg ;;
-
- --config-cache | -C)
- cache_file=config.cache ;;
-
- -datadir | --datadir | --datadi | --datad)
- ac_prev=datadir ;;
- -datadir=* | --datadir=* | --datadi=* | --datad=*)
- datadir=$ac_optarg ;;
-
- -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
- | --dataroo | --dataro | --datar)
- ac_prev=datarootdir ;;
- -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
- | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
- datarootdir=$ac_optarg ;;
-
- -disable-* | --disable-*)
- ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid feature name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"enable_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval enable_$ac_useropt=no ;;
-
- -docdir | --docdir | --docdi | --doc | --do)
- ac_prev=docdir ;;
- -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
- docdir=$ac_optarg ;;
-
- -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
- ac_prev=dvidir ;;
- -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
- dvidir=$ac_optarg ;;
-
- -enable-* | --enable-*)
- ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid feature name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"enable_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval enable_$ac_useropt=\$ac_optarg ;;
-
- -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
- | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
- | --exec | --exe | --ex)
- ac_prev=exec_prefix ;;
- -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
- | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
- | --exec=* | --exe=* | --ex=*)
- exec_prefix=$ac_optarg ;;
-
- -gas | --gas | --ga | --g)
- # Obsolete; use --with-gas.
- with_gas=yes ;;
-
- -help | --help | --hel | --he | -h)
- ac_init_help=long ;;
- -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
- ac_init_help=recursive ;;
- -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
- ac_init_help=short ;;
-
- -host | --host | --hos | --ho)
- ac_prev=host_alias ;;
- -host=* | --host=* | --hos=* | --ho=*)
- host_alias=$ac_optarg ;;
-
- -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
- ac_prev=htmldir ;;
- -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
- | --ht=*)
- htmldir=$ac_optarg ;;
-
- -includedir | --includedir | --includedi | --included | --include \
- | --includ | --inclu | --incl | --inc)
- ac_prev=includedir ;;
- -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
- | --includ=* | --inclu=* | --incl=* | --inc=*)
- includedir=$ac_optarg ;;
-
- -infodir | --infodir | --infodi | --infod | --info | --inf)
- ac_prev=infodir ;;
- -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
- infodir=$ac_optarg ;;
-
- -libdir | --libdir | --libdi | --libd)
- ac_prev=libdir ;;
- -libdir=* | --libdir=* | --libdi=* | --libd=*)
- libdir=$ac_optarg ;;
-
- -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
- | --libexe | --libex | --libe)
- ac_prev=libexecdir ;;
- -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
- | --libexe=* | --libex=* | --libe=*)
- libexecdir=$ac_optarg ;;
-
- -localedir | --localedir | --localedi | --localed | --locale)
- ac_prev=localedir ;;
- -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
- localedir=$ac_optarg ;;
-
- -localstatedir | --localstatedir | --localstatedi | --localstated \
- | --localstate | --localstat | --localsta | --localst | --locals)
- ac_prev=localstatedir ;;
- -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
- | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
- localstatedir=$ac_optarg ;;
-
- -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
- ac_prev=mandir ;;
- -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
- mandir=$ac_optarg ;;
-
- -nfp | --nfp | --nf)
- # Obsolete; use --without-fp.
- with_fp=no ;;
-
- -no-create | --no-create | --no-creat | --no-crea | --no-cre \
- | --no-cr | --no-c | -n)
- no_create=yes ;;
-
- -no-recursion | --no-recursion | --no-recursio | --no-recursi \
- | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
- no_recursion=yes ;;
-
- -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
- | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
- | --oldin | --oldi | --old | --ol | --o)
- ac_prev=oldincludedir ;;
- -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
- | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
- | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
- oldincludedir=$ac_optarg ;;
-
- -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
- ac_prev=prefix ;;
- -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
- prefix=$ac_optarg ;;
-
- -program-prefix | --program-prefix | --program-prefi | --program-pref \
- | --program-pre | --program-pr | --program-p)
- ac_prev=program_prefix ;;
- -program-prefix=* | --program-prefix=* | --program-prefi=* \
- | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
- program_prefix=$ac_optarg ;;
-
- -program-suffix | --program-suffix | --program-suffi | --program-suff \
- | --program-suf | --program-su | --program-s)
- ac_prev=program_suffix ;;
- -program-suffix=* | --program-suffix=* | --program-suffi=* \
- | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
- program_suffix=$ac_optarg ;;
-
- -program-transform-name | --program-transform-name \
- | --program-transform-nam | --program-transform-na \
- | --program-transform-n | --program-transform- \
- | --program-transform | --program-transfor \
- | --program-transfo | --program-transf \
- | --program-trans | --program-tran \
- | --progr-tra | --program-tr | --program-t)
- ac_prev=program_transform_name ;;
- -program-transform-name=* | --program-transform-name=* \
- | --program-transform-nam=* | --program-transform-na=* \
- | --program-transform-n=* | --program-transform-=* \
- | --program-transform=* | --program-transfor=* \
- | --program-transfo=* | --program-transf=* \
- | --program-trans=* | --program-tran=* \
- | --progr-tra=* | --program-tr=* | --program-t=*)
- program_transform_name=$ac_optarg ;;
-
- -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
- ac_prev=pdfdir ;;
- -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
- pdfdir=$ac_optarg ;;
-
- -psdir | --psdir | --psdi | --psd | --ps)
- ac_prev=psdir ;;
- -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
- psdir=$ac_optarg ;;
-
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil)
- silent=yes ;;
-
- -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
- ac_prev=sbindir ;;
- -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
- | --sbi=* | --sb=*)
- sbindir=$ac_optarg ;;
-
- -sharedstatedir | --sharedstatedir | --sharedstatedi \
- | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
- | --sharedst | --shareds | --shared | --share | --shar \
- | --sha | --sh)
- ac_prev=sharedstatedir ;;
- -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
- | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
- | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
- | --sha=* | --sh=*)
- sharedstatedir=$ac_optarg ;;
-
- -site | --site | --sit)
- ac_prev=site ;;
- -site=* | --site=* | --sit=*)
- site=$ac_optarg ;;
-
- -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
- ac_prev=srcdir ;;
- -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
- srcdir=$ac_optarg ;;
-
- -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
- | --syscon | --sysco | --sysc | --sys | --sy)
- ac_prev=sysconfdir ;;
- -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
- | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
- sysconfdir=$ac_optarg ;;
-
- -target | --target | --targe | --targ | --tar | --ta | --t)
- ac_prev=target_alias ;;
- -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
- target_alias=$ac_optarg ;;
-
- -v | -verbose | --verbose | --verbos | --verbo | --verb)
- verbose=yes ;;
-
- -version | --version | --versio | --versi | --vers | -V)
- ac_init_version=: ;;
-
- -with-* | --with-*)
- ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid package name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"with_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval with_$ac_useropt=\$ac_optarg ;;
-
- -without-* | --without-*)
- ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
- # Reject names that are not valid shell variable names.
- expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
- as_fn_error $? "invalid package name: $ac_useropt"
- ac_useropt_orig=$ac_useropt
- ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
- case $ac_user_opts in
- *"
-"with_$ac_useropt"
-"*) ;;
- *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
- ac_unrecognized_sep=', ';;
- esac
- eval with_$ac_useropt=no ;;
-
- --x)
- # Obsolete; use --with-x.
- with_x=yes ;;
-
- -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
- | --x-incl | --x-inc | --x-in | --x-i)
- ac_prev=x_includes ;;
- -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
- | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
- x_includes=$ac_optarg ;;
-
- -x-libraries | --x-libraries | --x-librarie | --x-librari \
- | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
- ac_prev=x_libraries ;;
- -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
- | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
- x_libraries=$ac_optarg ;;
-
- -*) as_fn_error $? "unrecognized option: \`$ac_option'
-Try \`$0 --help' for more information"
- ;;
-
- *=*)
- ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
- # Reject names that are not valid shell variable names.
- case $ac_envvar in #(
- '' | [0-9]* | *[!_$as_cr_alnum]* )
- as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
- esac
- eval $ac_envvar=\$ac_optarg
- export $ac_envvar ;;
-
- *)
- # FIXME: should be removed in autoconf 3.0.
- $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
- expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
- $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
- : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
- ;;
-
- esac
-done
-
-if test -n "$ac_prev"; then
- ac_option=--`echo $ac_prev | sed 's/_/-/g'`
- as_fn_error $? "missing argument to $ac_option"
-fi
-
-if test -n "$ac_unrecognized_opts"; then
- case $enable_option_checking in
- no) ;;
- fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
- *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
- esac
-fi
-
-# Check all directory arguments for consistency.
-for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \
- datadir sysconfdir sharedstatedir localstatedir includedir \
- oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
- libdir localedir mandir
-do
- eval ac_val=\$$ac_var
- # Remove trailing slashes.
- case $ac_val in
- */ )
- ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
- eval $ac_var=\$ac_val;;
- esac
- # Be sure to have absolute directory names.
- case $ac_val in
- [\\/$]* | ?:[\\/]* ) continue;;
- NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
- esac
- as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
-done
-
-# There might be people who depend on the old broken behavior: `$host'
-# used to hold the argument of --host etc.
-# FIXME: To remove some day.
-build=$build_alias
-host=$host_alias
-target=$target_alias
-
-# FIXME: To remove some day.
-if test "x$host_alias" != x; then
- if test "x$build_alias" = x; then
- cross_compiling=maybe
- elif test "x$build_alias" != "x$host_alias"; then
- cross_compiling=yes
- fi
-fi
-
-ac_tool_prefix=
-test -n "$host_alias" && ac_tool_prefix=$host_alias-
-
-test "$silent" = yes && exec 6>/dev/null
-
-
-ac_pwd=`pwd` && test -n "$ac_pwd" &&
-ac_ls_di=`ls -di .` &&
-ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
- as_fn_error $? "working directory cannot be determined"
-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
- as_fn_error $? "pwd does not report name of working directory"
-
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
- ac_srcdir_defaulted=yes
- # Try the directory containing this script, then the parent directory.
- ac_confdir=`$as_dirname -- "$as_myself" ||
-$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_myself" : 'X\(//\)[^/]' \| \
- X"$as_myself" : 'X\(//\)$' \| \
- X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_myself" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- srcdir=$ac_confdir
- if test ! -r "$srcdir/$ac_unique_file"; then
- srcdir=..
- fi
-else
- ac_srcdir_defaulted=no
-fi
-if test ! -r "$srcdir/$ac_unique_file"; then
- test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
- as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
-fi
-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
-ac_abs_confdir=`(
- cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
- pwd)`
-# When building in place, set srcdir=.
-if test "$ac_abs_confdir" = "$ac_pwd"; then
- srcdir=.
-fi
-# Remove unnecessary trailing slashes from srcdir.
-# Double slashes in file names in object file debugging info
-# mess up M-x gdb in Emacs.
-case $srcdir in
-*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
-esac
-for ac_var in $ac_precious_vars; do
- eval ac_env_${ac_var}_set=\${${ac_var}+set}
- eval ac_env_${ac_var}_value=\$${ac_var}
- eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
- eval ac_cv_env_${ac_var}_value=\$${ac_var}
-done
-
-#
-# Report the --help message.
-#
-if test "$ac_init_help" = "long"; then
- # Omit some internal or obsolete options to make the list less imposing.
- # This message is too long to be a string in the A/UX 3.1 sh.
- cat <<_ACEOF
-\`configure' configures xgboost 0.6-3 to adapt to many kinds of systems.
-
-Usage: $0 [OPTION]... [VAR=VALUE]...
-
-To assign environment variables (e.g., CC, CFLAGS...), specify them as
-VAR=VALUE. See below for descriptions of some of the useful variables.
-
-Defaults for the options are specified in brackets.
-
-Configuration:
- -h, --help display this help and exit
- --help=short display options specific to this package
- --help=recursive display the short help of all the included packages
- -V, --version display version information and exit
- -q, --quiet, --silent do not print \`checking ...' messages
- --cache-file=FILE cache test results in FILE [disabled]
- -C, --config-cache alias for \`--cache-file=config.cache'
- -n, --no-create do not create output files
- --srcdir=DIR find the sources in DIR [configure dir or \`..']
-
-Installation directories:
- --prefix=PREFIX install architecture-independent files in PREFIX
- [$ac_default_prefix]
- --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX
- [PREFIX]
-
-By default, \`make install' will install all the files in
-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify
-an installation prefix other than \`$ac_default_prefix' using \`--prefix',
-for instance \`--prefix=\$HOME'.
-
-For better control, use the options below.
-
-Fine tuning of the installation directories:
- --bindir=DIR user executables [EPREFIX/bin]
- --sbindir=DIR system admin executables [EPREFIX/sbin]
- --libexecdir=DIR program executables [EPREFIX/libexec]
- --sysconfdir=DIR read-only single-machine data [PREFIX/etc]
- --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com]
- --localstatedir=DIR modifiable single-machine data [PREFIX/var]
- --libdir=DIR object code libraries [EPREFIX/lib]
- --includedir=DIR C header files [PREFIX/include]
- --oldincludedir=DIR C header files for non-gcc [/usr/include]
- --datarootdir=DIR read-only arch.-independent data root [PREFIX/share]
- --datadir=DIR read-only architecture-independent data [DATAROOTDIR]
- --infodir=DIR info documentation [DATAROOTDIR/info]
- --localedir=DIR locale-dependent data [DATAROOTDIR/locale]
- --mandir=DIR man documentation [DATAROOTDIR/man]
- --docdir=DIR documentation root [DATAROOTDIR/doc/xgboost]
- --htmldir=DIR html documentation [DOCDIR]
- --dvidir=DIR dvi documentation [DOCDIR]
- --pdfdir=DIR pdf documentation [DOCDIR]
- --psdir=DIR ps documentation [DOCDIR]
-_ACEOF
-
- cat <<\_ACEOF
-_ACEOF
-fi
-
-if test -n "$ac_init_help"; then
- case $ac_init_help in
- short | recursive ) echo "Configuration of xgboost 0.6-3:";;
- esac
- cat <<\_ACEOF
-
-Some influential environment variables:
- CC C compiler command
- CFLAGS C compiler flags
- LDFLAGS linker flags, e.g. -L if you have libraries in a
- nonstandard directory
- LIBS libraries to pass to the linker, e.g. -l
- CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if
- you have headers in a nonstandard directory
-
-Use these variables to override the choices made by `configure' or to help
-it to find libraries and programs with nonstandard names/locations.
-
-Report bugs to the package provider.
-_ACEOF
-ac_status=$?
-fi
-
-if test "$ac_init_help" = "recursive"; then
- # If there are subdirs, report their specific --help.
- for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
- test -d "$ac_dir" ||
- { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
- continue
- ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
- ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
- # A ".." for each directory in $ac_dir_suffix.
- ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
- case $ac_top_builddir_sub in
- "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
- *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
- esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
- .) # We are building in place.
- ac_srcdir=.
- ac_top_srcdir=$ac_top_builddir_sub
- ac_abs_top_srcdir=$ac_pwd ;;
- [\\/]* | ?:[\\/]* ) # Absolute name.
- ac_srcdir=$srcdir$ac_dir_suffix;
- ac_top_srcdir=$srcdir
- ac_abs_top_srcdir=$srcdir ;;
- *) # Relative name.
- ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
- ac_top_srcdir=$ac_top_build_prefix$srcdir
- ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
- cd "$ac_dir" || { ac_status=$?; continue; }
- # Check for guested configure.
- if test -f "$ac_srcdir/configure.gnu"; then
- echo &&
- $SHELL "$ac_srcdir/configure.gnu" --help=recursive
- elif test -f "$ac_srcdir/configure"; then
- echo &&
- $SHELL "$ac_srcdir/configure" --help=recursive
- else
- $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
- fi || ac_status=$?
- cd "$ac_pwd" || { ac_status=$?; break; }
- done
-fi
-
-test -n "$ac_init_help" && exit $ac_status
-if $ac_init_version; then
- cat <<\_ACEOF
-xgboost configure 0.6-3
-generated by GNU Autoconf 2.69
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This configure script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it.
-_ACEOF
- exit
-fi
-
-## ------------------------ ##
-## Autoconf initialization. ##
-## ------------------------ ##
-
-# ac_fn_c_try_compile LINENO
-# --------------------------
-# Try to compile conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_compile ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- rm -f conftest.$ac_objext
- if { { ac_try="$ac_compile"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_compile") 2>conftest.err
- ac_status=$?
- if test -s conftest.err; then
- grep -v '^ *+' conftest.err >conftest.er1
- cat conftest.er1 >&5
- mv -f conftest.er1 conftest.err
- fi
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; } && {
- test -z "$ac_c_werror_flag" ||
- test ! -s conftest.err
- } && test -s conftest.$ac_objext; then :
- ac_retval=0
-else
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
- ac_retval=1
-fi
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_compile
-
-# ac_fn_c_try_link LINENO
-# -----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded.
-ac_fn_c_try_link ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- rm -f conftest.$ac_objext conftest$ac_exeext
- if { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>conftest.err
- ac_status=$?
- if test -s conftest.err; then
- grep -v '^ *+' conftest.err >conftest.er1
- cat conftest.er1 >&5
- mv -f conftest.er1 conftest.err
- fi
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; } && {
- test -z "$ac_c_werror_flag" ||
- test ! -s conftest.err
- } && test -s conftest$ac_exeext && {
- test "$cross_compiling" = yes ||
- test -x conftest$ac_exeext
- }; then :
- ac_retval=0
-else
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
- ac_retval=1
-fi
- # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
- # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
- # interfere with the next link command; also delete a directory that is
- # left behind by Apple's compiler. We do this before executing the actions.
- rm -rf conftest.dSYM conftest_ipa8_conftest.oo
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_link
-
-# ac_fn_c_try_run LINENO
-# ----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
-# that executables *can* be run.
-ac_fn_c_try_run ()
-{
- as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- if { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
- { { case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_try") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; }; then :
- ac_retval=0
-else
- $as_echo "$as_me: program exited with status $ac_status" >&5
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
- ac_retval=$ac_status
-fi
- rm -rf conftest.dSYM conftest_ipa8_conftest.oo
- eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
- as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_run
-cat >config.log <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by xgboost $as_me 0.6-3, which was
-generated by GNU Autoconf 2.69. Invocation command line was
-
- $ $0 $@
-
-_ACEOF
-exec 5>>config.log
-{
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown`
-
-/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown`
-/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown`
-/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown`
-/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown`
-/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown`
-
-_ASUNAME
-
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- $as_echo "PATH: $as_dir"
- done
-IFS=$as_save_IFS
-
-} >&5
-
-cat >&5 <<_ACEOF
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-_ACEOF
-
-
-# Keep a trace of the command line.
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Strip out --silent because we don't want to record it for future runs.
-# Also quote any args containing shell meta-characters.
-# Make two passes to allow for proper duplicate-argument suppression.
-ac_configure_args=
-ac_configure_args0=
-ac_configure_args1=
-ac_must_keep_next=false
-for ac_pass in 1 2
-do
- for ac_arg
- do
- case $ac_arg in
- -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil)
- continue ;;
- *\'*)
- ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
- esac
- case $ac_pass in
- 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
- 2)
- as_fn_append ac_configure_args1 " '$ac_arg'"
- if test $ac_must_keep_next = true; then
- ac_must_keep_next=false # Got value, back to normal.
- else
- case $ac_arg in
- *=* | --config-cache | -C | -disable-* | --disable-* \
- | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
- | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
- | -with-* | --with-* | -without-* | --without-* | --x)
- case "$ac_configure_args0 " in
- "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
- esac
- ;;
- -* ) ac_must_keep_next=true ;;
- esac
- fi
- as_fn_append ac_configure_args " '$ac_arg'"
- ;;
- esac
- done
-done
-{ ac_configure_args0=; unset ac_configure_args0;}
-{ ac_configure_args1=; unset ac_configure_args1;}
-
-# When interrupted or exit'd, cleanup temporary files, and complete
-# config.log. We remove comments because anyway the quotes in there
-# would cause problems or look ugly.
-# WARNING: Use '\'' to represent an apostrophe within the trap.
-# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
-trap 'exit_status=$?
- # Save into config.log some information that might help in debugging.
- {
- echo
-
- $as_echo "## ---------------- ##
-## Cache variables. ##
-## ---------------- ##"
- echo
- # The following way of writing the cache mishandles newlines in values,
-(
- for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
- eval ac_val=\$$ac_var
- case $ac_val in #(
- *${as_nl}*)
- case $ac_var in #(
- *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
- esac
- case $ac_var in #(
- _ | IFS | as_nl) ;; #(
- BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
- *) { eval $ac_var=; unset $ac_var;} ;;
- esac ;;
- esac
- done
- (set) 2>&1 |
- case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
- *${as_nl}ac_space=\ *)
- sed -n \
- "s/'\''/'\''\\\\'\'''\''/g;
- s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
- ;; #(
- *)
- sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
- ;;
- esac |
- sort
-)
- echo
-
- $as_echo "## ----------------- ##
-## Output variables. ##
-## ----------------- ##"
- echo
- for ac_var in $ac_subst_vars
- do
- eval ac_val=\$$ac_var
- case $ac_val in
- *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
- esac
- $as_echo "$ac_var='\''$ac_val'\''"
- done | sort
- echo
-
- if test -n "$ac_subst_files"; then
- $as_echo "## ------------------- ##
-## File substitutions. ##
-## ------------------- ##"
- echo
- for ac_var in $ac_subst_files
- do
- eval ac_val=\$$ac_var
- case $ac_val in
- *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
- esac
- $as_echo "$ac_var='\''$ac_val'\''"
- done | sort
- echo
- fi
-
- if test -s confdefs.h; then
- $as_echo "## ----------- ##
-## confdefs.h. ##
-## ----------- ##"
- echo
- cat confdefs.h
- echo
- fi
- test "$ac_signal" != 0 &&
- $as_echo "$as_me: caught signal $ac_signal"
- $as_echo "$as_me: exit $exit_status"
- } >&5
- rm -f core *.core core.conftest.* &&
- rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
- exit $exit_status
-' 0
-for ac_signal in 1 2 13 15; do
- trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
-done
-ac_signal=0
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -f -r conftest* confdefs.h
-
-$as_echo "/* confdefs.h */" > confdefs.h
-
-# Predefined preprocessor variables.
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_URL "$PACKAGE_URL"
-_ACEOF
-
-
-# Let the site file select an alternate cache file if it wants to.
-# Prefer an explicitly selected file to automatically selected ones.
-ac_site_file1=NONE
-ac_site_file2=NONE
-if test -n "$CONFIG_SITE"; then
- # We do not want a PATH search for config.site.
- case $CONFIG_SITE in #((
- -*) ac_site_file1=./$CONFIG_SITE;;
- */*) ac_site_file1=$CONFIG_SITE;;
- *) ac_site_file1=./$CONFIG_SITE;;
- esac
-elif test "x$prefix" != xNONE; then
- ac_site_file1=$prefix/share/config.site
- ac_site_file2=$prefix/etc/config.site
-else
- ac_site_file1=$ac_default_prefix/share/config.site
- ac_site_file2=$ac_default_prefix/etc/config.site
-fi
-for ac_site_file in "$ac_site_file1" "$ac_site_file2"
-do
- test "x$ac_site_file" = xNONE && continue
- if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
-$as_echo "$as_me: loading site script $ac_site_file" >&6;}
- sed 's/^/| /' "$ac_site_file" >&5
- . "$ac_site_file" \
- || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5; }
- fi
-done
-
-if test -r "$cache_file"; then
- # Some versions of bash will fail to source /dev/null (special files
- # actually), so we avoid doing that. DJGPP emulates it as a regular file.
- if test /dev/null != "$cache_file" && test -f "$cache_file"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
-$as_echo "$as_me: loading cache $cache_file" >&6;}
- case $cache_file in
- [\\/]* | ?:[\\/]* ) . "$cache_file";;
- *) . "./$cache_file";;
- esac
- fi
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
-$as_echo "$as_me: creating cache $cache_file" >&6;}
- >$cache_file
-fi
-
-# Check that the precious variables saved in the cache have kept the same
-# value.
-ac_cache_corrupted=false
-for ac_var in $ac_precious_vars; do
- eval ac_old_set=\$ac_cv_env_${ac_var}_set
- eval ac_new_set=\$ac_env_${ac_var}_set
- eval ac_old_val=\$ac_cv_env_${ac_var}_value
- eval ac_new_val=\$ac_env_${ac_var}_value
- case $ac_old_set,$ac_new_set in
- set,)
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
- ac_cache_corrupted=: ;;
- ,set)
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
-$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
- ac_cache_corrupted=: ;;
- ,);;
- *)
- if test "x$ac_old_val" != "x$ac_new_val"; then
- # differences in whitespace do not lead to failure.
- ac_old_val_w=`echo x $ac_old_val`
- ac_new_val_w=`echo x $ac_new_val`
- if test "$ac_old_val_w" != "$ac_new_val_w"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
-$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
- ac_cache_corrupted=:
- else
- { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
-$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
- eval $ac_var=\$ac_old_val
- fi
- { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5
-$as_echo "$as_me: former value: \`$ac_old_val'" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5
-$as_echo "$as_me: current value: \`$ac_new_val'" >&2;}
- fi;;
- esac
- # Pass precious variables to config.status.
- if test "$ac_new_set" = set; then
- case $ac_new_val in
- *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
- *) ac_arg=$ac_var=$ac_new_val ;;
- esac
- case " $ac_configure_args " in
- *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy.
- *) as_fn_append ac_configure_args " '$ac_arg'" ;;
- esac
- fi
-done
-if $ac_cache_corrupted; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
-$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
- as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
-fi
-## -------------------- ##
-## Main body of script. ##
-## -------------------- ##
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-# Use this line to set CC variable to a C compiler
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-if test -n "$ac_tool_prefix"; then
- # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_CC="${ac_tool_prefix}gcc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$ac_cv_prog_CC"; then
- ac_ct_CC=$CC
- # Extract the first word of "gcc", so it can be a program name with args.
-set dummy gcc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$ac_ct_CC"; then
- ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_ac_ct_CC="gcc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
- if test "x$ac_ct_CC" = x; then
- CC=""
- else
- case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
- CC=$ac_ct_CC
- fi
-else
- CC="$ac_cv_prog_CC"
-fi
-
-if test -z "$CC"; then
- if test -n "$ac_tool_prefix"; then
- # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
-set dummy ${ac_tool_prefix}cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_CC="${ac_tool_prefix}cc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- fi
-fi
-if test -z "$CC"; then
- # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
- ac_prog_rejected=no
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
- ac_prog_rejected=yes
- continue
- fi
- ac_cv_prog_CC="cc"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-if test $ac_prog_rejected = yes; then
- # We found a bogon in the path, so make sure we never use it.
- set dummy $ac_cv_prog_CC
- shift
- if test $# != 0; then
- # We chose a different compiler from the bogus one.
- # However, it has the same basename, so the bogon will be chosen
- # first if we set CC to just the basename; use the full file name.
- shift
- ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
- fi
-fi
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-fi
-if test -z "$CC"; then
- if test -n "$ac_tool_prefix"; then
- for ac_prog in cl.exe
- do
- # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
-set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$CC"; then
- ac_cv_prog_CC="$CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-CC=$ac_cv_prog_CC
-if test -n "$CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
-$as_echo "$CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- test -n "$CC" && break
- done
-fi
-if test -z "$CC"; then
- ac_ct_CC=$CC
- for ac_prog in cl.exe
-do
- # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_ac_ct_CC+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- if test -n "$ac_ct_CC"; then
- ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- for ac_exec_ext in '' $ac_executable_extensions; do
- if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
- ac_cv_prog_ac_ct_CC="$ac_prog"
- $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
- break 2
- fi
-done
- done
-IFS=$as_save_IFS
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
-$as_echo "$ac_ct_CC" >&6; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
- test -n "$ac_ct_CC" && break
-done
-
- if test "x$ac_ct_CC" = x; then
- CC=""
- else
- case $cross_compiling:$ac_tool_warned in
-yes:)
-{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
-$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
-ac_tool_warned=yes ;;
-esac
- CC=$ac_ct_CC
- fi
-fi
-
-fi
-
-
-test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5; }
-
-# Provide some information about the compiler.
-$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
-set X $ac_compile
-ac_compiler=$2
-for ac_option in --version -v -V -qversion; do
- { { ac_try="$ac_compiler $ac_option >&5"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_compiler $ac_option >&5") 2>conftest.err
- ac_status=$?
- if test -s conftest.err; then
- sed '10a\
-... rest of stderr output deleted ...
- 10q' conftest.err >conftest.er1
- cat conftest.er1 >&5
- fi
- rm -f conftest.er1 conftest.err
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }
-done
-
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
-# Try to create an executable without -o first, disregard a.out.
-# It will help us diagnose broken compilers, and finding out an intuition
-# of exeext.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
-$as_echo_n "checking whether the C compiler works... " >&6; }
-ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-
-# The possible output files:
-ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
-
-ac_rmfiles=
-for ac_file in $ac_files
-do
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
- * ) ac_rmfiles="$ac_rmfiles $ac_file";;
- esac
-done
-rm -f $ac_rmfiles
-
-if { { ac_try="$ac_link_default"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link_default") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; then :
- # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
-# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
-# in a Makefile. We should not override ac_cv_exeext if it was cached,
-# so that the user can short-circuit this test for compilers unknown to
-# Autoconf.
-for ac_file in $ac_files ''
-do
- test -f "$ac_file" || continue
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
- ;;
- [ab].out )
- # We found the default executable, but exeext='' is most
- # certainly right.
- break;;
- *.* )
- if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
- then :; else
- ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
- fi
- # We set ac_cv_exeext here because the later test for it is not
- # safe: cross compilers may not add the suffix if given an `-o'
- # argument, so we may need to know it at that point already.
- # Even if this section looks crufty: it has the advantage of
- # actually working.
- break;;
- * )
- break;;
- esac
-done
-test "$ac_cv_exeext" = no && ac_cv_exeext=
-
-else
- ac_file=''
-fi
-if test -z "$ac_file"; then :
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-$as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5; }
-else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
-$as_echo "yes" >&6; }
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
-$as_echo_n "checking for C compiler default output file name... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
-$as_echo "$ac_file" >&6; }
-ac_exeext=$ac_cv_exeext
-
-rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
-$as_echo_n "checking for suffix of executables... " >&6; }
-if { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; then :
- # If both `conftest.exe' and `conftest' are `present' (well, observable)
-# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will
-# work properly (i.e., refer to `conftest.exe'), while it won't with
-# `rm'.
-for ac_file in conftest.exe conftest conftest.*; do
- test -f "$ac_file" || continue
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
- *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
- break;;
- * ) break;;
- esac
-done
-else
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest conftest$ac_cv_exeext
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
-$as_echo "$ac_cv_exeext" >&6; }
-
-rm -f conftest.$ac_ext
-EXEEXT=$ac_cv_exeext
-ac_exeext=$EXEEXT
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include
-int
-main ()
-{
-FILE *f = fopen ("conftest.out", "w");
- return ferror (f) || fclose (f) != 0;
-
- ;
- return 0;
-}
-_ACEOF
-ac_clean_files="$ac_clean_files conftest.out"
-# Check that the compiler produces executables we can run. If not, either
-# the compiler is broken, or we cross compile.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
-$as_echo_n "checking whether we are cross compiling... " >&6; }
-if test "$cross_compiling" != yes; then
- { { ac_try="$ac_link"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_link") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }
- if { ac_try='./conftest$ac_cv_exeext'
- { { case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_try") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; }; then
- cross_compiling=no
- else
- if test "$cross_compiling" = maybe; then
- cross_compiling=yes
- else
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run C compiled programs.
-If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5; }
- fi
- fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
-$as_echo "$cross_compiling" >&6; }
-
-rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
-ac_clean_files=$ac_clean_files_save
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
-$as_echo_n "checking for suffix of object files... " >&6; }
-if ${ac_cv_objext+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-rm -f conftest.o conftest.obj
-if { { ac_try="$ac_compile"
-case "(($ac_try" in
- *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
- *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
- (eval "$ac_compile") 2>&5
- ac_status=$?
- $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
- test $ac_status = 0; }; then :
- for ac_file in conftest.o conftest.obj conftest.*; do
- test -f "$ac_file" || continue;
- case $ac_file in
- *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
- *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
- break;;
- esac
-done
-else
- $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5; }
-fi
-rm -f conftest.$ac_cv_objext conftest.$ac_ext
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
-$as_echo "$ac_cv_objext" >&6; }
-OBJEXT=$ac_cv_objext
-ac_objext=$OBJEXT
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
-$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if ${ac_cv_c_compiler_gnu+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-#ifndef __GNUC__
- choke me
-#endif
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_compiler_gnu=yes
-else
- ac_compiler_gnu=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-ac_cv_c_compiler_gnu=$ac_compiler_gnu
-
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
-$as_echo "$ac_cv_c_compiler_gnu" >&6; }
-if test $ac_compiler_gnu = yes; then
- GCC=yes
-else
- GCC=
-fi
-ac_test_CFLAGS=${CFLAGS+set}
-ac_save_CFLAGS=$CFLAGS
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
-$as_echo_n "checking whether $CC accepts -g... " >&6; }
-if ${ac_cv_prog_cc_g+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_save_c_werror_flag=$ac_c_werror_flag
- ac_c_werror_flag=yes
- ac_cv_prog_cc_g=no
- CFLAGS="-g"
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_prog_cc_g=yes
-else
- CFLAGS=""
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
- ac_c_werror_flag=$ac_save_c_werror_flag
- CFLAGS="-g"
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-int
-main ()
-{
-
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_prog_cc_g=yes
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
- ac_c_werror_flag=$ac_save_c_werror_flag
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
-$as_echo "$ac_cv_prog_cc_g" >&6; }
-if test "$ac_test_CFLAGS" = set; then
- CFLAGS=$ac_save_CFLAGS
-elif test $ac_cv_prog_cc_g = yes; then
- if test "$GCC" = yes; then
- CFLAGS="-g -O2"
- else
- CFLAGS="-g"
- fi
-else
- if test "$GCC" = yes; then
- CFLAGS="-O2"
- else
- CFLAGS=
- fi
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
-$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if ${ac_cv_prog_cc_c89+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_cv_prog_cc_c89=no
-ac_save_CC=$CC
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include
-#include
-struct stat;
-/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */
-struct buf { int x; };
-FILE * (*rcsopen) (struct buf *, struct stat *, int);
-static char *e (p, i)
- char **p;
- int i;
-{
- return p[i];
-}
-static char *f (char * (*g) (char **, int), char **p, ...)
-{
- char *s;
- va_list v;
- va_start (v,p);
- s = g (p, va_arg (v,int));
- va_end (v);
- return s;
-}
-
-/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has
- function prototypes and stuff, but not '\xHH' hex character constants.
- These don't provoke an error unfortunately, instead are silently treated
- as 'x'. The following induces an error, until -std is added to get
- proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an
- array size at least. It's necessary to write '\x00'==0 to get something
- that's true only with -std. */
-int osf4_cc_array ['\x00' == 0 ? 1 : -1];
-
-/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
- inside strings and character constants. */
-#define FOO(x) 'x'
-int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
-
-int test (int i, double x);
-struct s1 {int (*f) (int a);};
-struct s2 {int (*f) (double a);};
-int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
-int argc;
-char **argv;
-int
-main ()
-{
-return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1];
- ;
- return 0;
-}
-_ACEOF
-for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
- -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
-do
- CC="$ac_save_CC $ac_arg"
- if ac_fn_c_try_compile "$LINENO"; then :
- ac_cv_prog_cc_c89=$ac_arg
-fi
-rm -f core conftest.err conftest.$ac_objext
- test "x$ac_cv_prog_cc_c89" != "xno" && break
-done
-rm -f conftest.$ac_ext
-CC=$ac_save_CC
-
-fi
-# AC_CACHE_VAL
-case "x$ac_cv_prog_cc_c89" in
- x)
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
-$as_echo "none needed" >&6; } ;;
- xno)
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
-$as_echo "unsupported" >&6; } ;;
- *)
- CC="$CC $ac_cv_prog_cc_c89"
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
-$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
-esac
-if test "x$ac_cv_prog_cc_c89" != xno; then :
-
-fi
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-### Check whether backtrace() is part of libc or the external lib libexecinfo
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking Backtrace lib" >&5
-$as_echo_n "checking Backtrace lib... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for backtrace in -lexecinfo" >&5
-$as_echo_n "checking for backtrace in -lexecinfo... " >&6; }
-if ${ac_cv_lib_execinfo_backtrace+:} false; then :
- $as_echo_n "(cached) " >&6
-else
- ac_check_lib_save_LIBS=$LIBS
-LIBS="-lexecinfo $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-
-/* Override any GCC internal prototype to avoid an error.
- Use char because int might match the return type of a GCC
- builtin and then its argument prototype would still apply. */
-#ifdef __cplusplus
-extern "C"
-#endif
-char backtrace ();
-int
-main ()
-{
-return backtrace ();
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
- ac_cv_lib_execinfo_backtrace=yes
-else
- ac_cv_lib_execinfo_backtrace=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
- conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_execinfo_backtrace" >&5
-$as_echo "$ac_cv_lib_execinfo_backtrace" >&6; }
-if test "x$ac_cv_lib_execinfo_backtrace" = xyes; then :
- BACKTRACE_LIB=-lexecinfo
-else
- BACKTRACE_LIB=''
-fi
-
-
-### Endian detection
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking endian" >&5
-$as_echo_n "checking endian... " >&6; }
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: " >&5
-$as_echo "" >&6; }
-if test "$cross_compiling" = yes; then :
- { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
-$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
-as_fn_error $? "cannot run test program while cross compiling
-See \`config.log' for more details" "$LINENO" 5; }
-else
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include
-int
-main ()
-{
-const uint16_t endianness = 256; return !!(*(const uint8_t *)&endianness);
- ;
- return 0;
-}
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
- ENDIAN_FLAG="-DDMLC_CMAKE_LITTLE_ENDIAN=1"
-else
- ENDIAN_FLAG="-DDMLC_CMAKE_LITTLE_ENDIAN=0"
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
- conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-
-OPENMP_CXXFLAGS=""
-
-if test `uname -s` = "Linux"
-then
- OPENMP_CXXFLAGS="\$(SHLIB_OPENMP_CXXFLAGS)"
-fi
-
-if test `uname -s` = "Darwin"
-then
- OPENMP_CXXFLAGS='-Xclang -fopenmp'
- OPENMP_LIB='/usr/local/lib/libomp.dylib'
- ac_pkg_openmp=no
- { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether OpenMP will work in a package" >&5
-$as_echo_n "checking whether OpenMP will work in a package... " >&6; }
- cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h. */
-#include
-int
-main ()
-{
- return (omp_get_max_threads() <= 1);
- ;
- return 0;
-}
-_ACEOF
- ${CC} -o conftest conftest.c /usr/local/lib/libomp.dylib -Xclang -fopenmp 2>/dev/null && ./conftest && ac_pkg_openmp=yes
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${ac_pkg_openmp}" >&5
-$as_echo "${ac_pkg_openmp}" >&6; }
- if test "${ac_pkg_openmp}" = no; then
- OPENMP_CXXFLAGS=''
- OPENMP_LIB=''
- echo '*****************************************************************************************'
- echo 'WARNING: OpenMP is unavailable on this Mac OSX system. Training speed may be suboptimal.'
- echo ' To use all CPU cores for training jobs, you should install OpenMP by running\n'
- echo ' brew install libomp'
- echo '*****************************************************************************************'
- fi
-fi
-
-
-
-
-
-ac_config_files="$ac_config_files src/Makevars"
-
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems. If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
-
-_ACEOF
-
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, we kill variables containing newlines.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(
- for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
- eval ac_val=\$$ac_var
- case $ac_val in #(
- *${as_nl}*)
- case $ac_var in #(
- *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
-$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
- esac
- case $ac_var in #(
- _ | IFS | as_nl) ;; #(
- BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
- *) { eval $ac_var=; unset $ac_var;} ;;
- esac ;;
- esac
- done
-
- (set) 2>&1 |
- case $as_nl`(ac_space=' '; set) 2>&1` in #(
- *${as_nl}ac_space=\ *)
- # `set' does not quote correctly, so add quotes: double-quote
- # substitution turns \\\\ into \\, and sed turns \\ into \.
- sed -n \
- "s/'/'\\\\''/g;
- s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
- ;; #(
- *)
- # `set' quotes correctly as required by POSIX, so do not add quotes.
- sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
- ;;
- esac |
- sort
-) |
- sed '
- /^ac_cv_env_/b end
- t clear
- :clear
- s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
- t end
- s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
- :end' >>confcache
-if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
- if test -w "$cache_file"; then
- if test "x$cache_file" != "x/dev/null"; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
-$as_echo "$as_me: updating cache $cache_file" >&6;}
- if test ! -f "$cache_file" || test -h "$cache_file"; then
- cat confcache >"$cache_file"
- else
- case $cache_file in #(
- */* | ?:*)
- mv -f confcache "$cache_file"$$ &&
- mv -f "$cache_file"$$ "$cache_file" ;; #(
- *)
- mv -f confcache "$cache_file" ;;
- esac
- fi
- fi
- else
- { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
-$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
- fi
-fi
-rm -f confcache
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# Transform confdefs.h into DEFS.
-# Protect against shell expansion while executing Makefile rules.
-# Protect against Makefile macro expansion.
-#
-# If the first sed substitution is executed (which looks for macros that
-# take arguments), then branch to the quote section. Otherwise,
-# look for a macro that doesn't take arguments.
-ac_script='
-:mline
-/\\$/{
- N
- s,\\\n,,
- b mline
-}
-t clear
-:clear
-s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g
-t quote
-s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g
-t quote
-b any
-:quote
-s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g
-s/\[/\\&/g
-s/\]/\\&/g
-s/\$/$$/g
-H
-:any
-${
- g
- s/^\n//
- s/\n/ /g
- p
-}
-'
-DEFS=`sed -n "$ac_script" confdefs.h`
-
-
-ac_libobjs=
-ac_ltlibobjs=
-U=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
- # 1. Remove the extension, and $U if already installed.
- ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
- ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
- # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR
- # will be set to the directory where LIBOBJS objects are built.
- as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
- as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
-
-LTLIBOBJS=$ac_ltlibobjs
-
-
-
-: "${CONFIG_STATUS=./config.status}"
-ac_write_fail=0
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
-$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
-as_write_fail=0
-cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-
-SHELL=\${CONFIG_SHELL-$SHELL}
-export SHELL
-_ASEOF
-cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
-## -------------------- ##
-## M4sh Initialization. ##
-## -------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
- emulate sh
- NULLCMD=:
- # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
- # is contrary to our usage. Disable this feature.
- alias -g '${1+"$@"}'='"$@"'
- setopt NO_GLOB_SUBST
-else
- case `(set -o) 2>/dev/null` in #(
- *posix*) :
- set -o posix ;; #(
- *) :
- ;;
-esac
-fi
-
-
-as_nl='
-'
-export as_nl
-# Printing a long string crashes Solaris 7 /usr/bin/printf.
-as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
-as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
-# Prefer a ksh shell builtin over an external printf program on Solaris,
-# but without wasting forks for bash or zsh.
-if test -z "$BASH_VERSION$ZSH_VERSION" \
- && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='print -r --'
- as_echo_n='print -rn --'
-elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
- as_echo='printf %s\n'
- as_echo_n='printf %s'
-else
- if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
- as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
- as_echo_n='/usr/ucb/echo -n'
- else
- as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
- as_echo_n_body='eval
- arg=$1;
- case $arg in #(
- *"$as_nl"*)
- expr "X$arg" : "X\\(.*\\)$as_nl";
- arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
- esac;
- expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
- '
- export as_echo_n_body
- as_echo_n='sh -c $as_echo_n_body as_echo'
- fi
- export as_echo_body
- as_echo='sh -c $as_echo_body as_echo'
-fi
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
- PATH_SEPARATOR=:
- (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
- (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
- PATH_SEPARATOR=';'
- }
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order. Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-IFS=" "" $as_nl"
-
-# Find who we are. Look in the path if we contain no directory separator.
-as_myself=
-case $0 in #((
- *[\\/]* ) as_myself=$0 ;;
- *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
- IFS=$as_save_IFS
- test -z "$as_dir" && as_dir=.
- test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
- done
-IFS=$as_save_IFS
-
- ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
- as_myself=$0
-fi
-if test ! -f "$as_myself"; then
- $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
- exit 1
-fi
-
-# Unset variables that we do not need and which cause bugs (e.g. in
-# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1"
-# suppresses any "Segmentation fault" message there. '((' could
-# trigger a bug in pdksh 5.2.14.
-for as_var in BASH_ENV ENV MAIL MAILPATH
-do eval test x\${$as_var+set} = xset \
- && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-LC_ALL=C
-export LC_ALL
-LANGUAGE=C
-export LANGUAGE
-
-# CDPATH.
-(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
-
-
-# as_fn_error STATUS ERROR [LINENO LOG_FD]
-# ----------------------------------------
-# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
-# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
-# script with STATUS, using 1 if that was 0.
-as_fn_error ()
-{
- as_status=$1; test $as_status -eq 0 && as_status=1
- if test "$4"; then
- as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
- $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
- fi
- $as_echo "$as_me: error: $2" >&2
- as_fn_exit $as_status
-} # as_fn_error
-
-
-# as_fn_set_status STATUS
-# -----------------------
-# Set $? to STATUS, without forking.
-as_fn_set_status ()
-{
- return $1
-} # as_fn_set_status
-
-# as_fn_exit STATUS
-# -----------------
-# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
-as_fn_exit ()
-{
- set +e
- as_fn_set_status $1
- exit $1
-} # as_fn_exit
-
-# as_fn_unset VAR
-# ---------------
-# Portably unset VAR.
-as_fn_unset ()
-{
- { eval $1=; unset $1;}
-}
-as_unset=as_fn_unset
-# as_fn_append VAR VALUE
-# ----------------------
-# Append the text in VALUE to the end of the definition contained in VAR. Take
-# advantage of any shell optimizations that allow amortized linear growth over
-# repeated appends, instead of the typical quadratic growth present in naive
-# implementations.
-if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
- eval 'as_fn_append ()
- {
- eval $1+=\$2
- }'
-else
- as_fn_append ()
- {
- eval $1=\$$1\$2
- }
-fi # as_fn_append
-
-# as_fn_arith ARG...
-# ------------------
-# Perform arithmetic evaluation on the ARGs, and store the result in the
-# global $as_val. Take advantage of shells that can avoid forks. The arguments
-# must be portable across $(()) and expr.
-if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
- eval 'as_fn_arith ()
- {
- as_val=$(( $* ))
- }'
-else
- as_fn_arith ()
- {
- as_val=`expr "$@" || test $? -eq 1`
- }
-fi # as_fn_arith
-
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
- test "X`expr 00001 : '.*\(...\)'`" = X001; then
- as_expr=expr
-else
- as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
- as_basename=basename
-else
- as_basename=false
-fi
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
- as_dirname=dirname
-else
- as_dirname=false
-fi
-
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
- X"$0" : 'X\(//\)$' \| \
- X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X/"$0" |
- sed '/^.*\/\([^/][^/]*\)\/*$/{
- s//\1/
- q
- }
- /^X\/\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\/\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
-
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in #(((((
--n*)
- case `echo 'xy\c'` in
- *c*) ECHO_T=' ';; # ECHO_T is single tab character.
- xy) ECHO_C='\c';;
- *) echo `echo ksh88 bug on AIX 6.1` > /dev/null
- ECHO_T=' ';;
- esac;;
-*)
- ECHO_N='-n';;
-esac
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
- rm -f conf$$.dir/conf$$.file
-else
- rm -f conf$$.dir
- mkdir conf$$.dir 2>/dev/null
-fi
-if (echo >conf$$.file) 2>/dev/null; then
- if ln -s conf$$.file conf$$ 2>/dev/null; then
- as_ln_s='ln -s'
- # ... but there are two gotchas:
- # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
- # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
- # In both cases, we have to default to `cp -pR'.
- ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
- as_ln_s='cp -pR'
- elif ln conf$$.file conf$$ 2>/dev/null; then
- as_ln_s=ln
- else
- as_ln_s='cp -pR'
- fi
-else
- as_ln_s='cp -pR'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-
-# as_fn_mkdir_p
-# -------------
-# Create "$as_dir" as a directory, including parents if necessary.
-as_fn_mkdir_p ()
-{
-
- case $as_dir in #(
- -*) as_dir=./$as_dir;;
- esac
- test -d "$as_dir" || eval $as_mkdir_p || {
- as_dirs=
- while :; do
- case $as_dir in #(
- *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
- *) as_qdir=$as_dir;;
- esac
- as_dirs="'$as_qdir' $as_dirs"
- as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$as_dir" : 'X\(//\)[^/]' \| \
- X"$as_dir" : 'X\(//\)$' \| \
- X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$as_dir" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- test -d "$as_dir" && break
- done
- test -z "$as_dirs" || eval "mkdir $as_dirs"
- } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
-
-
-} # as_fn_mkdir_p
-if mkdir -p . 2>/dev/null; then
- as_mkdir_p='mkdir -p "$as_dir"'
-else
- test -d ./-p && rmdir ./-p
- as_mkdir_p=false
-fi
-
-
-# as_fn_executable_p FILE
-# -----------------------
-# Test if FILE is an executable regular file.
-as_fn_executable_p ()
-{
- test -f "$1" && test -x "$1"
-} # as_fn_executable_p
-as_test_x='test -x'
-as_executable_p=as_fn_executable_p
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-## ----------------------------------- ##
-## Main body of $CONFIG_STATUS script. ##
-## ----------------------------------- ##
-_ASEOF
-test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# Save the log message, to keep $0 and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by xgboost $as_me 0.6-3, which was
-generated by GNU Autoconf 2.69. Invocation command line was
-
- CONFIG_FILES = $CONFIG_FILES
- CONFIG_HEADERS = $CONFIG_HEADERS
- CONFIG_LINKS = $CONFIG_LINKS
- CONFIG_COMMANDS = $CONFIG_COMMANDS
- $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-_ACEOF
-
-case $ac_config_files in *"
-"*) set x $ac_config_files; shift; ac_config_files=$*;;
-esac
-
-
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-# Files that config.status was made for.
-config_files="$ac_config_files"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-ac_cs_usage="\
-\`$as_me' instantiates files and other configuration actions
-from templates according to the current configuration. Unless the files
-and actions are specified as TAGs, all are instantiated by default.
-
-Usage: $0 [OPTION]... [TAG]...
-
- -h, --help print this help, then exit
- -V, --version print version number and configuration settings, then exit
- --config print configuration, then exit
- -q, --quiet, --silent
- do not print progress messages
- -d, --debug don't remove temporary files
- --recheck update $as_me by reconfiguring in the same conditions
- --file=FILE[:TEMPLATE]
- instantiate the configuration file FILE
-
-Configuration files:
-$config_files
-
-Report bugs to the package provider."
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
-ac_cs_version="\\
-xgboost config.status 0.6-3
-configured by $0, generated by GNU Autoconf 2.69,
- with options \\"\$ac_cs_config\\"
-
-Copyright (C) 2012 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='$ac_pwd'
-srcdir='$srcdir'
-test -n "\$AWK" || AWK=awk
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# The default lists apply if the user does not specify any file.
-ac_need_defaults=:
-while test $# != 0
-do
- case $1 in
- --*=?*)
- ac_option=`expr "X$1" : 'X\([^=]*\)='`
- ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
- ac_shift=:
- ;;
- --*=)
- ac_option=`expr "X$1" : 'X\([^=]*\)='`
- ac_optarg=
- ac_shift=:
- ;;
- *)
- ac_option=$1
- ac_optarg=$2
- ac_shift=shift
- ;;
- esac
-
- case $ac_option in
- # Handling of the options.
- -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
- ac_cs_recheck=: ;;
- --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
- $as_echo "$ac_cs_version"; exit ;;
- --config | --confi | --conf | --con | --co | --c )
- $as_echo "$ac_cs_config"; exit ;;
- --debug | --debu | --deb | --de | --d | -d )
- debug=: ;;
- --file | --fil | --fi | --f )
- $ac_shift
- case $ac_optarg in
- *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
- '') as_fn_error $? "missing file argument" ;;
- esac
- as_fn_append CONFIG_FILES " '$ac_optarg'"
- ac_need_defaults=false;;
- --he | --h | --help | --hel | -h )
- $as_echo "$ac_cs_usage"; exit ;;
- -q | -quiet | --quiet | --quie | --qui | --qu | --q \
- | -silent | --silent | --silen | --sile | --sil | --si | --s)
- ac_cs_silent=: ;;
-
- # This is an error.
- -*) as_fn_error $? "unrecognized option: \`$1'
-Try \`$0 --help' for more information." ;;
-
- *) as_fn_append ac_config_targets " $1"
- ac_need_defaults=false ;;
-
- esac
- shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
- exec 6>/dev/null
- ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-if \$ac_cs_recheck; then
- set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
- shift
- \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
- CONFIG_SHELL='$SHELL'
- export CONFIG_SHELL
- exec "\$@"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-exec 5>>config.log
-{
- echo
- sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
- $as_echo "$ac_log"
-} >&5
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
- case $ac_config_target in
- "src/Makevars") CONFIG_FILES="$CONFIG_FILES src/Makevars" ;;
-
- *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
- esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used. Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
- test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-fi
-
-# Have a temporary directory for convenience. Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
- tmp= ac_tmp=
- trap 'exit_status=$?
- : "${ac_tmp:=$tmp}"
- { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
-' 0
- trap 'as_fn_exit 1' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
- tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
- test -d "$tmp"
-} ||
-{
- tmp=./conf$$-$RANDOM
- (umask 077 && mkdir "$tmp")
-} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
-ac_tmp=$tmp
-
-# Set up the scripts for CONFIG_FILES section.
-# No need to generate them if there are no CONFIG_FILES.
-# This happens for instance with `./config.status config.h'.
-if test -n "$CONFIG_FILES"; then
-
-
-ac_cr=`echo X | tr X '\015'`
-# On cygwin, bash can eat \r inside `` if the user requested igncr.
-# But we know of no other shell where ac_cr would be empty at this
-# point, so we can use a bashism as a fallback.
-if test "x$ac_cr" = x; then
- eval ac_cr=\$\'\\r\'
-fi
-ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null`
-if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
- ac_cs_awk_cr='\\r'
-else
- ac_cs_awk_cr=$ac_cr
-fi
-
-echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
-_ACEOF
-
-
-{
- echo "cat >conf$$subs.awk <<_ACEOF" &&
- echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
- echo "_ACEOF"
-} >conf$$subs.sh ||
- as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
-ac_delim='%!_!# '
-for ac_last_try in false false false false false :; do
- . ./conf$$subs.sh ||
- as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
-
- ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
- if test $ac_delim_n = $ac_delim_num; then
- break
- elif $ac_last_try; then
- as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
- else
- ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
- fi
-done
-rm -f conf$$subs.sh
-
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
-_ACEOF
-sed -n '
-h
-s/^/S["/; s/!.*/"]=/
-p
-g
-s/^[^!]*!//
-:repl
-t repl
-s/'"$ac_delim"'$//
-t delim
-:nl
-h
-s/\(.\{148\}\)..*/\1/
-t more1
-s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
-p
-n
-b repl
-:more1
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t nl
-:delim
-h
-s/\(.\{148\}\)..*/\1/
-t more2
-s/["\\]/\\&/g; s/^/"/; s/$/"/
-p
-b
-:more2
-s/["\\]/\\&/g; s/^/"/; s/$/"\\/
-p
-g
-s/.\{148\}//
-t delim
-' >$CONFIG_STATUS || ac_write_fail=1
-rm -f conf$$subs.awk
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-_ACAWK
-cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
- for (key in S) S_is_set[key] = 1
- FS = ""
-
-}
-{
- line = $ 0
- nfields = split(line, field, "@")
- substed = 0
- len = length(field[1])
- for (i = 2; i < nfields; i++) {
- key = field[i]
- keylen = length(key)
- if (S_is_set[key]) {
- value = S[key]
- line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
- len += length(value) + length(field[++i])
- substed = 1
- } else
- len += 1 + keylen
- }
-
- print line
-}
-
-_ACAWK
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
- sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
-else
- cat
-fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
- || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
-_ACEOF
-
-# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
-# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
- ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{
-h
-s///
-s/^/:/
-s/[ ]*$/:/
-s/:\$(srcdir):/:/g
-s/:\${srcdir}:/:/g
-s/:@srcdir@:/:/g
-s/^:*//
-s/:*$//
-x
-s/\(=[ ]*\).*/\1/
-G
-s/\n//
-s/^[^=]*=[ ]*$//
-}'
-fi
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-fi # test -n "$CONFIG_FILES"
-
-
-eval set X " :F $CONFIG_FILES "
-shift
-for ac_tag
-do
- case $ac_tag in
- :[FHLC]) ac_mode=$ac_tag; continue;;
- esac
- case $ac_mode$ac_tag in
- :[FHL]*:*);;
- :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
- :[FH]-) ac_tag=-:-;;
- :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
- esac
- ac_save_IFS=$IFS
- IFS=:
- set x $ac_tag
- IFS=$ac_save_IFS
- shift
- ac_file=$1
- shift
-
- case $ac_mode in
- :L) ac_source=$1;;
- :[FH])
- ac_file_inputs=
- for ac_f
- do
- case $ac_f in
- -) ac_f="$ac_tmp/stdin";;
- *) # Look for the file first in the build tree, then in the source tree
- # (if the path is not absolute). The absolute path cannot be DOS-style,
- # because $ac_f cannot contain `:'.
- test -f "$ac_f" ||
- case $ac_f in
- [\\/$]*) false;;
- *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
- esac ||
- as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
- esac
- case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
- as_fn_append ac_file_inputs " '$ac_f'"
- done
-
- # Let's still pretend it is `configure' which instantiates (i.e., don't
- # use $as_me), people would be surprised to read:
- # /* config.h. Generated by config.status. */
- configure_input='Generated from '`
- $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
- `' by configure.'
- if test x"$ac_file" != x-; then
- configure_input="$ac_file. $configure_input"
- { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
-$as_echo "$as_me: creating $ac_file" >&6;}
- fi
- # Neutralize special characters interpreted by sed in replacement strings.
- case $configure_input in #(
- *\&* | *\|* | *\\* )
- ac_sed_conf_input=`$as_echo "$configure_input" |
- sed 's/[\\\\&|]/\\\\&/g'`;; #(
- *) ac_sed_conf_input=$configure_input;;
- esac
-
- case $ac_tag in
- *:-:* | *:-) cat >"$ac_tmp/stdin" \
- || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
- esac
- ;;
- esac
-
- ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
- X"$ac_file" : 'X\(//\)[^/]' \| \
- X"$ac_file" : 'X\(//\)$' \| \
- X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-$as_echo X"$ac_file" |
- sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
- s//\1/
- q
- }
- /^X\(\/\/\)[^/].*/{
- s//\1/
- q
- }
- /^X\(\/\/\)$/{
- s//\1/
- q
- }
- /^X\(\/\).*/{
- s//\1/
- q
- }
- s/.*/./; q'`
- as_dir="$ac_dir"; as_fn_mkdir_p
- ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
- ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
- # A ".." for each directory in $ac_dir_suffix.
- ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
- case $ac_top_builddir_sub in
- "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
- *) ac_top_build_prefix=$ac_top_builddir_sub/ ;;
- esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
- .) # We are building in place.
- ac_srcdir=.
- ac_top_srcdir=$ac_top_builddir_sub
- ac_abs_top_srcdir=$ac_pwd ;;
- [\\/]* | ?:[\\/]* ) # Absolute name.
- ac_srcdir=$srcdir$ac_dir_suffix;
- ac_top_srcdir=$srcdir
- ac_abs_top_srcdir=$srcdir ;;
- *) # Relative name.
- ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
- ac_top_srcdir=$ac_top_build_prefix$srcdir
- ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
- case $ac_mode in
- :F)
- #
- # CONFIG_FILE
- #
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-ac_sed_dataroot='
-/datarootdir/ {
- p
- q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p'
-case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
- ac_datarootdir_hack='
- s&@datadir@&$datadir&g
- s&@docdir@&$docdir&g
- s&@infodir@&$infodir&g
- s&@localedir@&$localedir&g
- s&@mandir@&$mandir&g
- s&\\\${datarootdir}&$datarootdir&g' ;;
-esac
-_ACEOF
-
-# Neutralize VPATH when `$srcdir' = `.'.
-# Shell code in configure.ac might set extrasub.
-# FIXME: do we really want to maintain this feature?
-cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-ac_sed_extra="$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s|@configure_input@|$ac_sed_conf_input|;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@top_build_prefix@&$ac_top_build_prefix&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-$ac_datarootdir_hack
-"
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
- >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
- { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
- { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \
- "$ac_tmp/out"`; test -z "$ac_out"; } &&
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined. Please make sure it is defined" >&5
-$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined. Please make sure it is defined" >&2;}
-
- rm -f "$ac_tmp/stdin"
- case $ac_file in
- -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
- *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
- esac \
- || as_fn_error $? "could not create $ac_file" "$LINENO" 5
- ;;
-
-
-
- esac
-
-done # for ac_tag
-
-
-as_fn_exit 0
-_ACEOF
-ac_clean_files=$ac_clean_files_save
-
-test $ac_write_fail = 0 ||
- as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
-
-
-# configure is writing to config.log, and then calls config.status.
-# config.status does its own redirection, appending to config.log.
-# Unfortunately, on DOS this fails, as config.log is still kept open
-# by configure, so config.status won't be able to write to it; its
-# output is simply discarded. So we exec the FD to /dev/null,
-# effectively closing config.log, so it can be properly (re)opened and
-# appended to by config.status. When coming back to configure, we
-# need to make the FD available again.
-if test "$no_create" != yes; then
- ac_cs_success=:
- ac_config_status_args=
- test "$silent" = yes &&
- ac_config_status_args="$ac_config_status_args --quiet"
- exec 5>/dev/null
- $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
- exec 5>>config.log
- # Use ||, not &&, to avoid exiting from the if with $? = 1, which
- # would make configure fail if this is the last instruction.
- $ac_cs_success || as_fn_exit 1
-fi
-if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
- { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
-$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
-fi
-
-
diff --git a/ml-xgboost/R-package/configure.ac b/ml-xgboost/R-package/configure.ac
deleted file mode 100644
index c683a94..0000000
--- a/ml-xgboost/R-package/configure.ac
+++ /dev/null
@@ -1,55 +0,0 @@
-### configure.ac -*- Autoconf -*-
-
-AC_PREREQ(2.62)
-
-AC_INIT([xgboost],[0.6-3],[],[xgboost],[])
-
-# Use this line to set CC variable to a C compiler
-AC_PROG_CC
-
-### Check whether backtrace() is part of libc or the external lib libexecinfo
-AC_MSG_CHECKING([Backtrace lib])
-AC_MSG_RESULT([])
-AC_CHECK_LIB([execinfo], [backtrace], [BACKTRACE_LIB=-lexecinfo], [BACKTRACE_LIB=''])
-
-### Endian detection
-AC_MSG_CHECKING([endian])
-AC_MSG_RESULT([])
-AC_RUN_IFELSE([AC_LANG_PROGRAM([[#include ]], [[const uint16_t endianness = 256; return !!(*(const uint8_t *)&endianness);]])],
- [ENDIAN_FLAG="-DDMLC_CMAKE_LITTLE_ENDIAN=1"],
- [ENDIAN_FLAG="-DDMLC_CMAKE_LITTLE_ENDIAN=0"])
-
-OPENMP_CXXFLAGS=""
-
-if test `uname -s` = "Linux"
-then
- OPENMP_CXXFLAGS="\$(SHLIB_OPENMP_CXXFLAGS)"
-fi
-
-if test `uname -s` = "Darwin"
-then
- OPENMP_CXXFLAGS='-Xclang -fopenmp'
- OPENMP_LIB='/usr/local/lib/libomp.dylib'
- ac_pkg_openmp=no
- AC_MSG_CHECKING([whether OpenMP will work in a package])
- AC_LANG_CONFTEST([AC_LANG_PROGRAM([[#include ]], [[ return (omp_get_max_threads() <= 1); ]])])
- ${CC} -o conftest conftest.c /usr/local/lib/libomp.dylib -Xclang -fopenmp 2>/dev/null && ./conftest && ac_pkg_openmp=yes
- AC_MSG_RESULT([${ac_pkg_openmp}])
- if test "${ac_pkg_openmp}" = no; then
- OPENMP_CXXFLAGS=''
- OPENMP_LIB=''
- echo '*****************************************************************************************'
- echo 'WARNING: OpenMP is unavailable on this Mac OSX system. Training speed may be suboptimal.'
- echo ' To use all CPU cores for training jobs, you should install OpenMP by running\n'
- echo ' brew install libomp'
- echo '*****************************************************************************************'
- fi
-fi
-
-AC_SUBST(OPENMP_CXXFLAGS)
-AC_SUBST(OPENMP_LIB)
-AC_SUBST(ENDIAN_FLAG)
-AC_SUBST(BACKTRACE_LIB)
-AC_CONFIG_FILES([src/Makevars])
-AC_OUTPUT
-
diff --git a/ml-xgboost/R-package/configure.win b/ml-xgboost/R-package/configure.win
deleted file mode 100644
index e69de29..0000000
diff --git a/ml-xgboost/R-package/demo/00Index b/ml-xgboost/R-package/demo/00Index
deleted file mode 100644
index 5c949d0..0000000
--- a/ml-xgboost/R-package/demo/00Index
+++ /dev/null
@@ -1,15 +0,0 @@
-basic_walkthrough Basic feature walkthrough
-caret_wrapper Use xgboost to train in caret library
-custom_objective Cutomize loss function, and evaluation metric
-boost_from_prediction Boosting from existing prediction
-predict_first_ntree Predicting using first n trees
-generalized_linear_model Generalized Linear Model
-cross_validation Cross validation
-create_sparse_matrix Create Sparse Matrix
-predict_leaf_indices Predicting the corresponding leaves
-early_stopping Early Stop in training
-poisson_regression Poisson Regression on count data
-tweedie_regression Tweddie Regression
-gpu_accelerated GPU-accelerated tree building algorithms
-interaction_constraints Interaction constraints among features
-
diff --git a/ml-xgboost/R-package/demo/README.md b/ml-xgboost/R-package/demo/README.md
deleted file mode 100644
index e53afea..0000000
--- a/ml-xgboost/R-package/demo/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-XGBoost R Feature Walkthrough
-====
-* [Basic walkthrough of wrappers](basic_walkthrough.R)
-* [Train a xgboost model from caret library](caret_wrapper.R)
-* [Cutomize loss function, and evaluation metric](custom_objective.R)
-* [Boosting from existing prediction](boost_from_prediction.R)
-* [Predicting using first n trees](predict_first_ntree.R)
-* [Generalized Linear Model](generalized_linear_model.R)
-* [Cross validation](cross_validation.R)
-* [Create a sparse matrix from a dense one](create_sparse_matrix.R)
-* [Use GPU-accelerated tree building algorithms](gpu_accelerated.R)
-
-Benchmarks
-====
-* [Starter script for Kaggle Higgs Boson](../../demo/kaggle-higgs)
-
-Notes
-====
-* Contribution of examples, benchmarks is more than welcomed!
-* If you like to share how you use xgboost to solve your problem, send a pull request:)
diff --git a/ml-xgboost/R-package/demo/basic_walkthrough.R b/ml-xgboost/R-package/demo/basic_walkthrough.R
deleted file mode 100644
index bb6b850..0000000
--- a/ml-xgboost/R-package/demo/basic_walkthrough.R
+++ /dev/null
@@ -1,112 +0,0 @@
-require(xgboost)
-require(methods)
-
-# we load in the agaricus dataset
-# In this example, we are aiming to predict whether a mushroom is edible
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-# the loaded data is stored in sparseMatrix, and label is a numeric vector in {0,1}
-class(train$label)
-class(train$data)
-
-#-------------Basic Training using XGBoost-----------------
-# this is the basic usage of xgboost you can put matrix in data field
-# note: we are putting in sparse matrix here, xgboost naturally handles sparse input
-# use sparse matrix when your feature is sparse(e.g. when you are using one-hot encoding vector)
-print("Training xgboost with sparseMatrix")
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2, eta = 1, nrounds = 2,
- nthread = 2, objective = "binary:logistic")
-# alternatively, you can put in dense matrix, i.e. basic R-matrix
-print("Training xgboost with Matrix")
-bst <- xgboost(data = as.matrix(train$data), label = train$label, max_depth = 2, eta = 1, nrounds = 2,
- nthread = 2, objective = "binary:logistic")
-
-# you can also put in xgb.DMatrix object, which stores label, data and other meta datas needed for advanced features
-print("Training xgboost with xgb.DMatrix")
-dtrain <- xgb.DMatrix(data = train$data, label = train$label)
-bst <- xgboost(data = dtrain, max_depth = 2, eta = 1, nrounds = 2, nthread = 2,
- objective = "binary:logistic")
-
-# Verbose = 0,1,2
-print("Train xgboost with verbose 0, no message")
-bst <- xgboost(data = dtrain, max_depth = 2, eta = 1, nrounds = 2,
- nthread = 2, objective = "binary:logistic", verbose = 0)
-print("Train xgboost with verbose 1, print evaluation metric")
-bst <- xgboost(data = dtrain, max_depth = 2, eta = 1, nrounds = 2,
- nthread = 2, objective = "binary:logistic", verbose = 1)
-print("Train xgboost with verbose 2, also print information about tree")
-bst <- xgboost(data = dtrain, max_depth = 2, eta = 1, nrounds = 2,
- nthread = 2, objective = "binary:logistic", verbose = 2)
-
-# you can also specify data as file path to a LibSVM format input
-# since we do not have this file with us, the following line is just for illustration
-# bst <- xgboost(data = 'agaricus.train.svm', max_depth = 2, eta = 1, nrounds = 2,objective = "binary:logistic")
-
-#--------------------basic prediction using xgboost--------------
-# you can do prediction using the following line
-# you can put in Matrix, sparseMatrix, or xgb.DMatrix
-pred <- predict(bst, test$data)
-err <- mean(as.numeric(pred > 0.5) != test$label)
-print(paste("test-error=", err))
-
-#-------------------save and load models-------------------------
-# save model to binary local file
-xgb.save(bst, "xgboost.model")
-# load binary model to R
-bst2 <- xgb.load("xgboost.model")
-pred2 <- predict(bst2, test$data)
-# pred2 should be identical to pred
-print(paste("sum(abs(pred2-pred))=", sum(abs(pred2-pred))))
-
-# save model to R's raw vector
-raw = xgb.save.raw(bst)
-# load binary model to R
-bst3 <- xgb.load(raw)
-pred3 <- predict(bst3, test$data)
-# pred3 should be identical to pred
-print(paste("sum(abs(pred3-pred))=", sum(abs(pred3-pred))))
-
-#----------------Advanced features --------------
-# to use advanced features, we need to put data in xgb.DMatrix
-dtrain <- xgb.DMatrix(data = train$data, label=train$label)
-dtest <- xgb.DMatrix(data = test$data, label=test$label)
-#---------------Using watchlist----------------
-# watchlist is a list of xgb.DMatrix, each of them is tagged with name
-watchlist <- list(train=dtrain, test=dtest)
-# to train with watchlist, use xgb.train, which contains more advanced features
-# watchlist allows us to monitor the evaluation result on all data in the list
-print("Train xgboost using xgb.train with watchlist")
-bst <- xgb.train(data=dtrain, max_depth=2, eta=1, nrounds=2, watchlist=watchlist,
- nthread = 2, objective = "binary:logistic")
-# we can change evaluation metrics, or use multiple evaluation metrics
-print("train xgboost using xgb.train with watchlist, watch logloss and error")
-bst <- xgb.train(data=dtrain, max_depth=2, eta=1, nrounds=2, watchlist=watchlist,
- eval_metric = "error", eval_metric = "logloss",
- nthread = 2, objective = "binary:logistic")
-
-# xgb.DMatrix can also be saved using xgb.DMatrix.save
-xgb.DMatrix.save(dtrain, "dtrain.buffer")
-# to load it in, simply call xgb.DMatrix
-dtrain2 <- xgb.DMatrix("dtrain.buffer")
-bst <- xgb.train(data=dtrain2, max_depth=2, eta=1, nrounds=2, watchlist=watchlist,
- nthread = 2, objective = "binary:logistic")
-# information can be extracted from xgb.DMatrix using getinfo
-label = getinfo(dtest, "label")
-pred <- predict(bst, dtest)
-err <- as.numeric(sum(as.integer(pred > 0.5) != label))/length(label)
-print(paste("test-error=", err))
-
-# You can dump the tree you learned using xgb.dump into a text file
-dump_path = file.path(tempdir(), 'dump.raw.txt')
-xgb.dump(bst, dump_path, with_stats = T)
-
-# Finally, you can check which features are the most important.
-print("Most important features (look at column Gain):")
-imp_matrix <- xgb.importance(feature_names = colnames(train$data), model = bst)
-print(imp_matrix)
-
-# Feature importance bar plot by gain
-print("Feature importance Plot : ")
-print(xgb.plot.importance(importance_matrix = imp_matrix))
diff --git a/ml-xgboost/R-package/demo/boost_from_prediction.R b/ml-xgboost/R-package/demo/boost_from_prediction.R
deleted file mode 100644
index 1765650..0000000
--- a/ml-xgboost/R-package/demo/boost_from_prediction.R
+++ /dev/null
@@ -1,26 +0,0 @@
-require(xgboost)
-# load in the agaricus dataset
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-
-watchlist <- list(eval = dtest, train = dtrain)
-###
-# advanced: start from a initial base prediction
-#
-print('start running example to start from a initial prediction')
-# train xgboost for 1 round
-param <- list(max_depth=2, eta=1, nthread = 2, silent=1, objective='binary:logistic')
-bst <- xgb.train(param, dtrain, 1, watchlist)
-# Note: we need the margin value instead of transformed prediction in set_base_margin
-# do predict with output_margin=TRUE, will always give you margin values before logistic transformation
-ptrain <- predict(bst, dtrain, outputmargin=TRUE)
-ptest <- predict(bst, dtest, outputmargin=TRUE)
-# set the base_margin property of dtrain and dtest
-# base margin is the base prediction we will boost from
-setinfo(dtrain, "base_margin", ptrain)
-setinfo(dtest, "base_margin", ptest)
-
-print('this is result of boost from initial prediction')
-bst <- xgb.train(params = param, data = dtrain, nrounds = 1, watchlist = watchlist)
diff --git a/ml-xgboost/R-package/demo/caret_wrapper.R b/ml-xgboost/R-package/demo/caret_wrapper.R
deleted file mode 100644
index 751b202..0000000
--- a/ml-xgboost/R-package/demo/caret_wrapper.R
+++ /dev/null
@@ -1,35 +0,0 @@
-# install development version of caret library that contains xgboost models
-devtools::install_github("topepo/caret/pkg/caret")
-require(caret)
-require(xgboost)
-require(data.table)
-require(vcd)
-require(e1071)
-
-# Load Arthritis dataset in memory.
-data(Arthritis)
-# Create a copy of the dataset with data.table package (data.table is 100% compliant with R dataframe but its syntax is a lot more consistent and its performance are really good).
-df <- data.table(Arthritis, keep.rownames = F)
-
-# Let's add some new categorical features to see if it helps. Of course these feature are highly correlated to the Age feature. Usually it's not a good thing in ML, but Tree algorithms (including boosted trees) are able to select the best features, even in case of highly correlated features.
-# For the first feature we create groups of age by rounding the real age. Note that we transform it to factor (categorical data) so the algorithm treat them as independant values.
-df[,AgeDiscret:= as.factor(round(Age/10,0))]
-
-# Here is an even stronger simplification of the real age with an arbitrary split at 30 years old. I choose this value based on nothing. We will see later if simplifying the information based on arbitrary values is a good strategy (I am sure you already have an idea of how well it will work!).
-df[,AgeCat:= as.factor(ifelse(Age > 30, "Old", "Young"))]
-
-# We remove ID as there is nothing to learn from this feature (it will just add some noise as the dataset is small).
-df[,ID:=NULL]
-
-#-------------Basic Training using XGBoost in caret Library-----------------
-# Set up control parameters for caret::train
-# Here we use 10-fold cross-validation, repeating twice, and using random search for tuning hyper-parameters.
-fitControl <- trainControl(method = "repeatedcv", number = 10, repeats = 2, search = "random")
-# train a xgbTree model using caret::train
-model <- train(factor(Improved)~., data = df, method = "xgbTree", trControl = fitControl)
-
-# Instead of tree for our boosters, you can also fit a linear regression or logistic regression model using xgbLinear
-# model <- train(factor(Improved)~., data = df, method = "xgbLinear", trControl = fitControl)
-
-# See model results
-print(model)
diff --git a/ml-xgboost/R-package/demo/create_sparse_matrix.R b/ml-xgboost/R-package/demo/create_sparse_matrix.R
deleted file mode 100644
index 6069f33..0000000
--- a/ml-xgboost/R-package/demo/create_sparse_matrix.R
+++ /dev/null
@@ -1,89 +0,0 @@
-require(xgboost)
-require(Matrix)
-require(data.table)
-if (!require(vcd)) {
- install.packages('vcd') #Available in Cran. Used for its dataset with categorical values.
- require(vcd)
-}
-# According to its documentation, Xgboost works only on numbers.
-# Sometimes the dataset we have to work on have categorical data.
-# A categorical variable is one which have a fixed number of values. By example, if for each observation a variable called "Colour" can have only "red", "blue" or "green" as value, it is a categorical variable.
-#
-# In R, categorical variable is called Factor.
-# Type ?factor in console for more information.
-#
-# In this demo we will see how to transform a dense dataframe with categorical variables to a sparse matrix before analyzing it in Xgboost.
-# The method we are going to see is usually called "one hot encoding".
-
-#load Arthritis dataset in memory.
-data(Arthritis)
-
-# create a copy of the dataset with data.table package (data.table is 100% compliant with R dataframe but its syntax is a lot more consistent and its performance are really good).
-df <- data.table(Arthritis, keep.rownames = F)
-
-# Let's have a look to the data.table
-cat("Print the dataset\n")
-print(df)
-
-# 2 columns have factor type, one has ordinal type (ordinal variable is a categorical variable with values wich can be ordered, here: None > Some > Marked).
-cat("Structure of the dataset\n")
-str(df)
-
-# Let's add some new categorical features to see if it helps. Of course these feature are highly correlated to the Age feature. Usually it's not a good thing in ML, but Tree algorithms (including boosted trees) are able to select the best features, even in case of highly correlated features.
-
-# For the first feature we create groups of age by rounding the real age. Note that we transform it to factor (categorical data) so the algorithm treat them as independant values.
-df[,AgeDiscret:= as.factor(round(Age/10,0))]
-
-# Here is an even stronger simplification of the real age with an arbitrary split at 30 years old. I choose this value based on nothing. We will see later if simplifying the information based on arbitrary values is a good strategy (I am sure you already have an idea of how well it will work!).
-df[,AgeCat:= as.factor(ifelse(Age > 30, "Old", "Young"))]
-
-# We remove ID as there is nothing to learn from this feature (it will just add some noise as the dataset is small).
-df[,ID:=NULL]
-
-# List the different values for the column Treatment: Placebo, Treated.
-cat("Values of the categorical feature Treatment\n")
-print(levels(df[,Treatment]))
-
-# Next step, we will transform the categorical data to dummy variables.
-# This method is also called one hot encoding.
-# The purpose is to transform each value of each categorical feature in one binary feature.
-#
-# Let's take, the column Treatment will be replaced by two columns, Placebo, and Treated. Each of them will be binary. For example an observation which had the value Placebo in column Treatment before the transformation will have, after the transformation, the value 1 in the new column Placebo and the value 0 in the new column Treated.
-#
-# Formulae Improved~.-1 used below means transform all categorical features but column Improved to binary values.
-# Column Improved is excluded because it will be our output column, the one we want to predict.
-sparse_matrix = sparse.model.matrix(Improved~.-1, data = df)
-
-cat("Encoding of the sparse Matrix\n")
-print(sparse_matrix)
-
-# Create the output vector (not sparse)
-# 1. Set, for all rows, field in Y column to 0;
-# 2. set Y to 1 when Improved == Marked;
-# 3. Return Y column
-output_vector = df[,Y:=0][Improved == "Marked",Y:=1][,Y]
-
-# Following is the same process as other demo
-cat("Learning...\n")
-bst <- xgboost(data = sparse_matrix, label = output_vector, max_depth = 9,
- eta = 1, nthread = 2, nrounds = 10, objective = "binary:logistic")
-
-importance <- xgb.importance(feature_names = colnames(sparse_matrix), model = bst)
-print(importance)
-# According to the matrix below, the most important feature in this dataset to predict if the treatment will work is the Age. The second most important feature is having received a placebo or not. The sex is third. Then we see our generated features (AgeDiscret). We can see that their contribution is very low (Gain column).
-
-# Does these result make sense?
-# Let's check some Chi2 between each of these features and the outcome.
-
-print(chisq.test(df$Age, df$Y))
-# Pearson correlation between Age and illness disappearing is 35
-
-print(chisq.test(df$AgeDiscret, df$Y))
-# Our first simplification of Age gives a Pearson correlation of 8.
-
-print(chisq.test(df$AgeCat, df$Y))
-# The perfectly random split I did between young and old at 30 years old have a low correlation of 2. It's a result we may expect as may be in my mind > 30 years is being old (I am 32 and starting feeling old, this may explain that), but for the illness we are studying, the age to be vulnerable is not the same. Don't let your "gut" lower the quality of your model. In "data science", there is science :-)
-
-# As you can see, in general destroying information by simplifying it won't improve your model. Chi2 just demonstrates that. But in more complex cases, creating a new feature based on existing one which makes link with the outcome more obvious may help the algorithm and improve the model. The case studied here is not enough complex to show that. Check Kaggle forum for some challenging datasets.
-# However it's almost always worse when you add some arbitrary rules.
-# Moreover, you can notice that even if we have added some not useful new features highly correlated with other features, the boosting tree algorithm have been able to choose the best one, which in this case is the Age. Linear model may not be that strong in these scenario.
diff --git a/ml-xgboost/R-package/demo/cross_validation.R b/ml-xgboost/R-package/demo/cross_validation.R
deleted file mode 100644
index d074552..0000000
--- a/ml-xgboost/R-package/demo/cross_validation.R
+++ /dev/null
@@ -1,51 +0,0 @@
-require(xgboost)
-# load in the agaricus dataset
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-
-nrounds <- 2
-param <- list(max_depth=2, eta=1, silent=1, nthread=2, objective='binary:logistic')
-
-cat('running cross validation\n')
-# do cross validation, this will print result out as
-# [iteration] metric_name:mean_value+std_value
-# std_value is standard deviation of the metric
-xgb.cv(param, dtrain, nrounds, nfold=5, metrics={'error'})
-
-cat('running cross validation, disable standard deviation display\n')
-# do cross validation, this will print result out as
-# [iteration] metric_name:mean_value+std_value
-# std_value is standard deviation of the metric
-xgb.cv(param, dtrain, nrounds, nfold=5,
- metrics='error', showsd = FALSE)
-
-###
-# you can also do cross validation with cutomized loss function
-# See custom_objective.R
-##
-print ('running cross validation, with cutomsized loss function')
-
-logregobj <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- preds <- 1/(1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
-}
-evalerror <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- err <- as.numeric(sum(labels != (preds > 0)))/length(labels)
- return(list(metric = "error", value = err))
-}
-
-param <- list(max_depth=2, eta=1, silent=1,
- objective = logregobj, eval_metric = evalerror)
-# train with customized objective
-xgb.cv(params = param, data = dtrain, nrounds = nrounds, nfold = 5)
-
-# do cross validation with prediction values for each fold
-res <- xgb.cv(params = param, data = dtrain, nrounds = nrounds, nfold = 5, prediction = TRUE)
-res$evaluation_log
-length(res$pred)
diff --git a/ml-xgboost/R-package/demo/custom_objective.R b/ml-xgboost/R-package/demo/custom_objective.R
deleted file mode 100644
index ec7e7e8..0000000
--- a/ml-xgboost/R-package/demo/custom_objective.R
+++ /dev/null
@@ -1,65 +0,0 @@
-require(xgboost)
-# load in the agaricus dataset
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-
-# note: for customized objective function, we leave objective as default
-# note: what we are getting is margin value in prediction
-# you must know what you are doing
-watchlist <- list(eval = dtest, train = dtrain)
-num_round <- 2
-
-# user define objective function, given prediction, return gradient and second order gradient
-# this is loglikelihood loss
-logregobj <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- preds <- 1/(1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
-}
-
-# user defined evaluation function, return a pair metric_name, result
-# NOTE: when you do customized loss function, the default prediction value is margin
-# this may make buildin evalution metric not function properly
-# for example, we are doing logistic loss, the prediction is score before logistic transformation
-# the buildin evaluation error assumes input is after logistic transformation
-# Take this in mind when you use the customization, and maybe you need write customized evaluation function
-evalerror <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- err <- as.numeric(sum(labels != (preds > 0)))/length(labels)
- return(list(metric = "error", value = err))
-}
-
-param <- list(max_depth=2, eta=1, nthread = 2, verbosity=0,
- objective=logregobj, eval_metric=evalerror)
-print ('start training with user customized objective')
-# training with customized objective, we can also do step by step training
-# simply look at xgboost.py's implementation of train
-bst <- xgb.train(param, dtrain, num_round, watchlist)
-
-#
-# there can be cases where you want additional information
-# being considered besides the property of DMatrix you can get by getinfo
-# you can set additional information as attributes if DMatrix
-
-# set label attribute of dtrain to be label, we use label as an example, it can be anything
-attr(dtrain, 'label') <- getinfo(dtrain, 'label')
-# this is new customized objective, where you can access things you set
-# same thing applies to customized evaluation function
-logregobjattr <- function(preds, dtrain) {
- # now you can access the attribute in customized function
- labels <- attr(dtrain, 'label')
- preds <- 1/(1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
-}
-param <- list(max_depth=2, eta=1, nthread = 2, verbosity=0,
- objective=logregobjattr, eval_metric=evalerror)
-print ('start training with user customized objective, with additional attributes in DMatrix')
-# training with customized objective, we can also do step by step training
-# simply look at xgboost.py's implementation of train
-bst <- xgb.train(param, dtrain, num_round, watchlist)
diff --git a/ml-xgboost/R-package/demo/early_stopping.R b/ml-xgboost/R-package/demo/early_stopping.R
deleted file mode 100644
index 92a3ee8..0000000
--- a/ml-xgboost/R-package/demo/early_stopping.R
+++ /dev/null
@@ -1,40 +0,0 @@
-require(xgboost)
-# load in the agaricus dataset
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-# note: for customized objective function, we leave objective as default
-# note: what we are getting is margin value in prediction
-# you must know what you are doing
-param <- list(max_depth=2, eta=1, nthread=2, verbosity=0)
-watchlist <- list(eval = dtest)
-num_round <- 20
-# user define objective function, given prediction, return gradient and second order gradient
-# this is loglikelihood loss
-logregobj <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- preds <- 1/(1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
-}
-# user defined evaluation function, return a pair metric_name, result
-# NOTE: when you do customized loss function, the default prediction value is margin
-# this may make buildin evalution metric not function properly
-# for example, we are doing logistic loss, the prediction is score before logistic transformation
-# the buildin evaluation error assumes input is after logistic transformation
-# Take this in mind when you use the customization, and maybe you need write customized evaluation function
-evalerror <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- err <- as.numeric(sum(labels != (preds > 0)))/length(labels)
- return(list(metric = "error", value = err))
-}
-print ('start training with early Stopping setting')
-
-bst <- xgb.train(param, dtrain, num_round, watchlist,
- objective = logregobj, eval_metric = evalerror, maximize = FALSE,
- early_stopping_round = 3)
-bst <- xgb.cv(param, dtrain, num_round, nfold = 5,
- objective = logregobj, eval_metric = evalerror,
- maximize = FALSE, early_stopping_rounds = 3)
diff --git a/ml-xgboost/R-package/demo/generalized_linear_model.R b/ml-xgboost/R-package/demo/generalized_linear_model.R
deleted file mode 100644
index 3c2cdb5..0000000
--- a/ml-xgboost/R-package/demo/generalized_linear_model.R
+++ /dev/null
@@ -1,34 +0,0 @@
-require(xgboost)
-# load in the agaricus dataset
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-##
-# this script demonstrate how to fit generalized linear model in xgboost
-# basically, we are using linear model, instead of tree for our boosters
-# you can fit a linear regression, or logistic regression model
-##
-
-# change booster to gblinear, so that we are fitting a linear model
-# alpha is the L1 regularizer
-# lambda is the L2 regularizer
-# you can also set lambda_bias which is L2 regularizer on the bias term
-param <- list(objective = "binary:logistic", booster = "gblinear",
- nthread = 2, alpha = 0.0001, lambda = 1)
-
-# normally, you do not need to set eta (step_size)
-# XGBoost uses a parallel coordinate descent algorithm (shotgun),
-# there could be affection on convergence with parallelization on certain cases
-# setting eta to be smaller value, e.g 0.5 can make the optimization more stable
-
-##
-# the rest of settings are the same
-##
-watchlist <- list(eval = dtest, train = dtrain)
-num_round <- 2
-bst <- xgb.train(param, dtrain, num_round, watchlist)
-ypred <- predict(bst, dtest)
-labels <- getinfo(dtest, 'label')
-cat('error of preds=', mean(as.numeric(ypred>0.5)!=labels),'\n')
-
diff --git a/ml-xgboost/R-package/demo/gpu_accelerated.R b/ml-xgboost/R-package/demo/gpu_accelerated.R
deleted file mode 100644
index 321255c..0000000
--- a/ml-xgboost/R-package/demo/gpu_accelerated.R
+++ /dev/null
@@ -1,45 +0,0 @@
-# An example of using GPU-accelerated tree building algorithms
-#
-# NOTE: it can only run if you have a CUDA-enable GPU and the package was
-# specially compiled with GPU support.
-#
-# For the current functionality, see
-# https://xgboost.readthedocs.io/en/latest/gpu/index.html
-#
-
-library('xgboost')
-
-# Simulate N x p random matrix with some binomial response dependent on pp columns
-set.seed(111)
-N <- 1000000
-p <- 50
-pp <- 25
-X <- matrix(runif(N * p), ncol = p)
-betas <- 2 * runif(pp) - 1
-sel <- sort(sample(p, pp))
-m <- X[, sel] %*% betas - 1 + rnorm(N)
-y <- rbinom(N, 1, plogis(m))
-
-tr <- sample.int(N, N * 0.75)
-dtrain <- xgb.DMatrix(X[tr,], label = y[tr])
-dtest <- xgb.DMatrix(X[-tr,], label = y[-tr])
-wl <- list(train = dtrain, test = dtest)
-
-# An example of running 'gpu_hist' algorithm
-# which is
-# - similar to the 'hist'
-# - the fastest option for moderately large datasets
-# - current limitations: max_depth < 16, does not implement guided loss
-# You can use tree_method = 'gpu_hist' for another GPU accelerated algorithm,
-# which is slower, more memory-hungry, but does not use binning.
-param <- list(objective = 'reg:logistic', eval_metric = 'auc', subsample = 0.5, nthread = 4,
- max_bin = 64, tree_method = 'gpu_hist')
-pt <- proc.time()
-bst_gpu <- xgb.train(param, dtrain, watchlist = wl, nrounds = 50)
-proc.time() - pt
-
-# Compare to the 'hist' algorithm:
-param$tree_method <- 'hist'
-pt <- proc.time()
-bst_hist <- xgb.train(param, dtrain, watchlist = wl, nrounds = 50)
-proc.time() - pt
diff --git a/ml-xgboost/R-package/demo/interaction_constraints.R b/ml-xgboost/R-package/demo/interaction_constraints.R
deleted file mode 100644
index 2f2edb1..0000000
--- a/ml-xgboost/R-package/demo/interaction_constraints.R
+++ /dev/null
@@ -1,105 +0,0 @@
-library(xgboost)
-library(data.table)
-
-set.seed(1024)
-
-# Function to obtain a list of interactions fitted in trees, requires input of maximum depth
-treeInteractions <- function(input_tree, input_max_depth){
- trees <- copy(input_tree) # copy tree input to prevent overwriting
- if (input_max_depth < 2) return(list()) # no interactions if max depth < 2
- if (nrow(input_tree) == 1) return(list())
-
- # Attach parent nodes
- for (i in 2:input_max_depth){
- if (i == 2) trees[, ID_merge:=ID] else trees[, ID_merge:=get(paste0('parent_',i-2))]
- parents_left <- trees[!is.na(Split), list(i.id=ID, i.feature=Feature, ID_merge=Yes)]
- parents_right <- trees[!is.na(Split), list(i.id=ID, i.feature=Feature, ID_merge=No)]
-
- setorderv(trees, 'ID_merge')
- setorderv(parents_left, 'ID_merge')
- setorderv(parents_right, 'ID_merge')
-
- trees <- merge(trees, parents_left, by='ID_merge', all.x=T)
- trees[!is.na(i.id), c(paste0('parent_', i-1), paste0('parent_feat_', i-1)):=list(i.id, i.feature)]
- trees[, c('i.id','i.feature'):=NULL]
-
- trees <- merge(trees, parents_right, by='ID_merge', all.x=T)
- trees[!is.na(i.id), c(paste0('parent_', i-1), paste0('parent_feat_', i-1)):=list(i.id, i.feature)]
- trees[, c('i.id','i.feature'):=NULL]
- }
-
- # Extract nodes with interactions
- interaction_trees <- trees[!is.na(Split) & !is.na(parent_1),
- c('Feature',paste0('parent_feat_',1:(input_max_depth-1))), with=F]
- interaction_trees_split <- split(interaction_trees, 1:nrow(interaction_trees))
- interaction_list <- lapply(interaction_trees_split, as.character)
-
- # Remove NAs (no parent interaction)
- interaction_list <- lapply(interaction_list, function(x) x[!is.na(x)])
-
- # Remove non-interactions (same variable)
- interaction_list <- lapply(interaction_list, unique) # remove same variables
- interaction_length <- sapply(interaction_list, length)
- interaction_list <- interaction_list[interaction_length > 1]
- interaction_list <- unique(lapply(interaction_list, sort))
- return(interaction_list)
-}
-
-# Generate sample data
-x <- list()
-for (i in 1:10){
- x[[i]] = i*rnorm(1000, 10)
-}
-x <- as.data.table(x)
-
-y = -1*x[, rowSums(.SD)] + x[['V1']]*x[['V2']] + x[['V3']]*x[['V4']]*x[['V5']] + rnorm(1000, 0.001) + 3*sin(x[['V7']])
-
-train = as.matrix(x)
-
-# Interaction constraint list (column names form)
-interaction_list <- list(c('V1','V2'),c('V3','V4','V5'))
-
-# Convert interaction constraint list into feature index form
-cols2ids <- function(object, col_names) {
- LUT <- seq_along(col_names) - 1
- names(LUT) <- col_names
- rapply(object, function(x) LUT[x], classes="character", how="replace")
-}
-interaction_list_fid = cols2ids(interaction_list, colnames(train))
-
-# Fit model with interaction constraints
-bst = xgboost(data = train, label = y, max_depth = 4,
- eta = 0.1, nthread = 2, nrounds = 1000,
- interaction_constraints = interaction_list_fid)
-
-bst_tree <- xgb.model.dt.tree(colnames(train), bst)
-bst_interactions <- treeInteractions(bst_tree, 4) # interactions constrained to combinations of V1*V2 and V3*V4*V5
-
-# Fit model without interaction constraints
-bst2 = xgboost(data = train, label = y, max_depth = 4,
- eta = 0.1, nthread = 2, nrounds = 1000)
-
-bst2_tree <- xgb.model.dt.tree(colnames(train), bst2)
-bst2_interactions <- treeInteractions(bst2_tree, 4) # much more interactions
-
-# Fit model with both interaction and monotonicity constraints
-bst3 = xgboost(data = train, label = y, max_depth = 4,
- eta = 0.1, nthread = 2, nrounds = 1000,
- interaction_constraints = interaction_list_fid,
- monotone_constraints = c(-1,0,0,0,0,0,0,0,0,0))
-
-bst3_tree <- xgb.model.dt.tree(colnames(train), bst3)
-bst3_interactions <- treeInteractions(bst3_tree, 4) # interactions still constrained to combinations of V1*V2 and V3*V4*V5
-
-# Show monotonic constraints still apply by checking scores after incrementing V1
-x1 <- sort(unique(x[['V1']]))
-for (i in 1:length(x1)){
- testdata <- copy(x[, -c('V1')])
- testdata[['V1']] <- x1[i]
- testdata <- testdata[, paste0('V',1:10), with=F]
- pred <- predict(bst3, as.matrix(testdata))
-
- # Should not print out anything due to monotonic constraints
- if (i > 1) if (any(pred > prev_pred)) print(i)
- prev_pred <- pred
-}
diff --git a/ml-xgboost/R-package/demo/poisson_regression.R b/ml-xgboost/R-package/demo/poisson_regression.R
deleted file mode 100644
index f9dc4ac..0000000
--- a/ml-xgboost/R-package/demo/poisson_regression.R
+++ /dev/null
@@ -1,7 +0,0 @@
-data(mtcars)
-head(mtcars)
-bst = xgboost(data=as.matrix(mtcars[,-11]),label=mtcars[,11],
- objective='count:poisson',nrounds=5)
-pred = predict(bst,as.matrix(mtcars[,-11]))
-sqrt(mean((pred-mtcars[,11])^2))
-
diff --git a/ml-xgboost/R-package/demo/predict_first_ntree.R b/ml-xgboost/R-package/demo/predict_first_ntree.R
deleted file mode 100644
index 8934c55..0000000
--- a/ml-xgboost/R-package/demo/predict_first_ntree.R
+++ /dev/null
@@ -1,23 +0,0 @@
-require(xgboost)
-# load in the agaricus dataset
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-
-param <- list(max_depth=2, eta=1, silent=1, objective='binary:logistic')
-watchlist <- list(eval = dtest, train = dtrain)
-nrounds = 2
-
-# training the model for two rounds
-bst = xgb.train(param, dtrain, nrounds, nthread = 2, watchlist)
-cat('start testing prediction from first n trees\n')
-labels <- getinfo(dtest,'label')
-
-### predict using first 1 tree
-ypred1 = predict(bst, dtest, ntreelimit=1)
-# by default, we predict using all the trees
-ypred2 = predict(bst, dtest)
-
-cat('error of ypred1=', mean(as.numeric(ypred1>0.5)!=labels),'\n')
-cat('error of ypred2=', mean(as.numeric(ypred2>0.5)!=labels),'\n')
diff --git a/ml-xgboost/R-package/demo/predict_leaf_indices.R b/ml-xgboost/R-package/demo/predict_leaf_indices.R
deleted file mode 100644
index 054bde7..0000000
--- a/ml-xgboost/R-package/demo/predict_leaf_indices.R
+++ /dev/null
@@ -1,53 +0,0 @@
-require(xgboost)
-require(data.table)
-require(Matrix)
-
-set.seed(1982)
-
-# load in the agaricus dataset
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(data = agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(data = agaricus.test$data, label = agaricus.test$label)
-
-param <- list(max_depth=2, eta=1, silent=1, objective='binary:logistic')
-nrounds = 4
-
-# training the model for two rounds
-bst = xgb.train(params = param, data = dtrain, nrounds = nrounds, nthread = 2)
-
-# Model accuracy without new features
-accuracy.before <- sum((predict(bst, agaricus.test$data) >= 0.5) == agaricus.test$label) / length(agaricus.test$label)
-
-# by default, we predict using all the trees
-
-pred_with_leaf = predict(bst, dtest, predleaf = TRUE)
-head(pred_with_leaf)
-
-create.new.tree.features <- function(model, original.features){
- pred_with_leaf <- predict(model, original.features, predleaf = TRUE)
- cols <- list()
- for(i in 1:model$niter){
- # max is not the real max but it s not important for the purpose of adding features
- leaf.id <- sort(unique(pred_with_leaf[,i]))
- cols[[i]] <- factor(x = pred_with_leaf[,i], level = leaf.id)
- }
- cbind(original.features, sparse.model.matrix( ~ . -1, as.data.frame(cols)))
-}
-
-# Convert previous features to one hot encoding
-new.features.train <- create.new.tree.features(bst, agaricus.train$data)
-new.features.test <- create.new.tree.features(bst, agaricus.test$data)
-colnames(new.features.test) <- colnames(new.features.train)
-
-# learning with new features
-new.dtrain <- xgb.DMatrix(data = new.features.train, label = agaricus.train$label)
-new.dtest <- xgb.DMatrix(data = new.features.test, label = agaricus.test$label)
-watchlist <- list(train = new.dtrain)
-bst <- xgb.train(params = param, data = new.dtrain, nrounds = nrounds, nthread = 2)
-
-# Model accuracy with new features
-accuracy.after <- sum((predict(bst, new.dtest) >= 0.5) == agaricus.test$label) / length(agaricus.test$label)
-
-# Here the accuracy was already good and is now perfect.
-cat(paste("The accuracy was", accuracy.before, "before adding leaf features and it is now", accuracy.after, "!\n"))
diff --git a/ml-xgboost/R-package/demo/runall.R b/ml-xgboost/R-package/demo/runall.R
deleted file mode 100644
index 0c1392a..0000000
--- a/ml-xgboost/R-package/demo/runall.R
+++ /dev/null
@@ -1,14 +0,0 @@
-# running all scripts in demo folder
-demo(basic_walkthrough)
-demo(custom_objective)
-demo(boost_from_prediction)
-demo(predict_first_ntree)
-demo(generalized_linear_model)
-demo(cross_validation)
-demo(create_sparse_matrix)
-demo(predict_leaf_indices)
-demo(early_stopping)
-demo(poisson_regression)
-demo(caret_wrapper)
-demo(tweedie_regression)
-#demo(gpu_accelerated) # can only run when built with GPU support
\ No newline at end of file
diff --git a/ml-xgboost/R-package/demo/tweedie_regression.R b/ml-xgboost/R-package/demo/tweedie_regression.R
deleted file mode 100644
index 4d272f6..0000000
--- a/ml-xgboost/R-package/demo/tweedie_regression.R
+++ /dev/null
@@ -1,49 +0,0 @@
-library(xgboost)
-library(data.table)
-library(cplm)
-
-data(AutoClaim)
-
-# auto insurance dataset analyzed by Yip and Yau (2005)
-dt <- data.table(AutoClaim)
-
-# exclude these columns from the model matrix
-exclude <- c('POLICYNO', 'PLCYDATE', 'CLM_FREQ5', 'CLM_AMT5', 'CLM_FLAG', 'IN_YY')
-
-# retains the missing values
-# NOTE: this dataset is comes ready out of the box
-options(na.action = 'na.pass')
-x <- sparse.model.matrix(~ . - 1, data = dt[, -exclude, with = F])
-options(na.action = 'na.omit')
-
-# response
-y <- dt[, CLM_AMT5]
-
-d_train <- xgb.DMatrix(data = x, label = y, missing = NA)
-
-# the tweedie_variance_power parameter determines the shape of
-# distribution
-# - closer to 1 is more poisson like and the mass
-# is more concentrated near zero
-# - closer to 2 is more gamma like and the mass spreads to the
-# the right with less concentration near zero
-
-params <- list(
- objective = 'reg:tweedie',
- eval_metric = 'rmse',
- tweedie_variance_power = 1.4,
- max_depth = 6,
- eta = 1)
-
-bst <- xgb.train(
- data = d_train,
- params = params,
- maximize = FALSE,
- watchlist = list(train = d_train),
- nrounds = 20)
-
-var_imp <- xgb.importance(attr(x, 'Dimnames')[[2]], model = bst)
-
-preds <- predict(bst, d_train)
-
-rmse <- sqrt(sum(mean((y - preds)^2)))
\ No newline at end of file
diff --git a/ml-xgboost/R-package/man/agaricus.test.Rd b/ml-xgboost/R-package/man/agaricus.test.Rd
deleted file mode 100644
index e3694ae..0000000
--- a/ml-xgboost/R-package/man/agaricus.test.Rd
+++ /dev/null
@@ -1,33 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgboost.R
-\docType{data}
-\name{agaricus.test}
-\alias{agaricus.test}
-\title{Test part from Mushroom Data Set}
-\format{
-A list containing a label vector, and a dgCMatrix object with 1611
-rows and 126 variables
-}
-\usage{
-data(agaricus.test)
-}
-\description{
-This data set is originally from the Mushroom data set,
-UCI Machine Learning Repository.
-}
-\details{
-This data set includes the following fields:
-
-\itemize{
- \item \code{label} the label for each record
- \item \code{data} a sparse Matrix of \code{dgCMatrix} class, with 126 columns.
-}
-}
-\references{
-https://archive.ics.uci.edu/ml/datasets/Mushroom
-
-Bache, K. & Lichman, M. (2013). UCI Machine Learning Repository
-[http://archive.ics.uci.edu/ml]. Irvine, CA: University of California,
-School of Information and Computer Science.
-}
-\keyword{datasets}
diff --git a/ml-xgboost/R-package/man/agaricus.train.Rd b/ml-xgboost/R-package/man/agaricus.train.Rd
deleted file mode 100644
index 92692c9..0000000
--- a/ml-xgboost/R-package/man/agaricus.train.Rd
+++ /dev/null
@@ -1,33 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgboost.R
-\docType{data}
-\name{agaricus.train}
-\alias{agaricus.train}
-\title{Training part from Mushroom Data Set}
-\format{
-A list containing a label vector, and a dgCMatrix object with 6513
-rows and 127 variables
-}
-\usage{
-data(agaricus.train)
-}
-\description{
-This data set is originally from the Mushroom data set,
-UCI Machine Learning Repository.
-}
-\details{
-This data set includes the following fields:
-
-\itemize{
- \item \code{label} the label for each record
- \item \code{data} a sparse Matrix of \code{dgCMatrix} class, with 126 columns.
-}
-}
-\references{
-https://archive.ics.uci.edu/ml/datasets/Mushroom
-
-Bache, K. & Lichman, M. (2013). UCI Machine Learning Repository
-[http://archive.ics.uci.edu/ml]. Irvine, CA: University of California,
-School of Information and Computer Science.
-}
-\keyword{datasets}
diff --git a/ml-xgboost/R-package/man/callbacks.Rd b/ml-xgboost/R-package/man/callbacks.Rd
deleted file mode 100644
index 9f6f690..0000000
--- a/ml-xgboost/R-package/man/callbacks.Rd
+++ /dev/null
@@ -1,37 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{callbacks}
-\alias{callbacks}
-\title{Callback closures for booster training.}
-\description{
-These are used to perform various service tasks either during boosting iterations or at the end.
-This approach helps to modularize many of such tasks without bloating the main training methods,
-and it offers .
-}
-\details{
-By default, a callback function is run after each boosting iteration.
-An R-attribute \code{is_pre_iteration} could be set for a callback to define a pre-iteration function.
-
-When a callback function has \code{finalize} parameter, its finalizer part will also be run after
-the boosting is completed.
-
-WARNING: side-effects!!! Be aware that these callback functions access and modify things in
-the environment from which they are called from, which is a fairly uncommon thing to do in R.
-
-To write a custom callback closure, make sure you first understand the main concepts about R environments.
-Check either R documentation on \code{\link[base]{environment}} or the
-\href{http://adv-r.had.co.nz/Environments.html}{Environments chapter} from the "Advanced R"
-book by Hadley Wickham. Further, the best option is to read the code of some of the existing callbacks -
-choose ones that do something similar to what you want to achieve. Also, you would need to get familiar
-with the objects available inside of the \code{xgb.train} and \code{xgb.cv} internal environments.
-}
-\seealso{
-\code{\link{cb.print.evaluation}},
-\code{\link{cb.evaluation.log}},
-\code{\link{cb.reset.parameters}},
-\code{\link{cb.early.stop}},
-\code{\link{cb.save.model}},
-\code{\link{cb.cv.predict}},
-\code{\link{xgb.train}},
-\code{\link{xgb.cv}}
-}
diff --git a/ml-xgboost/R-package/man/cb.cv.predict.Rd b/ml-xgboost/R-package/man/cb.cv.predict.Rd
deleted file mode 100644
index ded899e..0000000
--- a/ml-xgboost/R-package/man/cb.cv.predict.Rd
+++ /dev/null
@@ -1,43 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{cb.cv.predict}
-\alias{cb.cv.predict}
-\title{Callback closure for returning cross-validation based predictions.}
-\usage{
-cb.cv.predict(save_models = FALSE)
-}
-\arguments{
-\item{save_models}{a flag for whether to save the folds' models.}
-}
-\value{
-Predictions are returned inside of the \code{pred} element, which is either a vector or a matrix,
-depending on the number of prediction outputs per data row. The order of predictions corresponds
-to the order of rows in the original dataset. Note that when a custom \code{folds} list is
-provided in \code{xgb.cv}, the predictions would only be returned properly when this list is a
-non-overlapping list of k sets of indices, as in a standard k-fold CV. The predictions would not be
-meaningful when user-provided folds have overlapping indices as in, e.g., random sampling splits.
-When some of the indices in the training dataset are not included into user-provided \code{folds},
-their prediction value would be \code{NA}.
-}
-\description{
-Callback closure for returning cross-validation based predictions.
-}
-\details{
-This callback function saves predictions for all of the test folds,
-and also allows to save the folds' models.
-
-It is a "finalizer" callback and it uses early stopping information whenever it is available,
-thus it must be run after the early stopping callback if the early stopping is used.
-
-Callback function expects the following values to be set in its calling frame:
-\code{bst_folds},
-\code{basket},
-\code{data},
-\code{end_iteration},
-\code{params},
-\code{num_parallel_tree},
-\code{num_class}.
-}
-\seealso{
-\code{\link{callbacks}}
-}
diff --git a/ml-xgboost/R-package/man/cb.early.stop.Rd b/ml-xgboost/R-package/man/cb.early.stop.Rd
deleted file mode 100644
index 1a099d7..0000000
--- a/ml-xgboost/R-package/man/cb.early.stop.Rd
+++ /dev/null
@@ -1,66 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{cb.early.stop}
-\alias{cb.early.stop}
-\title{Callback closure to activate the early stopping.}
-\usage{
-cb.early.stop(
- stopping_rounds,
- maximize = FALSE,
- metric_name = NULL,
- verbose = TRUE
-)
-}
-\arguments{
-\item{stopping_rounds}{The number of rounds with no improvement in
-the evaluation metric in order to stop the training.}
-
-\item{maximize}{whether to maximize the evaluation metric}
-
-\item{metric_name}{the name of an evaluation column to use as a criteria for early
-stopping. If not set, the last column would be used.
-Let's say the test data in \code{watchlist} was labelled as \code{dtest},
-and one wants to use the AUC in test data for early stopping regardless of where
-it is in the \code{watchlist}, then one of the following would need to be set:
-\code{metric_name='dtest-auc'} or \code{metric_name='dtest_auc'}.
-All dash '-' characters in metric names are considered equivalent to '_'.}
-
-\item{verbose}{whether to print the early stopping information.}
-}
-\description{
-Callback closure to activate the early stopping.
-}
-\details{
-This callback function determines the condition for early stopping
-by setting the \code{stop_condition = TRUE} flag in its calling frame.
-
-The following additional fields are assigned to the model's R object:
-\itemize{
-\item \code{best_score} the evaluation score at the best iteration
-\item \code{best_iteration} at which boosting iteration the best score has occurred (1-based index)
-\item \code{best_ntreelimit} to use with the \code{ntreelimit} parameter in \code{predict}.
- It differs from \code{best_iteration} in multiclass or random forest settings.
-}
-
-The Same values are also stored as xgb-attributes:
-\itemize{
-\item \code{best_iteration} is stored as a 0-based iteration index (for interoperability of binary models)
-\item \code{best_msg} message string is also stored.
-}
-
-At least one data element is required in the evaluation watchlist for early stopping to work.
-
-Callback function expects the following values to be set in its calling frame:
-\code{stop_condition},
-\code{bst_evaluation},
-\code{rank},
-\code{bst} (or \code{bst_folds} and \code{basket}),
-\code{iteration},
-\code{begin_iteration},
-\code{end_iteration},
-\code{num_parallel_tree}.
-}
-\seealso{
-\code{\link{callbacks}},
-\code{\link{xgb.attr}}
-}
diff --git a/ml-xgboost/R-package/man/cb.evaluation.log.Rd b/ml-xgboost/R-package/man/cb.evaluation.log.Rd
deleted file mode 100644
index 94f8a02..0000000
--- a/ml-xgboost/R-package/man/cb.evaluation.log.Rd
+++ /dev/null
@@ -1,31 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{cb.evaluation.log}
-\alias{cb.evaluation.log}
-\title{Callback closure for logging the evaluation history}
-\usage{
-cb.evaluation.log()
-}
-\description{
-Callback closure for logging the evaluation history
-}
-\details{
-This callback function appends the current iteration evaluation results \code{bst_evaluation}
-available in the calling parent frame to the \code{evaluation_log} list in a calling frame.
-
-The finalizer callback (called with \code{finalize = TURE} in the end) converts
-the \code{evaluation_log} list into a final data.table.
-
-The iteration evaluation result \code{bst_evaluation} must be a named numeric vector.
-
-Note: in the column names of the final data.table, the dash '-' character is replaced with
-the underscore '_' in order to make the column names more like regular R identifiers.
-
-Callback function expects the following values to be set in its calling frame:
-\code{evaluation_log},
-\code{bst_evaluation},
-\code{iteration}.
-}
-\seealso{
-\code{\link{callbacks}}
-}
diff --git a/ml-xgboost/R-package/man/cb.gblinear.history.Rd b/ml-xgboost/R-package/man/cb.gblinear.history.Rd
deleted file mode 100644
index 35ebeb6..0000000
--- a/ml-xgboost/R-package/man/cb.gblinear.history.Rd
+++ /dev/null
@@ -1,95 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{cb.gblinear.history}
-\alias{cb.gblinear.history}
-\title{Callback closure for collecting the model coefficients history of a gblinear booster
-during its training.}
-\usage{
-cb.gblinear.history(sparse = FALSE)
-}
-\arguments{
-\item{sparse}{when set to FALSE/TURE, a dense/sparse matrix is used to store the result.
-Sparse format is useful when one expects only a subset of coefficients to be non-zero,
-when using the "thrifty" feature selector with fairly small number of top features
-selected per iteration.}
-}
-\value{
-Results are stored in the \code{coefs} element of the closure.
-The \code{\link{xgb.gblinear.history}} convenience function provides an easy way to access it.
-With \code{xgb.train}, it is either a dense of a sparse matrix.
-While with \code{xgb.cv}, it is a list (an element per each fold) of such matrices.
-}
-\description{
-Callback closure for collecting the model coefficients history of a gblinear booster
-during its training.
-}
-\details{
-To keep things fast and simple, gblinear booster does not internally store the history of linear
-model coefficients at each boosting iteration. This callback provides a workaround for storing
-the coefficients' path, by extracting them after each training iteration.
-
-Callback function expects the following values to be set in its calling frame:
-\code{bst} (or \code{bst_folds}).
-}
-\examples{
-#### Binary classification:
-#
-# In the iris dataset, it is hard to linearly separate Versicolor class from the rest
-# without considering the 2nd order interactions:
-require(magrittr)
-x <- model.matrix(Species ~ .^2, iris)[,-1]
-colnames(x)
-dtrain <- xgb.DMatrix(scale(x), label = 1*(iris$Species == "versicolor"))
-param <- list(booster = "gblinear", objective = "reg:logistic", eval_metric = "auc",
- lambda = 0.0003, alpha = 0.0003, nthread = 2)
-# For 'shotgun', which is a default linear updater, using high eta values may result in
-# unstable behaviour in some datasets. With this simple dataset, however, the high learning
-# rate does not break the convergence, but allows us to illustrate the typical pattern of
-# "stochastic explosion" behaviour of this lock-free algorithm at early boosting iterations.
-bst <- xgb.train(param, dtrain, list(tr=dtrain), nrounds = 200, eta = 1.,
- callbacks = list(cb.gblinear.history()))
-# Extract the coefficients' path and plot them vs boosting iteration number:
-coef_path <- xgb.gblinear.history(bst)
-matplot(coef_path, type = 'l')
-
-# With the deterministic coordinate descent updater, it is safer to use higher learning rates.
-# Will try the classical componentwise boosting which selects a single best feature per round:
-bst <- xgb.train(param, dtrain, list(tr=dtrain), nrounds = 200, eta = 0.8,
- updater = 'coord_descent', feature_selector = 'thrifty', top_k = 1,
- callbacks = list(cb.gblinear.history()))
-xgb.gblinear.history(bst) \%>\% matplot(type = 'l')
-# Componentwise boosting is known to have similar effect to Lasso regularization.
-# Try experimenting with various values of top_k, eta, nrounds,
-# as well as different feature_selectors.
-
-# For xgb.cv:
-bst <- xgb.cv(param, dtrain, nfold = 5, nrounds = 100, eta = 0.8,
- callbacks = list(cb.gblinear.history()))
-# coefficients in the CV fold #3
-xgb.gblinear.history(bst)[[3]] \%>\% matplot(type = 'l')
-
-
-#### Multiclass classification:
-#
-dtrain <- xgb.DMatrix(scale(x), label = as.numeric(iris$Species) - 1)
-param <- list(booster = "gblinear", objective = "multi:softprob", num_class = 3,
- lambda = 0.0003, alpha = 0.0003, nthread = 2)
-# For the default linear updater 'shotgun' it sometimes is helpful
-# to use smaller eta to reduce instability
-bst <- xgb.train(param, dtrain, list(tr=dtrain), nrounds = 70, eta = 0.5,
- callbacks = list(cb.gblinear.history()))
-# Will plot the coefficient paths separately for each class:
-xgb.gblinear.history(bst, class_index = 0) \%>\% matplot(type = 'l')
-xgb.gblinear.history(bst, class_index = 1) \%>\% matplot(type = 'l')
-xgb.gblinear.history(bst, class_index = 2) \%>\% matplot(type = 'l')
-
-# CV:
-bst <- xgb.cv(param, dtrain, nfold = 5, nrounds = 70, eta = 0.5,
- callbacks = list(cb.gblinear.history(FALSE)))
-# 1st forld of 1st class
-xgb.gblinear.history(bst, class_index = 0)[[1]] \%>\% matplot(type = 'l')
-
-}
-\seealso{
-\code{\link{callbacks}}, \code{\link{xgb.gblinear.history}}.
-}
diff --git a/ml-xgboost/R-package/man/cb.print.evaluation.Rd b/ml-xgboost/R-package/man/cb.print.evaluation.Rd
deleted file mode 100644
index 59b9ba6..0000000
--- a/ml-xgboost/R-package/man/cb.print.evaluation.Rd
+++ /dev/null
@@ -1,29 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{cb.print.evaluation}
-\alias{cb.print.evaluation}
-\title{Callback closure for printing the result of evaluation}
-\usage{
-cb.print.evaluation(period = 1, showsd = TRUE)
-}
-\arguments{
-\item{period}{results would be printed every number of periods}
-
-\item{showsd}{whether standard deviations should be printed (when available)}
-}
-\description{
-Callback closure for printing the result of evaluation
-}
-\details{
-The callback function prints the result of evaluation at every \code{period} iterations.
-The initial and the last iteration's evaluations are always printed.
-
-Callback function expects the following values to be set in its calling frame:
-\code{bst_evaluation} (also \code{bst_evaluation_err} when available),
-\code{iteration},
-\code{begin_iteration},
-\code{end_iteration}.
-}
-\seealso{
-\code{\link{callbacks}}
-}
diff --git a/ml-xgboost/R-package/man/cb.reset.parameters.Rd b/ml-xgboost/R-package/man/cb.reset.parameters.Rd
deleted file mode 100644
index ee0a5d1..0000000
--- a/ml-xgboost/R-package/man/cb.reset.parameters.Rd
+++ /dev/null
@@ -1,36 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{cb.reset.parameters}
-\alias{cb.reset.parameters}
-\title{Callback closure for resetting the booster's parameters at each iteration.}
-\usage{
-cb.reset.parameters(new_params)
-}
-\arguments{
-\item{new_params}{a list where each element corresponds to a parameter that needs to be reset.
-Each element's value must be either a vector of values of length \code{nrounds}
-to be set at each iteration,
-or a function of two parameters \code{learning_rates(iteration, nrounds)}
-which returns a new parameter value by using the current iteration number
-and the total number of boosting rounds.}
-}
-\description{
-Callback closure for resetting the booster's parameters at each iteration.
-}
-\details{
-This is a "pre-iteration" callback function used to reset booster's parameters
-at the beginning of each iteration.
-
-Note that when training is resumed from some previous model, and a function is used to
-reset a parameter value, the \code{nrounds} argument in this function would be the
-the number of boosting rounds in the current training.
-
-Callback function expects the following values to be set in its calling frame:
-\code{bst} or \code{bst_folds},
-\code{iteration},
-\code{begin_iteration},
-\code{end_iteration}.
-}
-\seealso{
-\code{\link{callbacks}}
-}
diff --git a/ml-xgboost/R-package/man/cb.save.model.Rd b/ml-xgboost/R-package/man/cb.save.model.Rd
deleted file mode 100644
index fd564b3..0000000
--- a/ml-xgboost/R-package/man/cb.save.model.Rd
+++ /dev/null
@@ -1,33 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{cb.save.model}
-\alias{cb.save.model}
-\title{Callback closure for saving a model file.}
-\usage{
-cb.save.model(save_period = 0, save_name = "xgboost.model")
-}
-\arguments{
-\item{save_period}{save the model to disk after every
-\code{save_period} iterations; 0 means save the model at the end.}
-
-\item{save_name}{the name or path for the saved model file.
-It can contain a \code{\link[base]{sprintf}} formatting specifier
-to include the integer iteration number in the file name.
-E.g., with \code{save_name} = 'xgboost_%04d.model',
-the file saved at iteration 50 would be named "xgboost_0050.model".}
-}
-\description{
-Callback closure for saving a model file.
-}
-\details{
-This callback function allows to save an xgb-model file, either periodically after each \code{save_period}'s or at the end.
-
-Callback function expects the following values to be set in its calling frame:
-\code{bst},
-\code{iteration},
-\code{begin_iteration},
-\code{end_iteration}.
-}
-\seealso{
-\code{\link{callbacks}}
-}
diff --git a/ml-xgboost/R-package/man/dim.xgb.DMatrix.Rd b/ml-xgboost/R-package/man/dim.xgb.DMatrix.Rd
deleted file mode 100644
index 76c53de..0000000
--- a/ml-xgboost/R-package/man/dim.xgb.DMatrix.Rd
+++ /dev/null
@@ -1,28 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.R
-\name{dim.xgb.DMatrix}
-\alias{dim.xgb.DMatrix}
-\title{Dimensions of xgb.DMatrix}
-\usage{
-\method{dim}{xgb.DMatrix}(x)
-}
-\arguments{
-\item{x}{Object of class \code{xgb.DMatrix}}
-}
-\description{
-Returns a vector of numbers of rows and of columns in an \code{xgb.DMatrix}.
-}
-\details{
-Note: since \code{nrow} and \code{ncol} internally use \code{dim}, they can also
-be directly used with an \code{xgb.DMatrix} object.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-
-stopifnot(nrow(dtrain) == nrow(train$data))
-stopifnot(ncol(dtrain) == ncol(train$data))
-stopifnot(all(dim(dtrain) == dim(train$data)))
-
-}
diff --git a/ml-xgboost/R-package/man/dimnames.xgb.DMatrix.Rd b/ml-xgboost/R-package/man/dimnames.xgb.DMatrix.Rd
deleted file mode 100644
index 032cb95..0000000
--- a/ml-xgboost/R-package/man/dimnames.xgb.DMatrix.Rd
+++ /dev/null
@@ -1,35 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.R
-\name{dimnames.xgb.DMatrix}
-\alias{dimnames.xgb.DMatrix}
-\alias{dimnames<-.xgb.DMatrix}
-\title{Handling of column names of \code{xgb.DMatrix}}
-\usage{
-\method{dimnames}{xgb.DMatrix}(x)
-
-\method{dimnames}{xgb.DMatrix}(x) <- value
-}
-\arguments{
-\item{x}{object of class \code{xgb.DMatrix}}
-
-\item{value}{a list of two elements: the first one is ignored
-and the second one is column names}
-}
-\description{
-Only column names are supported for \code{xgb.DMatrix}, thus setting of
-row names would have no effect and returned row names would be NULL.
-}
-\details{
-Generic \code{dimnames} methods are used by \code{colnames}.
-Since row names are irrelevant, it is recommended to use \code{colnames} directly.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-dimnames(dtrain)
-colnames(dtrain)
-colnames(dtrain) <- make.names(1:ncol(train$data))
-print(dtrain, verbose=TRUE)
-
-}
diff --git a/ml-xgboost/R-package/man/getinfo.Rd b/ml-xgboost/R-package/man/getinfo.Rd
deleted file mode 100644
index 1751c48..0000000
--- a/ml-xgboost/R-package/man/getinfo.Rd
+++ /dev/null
@@ -1,45 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.R
-\name{getinfo}
-\alias{getinfo}
-\alias{getinfo.xgb.DMatrix}
-\title{Get information of an xgb.DMatrix object}
-\usage{
-getinfo(object, ...)
-
-\method{getinfo}{xgb.DMatrix}(object, name, ...)
-}
-\arguments{
-\item{object}{Object of class \code{xgb.DMatrix}}
-
-\item{...}{other parameters}
-
-\item{name}{the name of the information field to get (see details)}
-}
-\description{
-Get information of an xgb.DMatrix object
-}
-\details{
-The \code{name} field can be one of the following:
-
-\itemize{
- \item \code{label}: label Xgboost learn from ;
- \item \code{weight}: to do a weight rescale ;
- \item \code{base_margin}: base margin is the base prediction Xgboost will boost from ;
- \item \code{nrow}: number of rows of the \code{xgb.DMatrix}.
-
-}
-
-\code{group} can be setup by \code{setinfo} but can't be retrieved by \code{getinfo}.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-
-labels <- getinfo(dtrain, 'label')
-setinfo(dtrain, 'label', 1-labels)
-
-labels2 <- getinfo(dtrain, 'label')
-stopifnot(all(labels2 == 1-labels))
-}
diff --git a/ml-xgboost/R-package/man/predict.xgb.Booster.Rd b/ml-xgboost/R-package/man/predict.xgb.Booster.Rd
deleted file mode 100644
index 6430eab..0000000
--- a/ml-xgboost/R-package/man/predict.xgb.Booster.Rd
+++ /dev/null
@@ -1,202 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.Booster.R
-\name{predict.xgb.Booster}
-\alias{predict.xgb.Booster}
-\alias{predict.xgb.Booster.handle}
-\title{Predict method for eXtreme Gradient Boosting model}
-\usage{
-\method{predict}{xgb.Booster}(
- object,
- newdata,
- missing = NA,
- outputmargin = FALSE,
- ntreelimit = NULL,
- predleaf = FALSE,
- predcontrib = FALSE,
- approxcontrib = FALSE,
- predinteraction = FALSE,
- reshape = FALSE,
- training = FALSE,
- ...
-)
-
-\method{predict}{xgb.Booster.handle}(object, ...)
-}
-\arguments{
-\item{object}{Object of class \code{xgb.Booster} or \code{xgb.Booster.handle}}
-
-\item{newdata}{takes \code{matrix}, \code{dgCMatrix}, local data file or \code{xgb.DMatrix}.}
-
-\item{missing}{Missing is only used when input is dense matrix. Pick a float value that represents
-missing values in data (e.g., sometimes 0 or some other extreme value is used).}
-
-\item{outputmargin}{whether the prediction should be returned in the for of original untransformed
-sum of predictions from boosting iterations' results. E.g., setting \code{outputmargin=TRUE} for
-logistic regression would result in predictions for log-odds instead of probabilities.}
-
-\item{ntreelimit}{limit the number of model's trees or boosting iterations used in prediction (see Details).
-It will use all the trees by default (\code{NULL} value).}
-
-\item{predleaf}{whether predict leaf index.}
-
-\item{predcontrib}{whether to return feature contributions to individual predictions (see Details).}
-
-\item{approxcontrib}{whether to use a fast approximation for feature contributions (see Details).}
-
-\item{predinteraction}{whether to return contributions of feature interactions to individual predictions (see Details).}
-
-\item{reshape}{whether to reshape the vector of predictions to a matrix form when there are several
-prediction outputs per case. This option has no effect when either of predleaf, predcontrib,
-or predinteraction flags is TRUE.}
-
-\item{training}{whether is the prediction result used for training. For dart booster,
-training predicting will perform dropout.}
-
-\item{...}{Parameters passed to \code{predict.xgb.Booster}}
-}
-\value{
-For regression or binary classification, it returns a vector of length \code{nrows(newdata)}.
-For multiclass classification, either a \code{num_class * nrows(newdata)} vector or
-a \code{(nrows(newdata), num_class)} dimension matrix is returned, depending on
-the \code{reshape} value.
-
-When \code{predleaf = TRUE}, the output is a matrix object with the
-number of columns corresponding to the number of trees.
-
-When \code{predcontrib = TRUE} and it is not a multiclass setting, the output is a matrix object with
-\code{num_features + 1} columns. The last "+ 1" column in a matrix corresponds to bias.
-For a multiclass case, a list of \code{num_class} elements is returned, where each element is
-such a matrix. The contribution values are on the scale of untransformed margin
-(e.g., for binary classification would mean that the contributions are log-odds deviations from bias).
-
-When \code{predinteraction = TRUE} and it is not a multiclass setting, the output is a 3d array with
-dimensions \code{c(nrow, num_features + 1, num_features + 1)}. The off-diagonal (in the last two dimensions)
-elements represent different features interaction contributions. The array is symmetric WRT the last
-two dimensions. The "+ 1" columns corresponds to bias. Summing this array along the last dimension should
-produce practically the same result as predict with \code{predcontrib = TRUE}.
-For a multiclass case, a list of \code{num_class} elements is returned, where each element is
-such an array.
-}
-\description{
-Predicted values based on either xgboost model or model handle object.
-}
-\details{
-Note that \code{ntreelimit} is not necessarily equal to the number of boosting iterations
-and it is not necessarily equal to the number of trees in a model.
-E.g., in a random forest-like model, \code{ntreelimit} would limit the number of trees.
-But for multiclass classification, while there are multiple trees per iteration,
-\code{ntreelimit} limits the number of boosting iterations.
-
-Also note that \code{ntreelimit} would currently do nothing for predictions from gblinear,
-since gblinear doesn't keep its boosting history.
-
-One possible practical applications of the \code{predleaf} option is to use the model
-as a generator of new features which capture non-linearity and interactions,
-e.g., as implemented in \code{\link{xgb.create.features}}.
-
-Setting \code{predcontrib = TRUE} allows to calculate contributions of each feature to
-individual predictions. For "gblinear" booster, feature contributions are simply linear terms
-(feature_beta * feature_value). For "gbtree" booster, feature contributions are SHAP
-values (Lundberg 2017) that sum to the difference between the expected output
-of the model and the current prediction (where the hessian weights are used to compute the expectations).
-Setting \code{approxcontrib = TRUE} approximates these values following the idea explained
-in \url{http://blog.datadive.net/interpreting-random-forests/}.
-
-With \code{predinteraction = TRUE}, SHAP values of contributions of interaction of each pair of features
-are computed. Note that this operation might be rather expensive in terms of compute and memory.
-Since it quadratically depends on the number of features, it is recommended to perform selection
-of the most important features first. See below about the format of the returned results.
-}
-\examples{
-## binary classification:
-
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 0.5, nthread = 2, nrounds = 5, objective = "binary:logistic")
-# use all trees by default
-pred <- predict(bst, test$data)
-# use only the 1st tree
-pred1 <- predict(bst, test$data, ntreelimit = 1)
-
-# Predicting tree leafs:
-# the result is an nsamples X ntrees matrix
-pred_leaf <- predict(bst, test$data, predleaf = TRUE)
-str(pred_leaf)
-
-# Predicting feature contributions to predictions:
-# the result is an nsamples X (nfeatures + 1) matrix
-pred_contr <- predict(bst, test$data, predcontrib = TRUE)
-str(pred_contr)
-# verify that contributions' sums are equal to log-odds of predictions (up to float precision):
-summary(rowSums(pred_contr) - qlogis(pred))
-# for the 1st record, let's inspect its features that had non-zero contribution to prediction:
-contr1 <- pred_contr[1,]
-contr1 <- contr1[-length(contr1)] # drop BIAS
-contr1 <- contr1[contr1 != 0] # drop non-contributing features
-contr1 <- contr1[order(abs(contr1))] # order by contribution magnitude
-old_mar <- par("mar")
-par(mar = old_mar + c(0,7,0,0))
-barplot(contr1, horiz = TRUE, las = 2, xlab = "contribution to prediction in log-odds")
-par(mar = old_mar)
-
-
-## multiclass classification in iris dataset:
-
-lb <- as.numeric(iris$Species) - 1
-num_class <- 3
-set.seed(11)
-bst <- xgboost(data = as.matrix(iris[, -5]), label = lb,
- max_depth = 4, eta = 0.5, nthread = 2, nrounds = 10, subsample = 0.5,
- objective = "multi:softprob", num_class = num_class)
-# predict for softmax returns num_class probability numbers per case:
-pred <- predict(bst, as.matrix(iris[, -5]))
-str(pred)
-# reshape it to a num_class-columns matrix
-pred <- matrix(pred, ncol=num_class, byrow=TRUE)
-# convert the probabilities to softmax labels
-pred_labels <- max.col(pred) - 1
-# the following should result in the same error as seen in the last iteration
-sum(pred_labels != lb)/length(lb)
-
-# compare that to the predictions from softmax:
-set.seed(11)
-bst <- xgboost(data = as.matrix(iris[, -5]), label = lb,
- max_depth = 4, eta = 0.5, nthread = 2, nrounds = 10, subsample = 0.5,
- objective = "multi:softmax", num_class = num_class)
-pred <- predict(bst, as.matrix(iris[, -5]))
-str(pred)
-all.equal(pred, pred_labels)
-# prediction from using only 5 iterations should result
-# in the same error as seen in iteration 5:
-pred5 <- predict(bst, as.matrix(iris[, -5]), ntreelimit=5)
-sum(pred5 != lb)/length(lb)
-
-
-## random forest-like model of 25 trees for binary classification:
-
-set.seed(11)
-bst <- xgboost(data = train$data, label = train$label, max_depth = 5,
- nthread = 2, nrounds = 1, objective = "binary:logistic",
- num_parallel_tree = 25, subsample = 0.6, colsample_bytree = 0.1)
-# Inspect the prediction error vs number of trees:
-lb <- test$label
-dtest <- xgb.DMatrix(test$data, label=lb)
-err <- sapply(1:25, function(n) {
- pred <- predict(bst, dtest, ntreelimit=n)
- sum((pred > 0.5) != lb)/length(lb)
-})
-plot(err, type='l', ylim=c(0,0.1), xlab='#trees')
-
-}
-\references{
-Scott M. Lundberg, Su-In Lee, "A Unified Approach to Interpreting Model Predictions", NIPS Proceedings 2017, \url{https://arxiv.org/abs/1705.07874}
-
-Scott M. Lundberg, Su-In Lee, "Consistent feature attribution for tree ensembles", \url{https://arxiv.org/abs/1706.06060}
-}
-\seealso{
-\code{\link{xgb.train}}.
-}
diff --git a/ml-xgboost/R-package/man/print.xgb.Booster.Rd b/ml-xgboost/R-package/man/print.xgb.Booster.Rd
deleted file mode 100644
index d684882..0000000
--- a/ml-xgboost/R-package/man/print.xgb.Booster.Rd
+++ /dev/null
@@ -1,29 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.Booster.R
-\name{print.xgb.Booster}
-\alias{print.xgb.Booster}
-\title{Print xgb.Booster}
-\usage{
-\method{print}{xgb.Booster}(x, verbose = FALSE, ...)
-}
-\arguments{
-\item{x}{an xgb.Booster object}
-
-\item{verbose}{whether to print detailed data (e.g., attribute values)}
-
-\item{...}{not currently used}
-}
-\description{
-Print information about xgb.Booster.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-attr(bst, 'myattr') <- 'memo'
-
-print(bst)
-print(bst, verbose=TRUE)
-
-}
diff --git a/ml-xgboost/R-package/man/print.xgb.DMatrix.Rd b/ml-xgboost/R-package/man/print.xgb.DMatrix.Rd
deleted file mode 100644
index b1dd01b..0000000
--- a/ml-xgboost/R-package/man/print.xgb.DMatrix.Rd
+++ /dev/null
@@ -1,28 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.R
-\name{print.xgb.DMatrix}
-\alias{print.xgb.DMatrix}
-\title{Print xgb.DMatrix}
-\usage{
-\method{print}{xgb.DMatrix}(x, verbose = FALSE, ...)
-}
-\arguments{
-\item{x}{an xgb.DMatrix object}
-
-\item{verbose}{whether to print colnames (when present)}
-
-\item{...}{not currently used}
-}
-\description{
-Print information about xgb.DMatrix.
-Currently it displays dimensions and presence of info-fields and colnames.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-
-dtrain
-print(dtrain, verbose=TRUE)
-
-}
diff --git a/ml-xgboost/R-package/man/print.xgb.cv.Rd b/ml-xgboost/R-package/man/print.xgb.cv.Rd
deleted file mode 100644
index 05ad61e..0000000
--- a/ml-xgboost/R-package/man/print.xgb.cv.Rd
+++ /dev/null
@@ -1,31 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.cv.R
-\name{print.xgb.cv.synchronous}
-\alias{print.xgb.cv.synchronous}
-\title{Print xgb.cv result}
-\usage{
-\method{print}{xgb.cv.synchronous}(x, verbose = FALSE, ...)
-}
-\arguments{
-\item{x}{an \code{xgb.cv.synchronous} object}
-
-\item{verbose}{whether to print detailed data}
-
-\item{...}{passed to \code{data.table.print}}
-}
-\description{
-Prints formatted results of \code{xgb.cv}.
-}
-\details{
-When not verbose, it would only print the evaluation results,
-including the best iteration (when available).
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-cv <- xgb.cv(data = train$data, label = train$label, nfold = 5, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-print(cv)
-print(cv, verbose=TRUE)
-
-}
diff --git a/ml-xgboost/R-package/man/setinfo.Rd b/ml-xgboost/R-package/man/setinfo.Rd
deleted file mode 100644
index e133d3a..0000000
--- a/ml-xgboost/R-package/man/setinfo.Rd
+++ /dev/null
@@ -1,43 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.R
-\name{setinfo}
-\alias{setinfo}
-\alias{setinfo.xgb.DMatrix}
-\title{Set information of an xgb.DMatrix object}
-\usage{
-setinfo(object, ...)
-
-\method{setinfo}{xgb.DMatrix}(object, name, info, ...)
-}
-\arguments{
-\item{object}{Object of class "xgb.DMatrix"}
-
-\item{...}{other parameters}
-
-\item{name}{the name of the field to get}
-
-\item{info}{the specific field of information to set}
-}
-\description{
-Set information of an xgb.DMatrix object
-}
-\details{
-The \code{name} field can be one of the following:
-
-\itemize{
- \item \code{label}: label Xgboost learn from ;
- \item \code{weight}: to do a weight rescale ;
- \item \code{base_margin}: base margin is the base prediction Xgboost will boost from ;
- \item \code{group}: number of rows in each group (to use with \code{rank:pairwise} objective).
-}
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-
-labels <- getinfo(dtrain, 'label')
-setinfo(dtrain, 'label', 1-labels)
-labels2 <- getinfo(dtrain, 'label')
-stopifnot(all.equal(labels2, 1-labels))
-}
diff --git a/ml-xgboost/R-package/man/slice.xgb.DMatrix.Rd b/ml-xgboost/R-package/man/slice.xgb.DMatrix.Rd
deleted file mode 100644
index 9f27d4b..0000000
--- a/ml-xgboost/R-package/man/slice.xgb.DMatrix.Rd
+++ /dev/null
@@ -1,40 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.R
-\name{slice}
-\alias{slice}
-\alias{slice.xgb.DMatrix}
-\alias{[.xgb.DMatrix}
-\title{Get a new DMatrix containing the specified rows of
-original xgb.DMatrix object}
-\usage{
-slice(object, ...)
-
-\method{slice}{xgb.DMatrix}(object, idxset, ...)
-
-\method{[}{xgb.DMatrix}(object, idxset, colset = NULL)
-}
-\arguments{
-\item{object}{Object of class "xgb.DMatrix"}
-
-\item{...}{other parameters (currently not used)}
-
-\item{idxset}{a integer vector of indices of rows needed}
-
-\item{colset}{currently not used (columns subsetting is not available)}
-}
-\description{
-Get a new DMatrix containing the specified rows of
-original xgb.DMatrix object
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-
-dsub <- slice(dtrain, 1:42)
-labels1 <- getinfo(dsub, 'label')
-dsub <- dtrain[1:42, ]
-labels2 <- getinfo(dsub, 'label')
-all.equal(labels1, labels2)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.Booster.complete.Rd b/ml-xgboost/R-package/man/xgb.Booster.complete.Rd
deleted file mode 100644
index 2b38b4c..0000000
--- a/ml-xgboost/R-package/man/xgb.Booster.complete.Rd
+++ /dev/null
@@ -1,50 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.Booster.R
-\name{xgb.Booster.complete}
-\alias{xgb.Booster.complete}
-\title{Restore missing parts of an incomplete xgb.Booster object.}
-\usage{
-xgb.Booster.complete(object, saveraw = TRUE)
-}
-\arguments{
-\item{object}{object of class \code{xgb.Booster}}
-
-\item{saveraw}{a flag indicating whether to append \code{raw} Booster memory dump data
-when it doesn't already exist.}
-}
-\value{
-An object of \code{xgb.Booster} class.
-}
-\description{
-It attempts to complete an \code{xgb.Booster} object by restoring either its missing
-raw model memory dump (when it has no \code{raw} data but its \code{xgb.Booster.handle} is valid)
-or its missing internal handle (when its \code{xgb.Booster.handle} is not valid
-but it has a raw Booster memory dump).
-}
-\details{
-While this method is primarily for internal use, it might be useful in some practical situations.
-
-E.g., when an \code{xgb.Booster} model is saved as an R object and then is loaded as an R object,
-its handle (pointer) to an internal xgboost model would be invalid. The majority of xgboost methods
-should still work for such a model object since those methods would be using
-\code{xgb.Booster.complete} internally. However, one might find it to be more efficient to call the
-\code{xgb.Booster.complete} function explicitly once after loading a model as an R-object.
-That would prevent further repeated implicit reconstruction of an internal booster model.
-}
-\examples{
-
-data(agaricus.train, package='xgboost')
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-saveRDS(bst, "xgb.model.rds")
-
-bst1 <- readRDS("xgb.model.rds")
-if (file.exists("xgb.model.rds")) file.remove("xgb.model.rds")
-# the handle is invalid:
-print(bst1$handle)
-
-bst1 <- xgb.Booster.complete(bst1)
-# now the handle points to a valid internal booster model:
-print(bst1$handle)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.DMatrix.Rd b/ml-xgboost/R-package/man/xgb.DMatrix.Rd
deleted file mode 100644
index c3d47a9..0000000
--- a/ml-xgboost/R-package/man/xgb.DMatrix.Rd
+++ /dev/null
@@ -1,35 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.R
-\name{xgb.DMatrix}
-\alias{xgb.DMatrix}
-\title{Construct xgb.DMatrix object}
-\usage{
-xgb.DMatrix(data, info = list(), missing = NA, silent = FALSE, ...)
-}
-\arguments{
-\item{data}{a \code{matrix} object (either numeric or integer), a \code{dgCMatrix} object, or a character
-string representing a filename.}
-
-\item{info}{a named list of additional information to store in the \code{xgb.DMatrix} object.
-See \code{\link{setinfo}} for the specific allowed kinds of}
-
-\item{missing}{a float value to represents missing values in data (used only when input is a dense matrix).
-It is useful when a 0 or some other extreme value represents missing values in data.}
-
-\item{silent}{whether to suppress printing an informational message after loading from a file.}
-
-\item{...}{the \code{info} data could be passed directly as parameters, without creating an \code{info} list.}
-}
-\description{
-Construct xgb.DMatrix object from either a dense matrix, a sparse matrix, or a local file.
-Supported input file formats are either a libsvm text file or a binary file that was created previously by
-\code{\link{xgb.DMatrix.save}}).
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-xgb.DMatrix.save(dtrain, 'xgb.DMatrix.data')
-dtrain <- xgb.DMatrix('xgb.DMatrix.data')
-if (file.exists('xgb.DMatrix.data')) file.remove('xgb.DMatrix.data')
-}
diff --git a/ml-xgboost/R-package/man/xgb.DMatrix.save.Rd b/ml-xgboost/R-package/man/xgb.DMatrix.save.Rd
deleted file mode 100644
index 7f25c5a..0000000
--- a/ml-xgboost/R-package/man/xgb.DMatrix.save.Rd
+++ /dev/null
@@ -1,24 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.DMatrix.save.R
-\name{xgb.DMatrix.save}
-\alias{xgb.DMatrix.save}
-\title{Save xgb.DMatrix object to binary file}
-\usage{
-xgb.DMatrix.save(dmatrix, fname)
-}
-\arguments{
-\item{dmatrix}{the \code{xgb.DMatrix} object}
-
-\item{fname}{the name of the file to write.}
-}
-\description{
-Save xgb.DMatrix object to binary file
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-dtrain <- xgb.DMatrix(train$data, label=train$label)
-xgb.DMatrix.save(dtrain, 'xgb.DMatrix.data')
-dtrain <- xgb.DMatrix('xgb.DMatrix.data')
-if (file.exists('xgb.DMatrix.data')) file.remove('xgb.DMatrix.data')
-}
diff --git a/ml-xgboost/R-package/man/xgb.attr.Rd b/ml-xgboost/R-package/man/xgb.attr.Rd
deleted file mode 100644
index 03779e4..0000000
--- a/ml-xgboost/R-package/man/xgb.attr.Rd
+++ /dev/null
@@ -1,86 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.Booster.R
-\name{xgb.attr}
-\alias{xgb.attr}
-\alias{xgb.attr<-}
-\alias{xgb.attributes}
-\alias{xgb.attributes<-}
-\title{Accessors for serializable attributes of a model.}
-\usage{
-xgb.attr(object, name)
-
-xgb.attr(object, name) <- value
-
-xgb.attributes(object)
-
-xgb.attributes(object) <- value
-}
-\arguments{
-\item{object}{Object of class \code{xgb.Booster} or \code{xgb.Booster.handle}.}
-
-\item{name}{a non-empty character string specifying which attribute is to be accessed.}
-
-\item{value}{a value of an attribute for \code{xgb.attr<-}; for \code{xgb.attributes<-}
-it's a list (or an object coercible to a list) with the names of attributes to set
-and the elements corresponding to attribute values.
-Non-character values are converted to character.
-When attribute value is not a scalar, only the first index is used.
-Use \code{NULL} to remove an attribute.}
-}
-\value{
-\code{xgb.attr} returns either a string value of an attribute
-or \code{NULL} if an attribute wasn't stored in a model.
-
-\code{xgb.attributes} returns a list of all attribute stored in a model
-or \code{NULL} if a model has no stored attributes.
-}
-\description{
-These methods allow to manipulate the key-value attribute strings of an xgboost model.
-}
-\details{
-The primary purpose of xgboost model attributes is to store some meta-data about the model.
-Note that they are a separate concept from the object attributes in R.
-Specifically, they refer to key-value strings that can be attached to an xgboost model,
-stored together with the model's binary representation, and accessed later
-(from R or any other interface).
-In contrast, any R-attribute assigned to an R-object of \code{xgb.Booster} class
-would not be saved by \code{xgb.save} because an xgboost model is an external memory object
-and its serialization is handled externally.
-Also, setting an attribute that has the same name as one of xgboost's parameters wouldn't
-change the value of that parameter for a model.
-Use \code{\link{xgb.parameters<-}} to set or change model parameters.
-
-The attribute setters would usually work more efficiently for \code{xgb.Booster.handle}
-than for \code{xgb.Booster}, since only just a handle (pointer) would need to be copied.
-That would only matter if attributes need to be set many times.
-Note, however, that when feeding a handle of an \code{xgb.Booster} object to the attribute setters,
-the raw model cache of an \code{xgb.Booster} object would not be automatically updated,
-and it would be user's responsibility to call \code{xgb.serialize} to update it.
-
-The \code{xgb.attributes<-} setter either updates the existing or adds one or several attributes,
-but it doesn't delete the other existing attributes.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-
-xgb.attr(bst, "my_attribute") <- "my attribute value"
-print(xgb.attr(bst, "my_attribute"))
-xgb.attributes(bst) <- list(a = 123, b = "abc")
-
-xgb.save(bst, 'xgb.model')
-bst1 <- xgb.load('xgb.model')
-if (file.exists('xgb.model')) file.remove('xgb.model')
-print(xgb.attr(bst1, "my_attribute"))
-print(xgb.attributes(bst1))
-
-# deletion:
-xgb.attr(bst1, "my_attribute") <- NULL
-print(xgb.attributes(bst1))
-xgb.attributes(bst1) <- list(a = NULL, b = NULL)
-print(xgb.attributes(bst1))
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.config.Rd b/ml-xgboost/R-package/man/xgb.config.Rd
deleted file mode 100644
index a5187c8..0000000
--- a/ml-xgboost/R-package/man/xgb.config.Rd
+++ /dev/null
@@ -1,28 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.Booster.R
-\name{xgb.config}
-\alias{xgb.config}
-\alias{xgb.config<-}
-\title{Accessors for model parameters as JSON string.}
-\usage{
-xgb.config(object)
-
-xgb.config(object) <- value
-}
-\arguments{
-\item{object}{Object of class \code{xgb.Booster}}
-
-\item{value}{A JSON string.}
-}
-\description{
-Accessors for model parameters as JSON string.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-config <- xgb.config(bst)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.create.features.Rd b/ml-xgboost/R-package/man/xgb.create.features.Rd
deleted file mode 100644
index 9c59d90..0000000
--- a/ml-xgboost/R-package/man/xgb.create.features.Rd
+++ /dev/null
@@ -1,92 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.create.features.R
-\name{xgb.create.features}
-\alias{xgb.create.features}
-\title{Create new features from a previously learned model}
-\usage{
-xgb.create.features(model, data, ...)
-}
-\arguments{
-\item{model}{decision tree boosting model learned on the original data}
-
-\item{data}{original data (usually provided as a \code{dgCMatrix} matrix)}
-
-\item{...}{currently not used}
-}
-\value{
-\code{dgCMatrix} matrix including both the original data and the new features.
-}
-\description{
-May improve the learning by adding new features to the training data based on the decision trees from a previously learned model.
-}
-\details{
-This is the function inspired from the paragraph 3.1 of the paper:
-
-\strong{Practical Lessons from Predicting Clicks on Ads at Facebook}
-
-\emph{(Xinran He, Junfeng Pan, Ou Jin, Tianbing Xu, Bo Liu, Tao Xu, Yan, xin Shi, Antoine Atallah, Ralf Herbrich, Stuart Bowers,
-Joaquin Quinonero Candela)}
-
-International Workshop on Data Mining for Online Advertising (ADKDD) - August 24, 2014
-
-\url{https://research.fb.com/publications/practical-lessons-from-predicting-clicks-on-ads-at-facebook/}.
-
-Extract explaining the method:
-
-"We found that boosted decision trees are a powerful and very
-convenient way to implement non-linear and tuple transformations
-of the kind we just described. We treat each individual
-tree as a categorical feature that takes as value the
-index of the leaf an instance ends up falling in. We use
-1-of-K coding of this type of features.
-
-For example, consider the boosted tree model in Figure 1 with 2 subtrees,
-where the first subtree has 3 leafs and the second 2 leafs. If an
-instance ends up in leaf 2 in the first subtree and leaf 1 in
-second subtree, the overall input to the linear classifier will
-be the binary vector \code{[0, 1, 0, 1, 0]}, where the first 3 entries
-correspond to the leaves of the first subtree and last 2 to
-those of the second subtree.
-
-[...]
-
-We can understand boosted decision tree
-based transformation as a supervised feature encoding that
-converts a real-valued vector into a compact binary-valued
-vector. A traversal from root node to a leaf node represents
-a rule on certain features."
-}
-\examples{
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(data = agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(data = agaricus.test$data, label = agaricus.test$label)
-
-param <- list(max_depth=2, eta=1, silent=1, objective='binary:logistic')
-nrounds = 4
-
-bst = xgb.train(params = param, data = dtrain, nrounds = nrounds, nthread = 2)
-
-# Model accuracy without new features
-accuracy.before <- sum((predict(bst, agaricus.test$data) >= 0.5) == agaricus.test$label) /
- length(agaricus.test$label)
-
-# Convert previous features to one hot encoding
-new.features.train <- xgb.create.features(model = bst, agaricus.train$data)
-new.features.test <- xgb.create.features(model = bst, agaricus.test$data)
-
-# learning with new features
-new.dtrain <- xgb.DMatrix(data = new.features.train, label = agaricus.train$label)
-new.dtest <- xgb.DMatrix(data = new.features.test, label = agaricus.test$label)
-watchlist <- list(train = new.dtrain)
-bst <- xgb.train(params = param, data = new.dtrain, nrounds = nrounds, nthread = 2)
-
-# Model accuracy with new features
-accuracy.after <- sum((predict(bst, new.dtest) >= 0.5) == agaricus.test$label) /
- length(agaricus.test$label)
-
-# Here the accuracy was already good and is now perfect.
-cat(paste("The accuracy was", accuracy.before, "before adding leaf features and it is now",
- accuracy.after, "!\n"))
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.cv.Rd b/ml-xgboost/R-package/man/xgb.cv.Rd
deleted file mode 100644
index 8cb03a5..0000000
--- a/ml-xgboost/R-package/man/xgb.cv.Rd
+++ /dev/null
@@ -1,164 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.cv.R
-\name{xgb.cv}
-\alias{xgb.cv}
-\title{Cross Validation}
-\usage{
-xgb.cv(
- params = list(),
- data,
- nrounds,
- nfold,
- label = NULL,
- missing = NA,
- prediction = FALSE,
- showsd = TRUE,
- metrics = list(),
- obj = NULL,
- feval = NULL,
- stratified = TRUE,
- folds = NULL,
- train_folds = NULL,
- verbose = TRUE,
- print_every_n = 1L,
- early_stopping_rounds = NULL,
- maximize = NULL,
- callbacks = list(),
- ...
-)
-}
-\arguments{
-\item{params}{the list of parameters. Commonly used ones are:
-\itemize{
- \item \code{objective} objective function, common ones are
- \itemize{
- \item \code{reg:squarederror} Regression with squared loss
- \item \code{binary:logistic} logistic regression for classification
- }
- \item \code{eta} step size of each boosting step
- \item \code{max_depth} maximum depth of the tree
- \item \code{nthread} number of thread used in training, if not set, all threads are used
-}
-
- See \code{\link{xgb.train}} for further details.
- See also demo/ for walkthrough example in R.}
-
-\item{data}{takes an \code{xgb.DMatrix}, \code{matrix}, or \code{dgCMatrix} as the input.}
-
-\item{nrounds}{the max number of iterations}
-
-\item{nfold}{the original dataset is randomly partitioned into \code{nfold} equal size subsamples.}
-
-\item{label}{vector of response values. Should be provided only when data is an R-matrix.}
-
-\item{missing}{is only used when input is a dense matrix. By default is set to NA, which means
-that NA values should be considered as 'missing' by the algorithm.
-Sometimes, 0 or other extreme value might be used to represent missing values.}
-
-\item{prediction}{A logical value indicating whether to return the test fold predictions
-from each CV model. This parameter engages the \code{\link{cb.cv.predict}} callback.}
-
-\item{showsd}{\code{boolean}, whether to show standard deviation of cross validation}
-
-\item{metrics, }{list of evaluation metrics to be used in cross validation,
- when it is not specified, the evaluation metric is chosen according to objective function.
- Possible options are:
-\itemize{
- \item \code{error} binary classification error rate
- \item \code{rmse} Rooted mean square error
- \item \code{logloss} negative log-likelihood function
- \item \code{auc} Area under curve
- \item \code{aucpr} Area under PR curve
- \item \code{merror} Exact matching error, used to evaluate multi-class classification
-}}
-
-\item{obj}{customized objective function. Returns gradient and second order
-gradient with given prediction and dtrain.}
-
-\item{feval}{customized evaluation function. Returns
-\code{list(metric='metric-name', value='metric-value')} with given
-prediction and dtrain.}
-
-\item{stratified}{a \code{boolean} indicating whether sampling of folds should be stratified
-by the values of outcome labels.}
-
-\item{folds}{\code{list} provides a possibility to use a list of pre-defined CV folds
-(each element must be a vector of test fold's indices). When folds are supplied,
-the \code{nfold} and \code{stratified} parameters are ignored.}
-
-\item{train_folds}{\code{list} list specifying which indicies to use for training. If \code{NULL}
-(the default) all indices not specified in \code{folds} will be used for training.}
-
-\item{verbose}{\code{boolean}, print the statistics during the process}
-
-\item{print_every_n}{Print each n-th iteration evaluation messages when \code{verbose>0}.
-Default is 1 which means all messages are printed. This parameter is passed to the
-\code{\link{cb.print.evaluation}} callback.}
-
-\item{early_stopping_rounds}{If \code{NULL}, the early stopping function is not triggered.
-If set to an integer \code{k}, training with a validation set will stop if the performance
-doesn't improve for \code{k} rounds.
-Setting this parameter engages the \code{\link{cb.early.stop}} callback.}
-
-\item{maximize}{If \code{feval} and \code{early_stopping_rounds} are set,
-then this parameter must be set as well.
-When it is \code{TRUE}, it means the larger the evaluation score the better.
-This parameter is passed to the \code{\link{cb.early.stop}} callback.}
-
-\item{callbacks}{a list of callback functions to perform various task during boosting.
-See \code{\link{callbacks}}. Some of the callbacks are automatically created depending on the
-parameters' values. User can provide either existing or their own callback methods in order
-to customize the training process.}
-
-\item{...}{other parameters to pass to \code{params}.}
-}
-\value{
-An object of class \code{xgb.cv.synchronous} with the following elements:
-\itemize{
- \item \code{call} a function call.
- \item \code{params} parameters that were passed to the xgboost library. Note that it does not
- capture parameters changed by the \code{\link{cb.reset.parameters}} callback.
- \item \code{callbacks} callback functions that were either automatically assigned or
- explicitly passed.
- \item \code{evaluation_log} evaluation history stored as a \code{data.table} with the
- first column corresponding to iteration number and the rest corresponding to the
- CV-based evaluation means and standard deviations for the training and test CV-sets.
- It is created by the \code{\link{cb.evaluation.log}} callback.
- \item \code{niter} number of boosting iterations.
- \item \code{nfeatures} number of features in training data.
- \item \code{folds} the list of CV folds' indices - either those passed through the \code{folds}
- parameter or randomly generated.
- \item \code{best_iteration} iteration number with the best evaluation metric value
- (only available with early stopping).
- \item \code{best_ntreelimit} the \code{ntreelimit} value corresponding to the best iteration,
- which could further be used in \code{predict} method
- (only available with early stopping).
- \item \code{pred} CV prediction values available when \code{prediction} is set.
- It is either vector or matrix (see \code{\link{cb.cv.predict}}).
- \item \code{models} a list of the CV folds' models. It is only available with the explicit
- setting of the \code{cb.cv.predict(save_models = TRUE)} callback.
-}
-}
-\description{
-The cross validation function of xgboost
-}
-\details{
-The original sample is randomly partitioned into \code{nfold} equal size subsamples.
-
-Of the \code{nfold} subsamples, a single subsample is retained as the validation data for testing the model, and the remaining \code{nfold - 1} subsamples are used as training data.
-
-The cross-validation process is then repeated \code{nrounds} times, with each of the \code{nfold} subsamples used exactly once as the validation data.
-
-All observations are used for both training and validation.
-
-Adapted from \url{http://en.wikipedia.org/wiki/Cross-validation_\%28statistics\%29#k-fold_cross-validation}
-}
-\examples{
-data(agaricus.train, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-cv <- xgb.cv(data = dtrain, nrounds = 3, nthread = 2, nfold = 5, metrics = list("rmse","auc"),
- max_depth = 3, eta = 1, objective = "binary:logistic")
-print(cv)
-print(cv, verbose=TRUE)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.dump.Rd b/ml-xgboost/R-package/man/xgb.dump.Rd
deleted file mode 100644
index 210c6e2..0000000
--- a/ml-xgboost/R-package/man/xgb.dump.Rd
+++ /dev/null
@@ -1,62 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.dump.R
-\name{xgb.dump}
-\alias{xgb.dump}
-\title{Dump an xgboost model in text format.}
-\usage{
-xgb.dump(
- model,
- fname = NULL,
- fmap = "",
- with_stats = FALSE,
- dump_format = c("text", "json"),
- ...
-)
-}
-\arguments{
-\item{model}{the model object.}
-
-\item{fname}{the name of the text file where to save the model text dump.
-If not provided or set to \code{NULL}, the model is returned as a \code{character} vector.}
-
-\item{fmap}{feature map file representing feature types.
-Detailed description could be found at
-\url{https://github.com/dmlc/xgboost/wiki/Binary-Classification#dump-model}.
-See demo/ for walkthrough example in R, and
-\url{https://github.com/dmlc/xgboost/blob/master/demo/data/featmap.txt}
-for example Format.}
-
-\item{with_stats}{whether to dump some additional statistics about the splits.
-When this option is on, the model dump contains two additional values:
-gain is the approximate loss function gain we get in each split;
-cover is the sum of second order gradient in each node.}
-
-\item{dump_format}{either 'text' or 'json' format could be specified.}
-
-\item{...}{currently not used}
-}
-\value{
-If fname is not provided or set to \code{NULL} the function will return the model
-as a \code{character} vector. Otherwise it will return \code{TRUE}.
-}
-\description{
-Dump an xgboost model in text format.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-# save the model in file 'xgb.model.dump'
-dump_path = file.path(tempdir(), 'model.dump')
-xgb.dump(bst, dump_path, with_stats = TRUE)
-
-# print the model without saving it to a file
-print(xgb.dump(bst, with_stats = TRUE))
-
-# print in JSON format:
-cat(xgb.dump(bst, with_stats = TRUE, dump_format='json'))
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.gblinear.history.Rd b/ml-xgboost/R-package/man/xgb.gblinear.history.Rd
deleted file mode 100644
index bc8d467..0000000
--- a/ml-xgboost/R-package/man/xgb.gblinear.history.Rd
+++ /dev/null
@@ -1,29 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/callbacks.R
-\name{xgb.gblinear.history}
-\alias{xgb.gblinear.history}
-\title{Extract gblinear coefficients history.}
-\usage{
-xgb.gblinear.history(model, class_index = NULL)
-}
-\arguments{
-\item{model}{either an \code{xgb.Booster} or a result of \code{xgb.cv()}, trained
-using the \code{cb.gblinear.history()} callback.}
-
-\item{class_index}{zero-based class index to extract the coefficients for only that
-specific class in a multinomial multiclass model. When it is NULL, all the
-coefficients are returned. Has no effect in non-multiclass models.}
-}
-\value{
-For an \code{xgb.train} result, a matrix (either dense or sparse) with the columns
-corresponding to iteration's coefficients (in the order as \code{xgb.dump()} would
-return) and the rows corresponding to boosting iterations.
-
-For an \code{xgb.cv} result, a list of such matrices is returned with the elements
-corresponding to CV folds.
-}
-\description{
-A helper function to extract the matrix of linear coefficients' history
-from a gblinear model created while using the \code{cb.gblinear.history()}
-callback.
-}
diff --git a/ml-xgboost/R-package/man/xgb.importance.Rd b/ml-xgboost/R-package/man/xgb.importance.Rd
deleted file mode 100644
index 84a18e1..0000000
--- a/ml-xgboost/R-package/man/xgb.importance.Rd
+++ /dev/null
@@ -1,101 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.importance.R
-\name{xgb.importance}
-\alias{xgb.importance}
-\title{Importance of features in a model.}
-\usage{
-xgb.importance(
- feature_names = NULL,
- model = NULL,
- trees = NULL,
- data = NULL,
- label = NULL,
- target = NULL
-)
-}
-\arguments{
-\item{feature_names}{character vector of feature names. If the model already
-contains feature names, those would be used when \code{feature_names=NULL} (default value).
-Non-null \code{feature_names} could be provided to override those in the model.}
-
-\item{model}{object of class \code{xgb.Booster}.}
-
-\item{trees}{(only for the gbtree booster) an integer vector of tree indices that should be included
-into the importance calculation. If set to \code{NULL}, all trees of the model are parsed.
-It could be useful, e.g., in multiclass classification to get feature importances
-for each class separately. IMPORTANT: the tree index in xgboost models
-is zero-based (e.g., use \code{trees = 0:4} for first 5 trees).}
-
-\item{data}{deprecated.}
-
-\item{label}{deprecated.}
-
-\item{target}{deprecated.}
-}
-\value{
-For a tree model, a \code{data.table} with the following columns:
-\itemize{
- \item \code{Features} names of the features used in the model;
- \item \code{Gain} represents fractional contribution of each feature to the model based on
- the total gain of this feature's splits. Higher percentage means a more important
- predictive feature.
- \item \code{Cover} metric of the number of observation related to this feature;
- \item \code{Frequency} percentage representing the relative number of times
- a feature have been used in trees.
-}
-
-A linear model's importance \code{data.table} has the following columns:
-\itemize{
- \item \code{Features} names of the features used in the model;
- \item \code{Weight} the linear coefficient of this feature;
- \item \code{Class} (only for multiclass models) class label.
-}
-
-If \code{feature_names} is not provided and \code{model} doesn't have \code{feature_names},
-index of the features will be used instead. Because the index is extracted from the model dump
-(based on C++ code), it starts at 0 (as in C/C++ or Python) instead of 1 (usual in R).
-}
-\description{
-Creates a \code{data.table} of feature importances in a model.
-}
-\details{
-This function works for both linear and tree models.
-
-For linear models, the importance is the absolute magnitude of linear coefficients.
-For that reason, in order to obtain a meaningful ranking by importance for a linear model,
-the features need to be on the same scale (which you also would want to do when using either
-L1 or L2 regularization).
-}
-\examples{
-
-# binomial classification using gbtree:
-data(agaricus.train, package='xgboost')
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-xgb.importance(model = bst)
-
-# binomial classification using gblinear:
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, booster = "gblinear",
- eta = 0.3, nthread = 1, nrounds = 20, objective = "binary:logistic")
-xgb.importance(model = bst)
-
-# multiclass classification using gbtree:
-nclass <- 3
-nrounds <- 10
-mbst <- xgboost(data = as.matrix(iris[, -5]), label = as.numeric(iris$Species) - 1,
- max_depth = 3, eta = 0.2, nthread = 2, nrounds = nrounds,
- objective = "multi:softprob", num_class = nclass)
-# all classes clumped together:
-xgb.importance(model = mbst)
-# inspect importances separately for each class:
-xgb.importance(model = mbst, trees = seq(from=0, by=nclass, length.out=nrounds))
-xgb.importance(model = mbst, trees = seq(from=1, by=nclass, length.out=nrounds))
-xgb.importance(model = mbst, trees = seq(from=2, by=nclass, length.out=nrounds))
-
-# multiclass classification using gblinear:
-mbst <- xgboost(data = scale(as.matrix(iris[, -5])), label = as.numeric(iris$Species) - 1,
- booster = "gblinear", eta = 0.2, nthread = 1, nrounds = 15,
- objective = "multi:softprob", num_class = nclass)
-xgb.importance(model = mbst)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.load.Rd b/ml-xgboost/R-package/man/xgb.load.Rd
deleted file mode 100644
index 3f743e1..0000000
--- a/ml-xgboost/R-package/man/xgb.load.Rd
+++ /dev/null
@@ -1,41 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.load.R
-\name{xgb.load}
-\alias{xgb.load}
-\title{Load xgboost model from binary file}
-\usage{
-xgb.load(modelfile)
-}
-\arguments{
-\item{modelfile}{the name of the binary input file.}
-}
-\value{
-An object of \code{xgb.Booster} class.
-}
-\description{
-Load xgboost model from the binary model file.
-}
-\details{
-The input file is expected to contain a model saved in an xgboost-internal binary format
-using either \code{\link{xgb.save}} or \code{\link{cb.save.model}} in R, or using some
-appropriate methods from other xgboost interfaces. E.g., a model trained in Python and
-saved from there in xgboost format, could be loaded from R.
-
-Note: a model saved as an R-object, has to be loaded using corresponding R-methods,
-not \code{xgb.load}.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-xgb.save(bst, 'xgb.model')
-bst <- xgb.load('xgb.model')
-if (file.exists('xgb.model')) file.remove('xgb.model')
-pred <- predict(bst, test$data)
-}
-\seealso{
-\code{\link{xgb.save}}, \code{\link{xgb.Booster.complete}}.
-}
diff --git a/ml-xgboost/R-package/man/xgb.load.raw.Rd b/ml-xgboost/R-package/man/xgb.load.raw.Rd
deleted file mode 100644
index f0248cd..0000000
--- a/ml-xgboost/R-package/man/xgb.load.raw.Rd
+++ /dev/null
@@ -1,14 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.load.raw.R
-\name{xgb.load.raw}
-\alias{xgb.load.raw}
-\title{Load serialised xgboost model from R's raw vector}
-\usage{
-xgb.load.raw(buffer)
-}
-\arguments{
-\item{buffer}{the buffer returned by xgb.save.raw}
-}
-\description{
-User can generate raw memory buffer by calling xgb.save.raw
-}
diff --git a/ml-xgboost/R-package/man/xgb.model.dt.tree.Rd b/ml-xgboost/R-package/man/xgb.model.dt.tree.Rd
deleted file mode 100644
index cf17501..0000000
--- a/ml-xgboost/R-package/man/xgb.model.dt.tree.Rd
+++ /dev/null
@@ -1,83 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.model.dt.tree.R
-\name{xgb.model.dt.tree}
-\alias{xgb.model.dt.tree}
-\title{Parse a boosted tree model text dump}
-\usage{
-xgb.model.dt.tree(
- feature_names = NULL,
- model = NULL,
- text = NULL,
- trees = NULL,
- use_int_id = FALSE,
- ...
-)
-}
-\arguments{
-\item{feature_names}{character vector of feature names. If the model already
-contains feature names, those would be used when \code{feature_names=NULL} (default value).
-Non-null \code{feature_names} could be provided to override those in the model.}
-
-\item{model}{object of class \code{xgb.Booster}}
-
-\item{text}{\code{character} vector previously generated by the \code{xgb.dump}
-function (where parameter \code{with_stats = TRUE} should have been set).
-\code{text} takes precedence over \code{model}.}
-
-\item{trees}{an integer vector of tree indices that should be parsed.
-If set to \code{NULL}, all trees of the model are parsed.
-It could be useful, e.g., in multiclass classification to get only
-the trees of one certain class. IMPORTANT: the tree index in xgboost models
-is zero-based (e.g., use \code{trees = 0:4} for first 5 trees).}
-
-\item{use_int_id}{a logical flag indicating whether nodes in columns "Yes", "No", "Missing" should be
-represented as integers (when FALSE) or as "Tree-Node" character strings (when FALSE).}
-
-\item{...}{currently not used.}
-}
-\value{
-A \code{data.table} with detailed information about model trees' nodes.
-
-The columns of the \code{data.table} are:
-
-\itemize{
- \item \code{Tree}: integer ID of a tree in a model (zero-based index)
- \item \code{Node}: integer ID of a node in a tree (zero-based index)
- \item \code{ID}: character identifier of a node in a model (only when \code{use_int_id=FALSE})
- \item \code{Feature}: for a branch node, it's a feature id or name (when available);
- for a leaf note, it simply labels it as \code{'Leaf'}
- \item \code{Split}: location of the split for a branch node (split condition is always "less than")
- \item \code{Yes}: ID of the next node when the split condition is met
- \item \code{No}: ID of the next node when the split condition is not met
- \item \code{Missing}: ID of the next node when branch value is missing
- \item \code{Quality}: either the split gain (change in loss) or the leaf value
- \item \code{Cover}: metric related to the number of observation either seen by a split
- or collected by a leaf during training.
-}
-
-When \code{use_int_id=FALSE}, columns "Yes", "No", and "Missing" point to model-wide node identifiers
-in the "ID" column. When \code{use_int_id=TRUE}, those columns point to node identifiers from
-the corresponding trees in the "Node" column.
-}
-\description{
-Parse a boosted tree model text dump into a \code{data.table} structure.
-}
-\examples{
-# Basic use:
-
-data(agaricus.train, package='xgboost')
-
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-
-(dt <- xgb.model.dt.tree(colnames(agaricus.train$data), bst))
-
-# This bst model already has feature_names stored with it, so those would be used when
-# feature_names is not set:
-(dt <- xgb.model.dt.tree(model = bst))
-
-# How to match feature names of splits that are following a current 'Yes' branch:
-
-merge(dt, dt[, .(ID, Y.Feature=Feature)], by.x='Yes', by.y='ID', all.x=TRUE)[order(Tree,Node)]
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.parameters.Rd b/ml-xgboost/R-package/man/xgb.parameters.Rd
deleted file mode 100644
index ab26956..0000000
--- a/ml-xgboost/R-package/man/xgb.parameters.Rd
+++ /dev/null
@@ -1,31 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.Booster.R
-\name{xgb.parameters<-}
-\alias{xgb.parameters<-}
-\title{Accessors for model parameters.}
-\usage{
-xgb.parameters(object) <- value
-}
-\arguments{
-\item{object}{Object of class \code{xgb.Booster} or \code{xgb.Booster.handle}.}
-
-\item{value}{a list (or an object coercible to a list) with the names of parameters to set
-and the elements corresponding to parameter values.}
-}
-\description{
-Only the setter for xgboost parameters is currently implemented.
-}
-\details{
-Note that the setter would usually work more efficiently for \code{xgb.Booster.handle}
-than for \code{xgb.Booster}, since only just a handle would need to be copied.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-train <- agaricus.train
-
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-
-xgb.parameters(bst) <- list(eta = 0.1)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.plot.deepness.Rd b/ml-xgboost/R-package/man/xgb.plot.deepness.Rd
deleted file mode 100644
index b642398..0000000
--- a/ml-xgboost/R-package/man/xgb.plot.deepness.Rd
+++ /dev/null
@@ -1,80 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.ggplot.R, R/xgb.plot.deepness.R
-\name{xgb.ggplot.deepness}
-\alias{xgb.ggplot.deepness}
-\alias{xgb.plot.deepness}
-\title{Plot model trees deepness}
-\usage{
-xgb.ggplot.deepness(
- model = NULL,
- which = c("2x1", "max.depth", "med.depth", "med.weight")
-)
-
-xgb.plot.deepness(
- model = NULL,
- which = c("2x1", "max.depth", "med.depth", "med.weight"),
- plot = TRUE,
- ...
-)
-}
-\arguments{
-\item{model}{either an \code{xgb.Booster} model generated by the \code{xgb.train} function
-or a data.table result of the \code{xgb.model.dt.tree} function.}
-
-\item{which}{which distribution to plot (see details).}
-
-\item{plot}{(base R barplot) whether a barplot should be produced.
-If FALSE, only a data.table is returned.}
-
-\item{...}{other parameters passed to \code{barplot} or \code{plot}.}
-}
-\value{
-Other than producing plots (when \code{plot=TRUE}), the \code{xgb.plot.deepness} function
-silently returns a processed data.table where each row corresponds to a terminal leaf in a tree model,
-and contains information about leaf's depth, cover, and weight (which is used in calculating predictions).
-
-The \code{xgb.ggplot.deepness} silently returns either a list of two ggplot graphs when \code{which="2x1"}
-or a single ggplot graph for the other \code{which} options.
-}
-\description{
-Visualizes distributions related to depth of tree leafs.
-\code{xgb.plot.deepness} uses base R graphics, while \code{xgb.ggplot.deepness} uses the ggplot backend.
-}
-\details{
-When \code{which="2x1"}, two distributions with respect to the leaf depth
-are plotted on top of each other:
-\itemize{
- \item the distribution of the number of leafs in a tree model at a certain depth;
- \item the distribution of average weighted number of observations ("cover")
- ending up in leafs at certain depth.
-}
-Those could be helpful in determining sensible ranges of the \code{max_depth}
-and \code{min_child_weight} parameters.
-
-When \code{which="max.depth"} or \code{which="med.depth"}, plots of either maximum or median depth
-per tree with respect to tree number are created. And \code{which="med.weight"} allows to see how
-a tree's median absolute leaf weight changes through the iterations.
-
-This function was inspired by the blog post
-\url{https://github.com/aysent/random-forest-leaf-visualization}.
-}
-\examples{
-
-data(agaricus.train, package='xgboost')
-
-# Change max_depth to a higher number to get a more significant result
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 6,
- eta = 0.1, nthread = 2, nrounds = 50, objective = "binary:logistic",
- subsample = 0.5, min_child_weight = 2)
-
-xgb.plot.deepness(bst)
-xgb.ggplot.deepness(bst)
-
-xgb.plot.deepness(bst, which='max.depth', pch=16, col=rgb(0,0,1,0.3), cex=2)
-
-xgb.plot.deepness(bst, which='med.weight', pch=16, col=rgb(0,0,1,0.3), cex=2)
-
-}
-\seealso{
-\code{\link{xgb.train}}, \code{\link{xgb.model.dt.tree}}.
-}
diff --git a/ml-xgboost/R-package/man/xgb.plot.importance.Rd b/ml-xgboost/R-package/man/xgb.plot.importance.Rd
deleted file mode 100644
index 691a8fd..0000000
--- a/ml-xgboost/R-package/man/xgb.plot.importance.Rd
+++ /dev/null
@@ -1,94 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.ggplot.R, R/xgb.plot.importance.R
-\name{xgb.ggplot.importance}
-\alias{xgb.ggplot.importance}
-\alias{xgb.plot.importance}
-\title{Plot feature importance as a bar graph}
-\usage{
-xgb.ggplot.importance(
- importance_matrix = NULL,
- top_n = NULL,
- measure = NULL,
- rel_to_first = FALSE,
- n_clusters = c(1:10),
- ...
-)
-
-xgb.plot.importance(
- importance_matrix = NULL,
- top_n = NULL,
- measure = NULL,
- rel_to_first = FALSE,
- left_margin = 10,
- cex = NULL,
- plot = TRUE,
- ...
-)
-}
-\arguments{
-\item{importance_matrix}{a \code{data.table} returned by \code{\link{xgb.importance}}.}
-
-\item{top_n}{maximal number of top features to include into the plot.}
-
-\item{measure}{the name of importance measure to plot.
-When \code{NULL}, 'Gain' would be used for trees and 'Weight' would be used for gblinear.}
-
-\item{rel_to_first}{whether importance values should be represented as relative to the highest ranked feature.
-See Details.}
-
-\item{n_clusters}{(ggplot only) a \code{numeric} vector containing the min and the max range
-of the possible number of clusters of bars.}
-
-\item{...}{other parameters passed to \code{barplot} (except horiz, border, cex.names, names.arg, and las).}
-
-\item{left_margin}{(base R barplot) allows to adjust the left margin size to fit feature names.
-When it is NULL, the existing \code{par('mar')} is used.}
-
-\item{cex}{(base R barplot) passed as \code{cex.names} parameter to \code{barplot}.}
-
-\item{plot}{(base R barplot) whether a barplot should be produced.
-If FALSE, only a data.table is returned.}
-}
-\value{
-The \code{xgb.plot.importance} function creates a \code{barplot} (when \code{plot=TRUE})
-and silently returns a processed data.table with \code{n_top} features sorted by importance.
-
-The \code{xgb.ggplot.importance} function returns a ggplot graph which could be customized afterwards.
-E.g., to change the title of the graph, add \code{+ ggtitle("A GRAPH NAME")} to the result.
-}
-\description{
-Represents previously calculated feature importance as a bar graph.
-\code{xgb.plot.importance} uses base R graphics, while \code{xgb.ggplot.importance} uses the ggplot backend.
-}
-\details{
-The graph represents each feature as a horizontal bar of length proportional to the importance of a feature.
-Features are shown ranked in a decreasing importance order.
-It works for importances from both \code{gblinear} and \code{gbtree} models.
-
-When \code{rel_to_first = FALSE}, the values would be plotted as they were in \code{importance_matrix}.
-For gbtree model, that would mean being normalized to the total of 1
-("what is feature's importance contribution relative to the whole model?").
-For linear models, \code{rel_to_first = FALSE} would show actual values of the coefficients.
-Setting \code{rel_to_first = TRUE} allows to see the picture from the perspective of
-"what is feature's importance contribution relative to the most important feature?"
-
-The ggplot-backend method also performs 1-D clustering of the importance values,
-with bar colors corresponding to different clusters that have somewhat similar importance values.
-}
-\examples{
-data(agaricus.train)
-
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 3,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-
-importance_matrix <- xgb.importance(colnames(agaricus.train$data), model = bst)
-
-xgb.plot.importance(importance_matrix, rel_to_first = TRUE, xlab = "Relative importance")
-
-(gg <- xgb.ggplot.importance(importance_matrix, measure = "Frequency", rel_to_first = TRUE))
-gg + ggplot2::ylab("Frequency")
-
-}
-\seealso{
-\code{\link[graphics]{barplot}}.
-}
diff --git a/ml-xgboost/R-package/man/xgb.plot.multi.trees.Rd b/ml-xgboost/R-package/man/xgb.plot.multi.trees.Rd
deleted file mode 100644
index 74c4a06..0000000
--- a/ml-xgboost/R-package/man/xgb.plot.multi.trees.Rd
+++ /dev/null
@@ -1,82 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.plot.multi.trees.R
-\name{xgb.plot.multi.trees}
-\alias{xgb.plot.multi.trees}
-\title{Project all trees on one tree and plot it}
-\usage{
-xgb.plot.multi.trees(
- model,
- feature_names = NULL,
- features_keep = 5,
- plot_width = NULL,
- plot_height = NULL,
- render = TRUE,
- ...
-)
-}
-\arguments{
-\item{model}{produced by the \code{xgb.train} function.}
-
-\item{feature_names}{names of each feature as a \code{character} vector.}
-
-\item{features_keep}{number of features to keep in each position of the multi trees.}
-
-\item{plot_width}{width in pixels of the graph to produce}
-
-\item{plot_height}{height in pixels of the graph to produce}
-
-\item{render}{a logical flag for whether the graph should be rendered (see Value).}
-
-\item{...}{currently not used}
-}
-\value{
-When \code{render = TRUE}:
-returns a rendered graph object which is an \code{htmlwidget} of class \code{grViz}.
-Similar to ggplot objects, it needs to be printed to see it when not running from command line.
-
-When \code{render = FALSE}:
-silently returns a graph object which is of DiagrammeR's class \code{dgr_graph}.
-This could be useful if one wants to modify some of the graph attributes
-before rendering the graph with \code{\link[DiagrammeR]{render_graph}}.
-}
-\description{
-Visualization of the ensemble of trees as a single collective unit.
-}
-\details{
-This function tries to capture the complexity of a gradient boosted tree model
-in a cohesive way by compressing an ensemble of trees into a single tree-graph representation.
-The goal is to improve the interpretability of a model generally seen as black box.
-
-Note: this function is applicable to tree booster-based models only.
-
-It takes advantage of the fact that the shape of a binary tree is only defined by
-its depth (therefore, in a boosting model, all trees have similar shape).
-
-Moreover, the trees tend to reuse the same features.
-
-The function projects each tree onto one, and keeps for each position the
-\code{features_keep} first features (based on the Gain per feature measure).
-
-This function is inspired by this blog post:
-\url{https://wellecks.wordpress.com/2015/02/21/peering-into-the-black-box-visualizing-lambdamart/}
-}
-\examples{
-
-data(agaricus.train, package='xgboost')
-
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 15,
- eta = 1, nthread = 2, nrounds = 30, objective = "binary:logistic",
- min_child_weight = 50, verbose = 0)
-
-p <- xgb.plot.multi.trees(model = bst, features_keep = 3)
-print(p)
-
-\dontrun{
-# Below is an example of how to save this plot to a file.
-# Note that for `export_graph` to work, the DiagrammeRsvg and rsvg packages must also be installed.
-library(DiagrammeR)
-gr <- xgb.plot.multi.trees(model=bst, features_keep = 3, render=FALSE)
-export_graph(gr, 'tree.pdf', width=1500, height=600)
-}
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.plot.shap.Rd b/ml-xgboost/R-package/man/xgb.plot.shap.Rd
deleted file mode 100644
index 3cd3a89..0000000
--- a/ml-xgboost/R-package/man/xgb.plot.shap.Rd
+++ /dev/null
@@ -1,158 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.plot.shap.R
-\name{xgb.plot.shap}
-\alias{xgb.plot.shap}
-\title{SHAP contribution dependency plots}
-\usage{
-xgb.plot.shap(
- data,
- shap_contrib = NULL,
- features = NULL,
- top_n = 1,
- model = NULL,
- trees = NULL,
- target_class = NULL,
- approxcontrib = FALSE,
- subsample = NULL,
- n_col = 1,
- col = rgb(0, 0, 1, 0.2),
- pch = ".",
- discrete_n_uniq = 5,
- discrete_jitter = 0.01,
- ylab = "SHAP",
- plot_NA = TRUE,
- col_NA = rgb(0.7, 0, 1, 0.6),
- pch_NA = ".",
- pos_NA = 1.07,
- plot_loess = TRUE,
- col_loess = 2,
- span_loess = 0.5,
- which = c("1d", "2d"),
- plot = TRUE,
- ...
-)
-}
-\arguments{
-\item{data}{data as a \code{matrix} or \code{dgCMatrix}.}
-
-\item{shap_contrib}{a matrix of SHAP contributions that was computed earlier for the above
-\code{data}. When it is NULL, it is computed internally using \code{model} and \code{data}.}
-
-\item{features}{a vector of either column indices or of feature names to plot. When it is NULL,
-feature importance is calculated, and \code{top_n} high ranked features are taken.}
-
-\item{top_n}{when \code{features} is NULL, top_n [1, 100] most important features in a model are taken.}
-
-\item{model}{an \code{xgb.Booster} model. It has to be provided when either \code{shap_contrib}
-or \code{features} is missing.}
-
-\item{trees}{passed to \code{\link{xgb.importance}} when \code{features = NULL}.}
-
-\item{target_class}{is only relevant for multiclass models. When it is set to a 0-based class index,
-only SHAP contributions for that specific class are used.
-If it is not set, SHAP importances are averaged over all classes.}
-
-\item{approxcontrib}{passed to \code{\link{predict.xgb.Booster}} when \code{shap_contrib = NULL}.}
-
-\item{subsample}{a random fraction of data points to use for plotting. When it is NULL,
-it is set so that up to 100K data points are used.}
-
-\item{n_col}{a number of columns in a grid of plots.}
-
-\item{col}{color of the scatterplot markers.}
-
-\item{pch}{scatterplot marker.}
-
-\item{discrete_n_uniq}{a maximal number of unique values in a feature to consider it as discrete.}
-
-\item{discrete_jitter}{an \code{amount} parameter of jitter added to discrete features' positions.}
-
-\item{ylab}{a y-axis label in 1D plots.}
-
-\item{plot_NA}{whether the contributions of cases with missing values should also be plotted.}
-
-\item{col_NA}{a color of marker for missing value contributions.}
-
-\item{pch_NA}{a marker type for NA values.}
-
-\item{pos_NA}{a relative position of the x-location where NA values are shown:
-\code{min(x) + (max(x) - min(x)) * pos_NA}.}
-
-\item{plot_loess}{whether to plot loess-smoothed curves. The smoothing is only done for features with
-more than 5 distinct values.}
-
-\item{col_loess}{a color to use for the loess curves.}
-
-\item{span_loess}{the \code{span} parameter in \code{\link[stats]{loess}}'s call.}
-
-\item{which}{whether to do univariate or bivariate plotting. NOTE: only 1D is implemented so far.}
-
-\item{plot}{whether a plot should be drawn. If FALSE, only a lits of matrices is returned.}
-
-\item{...}{other parameters passed to \code{plot}.}
-}
-\value{
-In addition to producing plots (when \code{plot=TRUE}), it silently returns a list of two matrices:
-\itemize{
- \item \code{data} the values of selected features;
- \item \code{shap_contrib} the contributions of selected features.
-}
-}
-\description{
-Visualizing the SHAP feature contribution to prediction dependencies on feature value.
-}
-\details{
-These scatterplots represent how SHAP feature contributions depend of feature values.
-The similarity to partial dependency plots is that they also give an idea for how feature values
-affect predictions. However, in partial dependency plots, we usually see marginal dependencies
-of model prediction on feature value, while SHAP contribution dependency plots display the estimated
-contributions of a feature to model prediction for each individual case.
-
-When \code{plot_loess = TRUE} is set, feature values are rounded to 3 significant digits and
-weighted LOESS is computed and plotted, where weights are the numbers of data points
-at each rounded value.
-
-Note: SHAP contributions are shown on the scale of model margin. E.g., for a logistic binomial objective,
-the margin is prediction before a sigmoidal transform into probability-like values.
-Also, since SHAP stands for "SHapley Additive exPlanation" (model prediction = sum of SHAP
-contributions for all features + bias), depending on the objective used, transforming SHAP
-contributions for a feature from the marginal to the prediction space is not necessarily
-a meaningful thing to do.
-}
-\examples{
-
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-
-bst <- xgboost(agaricus.train$data, agaricus.train$label, nrounds = 50,
- eta = 0.1, max_depth = 3, subsample = .5,
- method = "hist", objective = "binary:logistic", nthread = 2, verbose = 0)
-
-xgb.plot.shap(agaricus.test$data, model = bst, features = "odor=none")
-contr <- predict(bst, agaricus.test$data, predcontrib = TRUE)
-xgb.plot.shap(agaricus.test$data, contr, model = bst, top_n = 12, n_col = 3)
-
-# multiclass example - plots for each class separately:
-nclass <- 3
-nrounds <- 20
-x <- as.matrix(iris[, -5])
-set.seed(123)
-is.na(x[sample(nrow(x) * 4, 30)]) <- TRUE # introduce some missing values
-mbst <- xgboost(data = x, label = as.numeric(iris$Species) - 1, nrounds = nrounds,
- max_depth = 2, eta = 0.3, subsample = .5, nthread = 2,
- objective = "multi:softprob", num_class = nclass, verbose = 0)
-trees0 <- seq(from=0, by=nclass, length.out=nrounds)
-col <- rgb(0, 0, 1, 0.5)
-xgb.plot.shap(x, model = mbst, trees = trees0, target_class = 0, top_n = 4,
- n_col = 2, col = col, pch = 16, pch_NA = 17)
-xgb.plot.shap(x, model = mbst, trees = trees0 + 1, target_class = 1, top_n = 4,
- n_col = 2, col = col, pch = 16, pch_NA = 17)
-xgb.plot.shap(x, model = mbst, trees = trees0 + 2, target_class = 2, top_n = 4,
- n_col = 2, col = col, pch = 16, pch_NA = 17)
-
-}
-\references{
-Scott M. Lundberg, Su-In Lee, "A Unified Approach to Interpreting Model Predictions", NIPS Proceedings 2017, \url{https://arxiv.org/abs/1705.07874}
-
-Scott M. Lundberg, Su-In Lee, "Consistent feature attribution for tree ensembles", \url{https://arxiv.org/abs/1706.06060}
-}
diff --git a/ml-xgboost/R-package/man/xgb.plot.tree.Rd b/ml-xgboost/R-package/man/xgb.plot.tree.Rd
deleted file mode 100644
index 3f9f99a..0000000
--- a/ml-xgboost/R-package/man/xgb.plot.tree.Rd
+++ /dev/null
@@ -1,91 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.plot.tree.R
-\name{xgb.plot.tree}
-\alias{xgb.plot.tree}
-\title{Plot a boosted tree model}
-\usage{
-xgb.plot.tree(
- feature_names = NULL,
- model = NULL,
- trees = NULL,
- plot_width = NULL,
- plot_height = NULL,
- render = TRUE,
- show_node_id = FALSE,
- ...
-)
-}
-\arguments{
-\item{feature_names}{names of each feature as a \code{character} vector.}
-
-\item{model}{produced by the \code{xgb.train} function.}
-
-\item{trees}{an integer vector of tree indices that should be visualized.
-If set to \code{NULL}, all trees of the model are included.
-IMPORTANT: the tree index in xgboost model is zero-based
-(e.g., use \code{trees = 0:2} for the first 3 trees in a model).}
-
-\item{plot_width}{the width of the diagram in pixels.}
-
-\item{plot_height}{the height of the diagram in pixels.}
-
-\item{render}{a logical flag for whether the graph should be rendered (see Value).}
-
-\item{show_node_id}{a logical flag for whether to show node id's in the graph.}
-
-\item{...}{currently not used.}
-}
-\value{
-When \code{render = TRUE}:
-returns a rendered graph object which is an \code{htmlwidget} of class \code{grViz}.
-Similar to ggplot objects, it needs to be printed to see it when not running from command line.
-
-When \code{render = FALSE}:
-silently returns a graph object which is of DiagrammeR's class \code{dgr_graph}.
-This could be useful if one wants to modify some of the graph attributes
-before rendering the graph with \code{\link[DiagrammeR]{render_graph}}.
-}
-\description{
-Read a tree model text dump and plot the model.
-}
-\details{
-The content of each node is organised that way:
-
-\itemize{
- \item Feature name.
- \item \code{Cover}: The sum of second order gradient of training data classified to the leaf.
- If it is square loss, this simply corresponds to the number of instances seen by a split
- or collected by a leaf during training.
- The deeper in the tree a node is, the lower this metric will be.
- \item \code{Gain} (for split nodes): the information gain metric of a split
- (corresponds to the importance of the node in the model).
- \item \code{Value} (for leafs): the margin value that the leaf may contribute to prediction.
-}
-The tree root nodes also indicate the Tree index (0-based).
-
-The "Yes" branches are marked by the "< split_value" label.
-The branches that also used for missing values are marked as bold
-(as in "carrying extra capacity").
-
-This function uses \href{http://www.graphviz.org/}{GraphViz} as a backend of DiagrammeR.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label, max_depth = 3,
- eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-# plot all the trees
-xgb.plot.tree(model = bst)
-# plot only the first tree and display the node ID:
-xgb.plot.tree(model = bst, trees = 0, show_node_id = TRUE)
-
-\dontrun{
-# Below is an example of how to save this plot to a file.
-# Note that for `export_graph` to work, the DiagrammeRsvg and rsvg packages must also be installed.
-library(DiagrammeR)
-gr <- xgb.plot.tree(model=bst, trees=0:1, render=FALSE)
-export_graph(gr, 'tree.pdf', width=1500, height=1900)
-export_graph(gr, 'tree.png', width=1500, height=1900)
-}
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.save.Rd b/ml-xgboost/R-package/man/xgb.save.Rd
deleted file mode 100644
index 7d1842d..0000000
--- a/ml-xgboost/R-package/man/xgb.save.Rd
+++ /dev/null
@@ -1,41 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.save.R
-\name{xgb.save}
-\alias{xgb.save}
-\title{Save xgboost model to binary file}
-\usage{
-xgb.save(model, fname)
-}
-\arguments{
-\item{model}{model object of \code{xgb.Booster} class.}
-
-\item{fname}{name of the file to write.}
-}
-\description{
-Save xgboost model to a file in binary format.
-}
-\details{
-This methods allows to save a model in an xgboost-internal binary format which is universal
-among the various xgboost interfaces. In R, the saved model file could be read-in later
-using either the \code{\link{xgb.load}} function or the \code{xgb_model} parameter
-of \code{\link{xgb.train}}.
-
-Note: a model can also be saved as an R-object (e.g., by using \code{\link[base]{readRDS}}
-or \code{\link[base]{save}}). However, it would then only be compatible with R, and
-corresponding R-methods would need to be used to load it.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-xgb.save(bst, 'xgb.model')
-bst <- xgb.load('xgb.model')
-if (file.exists('xgb.model')) file.remove('xgb.model')
-pred <- predict(bst, test$data)
-}
-\seealso{
-\code{\link{xgb.load}}, \code{\link{xgb.Booster.complete}}.
-}
diff --git a/ml-xgboost/R-package/man/xgb.save.raw.Rd b/ml-xgboost/R-package/man/xgb.save.raw.Rd
deleted file mode 100644
index 6f2faa0..0000000
--- a/ml-xgboost/R-package/man/xgb.save.raw.Rd
+++ /dev/null
@@ -1,27 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.save.raw.R
-\name{xgb.save.raw}
-\alias{xgb.save.raw}
-\title{Save xgboost model to R's raw vector,
-user can call xgb.load.raw to load the model back from raw vector}
-\usage{
-xgb.save.raw(model)
-}
-\arguments{
-\item{model}{the model object.}
-}
-\description{
-Save xgboost model from xgboost or xgb.train
-}
-\examples{
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-raw <- xgb.save.raw(bst)
-bst <- xgb.load.raw(raw)
-pred <- predict(bst, test$data)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.serialize.Rd b/ml-xgboost/R-package/man/xgb.serialize.Rd
deleted file mode 100644
index 952441d..0000000
--- a/ml-xgboost/R-package/man/xgb.serialize.Rd
+++ /dev/null
@@ -1,29 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.serialize.R
-\name{xgb.serialize}
-\alias{xgb.serialize}
-\title{Serialize the booster instance into R's raw vector. The serialization method differs
-from \code{\link{xgb.save.raw}} as the latter one saves only the model but not
-parameters. This serialization format is not stable across different xgboost versions.}
-\usage{
-xgb.serialize(booster)
-}
-\arguments{
-\item{booster}{the booster instance}
-}
-\description{
-Serialize the booster instance into R's raw vector. The serialization method differs
-from \code{\link{xgb.save.raw}} as the latter one saves only the model but not
-parameters. This serialization format is not stable across different xgboost versions.
-}
-\examples{
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2,objective = "binary:logistic")
-raw <- xgb.serialize(bst)
-bst <- xgb.unserialize(raw)
-
-}
diff --git a/ml-xgboost/R-package/man/xgb.train.Rd b/ml-xgboost/R-package/man/xgb.train.Rd
deleted file mode 100644
index a6c91cc..0000000
--- a/ml-xgboost/R-package/man/xgb.train.Rd
+++ /dev/null
@@ -1,299 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.train.R, R/xgboost.R
-\name{xgb.train}
-\alias{xgb.train}
-\alias{xgboost}
-\title{eXtreme Gradient Boosting Training}
-\usage{
-xgb.train(
- params = list(),
- data,
- nrounds,
- watchlist = list(),
- obj = NULL,
- feval = NULL,
- verbose = 1,
- print_every_n = 1L,
- early_stopping_rounds = NULL,
- maximize = NULL,
- save_period = NULL,
- save_name = "xgboost.model",
- xgb_model = NULL,
- callbacks = list(),
- ...
-)
-
-xgboost(
- data = NULL,
- label = NULL,
- missing = NA,
- weight = NULL,
- params = list(),
- nrounds,
- verbose = 1,
- print_every_n = 1L,
- early_stopping_rounds = NULL,
- maximize = NULL,
- save_period = NULL,
- save_name = "xgboost.model",
- xgb_model = NULL,
- callbacks = list(),
- ...
-)
-}
-\arguments{
-\item{params}{the list of parameters.
- The complete list of parameters is available at \url{http://xgboost.readthedocs.io/en/latest/parameter.html}.
- Below is a shorter summary:
-
-1. General Parameters
-
-\itemize{
- \item \code{booster} which booster to use, can be \code{gbtree} or \code{gblinear}. Default: \code{gbtree}.
-}
-
-2. Booster Parameters
-
-2.1. Parameter for Tree Booster
-
-\itemize{
- \item \code{eta} control the learning rate: scale the contribution of each tree by a factor of \code{0 < eta < 1} when it is added to the current approximation. Used to prevent overfitting by making the boosting process more conservative. Lower value for \code{eta} implies larger value for \code{nrounds}: low \code{eta} value means model more robust to overfitting but slower to compute. Default: 0.3
- \item \code{gamma} minimum loss reduction required to make a further partition on a leaf node of the tree. the larger, the more conservative the algorithm will be.
- \item \code{max_depth} maximum depth of a tree. Default: 6
- \item \code{min_child_weight} minimum sum of instance weight (hessian) needed in a child. If the tree partition step results in a leaf node with the sum of instance weight less than min_child_weight, then the building process will give up further partitioning. In linear regression mode, this simply corresponds to minimum number of instances needed to be in each node. The larger, the more conservative the algorithm will be. Default: 1
- \item \code{subsample} subsample ratio of the training instance. Setting it to 0.5 means that xgboost randomly collected half of the data instances to grow trees and this will prevent overfitting. It makes computation shorter (because less data to analyse). It is advised to use this parameter with \code{eta} and increase \code{nrounds}. Default: 1
- \item \code{colsample_bytree} subsample ratio of columns when constructing each tree. Default: 1
- \item \code{num_parallel_tree} Experimental parameter. number of trees to grow per round. Useful to test Random Forest through Xgboost (set \code{colsample_bytree < 1}, \code{subsample < 1} and \code{round = 1}) accordingly. Default: 1
- \item \code{monotone_constraints} A numerical vector consists of \code{1}, \code{0} and \code{-1} with its length equals to the number of features in the training data. \code{1} is increasing, \code{-1} is decreasing and \code{0} is no constraint.
- \item \code{interaction_constraints} A list of vectors specifying feature indices of permitted interactions. Each item of the list represents one permitted interaction where specified features are allowed to interact with each other. Feature index values should start from \code{0} (\code{0} references the first column). Leave argument unspecified for no interaction constraints.
-}
-
-2.2. Parameter for Linear Booster
-
-\itemize{
- \item \code{lambda} L2 regularization term on weights. Default: 0
- \item \code{lambda_bias} L2 regularization term on bias. Default: 0
- \item \code{alpha} L1 regularization term on weights. (there is no L1 reg on bias because it is not important). Default: 0
-}
-
-3. Task Parameters
-
-\itemize{
-\item \code{objective} specify the learning task and the corresponding learning objective, users can pass a self-defined function to it. The default objective options are below:
- \itemize{
- \item \code{reg:squarederror} Regression with squared loss (Default).
- \item \code{reg:logistic} logistic regression.
- \item \code{binary:logistic} logistic regression for binary classification. Output probability.
- \item \code{binary:logitraw} logistic regression for binary classification, output score before logistic transformation.
- \item \code{num_class} set the number of classes. To use only with multiclass objectives.
- \item \code{multi:softmax} set xgboost to do multiclass classification using the softmax objective. Class is represented by a number and should be from 0 to \code{num_class - 1}.
- \item \code{multi:softprob} same as softmax, but prediction outputs a vector of ndata * nclass elements, which can be further reshaped to ndata, nclass matrix. The result contains predicted probabilities of each data point belonging to each class.
- \item \code{rank:pairwise} set xgboost to do ranking task by minimizing the pairwise loss.
- }
- \item \code{base_score} the initial prediction score of all instances, global bias. Default: 0.5
- \item \code{eval_metric} evaluation metrics for validation data. Users can pass a self-defined function to it. Default: metric will be assigned according to objective(rmse for regression, and error for classification, mean average precision for ranking). List is provided in detail section.
-}}
-
-\item{data}{training dataset. \code{xgb.train} accepts only an \code{xgb.DMatrix} as the input.
-\code{xgboost}, in addition, also accepts \code{matrix}, \code{dgCMatrix}, or name of a local data file.}
-
-\item{nrounds}{max number of boosting iterations.}
-
-\item{watchlist}{named list of xgb.DMatrix datasets to use for evaluating model performance.
-Metrics specified in either \code{eval_metric} or \code{feval} will be computed for each
-of these datasets during each boosting iteration, and stored in the end as a field named
-\code{evaluation_log} in the resulting object. When either \code{verbose>=1} or
-\code{\link{cb.print.evaluation}} callback is engaged, the performance results are continuously
-printed out during the training.
-E.g., specifying \code{watchlist=list(validation1=mat1, validation2=mat2)} allows to track
-the performance of each round's model on mat1 and mat2.}
-
-\item{obj}{customized objective function. Returns gradient and second order
-gradient with given prediction and dtrain.}
-
-\item{feval}{customized evaluation function. Returns
-\code{list(metric='metric-name', value='metric-value')} with given
-prediction and dtrain.}
-
-\item{verbose}{If 0, xgboost will stay silent. If 1, it will print information about performance.
-If 2, some additional information will be printed out.
-Note that setting \code{verbose > 0} automatically engages the
-\code{cb.print.evaluation(period=1)} callback function.}
-
-\item{print_every_n}{Print each n-th iteration evaluation messages when \code{verbose>0}.
-Default is 1 which means all messages are printed. This parameter is passed to the
-\code{\link{cb.print.evaluation}} callback.}
-
-\item{early_stopping_rounds}{If \code{NULL}, the early stopping function is not triggered.
-If set to an integer \code{k}, training with a validation set will stop if the performance
-doesn't improve for \code{k} rounds.
-Setting this parameter engages the \code{\link{cb.early.stop}} callback.}
-
-\item{maximize}{If \code{feval} and \code{early_stopping_rounds} are set,
-then this parameter must be set as well.
-When it is \code{TRUE}, it means the larger the evaluation score the better.
-This parameter is passed to the \code{\link{cb.early.stop}} callback.}
-
-\item{save_period}{when it is non-NULL, model is saved to disk after every \code{save_period} rounds,
-0 means save at the end. The saving is handled by the \code{\link{cb.save.model}} callback.}
-
-\item{save_name}{the name or path for periodically saved model file.}
-
-\item{xgb_model}{a previously built model to continue the training from.
-Could be either an object of class \code{xgb.Booster}, or its raw data, or the name of a
-file with a previously saved model.}
-
-\item{callbacks}{a list of callback functions to perform various task during boosting.
-See \code{\link{callbacks}}. Some of the callbacks are automatically created depending on the
-parameters' values. User can provide either existing or their own callback methods in order
-to customize the training process.}
-
-\item{...}{other parameters to pass to \code{params}.}
-
-\item{label}{vector of response values. Should not be provided when data is
-a local data file name or an \code{xgb.DMatrix}.}
-
-\item{missing}{by default is set to NA, which means that NA values should be considered as 'missing'
-by the algorithm. Sometimes, 0 or other extreme value might be used to represent missing values.
-This parameter is only used when input is a dense matrix.}
-
-\item{weight}{a vector indicating the weight for each row of the input.}
-}
-\value{
-An object of class \code{xgb.Booster} with the following elements:
-\itemize{
- \item \code{handle} a handle (pointer) to the xgboost model in memory.
- \item \code{raw} a cached memory dump of the xgboost model saved as R's \code{raw} type.
- \item \code{niter} number of boosting iterations.
- \item \code{evaluation_log} evaluation history stored as a \code{data.table} with the
- first column corresponding to iteration number and the rest corresponding to evaluation
- metrics' values. It is created by the \code{\link{cb.evaluation.log}} callback.
- \item \code{call} a function call.
- \item \code{params} parameters that were passed to the xgboost library. Note that it does not
- capture parameters changed by the \code{\link{cb.reset.parameters}} callback.
- \item \code{callbacks} callback functions that were either automatically assigned or
- explicitly passed.
- \item \code{best_iteration} iteration number with the best evaluation metric value
- (only available with early stopping).
- \item \code{best_ntreelimit} the \code{ntreelimit} value corresponding to the best iteration,
- which could further be used in \code{predict} method
- (only available with early stopping).
- \item \code{best_score} the best evaluation metric value during early stopping.
- (only available with early stopping).
- \item \code{feature_names} names of the training dataset features
- (only when column names were defined in training data).
- \item \code{nfeatures} number of features in training data.
-}
-}
-\description{
-\code{xgb.train} is an advanced interface for training an xgboost model.
-The \code{xgboost} function is a simpler wrapper for \code{xgb.train}.
-}
-\details{
-These are the training functions for \code{xgboost}.
-
-The \code{xgb.train} interface supports advanced features such as \code{watchlist},
-customized objective and evaluation metric functions, therefore it is more flexible
-than the \code{xgboost} interface.
-
-Parallelization is automatically enabled if \code{OpenMP} is present.
-Number of threads can also be manually specified via \code{nthread} parameter.
-
-The evaluation metric is chosen automatically by Xgboost (according to the objective)
-when the \code{eval_metric} parameter is not provided.
-User may set one or several \code{eval_metric} parameters.
-Note that when using a customized metric, only this single metric can be used.
-The following is the list of built-in metrics for which Xgboost provides optimized implementation:
- \itemize{
- \item \code{rmse} root mean square error. \url{http://en.wikipedia.org/wiki/Root_mean_square_error}
- \item \code{logloss} negative log-likelihood. \url{http://en.wikipedia.org/wiki/Log-likelihood}
- \item \code{mlogloss} multiclass logloss. \url{http://wiki.fast.ai/index.php/Log_Loss}
- \item \code{error} Binary classification error rate. It is calculated as \code{(# wrong cases) / (# all cases)}.
- By default, it uses the 0.5 threshold for predicted values to define negative and positive instances.
- Different threshold (e.g., 0.) could be specified as "error@0."
- \item \code{merror} Multiclass classification error rate. It is calculated as \code{(# wrong cases) / (# all cases)}.
- \item \code{auc} Area under the curve. \url{http://en.wikipedia.org/wiki/Receiver_operating_characteristic#'Area_under_curve} for ranking evaluation.
- \item \code{aucpr} Area under the PR curve. \url{https://en.wikipedia.org/wiki/Precision_and_recall} for ranking evaluation.
- \item \code{ndcg} Normalized Discounted Cumulative Gain (for ranking task). \url{http://en.wikipedia.org/wiki/NDCG}
- }
-
-The following callbacks are automatically created when certain parameters are set:
-\itemize{
- \item \code{cb.print.evaluation} is turned on when \code{verbose > 0};
- and the \code{print_every_n} parameter is passed to it.
- \item \code{cb.evaluation.log} is on when \code{watchlist} is present.
- \item \code{cb.early.stop}: when \code{early_stopping_rounds} is set.
- \item \code{cb.save.model}: when \code{save_period > 0} is set.
-}
-}
-\examples{
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-watchlist <- list(train = dtrain, eval = dtest)
-
-## A simple xgb.train example:
-param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2,
- objective = "binary:logistic", eval_metric = "auc")
-bst <- xgb.train(param, dtrain, nrounds = 2, watchlist)
-
-
-## An xgb.train example where custom objective and evaluation metric are used:
-logregobj <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- preds <- 1/(1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
-}
-evalerror <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- err <- as.numeric(sum(labels != (preds > 0)))/length(labels)
- return(list(metric = "error", value = err))
-}
-
-# These functions could be used by passing them either:
-# as 'objective' and 'eval_metric' parameters in the params list:
-param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2,
- objective = logregobj, eval_metric = evalerror)
-bst <- xgb.train(param, dtrain, nrounds = 2, watchlist)
-
-# or through the ... arguments:
-param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2)
-bst <- xgb.train(param, dtrain, nrounds = 2, watchlist,
- objective = logregobj, eval_metric = evalerror)
-
-# or as dedicated 'obj' and 'feval' parameters of xgb.train:
-bst <- xgb.train(param, dtrain, nrounds = 2, watchlist,
- obj = logregobj, feval = evalerror)
-
-
-## An xgb.train example of using variable learning rates at each iteration:
-param <- list(max_depth = 2, eta = 1, verbose = 0, nthread = 2,
- objective = "binary:logistic", eval_metric = "auc")
-my_etas <- list(eta = c(0.5, 0.1))
-bst <- xgb.train(param, dtrain, nrounds = 2, watchlist,
- callbacks = list(cb.reset.parameters(my_etas)))
-
-## Early stopping:
-bst <- xgb.train(param, dtrain, nrounds = 25, watchlist,
- early_stopping_rounds = 3)
-
-## An 'xgboost' interface example:
-bst <- xgboost(data = agaricus.train$data, label = agaricus.train$label,
- max_depth = 2, eta = 1, nthread = 2, nrounds = 2,
- objective = "binary:logistic")
-pred <- predict(bst, agaricus.test$data)
-
-}
-\references{
-Tianqi Chen and Carlos Guestrin, "XGBoost: A Scalable Tree Boosting System",
-22nd SIGKDD Conference on Knowledge Discovery and Data Mining, 2016, \url{https://arxiv.org/abs/1603.02754}
-}
-\seealso{
-\code{\link{callbacks}},
-\code{\link{predict.xgb.Booster}},
-\code{\link{xgb.cv}}
-}
diff --git a/ml-xgboost/R-package/man/xgb.unserialize.Rd b/ml-xgboost/R-package/man/xgb.unserialize.Rd
deleted file mode 100644
index 7a11c5c..0000000
--- a/ml-xgboost/R-package/man/xgb.unserialize.Rd
+++ /dev/null
@@ -1,14 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/xgb.unserialize.R
-\name{xgb.unserialize}
-\alias{xgb.unserialize}
-\title{Load the instance back from \code{\link{xgb.serialize}}}
-\usage{
-xgb.unserialize(buffer)
-}
-\arguments{
-\item{buffer}{the buffer containing booster instance saved by \code{\link{xgb.serialize}}}
-}
-\description{
-Load the instance back from \code{\link{xgb.serialize}}
-}
diff --git a/ml-xgboost/R-package/man/xgboost-deprecated.Rd b/ml-xgboost/R-package/man/xgboost-deprecated.Rd
deleted file mode 100644
index 6ab0c6c..0000000
--- a/ml-xgboost/R-package/man/xgboost-deprecated.Rd
+++ /dev/null
@@ -1,16 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/utils.R
-\name{xgboost-deprecated}
-\alias{xgboost-deprecated}
-\title{Deprecation notices.}
-\description{
-At this time, some of the parameter names were changed in order to make the code style more uniform.
-The deprecated parameters would be removed in the next release.
-}
-\details{
-To see all the current deprecated and new parameters, check the \code{xgboost:::depr_par_lut} table.
-
-A deprecation warning is shown when any of the deprecated parameters is used in a call.
-An additional warning is shown when there was a partial match to a deprecated parameter
-(as R is able to partially match parameter names).
-}
diff --git a/ml-xgboost/R-package/remove_warning_suppression_pragma.sh b/ml-xgboost/R-package/remove_warning_suppression_pragma.sh
deleted file mode 100644
index 5399ac9..0000000
--- a/ml-xgboost/R-package/remove_warning_suppression_pragma.sh
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/bin/bash
-# remove all #pragma's that suppress compiler warnings
-set -e
-set -x
-for file in xgboost/src/dmlc-core/include/dmlc/*.h
-do
- sed -i.bak -e 's/^.*#pragma GCC diagnostic.*$//' -e 's/^.*#pragma clang diagnostic.*$//' -e 's/^.*#pragma warning.*$//' "${file}"
-done
-for file in xgboost/src/dmlc-core/include/dmlc/*.h.bak
-do
- rm "${file}"
-done
-set +x
-set +e
diff --git a/ml-xgboost/R-package/src/Makevars.in b/ml-xgboost/R-package/src/Makevars.in
deleted file mode 100644
index ac25b50..0000000
--- a/ml-xgboost/R-package/src/Makevars.in
+++ /dev/null
@@ -1,24 +0,0 @@
-# package root
-PKGROOT=../../
-ENABLE_STD_THREAD=1
-# _*_ mode: Makefile; _*_
-
-CXX_STD = CXX11
-
-XGB_RFLAGS = -DXGBOOST_STRICT_R_MODE=1 -DDMLC_LOG_BEFORE_THROW=0\
- -DDMLC_ENABLE_STD_THREAD=$(ENABLE_STD_THREAD) -DDMLC_DISABLE_STDIN=1\
- -DDMLC_LOG_CUSTOMIZE=1 -DXGBOOST_CUSTOMIZE_LOGGER=1\
- -DRABIT_CUSTOMIZE_MSG_ -DRABIT_STRICT_CXX98_
-
-# disable the use of thread_local for 32 bit windows:
-ifeq ($(R_OSTYPE)$(WIN),windows)
- XGB_RFLAGS += -DDMLC_CXX11_THREAD_LOCAL=0
-endif
-$(foreach v, $(XGB_RFLAGS), $(warning $(v)))
-
-PKG_CPPFLAGS= -I$(PKGROOT)/include -I$(PKGROOT)/dmlc-core/include -I$(PKGROOT)/rabit/include -I$(PKGROOT) $(XGB_RFLAGS)
-PKG_CXXFLAGS= @OPENMP_CXXFLAGS@ @ENDIAN_FLAG@ -pthread
-PKG_LIBS = @OPENMP_CXXFLAGS@ @OPENMP_LIB@ @ENDIAN_FLAG@ @BACKTRACE_LIB@ -pthread
-OBJECTS= ./xgboost_R.o ./xgboost_custom.o ./xgboost_assert.o ./init.o\
- $(PKGROOT)/amalgamation/xgboost-all0.o $(PKGROOT)/amalgamation/dmlc-minimum0.o\
- $(PKGROOT)/rabit/src/engine_empty.o $(PKGROOT)/rabit/src/c_api.o
diff --git a/ml-xgboost/R-package/src/Makevars.win b/ml-xgboost/R-package/src/Makevars.win
deleted file mode 100644
index 2e24116..0000000
--- a/ml-xgboost/R-package/src/Makevars.win
+++ /dev/null
@@ -1,38 +0,0 @@
-# package root
-PKGROOT=./
-ENABLE_STD_THREAD=0
-# _*_ mode: Makefile; _*_
-
-# This file is only used for windows compilation from github
-# It will be replaced with Makevars.in for the CRAN version
-.PHONY: all xgblib
-all: $(SHLIB)
-$(SHLIB): xgblib
-xgblib:
- cp -r ../../src .
- cp -r ../../rabit .
- cp -r ../../dmlc-core .
- cp -r ../../include .
- cp -r ../../amalgamation .
-
-CXX_STD = CXX11
-
-XGB_RFLAGS = -DXGBOOST_STRICT_R_MODE=1 -DDMLC_LOG_BEFORE_THROW=0\
- -DDMLC_ENABLE_STD_THREAD=$(ENABLE_STD_THREAD) -DDMLC_DISABLE_STDIN=1\
- -DDMLC_LOG_CUSTOMIZE=1 -DXGBOOST_CUSTOMIZE_LOGGER=1\
- -DRABIT_CUSTOMIZE_MSG_ -DRABIT_STRICT_CXX98_
-
-# disable the use of thread_local for 32 bit windows:
-ifeq ($(R_OSTYPE)$(WIN),windows)
- XGB_RFLAGS += -DDMLC_CXX11_THREAD_LOCAL=0
-endif
-$(foreach v, $(XGB_RFLAGS), $(warning $(v)))
-
-PKG_CPPFLAGS= -I$(PKGROOT)/include -I$(PKGROOT)/dmlc-core/include -I$(PKGROOT)/rabit/include -I$(PKGROOT) $(XGB_RFLAGS)
-PKG_CXXFLAGS= $(SHLIB_OPENMP_CXXFLAGS) $(SHLIB_PTHREAD_FLAGS)
-PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) $(SHLIB_PTHREAD_FLAGS)
-OBJECTS= ./xgboost_R.o ./xgboost_custom.o ./xgboost_assert.o ./init.o\
- $(PKGROOT)/amalgamation/xgboost-all0.o $(PKGROOT)/amalgamation/dmlc-minimum0.o\
- $(PKGROOT)/rabit/src/engine_empty.o $(PKGROOT)/rabit/src/c_api.o
-
-$(OBJECTS) : xgblib
diff --git a/ml-xgboost/R-package/src/init.c b/ml-xgboost/R-package/src/init.c
deleted file mode 100644
index 2093059..0000000
--- a/ml-xgboost/R-package/src/init.c
+++ /dev/null
@@ -1,85 +0,0 @@
-/* Copyright (c) 2015 by Contributors
- *
- * This file was initially generated using the following R command:
- * tools::package_native_routine_registration_skeleton('.', con = 'src/init.c', character_only = F)
- * and edited to conform to xgboost C linter requirements. For details, see
- * https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Registering-native-routines
- */
-#include
-#include
-#include
-#include
-
-/* FIXME:
-Check these declarations against the C/Fortran source code.
-*/
-
-/* .Call calls */
-extern SEXP XGBoosterBoostOneIter_R(SEXP, SEXP, SEXP, SEXP);
-extern SEXP XGBoosterCreate_R(SEXP);
-extern SEXP XGBoosterDumpModel_R(SEXP, SEXP, SEXP, SEXP);
-extern SEXP XGBoosterEvalOneIter_R(SEXP, SEXP, SEXP, SEXP);
-extern SEXP XGBoosterGetAttrNames_R(SEXP);
-extern SEXP XGBoosterGetAttr_R(SEXP, SEXP);
-extern SEXP XGBoosterLoadModelFromRaw_R(SEXP, SEXP);
-extern SEXP XGBoosterLoadModel_R(SEXP, SEXP);
-extern SEXP XGBoosterSaveJsonConfig_R(SEXP handle);
-extern SEXP XGBoosterLoadJsonConfig_R(SEXP handle, SEXP value);
-extern SEXP XGBoosterSerializeToBuffer_R(SEXP handle);
-extern SEXP XGBoosterUnserializeFromBuffer_R(SEXP handle, SEXP raw);
-extern SEXP XGBoosterModelToRaw_R(SEXP);
-extern SEXP XGBoosterPredict_R(SEXP, SEXP, SEXP, SEXP, SEXP);
-extern SEXP XGBoosterSaveModel_R(SEXP, SEXP);
-extern SEXP XGBoosterSetAttr_R(SEXP, SEXP, SEXP);
-extern SEXP XGBoosterSetParam_R(SEXP, SEXP, SEXP);
-extern SEXP XGBoosterUpdateOneIter_R(SEXP, SEXP, SEXP);
-extern SEXP XGCheckNullPtr_R(SEXP);
-extern SEXP XGDMatrixCreateFromCSC_R(SEXP, SEXP, SEXP, SEXP);
-extern SEXP XGDMatrixCreateFromFile_R(SEXP, SEXP);
-extern SEXP XGDMatrixCreateFromMat_R(SEXP, SEXP);
-extern SEXP XGDMatrixGetInfo_R(SEXP, SEXP);
-extern SEXP XGDMatrixNumCol_R(SEXP);
-extern SEXP XGDMatrixNumRow_R(SEXP);
-extern SEXP XGDMatrixSaveBinary_R(SEXP, SEXP, SEXP);
-extern SEXP XGDMatrixSetInfo_R(SEXP, SEXP, SEXP);
-extern SEXP XGDMatrixSliceDMatrix_R(SEXP, SEXP);
-
-static const R_CallMethodDef CallEntries[] = {
- {"XGBoosterBoostOneIter_R", (DL_FUNC) &XGBoosterBoostOneIter_R, 4},
- {"XGBoosterCreate_R", (DL_FUNC) &XGBoosterCreate_R, 1},
- {"XGBoosterDumpModel_R", (DL_FUNC) &XGBoosterDumpModel_R, 4},
- {"XGBoosterEvalOneIter_R", (DL_FUNC) &XGBoosterEvalOneIter_R, 4},
- {"XGBoosterGetAttrNames_R", (DL_FUNC) &XGBoosterGetAttrNames_R, 1},
- {"XGBoosterGetAttr_R", (DL_FUNC) &XGBoosterGetAttr_R, 2},
- {"XGBoosterLoadModelFromRaw_R", (DL_FUNC) &XGBoosterLoadModelFromRaw_R, 2},
- {"XGBoosterLoadModel_R", (DL_FUNC) &XGBoosterLoadModel_R, 2},
- {"XGBoosterSaveJsonConfig_R", (DL_FUNC) &XGBoosterSaveJsonConfig_R, 1},
- {"XGBoosterLoadJsonConfig_R", (DL_FUNC) &XGBoosterLoadJsonConfig_R, 2},
- {"XGBoosterSerializeToBuffer_R", (DL_FUNC) &XGBoosterSerializeToBuffer_R, 1},
- {"XGBoosterUnserializeFromBuffer_R", (DL_FUNC) &XGBoosterUnserializeFromBuffer_R, 2},
- {"XGBoosterModelToRaw_R", (DL_FUNC) &XGBoosterModelToRaw_R, 1},
- {"XGBoosterPredict_R", (DL_FUNC) &XGBoosterPredict_R, 5},
- {"XGBoosterSaveModel_R", (DL_FUNC) &XGBoosterSaveModel_R, 2},
- {"XGBoosterSetAttr_R", (DL_FUNC) &XGBoosterSetAttr_R, 3},
- {"XGBoosterSetParam_R", (DL_FUNC) &XGBoosterSetParam_R, 3},
- {"XGBoosterUpdateOneIter_R", (DL_FUNC) &XGBoosterUpdateOneIter_R, 3},
- {"XGCheckNullPtr_R", (DL_FUNC) &XGCheckNullPtr_R, 1},
- {"XGDMatrixCreateFromCSC_R", (DL_FUNC) &XGDMatrixCreateFromCSC_R, 4},
- {"XGDMatrixCreateFromFile_R", (DL_FUNC) &XGDMatrixCreateFromFile_R, 2},
- {"XGDMatrixCreateFromMat_R", (DL_FUNC) &XGDMatrixCreateFromMat_R, 2},
- {"XGDMatrixGetInfo_R", (DL_FUNC) &XGDMatrixGetInfo_R, 2},
- {"XGDMatrixNumCol_R", (DL_FUNC) &XGDMatrixNumCol_R, 1},
- {"XGDMatrixNumRow_R", (DL_FUNC) &XGDMatrixNumRow_R, 1},
- {"XGDMatrixSaveBinary_R", (DL_FUNC) &XGDMatrixSaveBinary_R, 3},
- {"XGDMatrixSetInfo_R", (DL_FUNC) &XGDMatrixSetInfo_R, 3},
- {"XGDMatrixSliceDMatrix_R", (DL_FUNC) &XGDMatrixSliceDMatrix_R, 2},
- {NULL, NULL, 0}
-};
-
-#if defined(_WIN32)
-__declspec(dllexport)
-#endif // defined(_WIN32)
-void R_init_xgboost(DllInfo *dll) {
- R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
- R_useDynamicSymbols(dll, FALSE);
-}
diff --git a/ml-xgboost/R-package/src/xgboost_R.cc b/ml-xgboost/R-package/src/xgboost_R.cc
deleted file mode 100644
index cb86ef4..0000000
--- a/ml-xgboost/R-package/src/xgboost_R.cc
+++ /dev/null
@@ -1,491 +0,0 @@
-// Copyright (c) 2014 by Contributors
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include "./xgboost_R.h"
-
-/*!
- * \brief macro to annotate begin of api
- */
-#define R_API_BEGIN() \
- GetRNGstate(); \
- try {
-/*!
- * \brief macro to annotate end of api
- */
-#define R_API_END() \
- } catch(dmlc::Error& e) { \
- PutRNGstate(); \
- error(e.what()); \
- } \
- PutRNGstate();
-
-/*!
- * \brief macro to check the call.
- */
-#define CHECK_CALL(x) \
- if ((x) != 0) { \
- error(XGBGetLastError()); \
- }
-
-
-using namespace dmlc;
-
-SEXP XGCheckNullPtr_R(SEXP handle) {
- return ScalarLogical(R_ExternalPtrAddr(handle) == NULL);
-}
-
-void _DMatrixFinalizer(SEXP ext) {
- R_API_BEGIN();
- if (R_ExternalPtrAddr(ext) == NULL) return;
- CHECK_CALL(XGDMatrixFree(R_ExternalPtrAddr(ext)));
- R_ClearExternalPtr(ext);
- R_API_END();
-}
-
-SEXP XGDMatrixCreateFromFile_R(SEXP fname, SEXP silent) {
- SEXP ret;
- R_API_BEGIN();
- DMatrixHandle handle;
- CHECK_CALL(XGDMatrixCreateFromFile(CHAR(asChar(fname)), asInteger(silent), &handle));
- ret = PROTECT(R_MakeExternalPtr(handle, R_NilValue, R_NilValue));
- R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE);
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGDMatrixCreateFromMat_R(SEXP mat,
- SEXP missing) {
- SEXP ret;
- R_API_BEGIN();
- SEXP dim = getAttrib(mat, R_DimSymbol);
- size_t nrow = static_cast(INTEGER(dim)[0]);
- size_t ncol = static_cast(INTEGER(dim)[1]);
- const bool is_int = TYPEOF(mat) == INTSXP;
- double *din;
- int *iin;
- if (is_int) {
- iin = INTEGER(mat);
- } else {
- din = REAL(mat);
- }
- std::vector data(nrow * ncol);
- #pragma omp parallel for schedule(static)
- for (omp_ulong i = 0; i < nrow; ++i) {
- for (size_t j = 0; j < ncol; ++j) {
- data[i * ncol +j] = is_int ? static_cast(iin[i + nrow * j]) : din[i + nrow * j];
- }
- }
- DMatrixHandle handle;
- CHECK_CALL(XGDMatrixCreateFromMat(BeginPtr(data), nrow, ncol, asReal(missing), &handle));
- ret = PROTECT(R_MakeExternalPtr(handle, R_NilValue, R_NilValue));
- R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE);
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGDMatrixCreateFromCSC_R(SEXP indptr,
- SEXP indices,
- SEXP data,
- SEXP num_row) {
- SEXP ret;
- R_API_BEGIN();
- const int *p_indptr = INTEGER(indptr);
- const int *p_indices = INTEGER(indices);
- const double *p_data = REAL(data);
- size_t nindptr = static_cast(length(indptr));
- size_t ndata = static_cast(length(data));
- size_t nrow = static_cast(INTEGER(num_row)[0]);
- std::vector col_ptr_(nindptr);
- std::vector indices_(ndata);
- std::vector data_(ndata);
-
- for (size_t i = 0; i < nindptr; ++i) {
- col_ptr_[i] = static_cast(p_indptr[i]);
- }
- #pragma omp parallel for schedule(static)
- for (int64_t i = 0; i < static_cast(ndata); ++i) {
- indices_[i] = static_cast(p_indices[i]);
- data_[i] = static_cast(p_data[i]);
- }
- DMatrixHandle handle;
- CHECK_CALL(XGDMatrixCreateFromCSCEx(BeginPtr(col_ptr_), BeginPtr(indices_),
- BeginPtr(data_), nindptr, ndata,
- nrow, &handle));
- ret = PROTECT(R_MakeExternalPtr(handle, R_NilValue, R_NilValue));
- R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE);
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGDMatrixSliceDMatrix_R(SEXP handle, SEXP idxset) {
- SEXP ret;
- R_API_BEGIN();
- int len = length(idxset);
- std::vector idxvec(len);
- for (int i = 0; i < len; ++i) {
- idxvec[i] = INTEGER(idxset)[i] - 1;
- }
- DMatrixHandle res;
- CHECK_CALL(XGDMatrixSliceDMatrixEx(R_ExternalPtrAddr(handle),
- BeginPtr(idxvec), len,
- &res,
- 0));
- ret = PROTECT(R_MakeExternalPtr(res, R_NilValue, R_NilValue));
- R_RegisterCFinalizerEx(ret, _DMatrixFinalizer, TRUE);
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGDMatrixSaveBinary_R(SEXP handle, SEXP fname, SEXP silent) {
- R_API_BEGIN();
- CHECK_CALL(XGDMatrixSaveBinary(R_ExternalPtrAddr(handle),
- CHAR(asChar(fname)),
- asInteger(silent)));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGDMatrixSetInfo_R(SEXP handle, SEXP field, SEXP array) {
- R_API_BEGIN();
- int len = length(array);
- const char *name = CHAR(asChar(field));
- if (!strcmp("group", name)) {
- std::vector vec(len);
- #pragma omp parallel for schedule(static)
- for (int i = 0; i < len; ++i) {
- vec[i] = static_cast(INTEGER(array)[i]);
- }
- CHECK_CALL(XGDMatrixSetUIntInfo(R_ExternalPtrAddr(handle),
- CHAR(asChar(field)),
- BeginPtr(vec), len));
- } else {
- std::vector vec(len);
- #pragma omp parallel for schedule(static)
- for (int i = 0; i < len; ++i) {
- vec[i] = REAL(array)[i];
- }
- CHECK_CALL(XGDMatrixSetFloatInfo(R_ExternalPtrAddr(handle),
- CHAR(asChar(field)),
- BeginPtr(vec), len));
- }
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGDMatrixGetInfo_R(SEXP handle, SEXP field) {
- SEXP ret;
- R_API_BEGIN();
- bst_ulong olen;
- const float *res;
- CHECK_CALL(XGDMatrixGetFloatInfo(R_ExternalPtrAddr(handle),
- CHAR(asChar(field)),
- &olen,
- &res));
- ret = PROTECT(allocVector(REALSXP, olen));
- for (size_t i = 0; i < olen; ++i) {
- REAL(ret)[i] = res[i];
- }
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGDMatrixNumRow_R(SEXP handle) {
- bst_ulong nrow;
- R_API_BEGIN();
- CHECK_CALL(XGDMatrixNumRow(R_ExternalPtrAddr(handle), &nrow));
- R_API_END();
- return ScalarInteger(static_cast(nrow));
-}
-
-SEXP XGDMatrixNumCol_R(SEXP handle) {
- bst_ulong ncol;
- R_API_BEGIN();
- CHECK_CALL(XGDMatrixNumCol(R_ExternalPtrAddr(handle), &ncol));
- R_API_END();
- return ScalarInteger(static_cast(ncol));
-}
-
-// functions related to booster
-void _BoosterFinalizer(SEXP ext) {
- if (R_ExternalPtrAddr(ext) == NULL) return;
- CHECK_CALL(XGBoosterFree(R_ExternalPtrAddr(ext)));
- R_ClearExternalPtr(ext);
-}
-
-SEXP XGBoosterCreate_R(SEXP dmats) {
- SEXP ret;
- R_API_BEGIN();
- int len = length(dmats);
- std::vector dvec;
- for (int i = 0; i < len; ++i) {
- dvec.push_back(R_ExternalPtrAddr(VECTOR_ELT(dmats, i)));
- }
- BoosterHandle handle;
- CHECK_CALL(XGBoosterCreate(BeginPtr(dvec), dvec.size(), &handle));
- ret = PROTECT(R_MakeExternalPtr(handle, R_NilValue, R_NilValue));
- R_RegisterCFinalizerEx(ret, _BoosterFinalizer, TRUE);
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGBoosterSetParam_R(SEXP handle, SEXP name, SEXP val) {
- R_API_BEGIN();
- CHECK_CALL(XGBoosterSetParam(R_ExternalPtrAddr(handle),
- CHAR(asChar(name)),
- CHAR(asChar(val))));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterUpdateOneIter_R(SEXP handle, SEXP iter, SEXP dtrain) {
- R_API_BEGIN();
- CHECK_CALL(XGBoosterUpdateOneIter(R_ExternalPtrAddr(handle),
- asInteger(iter),
- R_ExternalPtrAddr(dtrain)));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterBoostOneIter_R(SEXP handle, SEXP dtrain, SEXP grad, SEXP hess) {
- R_API_BEGIN();
- CHECK_EQ(length(grad), length(hess))
- << "gradient and hess must have same length";
- int len = length(grad);
- std::vector tgrad(len), thess(len);
- #pragma omp parallel for schedule(static)
- for (int j = 0; j < len; ++j) {
- tgrad[j] = REAL(grad)[j];
- thess[j] = REAL(hess)[j];
- }
- CHECK_CALL(XGBoosterBoostOneIter(R_ExternalPtrAddr(handle),
- R_ExternalPtrAddr(dtrain),
- BeginPtr(tgrad), BeginPtr(thess),
- len));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterEvalOneIter_R(SEXP handle, SEXP iter, SEXP dmats, SEXP evnames) {
- const char *ret;
- R_API_BEGIN();
- CHECK_EQ(length(dmats), length(evnames))
- << "dmats and evnams must have same length";
- int len = length(dmats);
- std::vector vec_dmats;
- std::vector vec_names;
- std::vector vec_sptr;
- for (int i = 0; i < len; ++i) {
- vec_dmats.push_back(R_ExternalPtrAddr(VECTOR_ELT(dmats, i)));
- vec_names.push_back(std::string(CHAR(asChar(VECTOR_ELT(evnames, i)))));
- }
- for (int i = 0; i < len; ++i) {
- vec_sptr.push_back(vec_names[i].c_str());
- }
- CHECK_CALL(XGBoosterEvalOneIter(R_ExternalPtrAddr(handle),
- asInteger(iter),
- BeginPtr(vec_dmats),
- BeginPtr(vec_sptr),
- len, &ret));
- R_API_END();
- return mkString(ret);
-}
-
-SEXP XGBoosterPredict_R(SEXP handle, SEXP dmat, SEXP option_mask,
- SEXP ntree_limit, SEXP training) {
- SEXP ret;
- R_API_BEGIN();
- bst_ulong olen;
- const float *res;
- CHECK_CALL(XGBoosterPredict(R_ExternalPtrAddr(handle),
- R_ExternalPtrAddr(dmat),
- asInteger(option_mask),
- asInteger(ntree_limit),
- asInteger(training),
- &olen, &res));
- ret = PROTECT(allocVector(REALSXP, olen));
- for (size_t i = 0; i < olen; ++i) {
- REAL(ret)[i] = res[i];
- }
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGBoosterLoadModel_R(SEXP handle, SEXP fname) {
- R_API_BEGIN();
- CHECK_CALL(XGBoosterLoadModel(R_ExternalPtrAddr(handle), CHAR(asChar(fname))));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterSaveModel_R(SEXP handle, SEXP fname) {
- R_API_BEGIN();
- CHECK_CALL(XGBoosterSaveModel(R_ExternalPtrAddr(handle), CHAR(asChar(fname))));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterModelToRaw_R(SEXP handle) {
- SEXP ret;
- R_API_BEGIN();
- bst_ulong olen;
- const char *raw;
- CHECK_CALL(XGBoosterGetModelRaw(R_ExternalPtrAddr(handle), &olen, &raw));
- ret = PROTECT(allocVector(RAWSXP, olen));
- if (olen != 0) {
- memcpy(RAW(ret), raw, olen);
- }
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGBoosterLoadModelFromRaw_R(SEXP handle, SEXP raw) {
- R_API_BEGIN();
- CHECK_CALL(XGBoosterLoadModelFromBuffer(R_ExternalPtrAddr(handle),
- RAW(raw),
- length(raw)));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterSaveJsonConfig_R(SEXP handle) {
- const char* ret;
- R_API_BEGIN();
- bst_ulong len {0};
- CHECK_CALL(XGBoosterSaveJsonConfig(R_ExternalPtrAddr(handle),
- &len,
- &ret));
- R_API_END();
- return mkString(ret);
-}
-
-SEXP XGBoosterLoadJsonConfig_R(SEXP handle, SEXP value) {
- R_API_BEGIN();
- XGBoosterLoadJsonConfig(R_ExternalPtrAddr(handle), CHAR(asChar(value)));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterSerializeToBuffer_R(SEXP handle) {
- SEXP ret;
- R_API_BEGIN();
- bst_ulong out_len;
- const char *raw;
- CHECK_CALL(XGBoosterSerializeToBuffer(R_ExternalPtrAddr(handle), &out_len, &raw));
- ret = PROTECT(allocVector(RAWSXP, out_len));
- if (out_len != 0) {
- memcpy(RAW(ret), raw, out_len);
- }
- R_API_END();
- UNPROTECT(1);
- return ret;
-}
-
-SEXP XGBoosterUnserializeFromBuffer_R(SEXP handle, SEXP raw) {
- R_API_BEGIN();
- XGBoosterUnserializeFromBuffer(R_ExternalPtrAddr(handle),
- RAW(raw),
- length(raw));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterDumpModel_R(SEXP handle, SEXP fmap, SEXP with_stats, SEXP dump_format) {
- SEXP out;
- R_API_BEGIN();
- bst_ulong olen;
- const char **res;
- const char *fmt = CHAR(asChar(dump_format));
- CHECK_CALL(XGBoosterDumpModelEx(R_ExternalPtrAddr(handle),
- CHAR(asChar(fmap)),
- asInteger(with_stats),
- fmt,
- &olen, &res));
- out = PROTECT(allocVector(STRSXP, olen));
- if (!strcmp("json", fmt)) {
- std::stringstream stream;
- stream << "[\n";
- for (size_t i = 0; i < olen; ++i) {
- stream << res[i];
- if (i < olen - 1) {
- stream << ",\n";
- } else {
- stream << "\n";
- }
- }
- stream << "]";
- SET_STRING_ELT(out, 0, mkChar(stream.str().c_str()));
- } else {
- for (size_t i = 0; i < olen; ++i) {
- std::stringstream stream;
- stream << "booster[" << i <<"]\n" << res[i];
- SET_STRING_ELT(out, i, mkChar(stream.str().c_str()));
- }
- }
- R_API_END();
- UNPROTECT(1);
- return out;
-}
-
-SEXP XGBoosterGetAttr_R(SEXP handle, SEXP name) {
- SEXP out;
- R_API_BEGIN();
- int success;
- const char *val;
- CHECK_CALL(XGBoosterGetAttr(R_ExternalPtrAddr(handle),
- CHAR(asChar(name)),
- &val,
- &success));
- if (success) {
- out = PROTECT(allocVector(STRSXP, 1));
- SET_STRING_ELT(out, 0, mkChar(val));
- } else {
- out = PROTECT(R_NilValue);
- }
- R_API_END();
- UNPROTECT(1);
- return out;
-}
-
-SEXP XGBoosterSetAttr_R(SEXP handle, SEXP name, SEXP val) {
- R_API_BEGIN();
- const char *v = isNull(val) ? nullptr : CHAR(asChar(val));
- CHECK_CALL(XGBoosterSetAttr(R_ExternalPtrAddr(handle),
- CHAR(asChar(name)), v));
- R_API_END();
- return R_NilValue;
-}
-
-SEXP XGBoosterGetAttrNames_R(SEXP handle) {
- SEXP out;
- R_API_BEGIN();
- bst_ulong len;
- const char **res;
- CHECK_CALL(XGBoosterGetAttrNames(R_ExternalPtrAddr(handle),
- &len, &res));
- if (len > 0) {
- out = PROTECT(allocVector(STRSXP, len));
- for (size_t i = 0; i < len; ++i) {
- SET_STRING_ELT(out, i, mkChar(res[i]));
- }
- } else {
- out = PROTECT(R_NilValue);
- }
- R_API_END();
- UNPROTECT(1);
- return out;
-}
diff --git a/ml-xgboost/R-package/src/xgboost_R.h b/ml-xgboost/R-package/src/xgboost_R.h
deleted file mode 100644
index be16ff9..0000000
--- a/ml-xgboost/R-package/src/xgboost_R.h
+++ /dev/null
@@ -1,247 +0,0 @@
-/*!
- * Copyright 2014 (c) by Contributors
- * \file xgboost_R.h
- * \author Tianqi Chen
- * \brief R wrapper of xgboost
- */
-#ifndef XGBOOST_R_H_ // NOLINT(*)
-#define XGBOOST_R_H_ // NOLINT(*)
-
-
-#include
-#include
-#include
-
-#include
-
-/*!
- * \brief check whether a handle is NULL
- * \param handle
- * \return whether it is null ptr
- */
-XGB_DLL SEXP XGCheckNullPtr_R(SEXP handle);
-
-/*!
- * \brief load a data matrix
- * \param fname name of the content
- * \param silent whether print messages
- * \return a loaded data matrix
- */
-XGB_DLL SEXP XGDMatrixCreateFromFile_R(SEXP fname, SEXP silent);
-
-/*!
- * \brief create matrix content from dense matrix
- * This assumes the matrix is stored in column major format
- * \param data R Matrix object
- * \param missing which value to represent missing value
- * \return created dmatrix
- */
-XGB_DLL SEXP XGDMatrixCreateFromMat_R(SEXP mat,
- SEXP missing);
-/*!
- * \brief create a matrix content from CSC format
- * \param indptr pointer to column headers
- * \param indices row indices
- * \param data content of the data
- * \param num_row numer of rows (when it's set to 0, then guess from data)
- * \return created dmatrix
- */
-XGB_DLL SEXP XGDMatrixCreateFromCSC_R(SEXP indptr,
- SEXP indices,
- SEXP data,
- SEXP num_row);
-
-/*!
- * \brief create a new dmatrix from sliced content of existing matrix
- * \param handle instance of data matrix to be sliced
- * \param idxset index set
- * \return a sliced new matrix
- */
-XGB_DLL SEXP XGDMatrixSliceDMatrix_R(SEXP handle, SEXP idxset);
-
-/*!
- * \brief load a data matrix into binary file
- * \param handle a instance of data matrix
- * \param fname file name
- * \param silent print statistics when saving
- * \return R_NilValue
- */
-XGB_DLL SEXP XGDMatrixSaveBinary_R(SEXP handle, SEXP fname, SEXP silent);
-
-/*!
- * \brief set information to dmatrix
- * \param handle a instance of data matrix
- * \param field field name, can be label, weight
- * \param array pointer to float vector
- * \return R_NilValue
- */
-XGB_DLL SEXP XGDMatrixSetInfo_R(SEXP handle, SEXP field, SEXP array);
-
-/*!
- * \brief get info vector from matrix
- * \param handle a instance of data matrix
- * \param field field name
- * \return info vector
- */
-XGB_DLL SEXP XGDMatrixGetInfo_R(SEXP handle, SEXP field);
-
-/*!
- * \brief return number of rows
- * \param handle an instance of data matrix
- */
-XGB_DLL SEXP XGDMatrixNumRow_R(SEXP handle);
-
-/*!
- * \brief return number of columns
- * \param handle an instance of data matrix
- */
-XGB_DLL SEXP XGDMatrixNumCol_R(SEXP handle);
-
-/*!
- * \brief create xgboost learner
- * \param dmats a list of dmatrix handles that will be cached
- */
-XGB_DLL SEXP XGBoosterCreate_R(SEXP dmats);
-
-/*!
- * \brief set parameters
- * \param handle handle
- * \param name parameter name
- * \param val value of parameter
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterSetParam_R(SEXP handle, SEXP name, SEXP val);
-
-/*!
- * \brief update the model in one round using dtrain
- * \param handle handle
- * \param iter current iteration rounds
- * \param dtrain training data
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterUpdateOneIter_R(SEXP ext, SEXP iter, SEXP dtrain);
-
-/*!
- * \brief update the model, by directly specify gradient and second order gradient,
- * this can be used to replace UpdateOneIter, to support customized loss function
- * \param handle handle
- * \param dtrain training data
- * \param grad gradient statistics
- * \param hess second order gradient statistics
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterBoostOneIter_R(SEXP handle, SEXP dtrain, SEXP grad, SEXP hess);
-
-/*!
- * \brief get evaluation statistics for xgboost
- * \param handle handle
- * \param iter current iteration rounds
- * \param dmats list of handles to dmatrices
- * \param evname name of evaluation
- * \return the string containing evaluation stats
- */
-XGB_DLL SEXP XGBoosterEvalOneIter_R(SEXP handle, SEXP iter, SEXP dmats, SEXP evnames);
-
-/*!
- * \brief make prediction based on dmat
- * \param handle handle
- * \param dmat data matrix
- * \param option_mask output_margin:1 predict_leaf:2
- * \param ntree_limit limit number of trees used in prediction
- * \param training Whether the prediction value is used for training.
- */
-XGB_DLL SEXP XGBoosterPredict_R(SEXP handle, SEXP dmat, SEXP option_mask,
- SEXP ntree_limit, SEXP training);
-/*!
- * \brief load model from existing file
- * \param handle handle
- * \param fname file name
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterLoadModel_R(SEXP handle, SEXP fname);
-
-/*!
- * \brief save model into existing file
- * \param handle handle
- * \param fname file name
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterSaveModel_R(SEXP handle, SEXP fname);
-
-/*!
- * \brief load model from raw array
- * \param handle handle
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterLoadModelFromRaw_R(SEXP handle, SEXP raw);
-
-/*!
- * \brief save model into R's raw array
- * \param handle handle
- * \return raw array
- */
-XGB_DLL SEXP XGBoosterModelToRaw_R(SEXP handle);
-
-/*!
- * \brief Save internal parameters as a JSON string
- * \param handle handle
- * \return JSON string
- */
-
-XGB_DLL SEXP XGBoosterSaveJsonConfig_R(SEXP handle);
-/*!
- * \brief Load the JSON string returnd by XGBoosterSaveJsonConfig_R
- * \param handle handle
- * \param value JSON string
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterLoadJsonConfig_R(SEXP handle, SEXP value);
-
-/*!
- * \brief Memory snapshot based serialization method. Saves everything states
- * into buffer.
- * \param handle handle to booster
- */
-XGB_DLL SEXP XGBoosterSerializeToBuffer_R(SEXP handle);
-
-/*!
- * \brief Memory snapshot based serialization method. Loads the buffer returned
- * from `XGBoosterSerializeToBuffer'.
- * \param handle handle to booster
- * \return raw byte array
- */
-XGB_DLL SEXP XGBoosterUnserializeFromBuffer_R(SEXP handle, SEXP raw);
-
-/*!
- * \brief dump model into a string
- * \param handle handle
- * \param fmap name to fmap can be empty string
- * \param with_stats whether dump statistics of splits
- * \param dump_format the format to dump the model in
- */
-XGB_DLL SEXP XGBoosterDumpModel_R(SEXP handle, SEXP fmap, SEXP with_stats, SEXP dump_format);
-
-/*!
- * \brief get learner attribute value
- * \param handle handle
- * \param name attribute name
- * \return character containing attribute value
- */
-XGB_DLL SEXP XGBoosterGetAttr_R(SEXP handle, SEXP name);
-
-/*!
- * \brief set learner attribute value
- * \param handle handle
- * \param name attribute name
- * \param val attribute value; NULL value would delete an attribute
- * \return R_NilValue
- */
-XGB_DLL SEXP XGBoosterSetAttr_R(SEXP handle, SEXP name, SEXP val);
-
-/*!
- * \brief get the names of learner attributes
- * \return string vector containing attribute names
- */
-XGB_DLL SEXP XGBoosterGetAttrNames_R(SEXP handle);
-
-#endif // XGBOOST_WRAPPER_R_H_ // NOLINT(*)
diff --git a/ml-xgboost/R-package/src/xgboost_assert.c b/ml-xgboost/R-package/src/xgboost_assert.c
deleted file mode 100644
index 4706a03..0000000
--- a/ml-xgboost/R-package/src/xgboost_assert.c
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2014 by Contributors
-#include
-#include
-#include
-
-// implements error handling
-void XGBoostAssert_R(int exp, const char *fmt, ...) {
- char buf[1024];
- if (exp == 0) {
- va_list args;
- va_start(args, fmt);
- vsprintf(buf, fmt, args);
- va_end(args);
- error("AssertError:%s\n", buf);
- }
-}
-void XGBoostCheck_R(int exp, const char *fmt, ...) {
- char buf[1024];
- if (exp == 0) {
- va_list args;
- va_start(args, fmt);
- vsprintf(buf, fmt, args);
- va_end(args);
- error("%s\n", buf);
- }
-}
diff --git a/ml-xgboost/R-package/src/xgboost_custom.cc b/ml-xgboost/R-package/src/xgboost_custom.cc
deleted file mode 100644
index 2387e72..0000000
--- a/ml-xgboost/R-package/src/xgboost_custom.cc
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright (c) 2015 by Contributors
-// This file contains the customization implementations of R module
-// to change behavior of libxgboost
-
-#include
-#include "../../src/common/random.h"
-#include "./xgboost_R.h"
-
-// redirect the messages to R's console.
-namespace dmlc {
-void CustomLogMessage::Log(const std::string& msg) {
- Rprintf("%s\n", msg.c_str());
-}
-} // namespace dmlc
-
-// implements rabit error handling.
-extern "C" {
- void XGBoostAssert_R(int exp, const char *fmt, ...);
- void XGBoostCheck_R(int exp, const char *fmt, ...);
-}
-
-namespace rabit {
-namespace utils {
-extern "C" {
- void (*Printf)(const char *fmt, ...) = Rprintf;
- void (*Assert)(int exp, const char *fmt, ...) = XGBoostAssert_R;
- void (*Check)(int exp, const char *fmt, ...) = XGBoostCheck_R;
- void (*Error)(const char *fmt, ...) = error;
-}
-}
-}
-
-namespace xgboost {
-ConsoleLogger::~ConsoleLogger() {
- if (cur_verbosity_ == LogVerbosity::kIgnore ||
- cur_verbosity_ <= global_verbosity_) {
- dmlc::CustomLogMessage::Log(log_stream_.str());
- }
-}
-TrackerLogger::~TrackerLogger() {
- dmlc::CustomLogMessage::Log(log_stream_.str());
-}
-} // namespace xgboost
-
-namespace xgboost {
-namespace common {
-
-// redirect the nath functions.
-bool CheckNAN(double v) {
- return ISNAN(v);
-}
-#if !defined(XGBOOST_USE_CUDA)
-double LogGamma(double v) {
- return lgammafn(v);
-}
-#endif // !defined(XGBOOST_USE_CUDA)
-// customize random engine.
-void CustomGlobalRandomEngine::seed(CustomGlobalRandomEngine::result_type val) {
- // ignore the seed
-}
-
-// use R's PRNG to replacd
-CustomGlobalRandomEngine::result_type
-CustomGlobalRandomEngine::operator()() {
- return static_cast(
- std::floor(unif_rand() * CustomGlobalRandomEngine::max()));
-}
-} // namespace common
-} // namespace xgboost
diff --git a/ml-xgboost/R-package/tests/testthat.R b/ml-xgboost/R-package/tests/testthat.R
deleted file mode 100644
index 53cc6ca..0000000
--- a/ml-xgboost/R-package/tests/testthat.R
+++ /dev/null
@@ -1,4 +0,0 @@
-library(testthat)
-library(xgboost)
-
-test_check("xgboost")
diff --git a/ml-xgboost/R-package/tests/testthat/test_basic.R b/ml-xgboost/R-package/tests/testthat/test_basic.R
deleted file mode 100644
index b23e4dd..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_basic.R
+++ /dev/null
@@ -1,384 +0,0 @@
-require(xgboost)
-
-context("basic functions")
-
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-set.seed(1994)
-
-# disable some tests for Win32
-windows_flag = .Platform$OS.type == "windows" &&
- .Machine$sizeof.pointer != 8
-solaris_flag = (Sys.info()['sysname'] == "SunOS")
-
-test_that("train and predict binary classification", {
- nrounds = 2
- expect_output(
- bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = nrounds, objective = "binary:logistic")
- , "train-error")
- expect_equal(class(bst), "xgb.Booster")
- expect_equal(bst$niter, nrounds)
- expect_false(is.null(bst$evaluation_log))
- expect_equal(nrow(bst$evaluation_log), nrounds)
- expect_lt(bst$evaluation_log[, min(train_error)], 0.03)
-
- pred <- predict(bst, test$data)
- expect_length(pred, 1611)
-
- pred1 <- predict(bst, train$data, ntreelimit = 1)
- expect_length(pred1, 6513)
- err_pred1 <- sum((pred1 > 0.5) != train$label)/length(train$label)
- err_log <- bst$evaluation_log[1, train_error]
- expect_lt(abs(err_pred1 - err_log), 10e-6)
-})
-
-test_that("parameter validation works", {
- p <- list(foo = "bar")
- nrounds = 1
- set.seed(1994)
-
- d <- cbind(
- x1 = rnorm(10),
- x2 = rnorm(10),
- x3 = rnorm(10))
- y <- d[,"x1"] + d[,"x2"]^2 +
- ifelse(d[,"x3"] > .5, d[,"x3"]^2, 2^d[,"x3"]) +
- rnorm(10)
- dtrain <- xgb.DMatrix(data=d, info = list(label=y))
-
- correct <- function() {
- params <- list(max_depth = 2, booster = "dart",
- rate_drop = 0.5, one_drop = TRUE,
- objective = "reg:squarederror")
- xgb.train(params = params, data = dtrain, nrounds = nrounds)
- }
- expect_silent(correct())
- incorrect <- function() {
- params <- list(max_depth = 2, booster = "dart",
- rate_drop = 0.5, one_drop = TRUE,
- objective = "reg:squarederror",
- foo = "bar", bar = "foo")
- output <- capture.output(
- xgb.train(params = params, data = dtrain, nrounds = nrounds))
- print(output)
- }
- expect_output(incorrect(), "bar, foo")
-})
-
-
-test_that("dart prediction works", {
- nrounds = 32
- set.seed(1994)
-
- d <- cbind(
- x1 = rnorm(100),
- x2 = rnorm(100),
- x3 = rnorm(100))
- y <- d[,"x1"] + d[,"x2"]^2 +
- ifelse(d[,"x3"] > .5, d[,"x3"]^2, 2^d[,"x3"]) +
- rnorm(100)
-
- set.seed(1994)
- booster_by_xgboost <- xgboost(data = d, label = y, max_depth = 2, booster = "dart",
- rate_drop = 0.5, one_drop = TRUE,
- eta = 1, nthread = 2, nrounds = nrounds, objective = "reg:squarederror")
- pred_by_xgboost_0 <- predict(booster_by_xgboost, newdata = d, ntreelimit = 0)
- pred_by_xgboost_1 <- predict(booster_by_xgboost, newdata = d, ntreelimit = nrounds)
- expect_true(all(matrix(pred_by_xgboost_0, byrow=TRUE) == matrix(pred_by_xgboost_1, byrow=TRUE)))
-
- pred_by_xgboost_2 <- predict(booster_by_xgboost, newdata = d, training = TRUE)
- expect_false(all(matrix(pred_by_xgboost_0, byrow=TRUE) == matrix(pred_by_xgboost_2, byrow=TRUE)))
-
- set.seed(1994)
- dtrain <- xgb.DMatrix(data=d, info = list(label=y))
- booster_by_train <- xgb.train( params = list(
- booster = "dart",
- max_depth = 2,
- eta = 1,
- rate_drop = 0.5,
- one_drop = TRUE,
- nthread = 1,
- tree_method= "exact",
- objective = "reg:squarederror"
- ),
- data = dtrain,
- nrounds = nrounds
- )
- pred_by_train_0 <- predict(booster_by_train, newdata = dtrain, ntreelimit = 0)
- pred_by_train_1 <- predict(booster_by_train, newdata = dtrain, ntreelimit = nrounds)
- pred_by_train_2 <- predict(booster_by_train, newdata = dtrain, training = TRUE)
-
- expect_true(all(matrix(pred_by_train_0, byrow=TRUE) == matrix(pred_by_xgboost_0, byrow=TRUE)))
- expect_true(all(matrix(pred_by_train_1, byrow=TRUE) == matrix(pred_by_xgboost_1, byrow=TRUE)))
- expect_true(all(matrix(pred_by_train_2, byrow=TRUE) == matrix(pred_by_xgboost_2, byrow=TRUE)))
-})
-
-test_that("train and predict softprob", {
- lb <- as.numeric(iris$Species) - 1
- set.seed(11)
- expect_output(
- bst <- xgboost(data = as.matrix(iris[, -5]), label = lb,
- max_depth = 3, eta = 0.5, nthread = 2, nrounds = 5,
- objective = "multi:softprob", num_class=3)
- , "train-merror")
- expect_false(is.null(bst$evaluation_log))
- expect_lt(bst$evaluation_log[, min(train_merror)], 0.025)
- expect_equal(bst$niter * 3, xgb.ntree(bst))
- pred <- predict(bst, as.matrix(iris[, -5]))
- expect_length(pred, nrow(iris) * 3)
- # row sums add up to total probability of 1:
- expect_equal(rowSums(matrix(pred, ncol=3, byrow=TRUE)), rep(1, nrow(iris)), tolerance = 1e-7)
- # manually calculate error at the last iteration:
- mpred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE)
- expect_equal(as.numeric(t(mpred)), pred)
- pred_labels <- max.col(mpred) - 1
- err <- sum(pred_labels != lb)/length(lb)
- expect_equal(bst$evaluation_log[5, train_merror], err, tolerance = 5e-6)
- # manually calculate error at the 1st iteration:
- mpred <- predict(bst, as.matrix(iris[, -5]), reshape = TRUE, ntreelimit = 1)
- pred_labels <- max.col(mpred) - 1
- err <- sum(pred_labels != lb)/length(lb)
- expect_equal(bst$evaluation_log[1, train_merror], err, tolerance = 5e-6)
-})
-
-test_that("train and predict softmax", {
- lb <- as.numeric(iris$Species) - 1
- set.seed(11)
- expect_output(
- bst <- xgboost(data = as.matrix(iris[, -5]), label = lb,
- max_depth = 3, eta = 0.5, nthread = 2, nrounds = 5,
- objective = "multi:softmax", num_class=3)
- , "train-merror")
- expect_false(is.null(bst$evaluation_log))
- expect_lt(bst$evaluation_log[, min(train_merror)], 0.025)
- expect_equal(bst$niter * 3, xgb.ntree(bst))
-
- pred <- predict(bst, as.matrix(iris[, -5]))
- expect_length(pred, nrow(iris))
- err <- sum(pred != lb)/length(lb)
- expect_equal(bst$evaluation_log[5, train_merror], err, tolerance = 5e-6)
-})
-
-test_that("train and predict RF", {
- set.seed(11)
- lb <- train$label
- # single iteration
- bst <- xgboost(data = train$data, label = lb, max_depth = 5,
- nthread = 2, nrounds = 1, objective = "binary:logistic",
- num_parallel_tree = 20, subsample = 0.6, colsample_bytree = 0.1)
- expect_equal(bst$niter, 1)
- expect_equal(xgb.ntree(bst), 20)
-
- pred <- predict(bst, train$data)
- pred_err <- sum((pred > 0.5) != lb)/length(lb)
- expect_lt(abs(bst$evaluation_log[1, train_error] - pred_err), 10e-6)
- #expect_lt(pred_err, 0.03)
-
- pred <- predict(bst, train$data, ntreelimit = 20)
- pred_err_20 <- sum((pred > 0.5) != lb)/length(lb)
- expect_equal(pred_err_20, pred_err)
-
- #pred <- predict(bst, train$data, ntreelimit = 1)
- #pred_err_1 <- sum((pred > 0.5) != lb)/length(lb)
- #expect_lt(pred_err, pred_err_1)
- #expect_lt(pred_err, 0.08)
-})
-
-test_that("train and predict RF with softprob", {
- lb <- as.numeric(iris$Species) - 1
- nrounds <- 15
- set.seed(11)
- bst <- xgboost(data = as.matrix(iris[, -5]), label = lb,
- max_depth = 3, eta = 0.9, nthread = 2, nrounds = nrounds,
- objective = "multi:softprob", num_class=3, verbose = 0,
- num_parallel_tree = 4, subsample = 0.5, colsample_bytree = 0.5)
- expect_equal(bst$niter, 15)
- expect_equal(xgb.ntree(bst), 15*3*4)
- # predict for all iterations:
- pred <- predict(bst, as.matrix(iris[, -5]), reshape=TRUE)
- expect_equal(dim(pred), c(nrow(iris), 3))
- pred_labels <- max.col(pred) - 1
- err <- sum(pred_labels != lb)/length(lb)
- expect_equal(bst$evaluation_log[nrounds, train_merror], err, tolerance = 5e-6)
- # predict for 7 iterations and adjust for 4 parallel trees per iteration
- pred <- predict(bst, as.matrix(iris[, -5]), reshape=TRUE, ntreelimit = 7 * 4)
- err <- sum((max.col(pred) - 1) != lb)/length(lb)
- expect_equal(bst$evaluation_log[7, train_merror], err, tolerance = 5e-6)
-})
-
-test_that("use of multiple eval metrics works", {
- expect_output(
- bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic",
- eval_metric = 'error', eval_metric = 'auc', eval_metric = "logloss")
- , "train-error.*train-auc.*train-logloss")
- expect_false(is.null(bst$evaluation_log))
- expect_equal(dim(bst$evaluation_log), c(2, 4))
- expect_equal(colnames(bst$evaluation_log), c("iter", "train_error", "train_auc", "train_logloss"))
-})
-
-
-test_that("training continuation works", {
- dtrain <- xgb.DMatrix(train$data, label = train$label)
- watchlist = list(train=dtrain)
- param <- list(objective = "binary:logistic", max_depth = 2, eta = 1, nthread = 2)
-
- # for the reference, use 4 iterations at once:
- set.seed(11)
- bst <- xgb.train(param, dtrain, nrounds = 4, watchlist, verbose = 0)
- # first two iterations:
- set.seed(11)
- bst1 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0)
- # continue for two more:
- bst2 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0, xgb_model = bst1)
- if (!windows_flag && !solaris_flag)
- expect_equal(bst$raw, bst2$raw)
- expect_false(is.null(bst2$evaluation_log))
- expect_equal(dim(bst2$evaluation_log), c(4, 2))
- expect_equal(bst2$evaluation_log, bst$evaluation_log)
- # test continuing from raw model data
- bst2 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0, xgb_model = bst1$raw)
- if (!windows_flag && !solaris_flag)
- expect_equal(bst$raw, bst2$raw)
- expect_equal(dim(bst2$evaluation_log), c(2, 2))
- # test continuing from a model in file
- xgb.save(bst1, "xgboost.model")
- bst2 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0, xgb_model = "xgboost.model")
- if (!windows_flag && !solaris_flag)
- expect_equal(bst$raw, bst2$raw)
- expect_equal(dim(bst2$evaluation_log), c(2, 2))
-})
-
-test_that("model serialization works", {
- out_path <- "model_serialization"
- dtrain <- xgb.DMatrix(train$data, label = train$label)
- watchlist = list(train=dtrain)
- param <- list(objective = "binary:logistic")
- booster <- xgb.train(param, dtrain, nrounds = 4, watchlist)
- raw <- xgb.serialize(booster)
- saveRDS(raw, out_path)
- raw <- readRDS(out_path)
-
- loaded <- xgb.unserialize(raw)
- raw_from_loaded <- xgb.serialize(loaded)
- expect_equal(raw, raw_from_loaded)
- file.remove(out_path)
-})
-
-test_that("xgb.cv works", {
- set.seed(11)
- expect_output(
- cv <- xgb.cv(data = train$data, label = train$label, max_depth = 2, nfold = 5,
- eta = 1., nthread = 2, nrounds = 2, objective = "binary:logistic",
- verbose=TRUE)
- , "train-error:")
- expect_is(cv, 'xgb.cv.synchronous')
- expect_false(is.null(cv$evaluation_log))
- expect_lt(cv$evaluation_log[, min(test_error_mean)], 0.03)
- expect_lt(cv$evaluation_log[, min(test_error_std)], 0.008)
- expect_equal(cv$niter, 2)
- expect_false(is.null(cv$folds) && is.list(cv$folds))
- expect_length(cv$folds, 5)
- expect_false(is.null(cv$params) && is.list(cv$params))
- expect_false(is.null(cv$callbacks))
- expect_false(is.null(cv$call))
-})
-
-test_that("xgb.cv works with stratified folds", {
- dtrain <- xgb.DMatrix(train$data, label = train$label)
- set.seed(314159)
- cv <- xgb.cv(data = dtrain, max_depth = 2, nfold = 5,
- eta = 1., nthread = 2, nrounds = 2, objective = "binary:logistic",
- verbose=TRUE, stratified = FALSE)
- set.seed(314159)
- cv2 <- xgb.cv(data = dtrain, max_depth = 2, nfold = 5,
- eta = 1., nthread = 2, nrounds = 2, objective = "binary:logistic",
- verbose=TRUE, stratified = TRUE)
- # Stratified folds should result in a different evaluation logs
- expect_true(all(cv$evaluation_log[, test_error_mean] != cv2$evaluation_log[, test_error_mean]))
-})
-
-test_that("train and predict with non-strict classes", {
- # standard dense matrix input
- train_dense <- as.matrix(train$data)
- bst <- xgboost(data = train_dense, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", verbose = 0)
- pr0 <- predict(bst, train_dense)
-
- # dense matrix-like input of non-matrix class
- class(train_dense) <- 'shmatrix'
- expect_true(is.matrix(train_dense))
- expect_error(
- bst <- xgboost(data = train_dense, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", verbose = 0)
- , regexp = NA)
- expect_error(pr <- predict(bst, train_dense), regexp = NA)
- expect_equal(pr0, pr)
-
- # dense matrix-like input of non-matrix class with some inheritance
- class(train_dense) <- c('pphmatrix','shmatrix')
- expect_true(is.matrix(train_dense))
- expect_error(
- bst <- xgboost(data = train_dense, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", verbose = 0)
- , regexp = NA)
- expect_error(pr <- predict(bst, train_dense), regexp = NA)
- expect_equal(pr0, pr)
-
- # when someone inhertis from xgb.Booster, it should still be possible to use it as xgb.Booster
- class(bst) <- c('super.Booster', 'xgb.Booster')
- expect_error(pr <- predict(bst, train_dense), regexp = NA)
- expect_equal(pr0, pr)
-})
-
-test_that("max_delta_step works", {
- dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
- watchlist <- list(train = dtrain)
- param <- list(objective = "binary:logistic", eval_metric="logloss", max_depth = 2, nthread = 2, eta = 0.5)
- nrounds = 5
- # model with no restriction on max_delta_step
- bst1 <- xgb.train(param, dtrain, nrounds, watchlist, verbose = 1)
- # model with restricted max_delta_step
- bst2 <- xgb.train(param, dtrain, nrounds, watchlist, verbose = 1, max_delta_step = 1)
- # the no-restriction model is expected to have consistently lower loss during the initial interations
- expect_true(all(bst1$evaluation_log$train_logloss < bst2$evaluation_log$train_logloss))
- expect_lt(mean(bst1$evaluation_log$train_logloss)/mean(bst2$evaluation_log$train_logloss), 0.8)
-})
-
-test_that("colsample_bytree works", {
- # Randomly generate data matrix by sampling from uniform distribution [-1, 1]
- set.seed(1)
- train_x <- matrix(runif(1000, min = -1, max = 1), ncol = 100)
- train_y <- as.numeric(rowSums(train_x) > 0)
- test_x <- matrix(runif(1000, min = -1, max = 1), ncol = 100)
- test_y <- as.numeric(rowSums(test_x) > 0)
- colnames(train_x) <- paste0("Feature_", sprintf("%03d", 1:100))
- colnames(test_x) <- paste0("Feature_", sprintf("%03d", 1:100))
- dtrain <- xgb.DMatrix(train_x, label = train_y)
- dtest <- xgb.DMatrix(test_x, label = test_y)
- watchlist <- list(train = dtrain, eval = dtest)
- ## Use colsample_bytree = 0.01, so that roughly one out of 100 features is chosen for
- ## each tree
- param <- list(max_depth = 2, eta = 0, nthread = 2,
- colsample_bytree = 0.01, objective = "binary:logistic",
- eval_metric = "auc")
- set.seed(2)
- bst <- xgb.train(param, dtrain, nrounds = 100, watchlist, verbose = 0)
- xgb.importance(model = bst)
- # If colsample_bytree works properly, a variety of features should be used
- # in the 100 trees
- expect_gte(nrow(xgb.importance(model = bst)), 30)
-})
-
-test_that("Configuration works", {
- bst <- xgboost(data = train$data, label = train$label, max_depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic",
- eval_metric = 'error', eval_metric = 'auc', eval_metric = "logloss")
- config <- xgb.config(bst)
- xgb.config(bst) <- config
- reloaded_config <- xgb.config(bst)
- expect_equal(config, reloaded_config);
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_callbacks.R b/ml-xgboost/R-package/tests/testthat/test_callbacks.R
deleted file mode 100644
index e7230d1..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_callbacks.R
+++ /dev/null
@@ -1,330 +0,0 @@
-# More specific testing of callbacks
-
-require(xgboost)
-require(data.table)
-
-context("callbacks")
-
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-
-# add some label noise for early stopping tests
-add.noise <- function(label, frac) {
- inoise <- sample(length(label), length(label) * frac)
- label[inoise] <- !label[inoise]
- label
-}
-set.seed(11)
-ltrain <- add.noise(train$label, 0.2)
-ltest <- add.noise(test$label, 0.2)
-dtrain <- xgb.DMatrix(train$data, label = ltrain)
-dtest <- xgb.DMatrix(test$data, label = ltest)
-watchlist = list(train=dtrain, test=dtest)
-
-
-err <- function(label, pr) sum((pr > 0.5) != label)/length(label)
-
-param <- list(objective = "binary:logistic", max_depth = 2, nthread = 2)
-
-
-test_that("cb.print.evaluation works as expected", {
-
- bst_evaluation <- c('train-auc'=0.9, 'test-auc'=0.8)
- bst_evaluation_err <- NULL
- begin_iteration <- 1
- end_iteration <- 7
-
- f0 <- cb.print.evaluation(period=0)
- f1 <- cb.print.evaluation(period=1)
- f5 <- cb.print.evaluation(period=5)
-
- expect_false(is.null(attr(f1, 'call')))
- expect_equal(attr(f1, 'name'), 'cb.print.evaluation')
-
- iteration <- 1
- expect_silent(f0())
- expect_output(f1(), "\\[1\\]\ttrain-auc:0.900000\ttest-auc:0.800000")
- expect_output(f5(), "\\[1\\]\ttrain-auc:0.900000\ttest-auc:0.800000")
- expect_null(f1())
-
- iteration <- 2
- expect_output(f1(), "\\[2\\]\ttrain-auc:0.900000\ttest-auc:0.800000")
- expect_silent(f5())
-
- iteration <- 7
- expect_output(f1(), "\\[7\\]\ttrain-auc:0.900000\ttest-auc:0.800000")
- expect_output(f5(), "\\[7\\]\ttrain-auc:0.900000\ttest-auc:0.800000")
-
- bst_evaluation_err <- c('train-auc'=0.1, 'test-auc'=0.2)
- expect_output(f1(), "\\[7\\]\ttrain-auc:0.900000\\+0.100000\ttest-auc:0.800000\\+0.200000")
-})
-
-test_that("cb.evaluation.log works as expected", {
-
- bst_evaluation <- c('train-auc'=0.9, 'test-auc'=0.8)
- bst_evaluation_err <- NULL
-
- evaluation_log <- list()
- f <- cb.evaluation.log()
-
- expect_false(is.null(attr(f, 'call')))
- expect_equal(attr(f, 'name'), 'cb.evaluation.log')
-
- iteration <- 1
- expect_silent(f())
- expect_equal(evaluation_log,
- list(c(iter=1, bst_evaluation)))
- iteration <- 2
- expect_silent(f())
- expect_equal(evaluation_log,
- list(c(iter=1, bst_evaluation), c(iter=2, bst_evaluation)))
- expect_silent(f(finalize = TRUE))
- expect_equal(evaluation_log,
- data.table(iter=1:2, train_auc=c(0.9,0.9), test_auc=c(0.8,0.8)))
-
- bst_evaluation_err <- c('train-auc'=0.1, 'test-auc'=0.2)
- evaluation_log <- list()
- f <- cb.evaluation.log()
-
- iteration <- 1
- expect_silent(f())
- expect_equal(evaluation_log,
- list(c(iter=1, c(bst_evaluation, bst_evaluation_err))))
- iteration <- 2
- expect_silent(f())
- expect_equal(evaluation_log,
- list(c(iter=1, c(bst_evaluation, bst_evaluation_err)),
- c(iter=2, c(bst_evaluation, bst_evaluation_err))))
- expect_silent(f(finalize = TRUE))
- expect_equal(evaluation_log,
- data.table(iter=1:2,
- train_auc_mean=c(0.9,0.9), train_auc_std=c(0.1,0.1),
- test_auc_mean=c(0.8,0.8), test_auc_std=c(0.2,0.2)))
-})
-
-
-param <- list(objective = "binary:logistic", max_depth = 4, nthread = 2)
-
-test_that("can store evaluation_log without printing", {
- expect_silent(
- bst <- xgb.train(param, dtrain, nrounds = 10, watchlist, eta = 1, verbose = 0)
- )
- expect_false(is.null(bst$evaluation_log))
- expect_false(is.null(bst$evaluation_log$train_error))
- expect_lt(bst$evaluation_log[, min(train_error)], 0.2)
-})
-
-test_that("cb.reset.parameters works as expected", {
-
- # fixed eta
- set.seed(111)
- bst0 <- xgb.train(param, dtrain, nrounds = 2, watchlist, eta = 0.9, verbose = 0)
- expect_false(is.null(bst0$evaluation_log))
- expect_false(is.null(bst0$evaluation_log$train_error))
-
- # same eta but re-set as a vector parameter in the callback
- set.seed(111)
- my_par <- list(eta = c(0.9, 0.9))
- bst1 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0,
- callbacks = list(cb.reset.parameters(my_par)))
- expect_false(is.null(bst1$evaluation_log$train_error))
- expect_equal(bst0$evaluation_log$train_error,
- bst1$evaluation_log$train_error)
-
- # same eta but re-set via a function in the callback
- set.seed(111)
- my_par <- list(eta = function(itr, itr_end) 0.9)
- bst2 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0,
- callbacks = list(cb.reset.parameters(my_par)))
- expect_false(is.null(bst2$evaluation_log$train_error))
- expect_equal(bst0$evaluation_log$train_error,
- bst2$evaluation_log$train_error)
-
- # different eta re-set as a vector parameter in the callback
- set.seed(111)
- my_par <- list(eta = c(0.6, 0.5))
- bst3 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0,
- callbacks = list(cb.reset.parameters(my_par)))
- expect_false(is.null(bst3$evaluation_log$train_error))
- expect_false(all(bst0$evaluation_log$train_error == bst3$evaluation_log$train_error))
-
- # resetting multiple parameters at the same time runs with no error
- my_par <- list(eta = c(1., 0.5), gamma = c(1, 2), max_depth = c(4, 8))
- expect_error(
- bst4 <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0,
- callbacks = list(cb.reset.parameters(my_par)))
- , NA) # NA = no error
- # CV works as well
- expect_error(
- bst4 <- xgb.cv(param, dtrain, nfold = 2, nrounds = 2, verbose = 0,
- callbacks = list(cb.reset.parameters(my_par)))
- , NA) # NA = no error
-
- # expect no learning with 0 learning rate
- my_par <- list(eta = c(0., 0.))
- bstX <- xgb.train(param, dtrain, nrounds = 2, watchlist, verbose = 0,
- callbacks = list(cb.reset.parameters(my_par)))
- expect_false(is.null(bstX$evaluation_log$train_error))
- er <- unique(bstX$evaluation_log$train_error)
- expect_length(er, 1)
- expect_gt(er, 0.4)
-})
-
-test_that("cb.save.model works as expected", {
- files <- c('xgboost_01.model', 'xgboost_02.model', 'xgboost.model')
- for (f in files) if (file.exists(f)) file.remove(f)
-
- bst <- xgb.train(param, dtrain, nrounds = 2, watchlist, eta = 1, verbose = 0,
- save_period = 1, save_name = "xgboost_%02d.model")
- expect_true(file.exists('xgboost_01.model'))
- expect_true(file.exists('xgboost_02.model'))
- b1 <- xgb.load('xgboost_01.model')
- expect_equal(xgb.ntree(b1), 1)
- b2 <- xgb.load('xgboost_02.model')
- expect_equal(xgb.ntree(b2), 2)
-
- xgb.config(b2) <- xgb.config(bst)
- expect_equal(xgb.config(bst), xgb.config(b2))
- expect_equal(bst$raw, b2$raw)
-
- # save_period = 0 saves the last iteration's model
- bst <- xgb.train(param, dtrain, nrounds = 2, watchlist, eta = 1, verbose = 0,
- save_period = 0)
- expect_true(file.exists('xgboost.model'))
- b2 <- xgb.load('xgboost.model')
- xgb.config(b2) <- xgb.config(bst)
- expect_equal(bst$raw, b2$raw)
-
- for (f in files) if (file.exists(f)) file.remove(f)
-})
-
-test_that("early stopping xgb.train works", {
- set.seed(11)
- expect_output(
- bst <- xgb.train(param, dtrain, nrounds = 20, watchlist, eta = 0.3,
- early_stopping_rounds = 3, maximize = FALSE)
- , "Stopping. Best iteration")
- expect_false(is.null(bst$best_iteration))
- expect_lt(bst$best_iteration, 19)
- expect_equal(bst$best_iteration, bst$best_ntreelimit)
-
- pred <- predict(bst, dtest)
- expect_equal(length(pred), 1611)
- err_pred <- err(ltest, pred)
- err_log <- bst$evaluation_log[bst$best_iteration, test_error]
- expect_equal(err_log, err_pred, tolerance = 5e-6)
-
- set.seed(11)
- expect_silent(
- bst0 <- xgb.train(param, dtrain, nrounds = 20, watchlist, eta = 0.3,
- early_stopping_rounds = 3, maximize = FALSE, verbose = 0)
- )
- expect_equal(bst$evaluation_log, bst0$evaluation_log)
-
- xgb.save(bst, "model.bin")
- loaded <- xgb.load("model.bin")
-
- expect_false(is.null(loaded$best_iteration))
- expect_equal(loaded$best_iteration, bst$best_ntreelimit)
- expect_equal(loaded$best_ntreelimit, bst$best_ntreelimit)
-
- file.remove("model.bin")
-})
-
-test_that("early stopping using a specific metric works", {
- set.seed(11)
- expect_output(
- bst <- xgb.train(param, dtrain, nrounds = 20, watchlist, eta = 0.6,
- eval_metric="logloss", eval_metric="auc",
- callbacks = list(cb.early.stop(stopping_rounds = 3, maximize = FALSE,
- metric_name = 'test_logloss')))
- , "Stopping. Best iteration")
- expect_false(is.null(bst$best_iteration))
- expect_lt(bst$best_iteration, 19)
- expect_equal(bst$best_iteration, bst$best_ntreelimit)
-
- pred <- predict(bst, dtest, ntreelimit = bst$best_ntreelimit)
- expect_equal(length(pred), 1611)
- logloss_pred <- sum(-ltest * log(pred) - (1 - ltest) * log(1 - pred)) / length(ltest)
- logloss_log <- bst$evaluation_log[bst$best_iteration, test_logloss]
- expect_equal(logloss_log, logloss_pred, tolerance = 1e-5)
-})
-
-test_that("early stopping xgb.cv works", {
- set.seed(11)
- expect_output(
- cv <- xgb.cv(param, dtrain, nfold = 5, eta = 0.3, nrounds = 20,
- early_stopping_rounds = 3, maximize = FALSE)
- , "Stopping. Best iteration")
- expect_false(is.null(cv$best_iteration))
- expect_lt(cv$best_iteration, 19)
- expect_equal(cv$best_iteration, cv$best_ntreelimit)
- # the best error is min error:
- expect_true(cv$evaluation_log[, test_error_mean[cv$best_iteration] == min(test_error_mean)])
-})
-
-test_that("prediction in xgb.cv works", {
- set.seed(11)
- nrounds = 4
- cv <- xgb.cv(param, dtrain, nfold = 5, eta = 0.5, nrounds = nrounds, prediction = TRUE, verbose = 0)
- expect_false(is.null(cv$evaluation_log))
- expect_false(is.null(cv$pred))
- expect_length(cv$pred, nrow(train$data))
- err_pred <- mean( sapply(cv$folds, function(f) mean(err(ltrain[f], cv$pred[f]))) )
- err_log <- cv$evaluation_log[nrounds, test_error_mean]
- expect_equal(err_pred, err_log, tolerance = 1e-6)
-
- # save CV models
- set.seed(11)
- cvx <- xgb.cv(param, dtrain, nfold = 5, eta = 0.5, nrounds = nrounds, prediction = TRUE, verbose = 0,
- callbacks = list(cb.cv.predict(save_models = TRUE)))
- expect_equal(cv$evaluation_log, cvx$evaluation_log)
- expect_length(cvx$models, 5)
- expect_true(all(sapply(cvx$models, class) == 'xgb.Booster'))
-})
-
-test_that("prediction in xgb.cv works for gblinear too", {
- set.seed(11)
- p <- list(booster = 'gblinear', objective = "reg:logistic", nthread = 2)
- cv <- xgb.cv(p, dtrain, nfold = 5, eta = 0.5, nrounds = 2, prediction = TRUE, verbose = 0)
- expect_false(is.null(cv$evaluation_log))
- expect_false(is.null(cv$pred))
- expect_length(cv$pred, nrow(train$data))
-})
-
-test_that("prediction in early-stopping xgb.cv works", {
- set.seed(11)
- expect_output(
- cv <- xgb.cv(param, dtrain, nfold = 5, eta = 0.1, nrounds = 20,
- early_stopping_rounds = 5, maximize = FALSE, stratified = FALSE,
- prediction = TRUE)
- , "Stopping. Best iteration")
-
- expect_false(is.null(cv$best_iteration))
- expect_lt(cv$best_iteration, 19)
- expect_false(is.null(cv$evaluation_log))
- expect_false(is.null(cv$pred))
- expect_length(cv$pred, nrow(train$data))
-
- err_pred <- mean( sapply(cv$folds, function(f) mean(err(ltrain[f], cv$pred[f]))) )
- err_log <- cv$evaluation_log[cv$best_iteration, test_error_mean]
- expect_equal(err_pred, err_log, tolerance = 1e-6)
- err_log_last <- cv$evaluation_log[cv$niter, test_error_mean]
- expect_gt(abs(err_pred - err_log_last), 1e-4)
-})
-
-test_that("prediction in xgb.cv for softprob works", {
- lb <- as.numeric(iris$Species) - 1
- set.seed(11)
- expect_warning(
- cv <- xgb.cv(data = as.matrix(iris[, -5]), label = lb, nfold = 4,
- eta = 0.5, nrounds = 5, max_depth = 3, nthread = 2,
- subsample = 0.8, gamma = 2, verbose = 0,
- prediction = TRUE, objective = "multi:softprob", num_class = 3)
- , NA)
- expect_false(is.null(cv$pred))
- expect_equal(dim(cv$pred), c(nrow(iris), 3))
- expect_lt(diff(range(rowSums(cv$pred))), 1e-6)
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_custom_objective.R b/ml-xgboost/R-package/tests/testthat/test_custom_objective.R
deleted file mode 100644
index ab01147..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_custom_objective.R
+++ /dev/null
@@ -1,77 +0,0 @@
-context('Test models with custom objective')
-
-require(xgboost)
-
-set.seed(1994)
-
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-watchlist <- list(eval = dtest, train = dtrain)
-
-logregobj <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- preds <- 1 / (1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
-}
-
-evalerror <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- err <- as.numeric(sum(labels != (preds > 0))) / length(labels)
- return(list(metric = "error", value = err))
-}
-
-param <- list(max_depth=2, eta=1, nthread = 2,
- objective=logregobj, eval_metric=evalerror)
-num_round <- 2
-
-test_that("custom objective works", {
- bst <- xgb.train(param, dtrain, num_round, watchlist)
- expect_equal(class(bst), "xgb.Booster")
- expect_false(is.null(bst$evaluation_log))
- expect_false(is.null(bst$evaluation_log$eval_error))
- expect_lt(bst$evaluation_log[num_round, eval_error], 0.03)
-})
-
-test_that("custom objective in CV works", {
- cv <- xgb.cv(param, dtrain, num_round, nfold=10, verbose=FALSE)
- expect_false(is.null(cv$evaluation_log))
- expect_equal(dim(cv$evaluation_log), c(2, 5))
- expect_lt(cv$evaluation_log[num_round, test_error_mean], 0.03)
-})
-
-test_that("custom objective using DMatrix attr works", {
-
- attr(dtrain, 'label') <- getinfo(dtrain, 'label')
-
- logregobjattr <- function(preds, dtrain) {
- labels <- attr(dtrain, 'label')
- preds <- 1 / (1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
- }
- param$objective = logregobjattr
- bst <- xgb.train(param, dtrain, num_round, watchlist)
- expect_equal(class(bst), "xgb.Booster")
-})
-
-test_that("custom objective with multi-class works", {
- data = as.matrix(iris[, -5])
- label = as.numeric(iris$Species) - 1
- dtrain <- xgb.DMatrix(data = data, label = label)
- nclasses <- 3
-
- fake_softprob <- function(preds, dtrain) {
- expect_true(all(matrix(preds) == 0.5))
- grad <- rnorm(dim(as.matrix(preds))[1])
- expect_equal(dim(data)[1] * nclasses, dim(as.matrix(preds))[1])
- hess <- rnorm(dim(as.matrix(preds))[1])
- return (list(grad = grad, hess = hess))
- }
- param$objective = fake_softprob
- bst <- xgb.train(param, dtrain, 1, num_class=nclasses)
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_dmatrix.R b/ml-xgboost/R-package/tests/testthat/test_dmatrix.R
deleted file mode 100644
index c063589..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_dmatrix.R
+++ /dev/null
@@ -1,117 +0,0 @@
-require(xgboost)
-require(Matrix)
-
-context("testing xgb.DMatrix functionality")
-
-data(agaricus.test, package='xgboost')
-test_data <- agaricus.test$data[1:100,]
-test_label <- agaricus.test$label[1:100]
-
-test_that("xgb.DMatrix: basic construction", {
- # from sparse matrix
- dtest1 <- xgb.DMatrix(test_data, label=test_label)
-
- # from dense matrix
- dtest2 <- xgb.DMatrix(as.matrix(test_data), label=test_label)
- expect_equal(getinfo(dtest1, 'label'), getinfo(dtest2, 'label'))
- expect_equal(dim(dtest1), dim(dtest2))
-
- #from dense integer matrix
- int_data <- as.matrix(test_data)
- storage.mode(int_data) <- "integer"
- dtest3 <- xgb.DMatrix(int_data, label=test_label)
- expect_equal(dim(dtest1), dim(dtest3))
-})
-
-test_that("xgb.DMatrix: saving, loading", {
- # save to a local file
- dtest1 <- xgb.DMatrix(test_data, label=test_label)
- tmp_file <- tempfile('xgb.DMatrix_')
- expect_true(xgb.DMatrix.save(dtest1, tmp_file))
- # read from a local file
- expect_output(dtest3 <- xgb.DMatrix(tmp_file), "entries loaded from")
- expect_output(dtest3 <- xgb.DMatrix(tmp_file, silent = TRUE), NA)
- unlink(tmp_file)
- expect_equal(getinfo(dtest1, 'label'), getinfo(dtest3, 'label'))
-
- # from a libsvm text file
- tmp <- c("0 1:1 2:1","1 3:1","0 1:1")
- tmp_file <- 'tmp.libsvm'
- writeLines(tmp, tmp_file)
- dtest4 <- xgb.DMatrix(tmp_file, silent = TRUE)
- expect_equal(dim(dtest4), c(3, 4))
- expect_equal(getinfo(dtest4, 'label'), c(0,1,0))
- unlink(tmp_file)
-})
-
-test_that("xgb.DMatrix: getinfo & setinfo", {
- dtest <- xgb.DMatrix(test_data)
- expect_true(setinfo(dtest, 'label', test_label))
- labels <- getinfo(dtest, 'label')
- expect_equal(test_label, getinfo(dtest, 'label'))
-
- expect_true(setinfo(dtest, 'label_lower_bound', test_label))
- expect_equal(test_label, getinfo(dtest, 'label_lower_bound'))
-
- expect_true(setinfo(dtest, 'label_upper_bound', test_label))
- expect_equal(test_label, getinfo(dtest, 'label_upper_bound'))
-
- expect_true(length(getinfo(dtest, 'weight')) == 0)
- expect_true(length(getinfo(dtest, 'base_margin')) == 0)
-
- expect_true(setinfo(dtest, 'weight', test_label))
- expect_true(setinfo(dtest, 'base_margin', test_label))
- expect_true(setinfo(dtest, 'group', c(50,50)))
- expect_error(setinfo(dtest, 'group', test_label))
-
- # providing character values will give a warning
- expect_warning(setinfo(dtest, 'weight', rep('a', nrow(test_data))))
-
- # any other label should error
- expect_error(setinfo(dtest, 'asdf', test_label))
-})
-
-test_that("xgb.DMatrix: slice, dim", {
- dtest <- xgb.DMatrix(test_data, label=test_label)
- expect_equal(dim(dtest), dim(test_data))
- dsub1 <- slice(dtest, 1:42)
- expect_equal(nrow(dsub1), 42)
- expect_equal(ncol(dsub1), ncol(test_data))
-
- dsub2 <- dtest[1:42,]
- expect_equal(dim(dtest), dim(test_data))
- expect_equal(getinfo(dsub1, 'label'), getinfo(dsub2, 'label'))
-})
-
-test_that("xgb.DMatrix: slice, trailing empty rows", {
- data(agaricus.train, package='xgboost')
- train_data <- agaricus.train$data
- train_label <- agaricus.train$label
- dtrain <- xgb.DMatrix(data=train_data, label=train_label)
- slice(dtrain, 6513L)
- train_data[6513, ] <- 0
- dtrain <- xgb.DMatrix(data=train_data, label=train_label)
- slice(dtrain, 6513L)
- expect_equal(nrow(dtrain), 6513)
-})
-
-test_that("xgb.DMatrix: colnames", {
- dtest <- xgb.DMatrix(test_data, label=test_label)
- expect_equal(colnames(dtest), colnames(test_data))
- expect_error( colnames(dtest) <- 'asdf')
- new_names <- make.names(1:ncol(test_data))
- expect_silent( colnames(dtest) <- new_names)
- expect_equal(colnames(dtest), new_names)
- expect_silent(colnames(dtest) <- NULL)
- expect_null(colnames(dtest))
-})
-
-test_that("xgb.DMatrix: nrow is correct for a very sparse matrix", {
- set.seed(123)
- nr <- 1000
- x <- rsparsematrix(nr, 100, density=0.0005)
- # we want it very sparse, so that last rows are empty
- expect_lt(max(x@i), nr)
- dtest <- xgb.DMatrix(x)
- expect_equal(dim(dtest), dim(x))
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_gc_safety.R b/ml-xgboost/R-package/tests/testthat/test_gc_safety.R
deleted file mode 100644
index b90f0f4..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_gc_safety.R
+++ /dev/null
@@ -1,15 +0,0 @@
-require(xgboost)
-
-context("Garbage Collection Safety Check")
-
-test_that("train and prediction when gctorture is on", {
- data(agaricus.train, package='xgboost')
- data(agaricus.test, package='xgboost')
- train <- agaricus.train
- test <- agaricus.test
- gctorture(TRUE)
- bst <- xgboost(data = train$data, label = train$label, max.depth = 2,
- eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
- pred <- predict(bst, test$data)
- gctorture(FALSE)
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_glm.R b/ml-xgboost/R-package/tests/testthat/test_glm.R
deleted file mode 100644
index 9b4aa73..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_glm.R
+++ /dev/null
@@ -1,48 +0,0 @@
-context('Test generalized linear models')
-
-require(xgboost)
-
-test_that("gblinear works", {
- data(agaricus.train, package='xgboost')
- data(agaricus.test, package='xgboost')
- dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
- dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-
- param <- list(objective = "binary:logistic", booster = "gblinear",
- nthread = 2, eta = 0.8, alpha = 0.0001, lambda = 0.0001)
- watchlist <- list(eval = dtest, train = dtrain)
-
- n <- 5 # iterations
- ERR_UL <- 0.005 # upper limit for the test set error
- VERB <- 0 # chatterbox switch
-
- param$updater = 'shotgun'
- bst <- xgb.train(param, dtrain, n, watchlist, verbose = VERB, feature_selector = 'shuffle')
- ypred <- predict(bst, dtest)
- expect_equal(length(getinfo(dtest, 'label')), 1611)
- expect_lt(bst$evaluation_log$eval_error[n], ERR_UL)
-
- bst <- xgb.train(param, dtrain, n, watchlist, verbose = VERB, feature_selector = 'cyclic',
- callbacks = list(cb.gblinear.history()))
- expect_lt(bst$evaluation_log$eval_error[n], ERR_UL)
- h <- xgb.gblinear.history(bst)
- expect_equal(dim(h), c(n, ncol(dtrain) + 1))
- expect_is(h, "matrix")
-
- param$updater = 'coord_descent'
- bst <- xgb.train(param, dtrain, n, watchlist, verbose = VERB, feature_selector = 'cyclic')
- expect_lt(bst$evaluation_log$eval_error[n], ERR_UL)
-
- bst <- xgb.train(param, dtrain, n, watchlist, verbose = VERB, feature_selector = 'shuffle')
- expect_lt(bst$evaluation_log$eval_error[n], ERR_UL)
-
- bst <- xgb.train(param, dtrain, 2, watchlist, verbose = VERB, feature_selector = 'greedy')
- expect_lt(bst$evaluation_log$eval_error[2], ERR_UL)
-
- bst <- xgb.train(param, dtrain, n, watchlist, verbose = VERB, feature_selector = 'thrifty',
- top_k = 50, callbacks = list(cb.gblinear.history(sparse = TRUE)))
- expect_lt(bst$evaluation_log$eval_error[n], ERR_UL)
- h <- xgb.gblinear.history(bst)
- expect_equal(dim(h), c(n, ncol(dtrain) + 1))
- expect_s4_class(h, "dgCMatrix")
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_helpers.R b/ml-xgboost/R-package/tests/testthat/test_helpers.R
deleted file mode 100644
index 5c14d53..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_helpers.R
+++ /dev/null
@@ -1,376 +0,0 @@
-context('Test helper functions')
-
-require(xgboost)
-require(data.table)
-require(Matrix)
-require(vcd, quietly = TRUE)
-
-float_tolerance = 5e-6
-
-# disable some tests for 32-bit environment
-flag_32bit = .Machine$sizeof.pointer != 8
-
-set.seed(1982)
-data(Arthritis)
-df <- data.table(Arthritis, keep.rownames = F)
-df[,AgeDiscret := as.factor(round(Age / 10,0))]
-df[,AgeCat := as.factor(ifelse(Age > 30, "Old", "Young"))]
-df[,ID := NULL]
-sparse_matrix <- sparse.model.matrix(Improved~.-1, data = df)
-label <- df[, ifelse(Improved == "Marked", 1, 0)]
-
-# binary
-nrounds <- 12
-bst.Tree <- xgboost(data = sparse_matrix, label = label, max_depth = 9,
- eta = 1, nthread = 2, nrounds = nrounds, verbose = 0,
- objective = "binary:logistic", booster = "gbtree")
-
-bst.GLM <- xgboost(data = sparse_matrix, label = label,
- eta = 1, nthread = 1, nrounds = nrounds, verbose = 0,
- objective = "binary:logistic", booster = "gblinear")
-
-feature.names <- colnames(sparse_matrix)
-
-# multiclass
-mlabel <- as.numeric(iris$Species) - 1
-nclass <- 3
-mbst.Tree <- xgboost(data = as.matrix(iris[, -5]), label = mlabel, verbose = 0,
- max_depth = 3, eta = 0.5, nthread = 2, nrounds = nrounds,
- objective = "multi:softprob", num_class = nclass, base_score = 0)
-
-mbst.GLM <- xgboost(data = as.matrix(iris[, -5]), label = mlabel, verbose = 0,
- booster = "gblinear", eta = 0.1, nthread = 1, nrounds = nrounds,
- objective = "multi:softprob", num_class = nclass, base_score = 0)
-
-
-test_that("xgb.dump works", {
- if (!flag_32bit)
- expect_length(xgb.dump(bst.Tree), 200)
- dump_file = file.path(tempdir(), 'xgb.model.dump')
- expect_true(xgb.dump(bst.Tree, dump_file, with_stats = T))
- expect_true(file.exists(dump_file))
- expect_gt(file.size(dump_file), 8000)
-
- # JSON format
- dmp <- xgb.dump(bst.Tree, dump_format = "json")
- expect_length(dmp, 1)
- if (!flag_32bit)
- expect_length(grep('nodeid', strsplit(dmp, '\n')[[1]]), 188)
-})
-
-test_that("xgb.dump works for gblinear", {
- expect_length(xgb.dump(bst.GLM), 14)
- # also make sure that it works properly for a sparse model where some coefficients
- # are 0 from setting large L1 regularization:
- bst.GLM.sp <- xgboost(data = sparse_matrix, label = label, eta = 1, nthread = 2, nrounds = 1,
- alpha=2, objective = "binary:logistic", booster = "gblinear")
- d.sp <- xgb.dump(bst.GLM.sp)
- expect_length(d.sp, 14)
- expect_gt(sum(d.sp == "0"), 0)
-
- # JSON format
- dmp <- xgb.dump(bst.GLM.sp, dump_format = "json")
- expect_length(dmp, 1)
- expect_length(grep('\\d', strsplit(dmp, '\n')[[1]]), 11)
-})
-
-test_that("predict leafs works", {
- # no error for gbtree
- expect_error(pred_leaf <- predict(bst.Tree, sparse_matrix, predleaf = TRUE), regexp = NA)
- expect_equal(dim(pred_leaf), c(nrow(sparse_matrix), nrounds))
- # error for gblinear
- expect_error(predict(bst.GLM, sparse_matrix, predleaf = TRUE))
-})
-
-test_that("predict feature contributions works", {
- # gbtree binary classifier
- expect_error(pred_contr <- predict(bst.Tree, sparse_matrix, predcontrib = TRUE), regexp = NA)
- expect_equal(dim(pred_contr), c(nrow(sparse_matrix), ncol(sparse_matrix) + 1))
- expect_equal(colnames(pred_contr), c(colnames(sparse_matrix), "BIAS"))
- pred <- predict(bst.Tree, sparse_matrix, outputmargin = TRUE)
- expect_lt(max(abs(rowSums(pred_contr) - pred)), 1e-5)
- # must work with data that has no column names
- X <- sparse_matrix
- colnames(X) <- NULL
- expect_error(pred_contr_ <- predict(bst.Tree, X, predcontrib = TRUE), regexp = NA)
- expect_equal(pred_contr, pred_contr_, check.attributes = FALSE,
- tolerance = float_tolerance)
-
- # gbtree binary classifier (approximate method)
- expect_error(pred_contr <- predict(bst.Tree, sparse_matrix, predcontrib = TRUE, approxcontrib = TRUE), regexp = NA)
- expect_equal(dim(pred_contr), c(nrow(sparse_matrix), ncol(sparse_matrix) + 1))
- expect_equal(colnames(pred_contr), c(colnames(sparse_matrix), "BIAS"))
- pred <- predict(bst.Tree, sparse_matrix, outputmargin = TRUE)
- expect_lt(max(abs(rowSums(pred_contr) - pred)), 1e-5)
-
- # gblinear binary classifier
- expect_error(pred_contr <- predict(bst.GLM, sparse_matrix, predcontrib = TRUE), regexp = NA)
- expect_equal(dim(pred_contr), c(nrow(sparse_matrix), ncol(sparse_matrix) + 1))
- expect_equal(colnames(pred_contr), c(colnames(sparse_matrix), "BIAS"))
- pred <- predict(bst.GLM, sparse_matrix, outputmargin = TRUE)
- expect_lt(max(abs(rowSums(pred_contr) - pred)), 1e-5)
- # manual calculation of linear terms
- coefs <- xgb.dump(bst.GLM)[-c(1,2,4)] %>% as.numeric
- coefs <- c(coefs[-1], coefs[1]) # intercept must be the last
- pred_contr_manual <- sweep(cbind(sparse_matrix, 1), 2, coefs, FUN="*")
- expect_equal(as.numeric(pred_contr), as.numeric(pred_contr_manual),
- tolerance = float_tolerance)
-
- # gbtree multiclass
- pred <- predict(mbst.Tree, as.matrix(iris[, -5]), outputmargin = TRUE, reshape = TRUE)
- pred_contr <- predict(mbst.Tree, as.matrix(iris[, -5]), predcontrib = TRUE)
- expect_is(pred_contr, "list")
- expect_length(pred_contr, 3)
- for (g in seq_along(pred_contr)) {
- expect_equal(colnames(pred_contr[[g]]), c(colnames(iris[, -5]), "BIAS"))
- expect_lt(max(abs(rowSums(pred_contr[[g]]) - pred[, g])), 1e-5)
- }
-
- # gblinear multiclass (set base_score = 0, which is base margin in multiclass)
- pred <- predict(mbst.GLM, as.matrix(iris[, -5]), outputmargin = TRUE, reshape = TRUE)
- pred_contr <- predict(mbst.GLM, as.matrix(iris[, -5]), predcontrib = TRUE)
- expect_length(pred_contr, 3)
- coefs_all <- xgb.dump(mbst.GLM)[-c(1,2,6)] %>% as.numeric %>% matrix(ncol = 3, byrow = TRUE)
- for (g in seq_along(pred_contr)) {
- expect_equal(colnames(pred_contr[[g]]), c(colnames(iris[, -5]), "BIAS"))
- expect_lt(max(abs(rowSums(pred_contr[[g]]) - pred[, g])), float_tolerance)
- # manual calculation of linear terms
- coefs <- c(coefs_all[-1, g], coefs_all[1, g]) # intercept needs to be the last
- pred_contr_manual <- sweep(as.matrix(cbind(iris[,-5], 1)), 2, coefs, FUN="*")
- expect_equal(as.numeric(pred_contr[[g]]), as.numeric(pred_contr_manual),
- tolerance = float_tolerance)
- }
-})
-
-test_that("SHAPs sum to predictions, with or without DART", {
- d <- cbind(
- x1 = rnorm(100),
- x2 = rnorm(100),
- x3 = rnorm(100))
- y <- d[,"x1"] + d[,"x2"]^2 +
- ifelse(d[,"x3"] > .5, d[,"x3"]^2, 2^d[,"x3"]) +
- rnorm(100)
- nrounds <- 30
-
- for (booster in list("gbtree", "dart")) {
- fit <- xgboost(
- params = c(
- list(
- booster = booster,
- objective = "reg:squarederror",
- eval_metric = "rmse"),
- if (booster == "dart")
- list(rate_drop = .01, one_drop = T)),
- data = d,
- label = y,
- nrounds = nrounds)
-
- pr <- function(...)
- predict(fit, newdata = d, ...)
- pred <- pr()
- shap <- pr(predcontrib = T)
- shapi <- pr(predinteraction = T)
- tol = 1e-5
-
- expect_equal(rowSums(shap), pred, tol = tol)
- expect_equal(apply(shapi, 1, sum), pred, tol = tol)
- for (i in 1 : nrow(d))
- for (f in list(rowSums, colSums))
- expect_equal(f(shapi[i,,]), shap[i,], tol = tol)
- }
-})
-
-test_that("xgb-attribute functionality", {
- val <- "my attribute value"
- list.val <- list(my_attr=val, a=123, b='ok')
- list.ch <- list.val[order(names(list.val))]
- list.ch <- lapply(list.ch, as.character)
- # note: iter is 0-index in xgb attributes
- list.default <- list(niter = as.character(nrounds - 1))
- list.ch <- c(list.ch, list.default)
- # proper input:
- expect_error(xgb.attr(bst.Tree, NULL))
- expect_error(xgb.attr(val, val))
- # set & get:
- expect_null(xgb.attr(bst.Tree, "asdf"))
- expect_equal(xgb.attributes(bst.Tree), list.default)
- xgb.attr(bst.Tree, "my_attr") <- val
- expect_equal(xgb.attr(bst.Tree, "my_attr"), val)
- xgb.attributes(bst.Tree) <- list.val
- expect_equal(xgb.attributes(bst.Tree), list.ch)
- # serializing:
- xgb.save(bst.Tree, 'xgb.model')
- bst <- xgb.load('xgb.model')
- if (file.exists('xgb.model')) file.remove('xgb.model')
- expect_equal(xgb.attr(bst, "my_attr"), val)
- expect_equal(xgb.attributes(bst), list.ch)
- # deletion:
- xgb.attr(bst, "my_attr") <- NULL
- expect_null(xgb.attr(bst, "my_attr"))
- expect_equal(xgb.attributes(bst), list.ch[c("a", "b", "niter")])
- xgb.attributes(bst) <- list(a=NULL, b=NULL)
- expect_equal(xgb.attributes(bst), list.default)
- xgb.attributes(bst) <- list(niter=NULL)
- expect_null(xgb.attributes(bst))
-})
-
-if (grepl('Windows', Sys.info()[['sysname']]) ||
- grepl('Linux', Sys.info()[['sysname']]) ||
- grepl('Darwin', Sys.info()[['sysname']])) {
- test_that("xgb-attribute numeric precision", {
- # check that lossless conversion works with 17 digits
- # numeric -> character -> numeric
- X <- 10^runif(100, -20, 20)
- if (capabilities('long.double')) {
- X2X <- as.numeric(format(X, digits = 17))
- expect_identical(X, X2X)
- }
- # retrieved attributes to be the same as written
- for (x in X) {
- xgb.attr(bst.Tree, "x") <- x
- expect_equal(as.numeric(xgb.attr(bst.Tree, "x")), x, tolerance = float_tolerance)
- xgb.attributes(bst.Tree) <- list(a = "A", b = x)
- expect_equal(as.numeric(xgb.attr(bst.Tree, "b")), x, tolerance = float_tolerance)
- }
- })
-}
-
-test_that("xgb.Booster serializing as R object works", {
- saveRDS(bst.Tree, 'xgb.model.rds')
- bst <- readRDS('xgb.model.rds')
- if (file.exists('xgb.model.rds')) file.remove('xgb.model.rds')
- dtrain <- xgb.DMatrix(sparse_matrix, label = label)
- expect_equal(predict(bst.Tree, dtrain), predict(bst, dtrain), tolerance = float_tolerance)
- expect_equal(xgb.dump(bst.Tree), xgb.dump(bst))
- xgb.save(bst, 'xgb.model')
- if (file.exists('xgb.model')) file.remove('xgb.model')
- nil_ptr <- new("externalptr")
- class(nil_ptr) <- "xgb.Booster.handle"
- expect_true(identical(bst$handle, nil_ptr))
- bst <- xgb.Booster.complete(bst)
- expect_true(!identical(bst$handle, nil_ptr))
- expect_equal(predict(bst.Tree, dtrain), predict(bst, dtrain), tolerance = float_tolerance)
-})
-
-test_that("xgb.model.dt.tree works with and without feature names", {
- names.dt.trees <- c("Tree", "Node", "ID", "Feature", "Split", "Yes", "No", "Missing", "Quality", "Cover")
- dt.tree <- xgb.model.dt.tree(feature_names = feature.names, model = bst.Tree)
- expect_equal(names.dt.trees, names(dt.tree))
- if (!flag_32bit)
- expect_equal(dim(dt.tree), c(188, 10))
- expect_output(str(dt.tree), 'Feature.*\\"Age\\"')
-
- dt.tree.0 <- xgb.model.dt.tree(model = bst.Tree)
- expect_equal(dt.tree, dt.tree.0)
-
- # when model contains no feature names:
- bst.Tree.x <- bst.Tree
- bst.Tree.x$feature_names <- NULL
- dt.tree.x <- xgb.model.dt.tree(model = bst.Tree.x)
- expect_output(str(dt.tree.x), 'Feature.*\\"3\\"')
- expect_equal(dt.tree[, -4, with=FALSE], dt.tree.x[, -4, with=FALSE])
-
- # using integer node ID instead of character
- dt.tree.int <- xgb.model.dt.tree(model = bst.Tree, use_int_id = TRUE)
- expect_equal(as.integer(tstrsplit(dt.tree$Yes, '-')[[2]]), dt.tree.int$Yes)
- expect_equal(as.integer(tstrsplit(dt.tree$No, '-')[[2]]), dt.tree.int$No)
- expect_equal(as.integer(tstrsplit(dt.tree$Missing, '-')[[2]]), dt.tree.int$Missing)
-})
-
-test_that("xgb.model.dt.tree throws error for gblinear", {
- expect_error(xgb.model.dt.tree(model = bst.GLM))
-})
-
-test_that("xgb.importance works with and without feature names", {
- importance.Tree <- xgb.importance(feature_names = feature.names, model = bst.Tree)
- if (!flag_32bit)
- expect_equal(dim(importance.Tree), c(7, 4))
- expect_equal(colnames(importance.Tree), c("Feature", "Gain", "Cover", "Frequency"))
- expect_output(str(importance.Tree), 'Feature.*\\"Age\\"')
-
- importance.Tree.0 <- xgb.importance(model = bst.Tree)
- expect_equal(importance.Tree, importance.Tree.0, tolerance = float_tolerance)
-
- # when model contains no feature names:
- bst.Tree.x <- bst.Tree
- bst.Tree.x$feature_names <- NULL
- importance.Tree.x <- xgb.importance(model = bst.Tree)
- expect_equal(importance.Tree[, -1, with=FALSE], importance.Tree.x[, -1, with=FALSE],
- tolerance = float_tolerance)
-
- imp2plot <- xgb.plot.importance(importance_matrix = importance.Tree)
- expect_equal(colnames(imp2plot), c("Feature", "Gain", "Cover", "Frequency", "Importance"))
- xgb.ggplot.importance(importance_matrix = importance.Tree)
-
- # for multiclass
- imp.Tree <- xgb.importance(model = mbst.Tree)
- expect_equal(dim(imp.Tree), c(4, 4))
- xgb.importance(model = mbst.Tree, trees = seq(from=0, by=nclass, length.out=nrounds))
-})
-
-test_that("xgb.importance works with GLM model", {
- importance.GLM <- xgb.importance(feature_names = feature.names, model = bst.GLM)
- expect_equal(dim(importance.GLM), c(10, 2))
- expect_equal(colnames(importance.GLM), c("Feature", "Weight"))
- xgb.importance(model = bst.GLM)
- imp2plot <- xgb.plot.importance(importance.GLM)
- expect_equal(colnames(imp2plot), c("Feature", "Weight", "Importance"))
- xgb.ggplot.importance(importance.GLM)
-
- # for multiclass
- imp.GLM <- xgb.importance(model = mbst.GLM)
- expect_equal(dim(imp.GLM), c(12, 3))
- expect_equal(imp.GLM$Class, rep(0:2, each=4))
-})
-
-test_that("xgb.model.dt.tree and xgb.importance work with a single split model", {
- bst1 <- xgboost(data = sparse_matrix, label = label, max_depth = 1,
- eta = 1, nthread = 2, nrounds = 1, verbose = 0,
- objective = "binary:logistic")
- expect_error(dt <- xgb.model.dt.tree(model = bst1), regexp = NA) # no error
- expect_equal(nrow(dt), 3)
- expect_error(imp <- xgb.importance(model = bst1), regexp = NA) # no error
- expect_equal(nrow(imp), 1)
- expect_equal(imp$Gain, 1)
-})
-
-test_that("xgb.plot.tree works with and without feature names", {
- xgb.plot.tree(feature_names = feature.names, model = bst.Tree)
- xgb.plot.tree(model = bst.Tree)
-})
-
-test_that("xgb.plot.multi.trees works with and without feature names", {
- xgb.plot.multi.trees(model = bst.Tree, feature_names = feature.names, features_keep = 3)
- xgb.plot.multi.trees(model = bst.Tree, features_keep = 3)
-})
-
-test_that("xgb.plot.deepness works", {
- d2p <- xgb.plot.deepness(model = bst.Tree)
- expect_equal(colnames(d2p), c("ID", "Tree", "Depth", "Cover", "Weight"))
- xgb.plot.deepness(model = bst.Tree, which = "med.depth")
- xgb.ggplot.deepness(model = bst.Tree)
-})
-
-test_that("xgb.plot.shap works", {
- sh <- xgb.plot.shap(data = sparse_matrix, model = bst.Tree, top_n = 2, col = 4)
- expect_equal(names(sh), c("data", "shap_contrib"))
- expect_equal(NCOL(sh$data), 2)
- expect_equal(NCOL(sh$shap_contrib), 2)
-})
-
-test_that("check.deprecation works", {
- ttt <- function(a = NNULL, DUMMY=NULL, ...) {
- check.deprecation(...)
- as.list((environment()))
- }
- res <- ttt(a = 1, DUMMY = 2, z = 3)
- expect_equal(res, list(a = 1, DUMMY = 2))
- expect_warning(
- res <- ttt(a = 1, dummy = 22, z = 3)
- , "\'dummy\' is deprecated")
- expect_equal(res, list(a = 1, DUMMY = 22))
- expect_warning(
- res <- ttt(a = 1, dumm = 22, z = 3)
- , "\'dumm\' was partially matched to \'dummy\'")
- expect_equal(res, list(a = 1, DUMMY = 22))
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_interaction_constraints.R b/ml-xgboost/R-package/tests/testthat/test_interaction_constraints.R
deleted file mode 100644
index 9a3ddf4..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_interaction_constraints.R
+++ /dev/null
@@ -1,55 +0,0 @@
-require(xgboost)
-
-context("interaction constraints")
-
-set.seed(1024)
-x1 <- rnorm(1000, 1)
-x2 <- rnorm(1000, 1)
-x3 <- sample(c(1,2,3), size=1000, replace=TRUE)
-y <- x1 + x2 + x3 + x1*x2*x3 + rnorm(1000, 0.001) + 3*sin(x1)
-train <- matrix(c(x1,x2,x3), ncol = 3)
-
-test_that("interaction constraints for regression", {
- # Fit a model that only allows interaction between x1 and x2
- bst <- xgboost(data = train, label = y, max_depth = 3,
- eta = 0.1, nthread = 2, nrounds = 100, verbose = 0,
- interaction_constraints = list(c(0,1)))
-
- # Set all observations to have the same x3 values then increment
- # by the same amount
- preds <- lapply(c(1,2,3), function(x){
- tmat <- matrix(c(x1,x2,rep(x,1000)), ncol=3)
- return(predict(bst, tmat))
- })
-
- # Check incrementing x3 has the same effect on all observations
- # since x3 is constrained to be independent of x1 and x2
- # and all observations start off from the same x3 value
- diff1 <- preds[[2]] - preds[[1]]
- test1 <- all(abs(diff1 - diff1[1]) < 1e-4)
-
- diff2 <- preds[[3]] - preds[[2]]
- test2 <- all(abs(diff2 - diff2[1]) < 1e-4)
-
- expect_true({
- test1 & test2
- }, "Interaction Contraint Satisfied")
-})
-
-test_that("interaction constraints scientific representation", {
- rows <- 10
- ## When number exceeds 1e5, R paste function uses scientific representation.
- ## See: https://github.com/dmlc/xgboost/issues/5179
- cols <- 1e5+10
-
- d <- matrix(rexp(rows, rate=.1), nrow=rows, ncol=cols)
- y <- rnorm(rows)
-
- dtrain <- xgb.DMatrix(data=d, info = list(label=y))
- inc <- list(c(seq.int(from = 0, to = cols, by = 1)))
-
- with_inc <- xgb.train(data=dtrain, tree_method='hist',
- interaction_constraints=inc, nrounds=10)
- without_inc <- xgb.train(data=dtrain, tree_method='hist', nrounds=10)
- expect_equal(xgb.save.raw(with_inc), xgb.save.raw(without_inc))
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_interactions.R b/ml-xgboost/R-package/tests/testthat/test_interactions.R
deleted file mode 100644
index 20ee90c..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_interactions.R
+++ /dev/null
@@ -1,141 +0,0 @@
-context('Test prediction of feature interactions')
-
-require(xgboost)
-require(magrittr)
-
-set.seed(123)
-
-test_that("predict feature interactions works", {
- # simulate some binary data and a linear outcome with an interaction term
- N <- 1000
- P <- 5
- X <- matrix(rbinom(N * P, 1, 0.5), ncol=P, dimnames = list(NULL, letters[1:P]))
- # center the data (as contributions are computed WRT feature means)
- X <- scale(X, scale=FALSE)
-
- # outcome without any interactions, without any noise:
- f <- function(x) 2 * x[, 1] - 3 * x[, 2]
- # outcome with interactions, without noise:
- f_int <- function(x) f(x) + 2 * x[, 2] * x[, 3]
- # outcome with interactions, with noise:
- #f_int_noise <- function(x) f_int(x) + rnorm(N, 0, 0.3)
-
- y <- f_int(X)
-
- dm <- xgb.DMatrix(X, label = y)
- param <- list(eta=0.1, max_depth=4, base_score=mean(y), lambda=0, nthread=2)
- b <- xgb.train(param, dm, 100)
-
- pred = predict(b, dm, outputmargin=TRUE)
-
- # SHAP contributions:
- cont <- predict(b, dm, predcontrib=TRUE)
- expect_equal(dim(cont), c(N, P+1))
- # make sure for each row they add up to marginal predictions
- max(abs(rowSums(cont) - pred)) %>% expect_lt(0.001)
- # Hand-construct the 'ground truth' feature contributions:
- gt_cont <- cbind(
- 2. * X[, 1],
- -3. * X[, 2] + 1. * X[, 2] * X[, 3], # attribute a HALF of the interaction term to feature #2
- 1. * X[, 2] * X[, 3] # and another HALF of the interaction term to feature #3
- )
- gt_cont <- cbind(gt_cont, matrix(0, nrow=N, ncol=P + 1 - 3))
- # These should be relatively close:
- expect_lt(max(abs(cont - gt_cont)), 0.05)
-
-
- # SHAP interaction contributions:
- intr <- predict(b, dm, predinteraction=TRUE)
- expect_equal(dim(intr), c(N, P+1, P+1))
- # check assigned colnames
- cn <- c(letters[1:P], "BIAS")
- expect_equal(dimnames(intr), list(NULL, cn, cn))
-
- # check the symmetry
- max(abs(aperm(intr, c(1,3,2)) - intr)) %>% expect_lt(0.00001)
-
- # sums WRT columns must be close to feature contributions
- max(abs(apply(intr, c(1,2), sum) - cont)) %>% expect_lt(0.00001)
-
- # diagonal terms for features 3,4,5 must be close to zero
- Reduce(max, sapply(3:P, function(i) max(abs(intr[, i, i])))) %>% expect_lt(0.05)
-
- # BIAS must have no interactions
- max(abs(intr[, 1:P, P+1])) %>% expect_lt(0.00001)
-
- # interactions other than 2 x 3 must be close to zero
- intr23 <- intr
- intr23[,2,3] <- 0
- Reduce(max, sapply(1:P, function(i) max(abs(intr23[, i, (i+1):(P+1)])))) %>% expect_lt(0.05)
-
- # Construct the 'ground truth' contributions of interactions directly from the linear terms:
- gt_intr <- array(0, c(N, P+1, P+1))
- gt_intr[,2,3] <- 1. * X[, 2] * X[, 3] # attribute a HALF of the interaction term to each symmetric element
- gt_intr[,3,2] <- gt_intr[, 2, 3]
- # merge-in the diagonal based on 'ground truth' feature contributions
- intr_diag = gt_cont - apply(gt_intr, c(1,2), sum)
- for(j in seq_len(P)) {
- gt_intr[,j,j] = intr_diag[,j]
- }
- # These should be relatively close:
- expect_lt(max(abs(intr - gt_intr)), 0.1)
-})
-
-test_that("SHAP contribution values are not NAN", {
- d <- data.frame(
- x1 = c(-2.3, 1.4, 5.9, 2, 2.5, 0.3, -3.6, -0.2, 0.5, -2.8, -4.6, 3.3, -1.2,
- -1.1, -2.3, 0.4, -1.5, -0.2, -1, 3.7),
- x2 = c(291.179171, 269.198331, 289.942097, 283.191669, 269.673332,
- 294.158346, 287.255835, 291.530838, 285.899586, 269.290833,
- 268.649586, 291.530841, 280.074593, 269.484168, 293.94042,
- 294.327506, 296.20709, 295.441669, 283.16792, 270.227085),
- y = c(9, 15, 5.7, 9.2, 22.4, 5, 9, 3.2, 7.2, 13.1, 7.8, 16.9, 6.5, 22.1,
- 5.3, 10.4, 11.1, 13.9, 11, 20.5),
- fold = c(2, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2))
-
- ivs <- c("x1", "x2")
-
- fit <- xgboost(
- verbose = 0,
- params = list(
- objective = "reg:squarederror",
- eval_metric = "rmse"),
- data = as.matrix(subset(d, fold == 2)[, ivs]),
- label = subset(d, fold == 2)$y,
- nthread = 1,
- nrounds = 3)
-
- shaps <- as.data.frame(predict(fit,
- newdata = as.matrix(subset(d, fold == 1)[, ivs]),
- predcontrib = T))
- result <- cbind(shaps, sum = rowSums(shaps), pred = predict(fit,
- newdata = as.matrix(subset(d, fold == 1)[, ivs])))
-
- expect_true(identical(TRUE, all.equal(result$sum, result$pred, tol = 1e-6)))
-})
-
-
-test_that("multiclass feature interactions work", {
- dm <- xgb.DMatrix(as.matrix(iris[,-5]), label=as.numeric(iris$Species)-1)
- param <- list(eta=0.1, max_depth=4, objective='multi:softprob', num_class=3)
- b <- xgb.train(param, dm, 40)
- pred = predict(b, dm, outputmargin=TRUE) %>% array(c(3, 150)) %>% t
-
- # SHAP contributions:
- cont <- predict(b, dm, predcontrib=TRUE)
- expect_length(cont, 3)
- # rewrap them as a 3d array
- cont <- unlist(cont) %>% array(c(150, 5, 3))
- # make sure for each row they add up to marginal predictions
- max(abs(apply(cont, c(1,3), sum) - pred)) %>% expect_lt(0.001)
-
- # SHAP interaction contributions:
- intr <- predict(b, dm, predinteraction=TRUE)
- expect_length(intr, 3)
- # rewrap them as a 4d array
- intr <- unlist(intr) %>% array(c(150, 5, 5, 3)) %>% aperm(c(4, 1, 2, 3)) # [grp, row, col, col]
- # check the symmetry
- max(abs(aperm(intr, c(1,2,4,3)) - intr)) %>% expect_lt(0.00001)
- # sums WRT columns must be close to feature contributions
- max(abs(apply(intr, c(1,2,3), sum) - aperm(cont, c(3,1,2)))) %>% expect_lt(0.00001)
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_lint.R b/ml-xgboost/R-package/tests/testthat/test_lint.R
deleted file mode 100644
index 2f2a07d..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_lint.R
+++ /dev/null
@@ -1,27 +0,0 @@
-context("Code is of high quality and lint free")
-test_that("Code Lint", {
- skip_on_cran()
- skip_on_travis()
- skip_if_not_installed("lintr")
- my_linters <- list(
- absolute_paths_linter=lintr::absolute_paths_linter,
- assignment_linter=lintr::assignment_linter,
- closed_curly_linter=lintr::closed_curly_linter,
- commas_linter=lintr::commas_linter,
- # commented_code_linter=lintr::commented_code_linter,
- infix_spaces_linter=lintr::infix_spaces_linter,
- line_length_linter=lintr::line_length_linter,
- no_tab_linter=lintr::no_tab_linter,
- object_usage_linter=lintr::object_usage_linter,
- # snake_case_linter=lintr::snake_case_linter,
- # multiple_dots_linter=lintr::multiple_dots_linter,
- object_length_linter=lintr::object_length_linter,
- open_curly_linter=lintr::open_curly_linter,
- # single_quotes_linter=lintr::single_quotes_linter,
- spaces_inside_linter=lintr::spaces_inside_linter,
- spaces_left_parentheses_linter=lintr::spaces_left_parentheses_linter,
- trailing_blank_lines_linter=lintr::trailing_blank_lines_linter,
- trailing_whitespace_linter=lintr::trailing_whitespace_linter
- )
- # lintr::expect_lint_free(linters=my_linters) # uncomment this if you want to check code quality
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_monotone.R b/ml-xgboost/R-package/tests/testthat/test_monotone.R
deleted file mode 100644
index 9991e91..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_monotone.R
+++ /dev/null
@@ -1,24 +0,0 @@
-require(xgboost)
-
-context("monotone constraints")
-
-set.seed(1024)
-x = rnorm(1000, 10)
-y = -1*x + rnorm(1000, 0.001) + 3*sin(x)
-train = matrix(x, ncol = 1)
-
-
-test_that("monotone constraints for regression", {
- bst = xgboost(data = train, label = y, max_depth = 2,
- eta = 0.1, nthread = 2, nrounds = 100, verbose = 0,
- monotone_constraints = -1)
-
- pred = predict(bst, train)
-
- ind = order(train[,1])
- pred.ord = pred[ind]
- expect_true({
- !any(diff(pred.ord) > 0)
- }, "Monotone Contraint Satisfied")
-
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_parameter_exposure.R b/ml-xgboost/R-package/tests/testthat/test_parameter_exposure.R
deleted file mode 100644
index 1a0dcb3..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_parameter_exposure.R
+++ /dev/null
@@ -1,30 +0,0 @@
-context('Test model params and call are exposed to R')
-
-require(xgboost)
-
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-
-bst <- xgboost(data = dtrain,
- max_depth = 2,
- eta = 1,
- nrounds = 10,
- nthread = 1,
- verbose = 0,
- objective = "binary:logistic")
-
-test_that("call is exposed to R", {
- expect_false(is.null(bst$call))
- expect_is(bst$call, "call")
-})
-
-test_that("params is exposed to R", {
- model_params <- bst$params
- expect_is(model_params, "list")
- expect_equal(model_params$eta, 1)
- expect_equal(model_params$max_depth, 2)
- expect_equal(model_params$objective, "binary:logistic")
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_poisson_regression.R b/ml-xgboost/R-package/tests/testthat/test_poisson_regression.R
deleted file mode 100644
index a48f2fc..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_poisson_regression.R
+++ /dev/null
@@ -1,14 +0,0 @@
-context('Test poisson regression model')
-
-require(xgboost)
-set.seed(1994)
-
-test_that("poisson regression works", {
- data(mtcars)
- bst <- xgboost(data = as.matrix(mtcars[,-11]), label = mtcars[,11],
- objective = 'count:poisson', nrounds=10, verbose=0)
- expect_equal(class(bst), "xgb.Booster")
- pred <- predict(bst, as.matrix(mtcars[, -11]))
- expect_equal(length(pred), 32)
- expect_lt(sqrt(mean( (pred - mtcars[,11])^2 )), 1.2)
-})
diff --git a/ml-xgboost/R-package/tests/testthat/test_update.R b/ml-xgboost/R-package/tests/testthat/test_update.R
deleted file mode 100644
index fa48c91..0000000
--- a/ml-xgboost/R-package/tests/testthat/test_update.R
+++ /dev/null
@@ -1,107 +0,0 @@
-require(xgboost)
-
-context("update trees in an existing model")
-
-data(agaricus.train, package = 'xgboost')
-data(agaricus.test, package = 'xgboost')
-dtrain <- xgb.DMatrix(agaricus.train$data, label = agaricus.train$label)
-dtest <- xgb.DMatrix(agaricus.test$data, label = agaricus.test$label)
-
-# Disable flaky tests for 32-bit Windows.
-# See https://github.com/dmlc/xgboost/issues/3720
-win32_flag = .Platform$OS.type == "windows" && .Machine$sizeof.pointer != 8
-
-test_that("updating the model works", {
- watchlist = list(train = dtrain, test = dtest)
-
- # no-subsampling
- p1 <- list(objective = "binary:logistic", max_depth = 2, eta = 0.05, nthread = 2)
- set.seed(11)
- bst1 <- xgb.train(p1, dtrain, nrounds = 10, watchlist, verbose = 0)
- tr1 <- xgb.model.dt.tree(model = bst1)
-
- # with subsampling
- p2 <- modifyList(p1, list(subsample = 0.1))
- set.seed(11)
- bst2 <- xgb.train(p2, dtrain, nrounds = 10, watchlist, verbose = 0)
- tr2 <- xgb.model.dt.tree(model = bst2)
-
- # the same no-subsampling boosting with an extra 'refresh' updater:
- p1r <- modifyList(p1, list(updater = 'grow_colmaker,prune,refresh', refresh_leaf = FALSE))
- set.seed(11)
- bst1r <- xgb.train(p1r, dtrain, nrounds = 10, watchlist, verbose = 0)
- tr1r <- xgb.model.dt.tree(model = bst1r)
- # all should be the same when no subsampling
- expect_equal(bst1$evaluation_log, bst1r$evaluation_log)
- if (!win32_flag) {
- expect_equal(tr1, tr1r, tolerance = 0.00001, check.attributes = FALSE)
- }
-
- # the same boosting with subsampling with an extra 'refresh' updater:
- p2r <- modifyList(p2, list(updater = 'grow_colmaker,prune,refresh', refresh_leaf = FALSE))
- set.seed(11)
- bst2r <- xgb.train(p2r, dtrain, nrounds = 10, watchlist, verbose = 0)
- tr2r <- xgb.model.dt.tree(model = bst2r)
- # should be the same evaluation but different gains and larger cover
- expect_equal(bst2$evaluation_log, bst2r$evaluation_log)
- if (!win32_flag) {
- expect_equal(tr2[Feature == 'Leaf']$Quality, tr2r[Feature == 'Leaf']$Quality)
- }
- expect_gt(sum(abs(tr2[Feature != 'Leaf']$Quality - tr2r[Feature != 'Leaf']$Quality)), 100)
- expect_gt(sum(tr2r$Cover) / sum(tr2$Cover), 1.5)
-
- # process type 'update' for no-subsampling model, refreshing the tree stats AND leaves from training data:
- p1u <- modifyList(p1, list(process_type = 'update', updater = 'refresh', refresh_leaf = TRUE))
- bst1u <- xgb.train(p1u, dtrain, nrounds = 10, watchlist, verbose = 0, xgb_model = bst1)
- tr1u <- xgb.model.dt.tree(model = bst1u)
- # all should be the same when no subsampling
- expect_equal(bst1$evaluation_log, bst1u$evaluation_log)
- expect_equal(tr1, tr1u, tolerance = 0.00001, check.attributes = FALSE)
-
- # process type 'update' for model with subsampling, refreshing only the tree stats from training data:
- p2u <- modifyList(p2, list(process_type = 'update', updater = 'refresh', refresh_leaf = FALSE))
- bst2u <- xgb.train(p2u, dtrain, nrounds = 10, watchlist, verbose = 0, xgb_model = bst2)
- tr2u <- xgb.model.dt.tree(model = bst2u)
- # should be the same evaluation but different gains and larger cover
- expect_equal(bst2$evaluation_log, bst2u$evaluation_log)
- expect_equal(tr2[Feature == 'Leaf']$Quality, tr2u[Feature == 'Leaf']$Quality)
- expect_gt(sum(abs(tr2[Feature != 'Leaf']$Quality - tr2u[Feature != 'Leaf']$Quality)), 100)
- expect_gt(sum(tr2u$Cover) / sum(tr2$Cover), 1.5)
- # the results should be the same as for the model with an extra 'refresh' updater
- expect_equal(bst2r$evaluation_log, bst2u$evaluation_log)
- if (!win32_flag) {
- expect_equal(tr2r, tr2u, tolerance = 0.00001, check.attributes = FALSE)
- }
-
- # process type 'update' for no-subsampling model, refreshing only the tree stats from TEST data:
- p1ut <- modifyList(p1, list(process_type = 'update', updater = 'refresh', refresh_leaf = FALSE))
- bst1ut <- xgb.train(p1ut, dtest, nrounds = 10, watchlist, verbose = 0, xgb_model = bst1)
- tr1ut <- xgb.model.dt.tree(model = bst1ut)
- # should be the same evaluations but different gains and smaller cover (test data is smaller)
- expect_equal(bst1$evaluation_log, bst1ut$evaluation_log)
- expect_equal(tr1[Feature == 'Leaf']$Quality, tr1ut[Feature == 'Leaf']$Quality)
- expect_gt(sum(abs(tr1[Feature != 'Leaf']$Quality - tr1ut[Feature != 'Leaf']$Quality)), 100)
- expect_lt(sum(tr1ut$Cover) / sum(tr1$Cover), 0.5)
-})
-
-test_that("updating works for multiclass & multitree", {
- dtr <- xgb.DMatrix(as.matrix(iris[, -5]), label = as.numeric(iris$Species) - 1)
- watchlist <- list(train = dtr)
- p0 <- list(max_depth = 2, eta = 0.5, nthread = 2, subsample = 0.6,
- objective = "multi:softprob", num_class = 3, num_parallel_tree = 2,
- base_score = 0)
- set.seed(121)
- bst0 <- xgb.train(p0, dtr, 5, watchlist, verbose = 0)
- tr0 <- xgb.model.dt.tree(model = bst0)
-
- # run update process for an original model with subsampling
- p0u <- modifyList(p0, list(process_type='update', updater='refresh', refresh_leaf=FALSE))
- bst0u <- xgb.train(p0u, dtr, nrounds = bst0$niter, watchlist, xgb_model = bst0, verbose = 0)
- tr0u <- xgb.model.dt.tree(model = bst0u)
-
- # should be the same evaluation but different gains and larger cover
- expect_equal(bst0$evaluation_log, bst0u$evaluation_log)
- expect_equal(tr0[Feature == 'Leaf']$Quality, tr0u[Feature == 'Leaf']$Quality)
- expect_gt(sum(abs(tr0[Feature != 'Leaf']$Quality - tr0u[Feature != 'Leaf']$Quality)), 100)
- expect_gt(sum(tr0u$Cover) / sum(tr0$Cover), 1.5)
-})
diff --git a/ml-xgboost/R-package/vignettes/discoverYourData.Rmd b/ml-xgboost/R-package/vignettes/discoverYourData.Rmd
deleted file mode 100644
index 67b7340..0000000
--- a/ml-xgboost/R-package/vignettes/discoverYourData.Rmd
+++ /dev/null
@@ -1,338 +0,0 @@
----
-title: "Understand your dataset with Xgboost"
-output:
- rmarkdown::html_vignette:
- css: vignette.css
- number_sections: yes
- toc: yes
-author: Tianqi Chen, Tong He, Michaël Benesty, Yuan Tang
-vignette: >
- %\VignetteIndexEntry{Discover your data}
- %\VignetteEngine{knitr::rmarkdown}
- \usepackage[utf8]{inputenc}
----
-
-Understand your dataset with XGBoost
-====================================
-
-Introduction
-------------
-
-The purpose of this vignette is to show you how to use **Xgboost** to discover and understand your own dataset better.
-
-This vignette is not about predicting anything (see [Xgboost presentation](https://github.com/dmlc/xgboost/blob/master/R-package/vignettes/xgboostPresentation.Rmd)). We will explain how to use **Xgboost** to highlight the *link* between the *features* of your data and the *outcome*.
-
-Package loading:
-
-```{r libLoading, results='hold', message=F, warning=F}
-require(xgboost)
-require(Matrix)
-require(data.table)
-if (!require('vcd')) install.packages('vcd')
-```
-
-> **VCD** package is used for one of its embedded dataset only.
-
-Preparation of the dataset
---------------------------
-
-### Numeric v.s. categorical variables
-
-
-**Xgboost** manages only `numeric` vectors.
-
-What to do when you have *categorical* data?
-
-A *categorical* variable has a fixed number of different values. For instance, if a variable called *Colour* can have only one of these three values, *red*, *blue* or *green*, then *Colour* is a *categorical* variable.
-
-> In **R**, a *categorical* variable is called `factor`.
->
-> Type `?factor` in the console for more information.
-
-To answer the question above we will convert *categorical* variables to `numeric` one.
-
-### Conversion from categorical to numeric variables
-
-#### Looking at the raw data
-
-In this Vignette we will see how to transform a *dense* `data.frame` (*dense* = few zeroes in the matrix) with *categorical* variables to a very *sparse* matrix (*sparse* = lots of zero in the matrix) of `numeric` features.
-
-The method we are going to see is usually called [one-hot encoding](http://en.wikipedia.org/wiki/One-hot).
-
-The first step is to load `Arthritis` dataset in memory and wrap it with `data.table` package.
-
-```{r, results='hide'}
-data(Arthritis)
-df <- data.table(Arthritis, keep.rownames = F)
-```
-
-> `data.table` is 100% compliant with **R** `data.frame` but its syntax is more consistent and its performance for large dataset is [best in class](http://stackoverflow.com/questions/21435339/data-table-vs-dplyr-can-one-do-something-well-the-other-cant-or-does-poorly) (`dplyr` from **R** and `Pandas` from **Python** [included](https://github.com/Rdatatable/data.table/wiki/Benchmarks-%3A-Grouping)). Some parts of **Xgboost** **R** package use `data.table`.
-
-The first thing we want to do is to have a look to the first few lines of the `data.table`:
-
-```{r}
-head(df)
-```
-
-Now we will check the format of each column.
-
-```{r}
-str(df)
-```
-
-2 columns have `factor` type, one has `ordinal` type.
-
-> `ordinal` variable :
->
-> * can take a limited number of values (like `factor`) ;
-> * these values are ordered (unlike `factor`). Here these ordered values are: `Marked > Some > None`
-
-#### Creation of new features based on old ones
-
-We will add some new *categorical* features to see if it helps.
-
-##### Grouping per 10 years
-
-For the first feature we create groups of age by rounding the real age.
-
-Note that we transform it to `factor` so the algorithm treat these age groups as independent values.
-
-Therefore, 20 is not closer to 30 than 60. To make it short, the distance between ages is lost in this transformation.
-
-```{r}
-head(df[,AgeDiscret := as.factor(round(Age/10,0))])
-```
-
-##### Random split into two groups
-
-Following is an even stronger simplification of the real age with an arbitrary split at 30 years old. We choose this value **based on nothing**. We will see later if simplifying the information based on arbitrary values is a good strategy (you may already have an idea of how well it will work...).
-
-```{r}
-head(df[,AgeCat:= as.factor(ifelse(Age > 30, "Old", "Young"))])
-```
-
-##### Risks in adding correlated features
-
-These new features are highly correlated to the `Age` feature because they are simple transformations of this feature.
-
-For many machine learning algorithms, using correlated features is not a good idea. It may sometimes make prediction less accurate, and most of the time make interpretation of the model almost impossible. GLM, for instance, assumes that the features are uncorrelated.
-
-Fortunately, decision tree algorithms (including boosted trees) are very robust to these features. Therefore we have nothing to do to manage this situation.
-
-##### Cleaning data
-
-We remove ID as there is nothing to learn from this feature (it would just add some noise).
-
-```{r, results='hide'}
-df[,ID:=NULL]
-```
-
-We will list the different values for the column `Treatment`:
-
-```{r}
-levels(df[,Treatment])
-```
-
-
-#### Encoding categorical features
-
-Next step, we will transform the categorical data to dummy variables.
-Several encoding methods exist, e.g., [one-hot encoding](http://en.wikipedia.org/wiki/One-hot) is a common approach.
-We will use the [dummy contrast coding](http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm#dummy) which is popular because it produces "full rank" encoding (also see [this blog post by Max Kuhn](http://appliedpredictivemodeling.com/blog/2013/10/23/the-basics-of-encoding-categorical-data-for-predictive-models)).
-
-The purpose is to transform each value of each *categorical* feature into a *binary* feature `{0, 1}`.
-
-For example, the column `Treatment` will be replaced by two columns, `TreatmentPlacebo`, and `TreatmentTreated`. Each of them will be *binary*. Therefore, an observation which has the value `Placebo` in column `Treatment` before the transformation will have after the transformation the value `1` in the new column `TreatmentPlacebo` and the value `0` in the new column `TreatmentTreated`. The column `TreatmentPlacebo` will disappear during the contrast encoding, as it would be absorbed into a common constant intercept column.
-
-Column `Improved` is excluded because it will be our `label` column, the one we want to predict.
-
-```{r, warning=FALSE,message=FALSE}
-sparse_matrix <- sparse.model.matrix(Improved ~ ., data = df)[,-1]
-head(sparse_matrix)
-```
-
-> Formula `Improved ~ .` used above means transform all *categorical* features but column `Improved` to binary values. The `-1` column selection removes the intercept column which is full of `1` (this column is generated by the conversion). For more information, you can type `?sparse.model.matrix` in the console.
-
-Create the output `numeric` vector (not as a sparse `Matrix`):
-
-```{r}
-output_vector = df[,Improved] == "Marked"
-```
-
-1. set `Y` vector to `0`;
-2. set `Y` to `1` for rows where `Improved == Marked` is `TRUE` ;
-3. return `Y` vector.
-
-Build the model
----------------
-
-The code below is very usual. For more information, you can look at the documentation of `xgboost` function (or at the vignette [Xgboost presentation](https://github.com/dmlc/xgboost/blob/master/R-package/vignettes/xgboostPresentation.Rmd)).
-
-```{r}
-bst <- xgboost(data = sparse_matrix, label = output_vector, max_depth = 4,
- eta = 1, nthread = 2, nrounds = 10,objective = "binary:logistic")
-
-```
-
-You can see some `train-error: 0.XXXXX` lines followed by a number. It decreases. Each line shows how well the model explains your data. Lower is better.
-
-A model which fits too well may [overfit](http://en.wikipedia.org/wiki/Overfitting) (meaning it copy/paste too much the past, and won't be that good to predict the future).
-
-> Here you can see the numbers decrease until line 7 and then increase.
->
-> It probably means we are overfitting. To fix that I should reduce the number of rounds to `nrounds = 4`. I will let things like that because I don't really care for the purpose of this example :-)
-
-Feature importance
-------------------
-
-## Measure feature importance
-
-
-### Build the feature importance data.table
-
-Remember, each binary column corresponds to a single value of one of *categorical* features.
-
-```{r}
-importance <- xgb.importance(feature_names = colnames(sparse_matrix), model = bst)
-head(importance)
-```
-
-> The column `Gain` provide the information we are looking for.
->
-> As you can see, features are classified by `Gain`.
-
-`Gain` is the improvement in accuracy brought by a feature to the branches it is on. The idea is that before adding a new split on a feature X to the branch there was some wrongly classified elements, after adding the split on this feature, there are two new branches, and each of these branch is more accurate (one branch saying if your observation is on this branch then it should be classified as `1`, and the other branch saying the exact opposite).
-
-`Cover` measures the relative quantity of observations concerned by a feature.
-
-`Frequency` is a simpler way to measure the `Gain`. It just counts the number of times a feature is used in all generated trees. You should not use it (unless you know why you want to use it).
-
-#### Improvement in the interpretability of feature importance data.table
-
-We can go deeper in the analysis of the model. In the `data.table` above, we have discovered which features counts to predict if the illness will go or not. But we don't yet know the role of these features. For instance, one of the question we may want to answer would be: does receiving a placebo treatment helps to recover from the illness?
-
-One simple solution is to count the co-occurrences of a feature and a class of the classification.
-
-For that purpose we will execute the same function as above but using two more parameters, `data` and `label`.
-
-```{r}
-importanceRaw <- xgb.importance(feature_names = colnames(sparse_matrix), model = bst, data = sparse_matrix, label = output_vector)
-
-# Cleaning for better display
-importanceClean <- importanceRaw[,`:=`(Cover=NULL, Frequency=NULL)]
-
-head(importanceClean)
-```
-
-> In the table above we have removed two not needed columns and select only the first lines.
-
-First thing you notice is the new column `Split`. It is the split applied to the feature on a branch of one of the tree. Each split is present, therefore a feature can appear several times in this table. Here we can see the feature `Age` is used several times with different splits.
-
-How the split is applied to count the co-occurrences? It is always `<`. For instance, in the second line, we measure the number of persons under 61.5 years with the illness gone after the treatment.
-
-The two other new columns are `RealCover` and `RealCover %`. In the first column it measures the number of observations in the dataset where the split is respected and the label marked as `1`. The second column is the percentage of the whole population that `RealCover` represents.
-
-Therefore, according to our findings, getting a placebo doesn't seem to help but being younger than 61 years may help (seems logic).
-
-> You may wonder how to interpret the `< 1.00001` on the first line. Basically, in a sparse `Matrix`, there is no `0`, therefore, looking for one hot-encoded categorical observations validating the rule `< 1.00001` is like just looking for `1` for this feature.
-
-### Plotting the feature importance
-
-
-All these things are nice, but it would be even better to plot the results.
-
-```{r, fig.width=8, fig.height=5, fig.align='center'}
-xgb.plot.importance(importance_matrix = importance)
-```
-
-Feature have automatically been divided in 2 clusters: the interesting features... and the others.
-
-> Depending of the dataset and the learning parameters you may have more than two clusters. Default value is to limit them to `10`, but you can increase this limit. Look at the function documentation for more information.
-
-According to the plot above, the most important features in this dataset to predict if the treatment will work are :
-
-* the Age ;
-* having received a placebo or not ;
-* the sex is third but already included in the not interesting features group ;
-* then we see our generated features (AgeDiscret). We can see that their contribution is very low.
-
-### Do these results make sense?
-
-
-Let's check some **Chi2** between each of these features and the label.
-
-Higher **Chi2** means better correlation.
-
-```{r, warning=FALSE, message=FALSE}
-c2 <- chisq.test(df$Age, output_vector)
-print(c2)
-```
-
-Pearson correlation between Age and illness disappearing is **`r round(c2$statistic, 2 )`**.
-
-```{r, warning=FALSE, message=FALSE}
-c2 <- chisq.test(df$AgeDiscret, output_vector)
-print(c2)
-```
-
-Our first simplification of Age gives a Pearson correlation is **`r round(c2$statistic, 2)`**.
-
-```{r, warning=FALSE, message=FALSE}
-c2 <- chisq.test(df$AgeCat, output_vector)
-print(c2)
-```
-
-The perfectly random split I did between young and old at 30 years old have a low correlation of **`r round(c2$statistic, 2)`**. It's a result we may expect as may be in my mind > 30 years is being old (I am 32 and starting feeling old, this may explain that), but for the illness we are studying, the age to be vulnerable is not the same.
-
-Morality: don't let your *gut* lower the quality of your model.
-
-In *data science* expression, there is the word *science* :-)
-
-Conclusion
-----------
-
-As you can see, in general *destroying information by simplifying it won't improve your model*. **Chi2** just demonstrates that.
-
-But in more complex cases, creating a new feature based on existing one which makes link with the outcome more obvious may help the algorithm and improve the model.
-
-The case studied here is not enough complex to show that. Check [Kaggle website](http://www.kaggle.com/) for some challenging datasets. However it's almost always worse when you add some arbitrary rules.
-
-Moreover, you can notice that even if we have added some not useful new features highly correlated with other features, the boosting tree algorithm have been able to choose the best one, which in this case is the Age.
-
-Linear model may not be that smart in this scenario.
-
-Special Note: What about Random Forests™?
------------------------------------------
-
-As you may know, [Random Forests™](http://en.wikipedia.org/wiki/Random_forest) algorithm is cousin with boosting and both are part of the [ensemble learning](http://en.wikipedia.org/wiki/Ensemble_learning) family.
-
-Both trains several decision trees for one dataset. The *main* difference is that in Random Forests™, trees are independent and in boosting, the tree `N+1` focus its learning on the loss (<=> what has not been well modeled by the tree `N`).
-
-This difference have an impact on a corner case in feature importance analysis: the *correlated features*.
-
-Imagine two features perfectly correlated, feature `A` and feature `B`. For one specific tree, if the algorithm needs one of them, it will choose randomly (true in both boosting and Random Forests™).
-
-However, in Random Forests™ this random choice will be done for each tree, because each tree is independent from the others. Therefore, approximatively, depending of your parameters, 50% of the trees will choose feature `A` and the other 50% will choose feature `B`. So the *importance* of the information contained in `A` and `B` (which is the same, because they are perfectly correlated) is diluted in `A` and `B`. So you won't easily know this information is important to predict what you want to predict! It is even worse when you have 10 correlated features...
-
-In boosting, when a specific link between feature and outcome have been learned by the algorithm, it will try to not refocus on it (in theory it is what happens, reality is not always that simple). Therefore, all the importance will be on feature `A` or on feature `B` (but not both). You will know that one feature have an important role in the link between the observations and the label. It is still up to you to search for the correlated features to the one detected as important if you need to know all of them.
-
-If you want to try Random Forests™ algorithm, you can tweak Xgboost parameters!
-
-For instance, to compute a model with 1000 trees, with a 0.5 factor on sampling rows and columns:
-
-```{r, warning=FALSE, message=FALSE}
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-
-#Random Forest™ - 1000 trees
-bst <- xgboost(data = train$data, label = train$label, max_depth = 4, num_parallel_tree = 1000, subsample = 0.5, colsample_bytree =0.5, nrounds = 1, objective = "binary:logistic")
-
-#Boosting - 3 rounds
-bst <- xgboost(data = train$data, label = train$label, max_depth = 4, nrounds = 3, objective = "binary:logistic")
-```
-
-> Note that the parameter `round` is set to `1`.
-
-> [**Random Forests™**](https://www.stat.berkeley.edu/~breiman/RandomForests/cc_papers.htm) is a trademark of Leo Breiman and Adele Cutler and is licensed exclusively to Salford Systems for the commercial release of the software.
diff --git a/ml-xgboost/R-package/vignettes/vignette.css b/ml-xgboost/R-package/vignettes/vignette.css
deleted file mode 100644
index 59dfcd8..0000000
--- a/ml-xgboost/R-package/vignettes/vignette.css
+++ /dev/null
@@ -1,225 +0,0 @@
-body {
- margin: 0 auto;
- background-color: white;
-
-/* --------- FONT FAMILY --------
- following are some optional font families. Usually a family
- is safer to choose than a specific font,
- which may not be on the users computer */
-/ font-family:Georgia, Palatino, serif;
- font-family: "Open Sans", "Book Antiqua", Palatino, serif;
-/ font-family:Arial, Helvetica, sans-serif;
-/ font-family:Tahoma, Verdana, Geneva, sans-serif;
-/ font-family:Courier, monospace;
-/ font-family:"Times New Roman", Times, serif;
-
-/* -------------- COLOR OPTIONS ------------
- following are additional color options for base font
- you could uncomment another one to easily change the base color
- or add one to a specific element style below */
- color: #333333; /* dark gray not black */
-/ color: #000000; /* black */
-/ color: #666666; /* medium gray black */
-/ color: #E3E3E3; /* very light gray */
-/ color: white;
-
- line-height: 100%;
- max-width: 800px;
- padding: 10px;
- font-size: 17px;
- text-align: justify;
- text-justify: inter-word;
-}
-
-
-p {
- line-height: 150%;
-/ max-width: 540px;
- max-width: 960px;
- margin-bottom: 5px;
- font-weight: 400;
-/ color: #333333
-}
-
-
-h1, h2, h3, h4, h5, h6 {
- font-weight: 400;
- margin-top: 35px;
- margin-bottom: 15px;
- padding-top: 10px;
-}
-
-h1 {
- margin-top: 70px;
- color: #606AAA;
- font-size:230%;
- font-variant:small-caps;
- padding-bottom:20px;
- width:100%;
- border-bottom:1px solid #606AAA;
-}
-
-h2 {
- font-size:160%;
-}
-
-h3 {
- font-size:130%;
-}
-
-h4 {
- font-size:120%;
- font-variant:small-caps;
-}
-
-h5 {
- font-size:120%;
-}
-
-h6 {
- font-size:120%;
- font-variant:small-caps;
-}
-
-a {
- color: #606AAA;
- margin: 0;
- padding: 0;
- vertical-align: baseline;
-}
-
-a:hover {
- text-decoration: blink;
- color: green;
-}
-
-a:visited {
- color: gray;
-}
-
-ul, ol {
- padding: 0;
- margin: 0px 0px 0px 50px;
-}
-ul {
- list-style-type: square;
- list-style-position: inside;
-
-}
-
-li {
- line-height:150%
-}
-
-li ul, li ul {
- margin-left: 24px;
-}
-
-pre {
- padding: 0px 10px;
- max-width: 800px;
- white-space: pre-wrap;
-}
-
-code {
- font-family: Consolas, Monaco, Andale Mono, monospace, courrier new;
- line-height: 1.5;
- font-size: 15px;
- background: #F8F8F8;
- border-radius: 4px;
- padding: 5px;
- display: inline-block;
- max-width: 800px;
- white-space: pre-wrap;
-}
-
-
-li code, p code {
- background: #CDCDCD;
- color: #606AAA;
- padding: 0px 5px 0px 5px;
-}
-
-code.r, code.cpp {
- display: block;
- word-wrap: break-word;
- border: 1px solid #606AAA;
-}
-
-aside {
- display: block;
- float: right;
- width: 390px;
-}
-
-blockquote {
- border-left:.5em solid #606AAA;
- background: #F8F8F8;
- padding: 0em 1em 0em 1em;
- margin-left:10px;
- max-width: 500px;
-}
-
-blockquote cite {
- line-height:10px;
- color:#bfbfbf;
-}
-
-blockquote cite:before {
- /content: '\2014 \00A0';
-}
-
-blockquote p, blockquote li {
- color: #666;
-}
-hr {
-/ width: 540px;
- text-align: left;
- margin: 0 auto 0 0;
- color: #999;
-}
-
-
-/* table */
-
-table {
- width: 100%;
- border-top: 1px solid #919699;
- border-left: 1px solid #919699;
- border-spacing: 0;
-}
-
-table th {
- padding: 4px 8px 4px 8px;
- text-align: center;
- color: white;
- background: #606AAA;
- border-bottom: 1px solid #919699;
- border-right: 1px solid #919699;
-}
-table th p {
- font-weight: bold;
- margin-bottom: 0px;
-}
-
-table td {
- padding: 8px;
- vertical-align: top;
- border-bottom: 1px solid #919699;
- border-right: 1px solid #919699;
-}
-
-table td:last-child {
- /background: lightgray;
- text-align: right;
-}
-
-table td p {
- margin-bottom: 0px;
-}
-table td p + p {
- margin-top: 5px;
-}
-table td p + p + p {
- margin-top: 5px;
-}
diff --git a/ml-xgboost/R-package/vignettes/xgboost.Rnw b/ml-xgboost/R-package/vignettes/xgboost.Rnw
deleted file mode 100644
index dfbb2f1..0000000
--- a/ml-xgboost/R-package/vignettes/xgboost.Rnw
+++ /dev/null
@@ -1,222 +0,0 @@
-\documentclass{article}
-\RequirePackage{url}
-\usepackage{hyperref}
-\RequirePackage{amsmath}
-\RequirePackage{natbib}
-\RequirePackage[a4paper,lmargin={1.25in},rmargin={1.25in},tmargin={1in},bmargin={1in}]{geometry}
-
-\makeatletter
-% \VignetteIndexEntry{xgboost: eXtreme Gradient Boosting}
-%\VignetteKeywords{xgboost, gbm, gradient boosting machines}
-%\VignettePackage{xgboost}
-% \VignetteEngine{knitr::knitr}
-\makeatother
-
-\begin{document}
-%\SweaveOpts{concordance=TRUE}
-
-<>=
-if (require('knitr')) opts_chunk$set(fig.width = 5, fig.height = 5, fig.align = 'center', tidy = FALSE, warning = FALSE, cache = TRUE)
-@
-
-%
-<>=
-xgboost.version <- packageDescription("xgboost")$Version
-
-@
-%
-
- \begin{center}
- \vspace*{6\baselineskip}
- \rule{\textwidth}{1.6pt}\vspace*{-\baselineskip}\vspace*{2pt}
- \rule{\textwidth}{0.4pt}\\[2\baselineskip]
- {\LARGE \textbf{xgboost: eXtreme Gradient Boosting}}\\[1.2\baselineskip]
- \rule{\textwidth}{0.4pt}\vspace*{-\baselineskip}\vspace{3.2pt}
- \rule{\textwidth}{1.6pt}\\[2\baselineskip]
- {\Large Tianqi Chen, Tong He}\\[\baselineskip]
- {\large Package Version: \Sexpr{xgboost.version}}\\[\baselineskip]
- {\large \today}\par
- \vfill
- \end{center}
-
-\thispagestyle{empty}
-
-\clearpage
-
-\setcounter{page}{1}
-
-\section{Introduction}
-
-This is an introductory document of using the \verb@xgboost@ package in R.
-
-\verb@xgboost@ is short for eXtreme Gradient Boosting package. It is an efficient
- and scalable implementation of gradient boosting framework by \citep{friedman2001greedy} \citep{friedman2000additive}.
-The package includes efficient linear model solver and tree learning algorithm.
-It supports various objective functions, including regression, classification
-and ranking. The package is made to be extendible, so that users are also allowed to define their own objectives easily. It has several features:
-\begin{enumerate}
- \item{Speed: }{\verb@xgboost@ can automatically do parallel computation on
- Windows and Linux, with openmp. It is generally over 10 times faster than
- \verb@gbm@.}
- \item{Input Type: }{\verb@xgboost@ takes several types of input data:}
- \begin{itemize}
- \item{Dense Matrix: }{R's dense matrix, i.e. \verb@matrix@}
- \item{Sparse Matrix: }{R's sparse matrix \verb@Matrix::dgCMatrix@}
- \item{Data File: }{Local data files}
- \item{xgb.DMatrix: }{\verb@xgboost@'s own class. Recommended.}
- \end{itemize}
- \item{Sparsity: }{\verb@xgboost@ accepts sparse input for both tree booster
- and linear booster, and is optimized for sparse input.}
- \item{Customization: }{\verb@xgboost@ supports customized objective function
- and evaluation function}
- \item{Performance: }{\verb@xgboost@ has better performance on several different
- datasets.}
-\end{enumerate}
-
-
-\section{Example with Mushroom data}
-
-In this section, we will illustrate some common usage of \verb@xgboost@. The
-Mushroom data is cited from UCI Machine Learning Repository. \citep{Bache+Lichman:2013}
-
-<>=
-library(xgboost)
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-bst <- xgboost(data = train$data, label = train$label, max_depth = 2, eta = 1,
- nrounds = 2, objective = "binary:logistic")
-xgb.save(bst, 'model.save')
-bst = xgb.load('model.save')
-pred <- predict(bst, test$data)
-@
-
-\verb@xgboost@ is the main function to train a \verb@Booster@, i.e. a model.
-\verb@predict@ does prediction on the model.
-
-Here we can save the model to a binary local file, and load it when needed.
-We can't inspect the trees inside. However we have another function to save the
-model in plain text.
-<>=
-xgb.dump(bst, 'model.dump')
-@
-
-The output looks like
-
-\begin{verbatim}
-booster[0]:
-0:[f28<1.00001] yes=1,no=2,missing=2
- 1:[f108<1.00001] yes=3,no=4,missing=4
- 3:leaf=1.85965
- 4:leaf=-1.94071
- 2:[f55<1.00001] yes=5,no=6,missing=6
- 5:leaf=-1.70044
- 6:leaf=1.71218
-booster[1]:
-0:[f59<1.00001] yes=1,no=2,missing=2
- 1:leaf=-6.23624
- 2:[f28<1.00001] yes=3,no=4,missing=4
- 3:leaf=-0.96853
- 4:leaf=0.784718
-\end{verbatim}
-
-It is important to know \verb@xgboost@'s own data type: \verb@xgb.DMatrix@.
-It speeds up \verb@xgboost@, and is needed for advanced features such as
-training from initial prediction value, weighted training instance.
-
-We can use \verb@xgb.DMatrix@ to construct an \verb@xgb.DMatrix@ object:
-<>=
-dtrain <- xgb.DMatrix(train$data, label = train$label)
-class(dtrain)
-head(getinfo(dtrain,'label'))
-@
-
-We can also save the matrix to a binary file. Then load it simply with
-\verb@xgb.DMatrix@
-<>=
-xgb.DMatrix.save(dtrain, 'xgb.DMatrix')
-dtrain = xgb.DMatrix('xgb.DMatrix')
-@
-
-\section{Advanced Examples}
-
-The function \verb@xgboost@ is a simple function with less parameter, in order
-to be R-friendly. The core training function is wrapped in \verb@xgb.train@. It is more flexible than \verb@xgboost@, but it requires users to read the document a bit more carefully.
-
-\verb@xgb.train@ only accept a \verb@xgb.DMatrix@ object as its input, while it supports advanced features as custom objective and evaluation functions.
-
-<>=
-logregobj <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- preds <- 1/(1 + exp(-preds))
- grad <- preds - labels
- hess <- preds * (1 - preds)
- return(list(grad = grad, hess = hess))
-}
-
-evalerror <- function(preds, dtrain) {
- labels <- getinfo(dtrain, "label")
- err <- sqrt(mean((preds-labels)^2))
- return(list(metric = "MSE", value = err))
-}
-
-dtest <- xgb.DMatrix(test$data, label = test$label)
-watchlist <- list(eval = dtest, train = dtrain)
-param <- list(max_depth = 2, eta = 1, silent = 1)
-
-bst <- xgb.train(param, dtrain, nrounds = 2, watchlist, logregobj, evalerror, maximize = FALSE)
-@
-
-The gradient and second order gradient is required for the output of customized
-objective function.
-
-We also have \verb@slice@ for row extraction. It is useful in
-cross-validation.
-
-For a walkthrough demo, please see \verb@R-package/demo/@ for further
-details.
-
-\section{The Higgs Boson competition}
-
-We have made a demo for \href{http://www.kaggle.com/c/higgs-boson}{the Higgs
-Boson Machine Learning Challenge}.
-
-Here are the instructions to make a submission
-\begin{enumerate}
- \item Download the \href{http://www.kaggle.com/c/higgs-boson/data}{datasets}
- and extract them to \verb@data/@.
- \item Run scripts under \verb@xgboost/demo/kaggle-higgs/@:
- \href{https://github.com/tqchen/xgboost/blob/master/demo/kaggle-higgs/higgs-train.R}{higgs-train.R}
- and \href{https://github.com/tqchen/xgboost/blob/master/demo/kaggle-higgs/higgs-pred.R}{higgs-pred.R}.
- The computation will take less than a minute on Intel i7.
- \item Go to the \href{http://www.kaggle.com/c/higgs-boson/submissions/attach}{submission page}
- and submit your result.
-\end{enumerate}
-
-We provide \href{https://github.com/tqchen/xgboost/blob/master/demo/kaggle-higgs/speedtest.R}{a script}
-to compare the time cost on the higgs dataset with \verb@gbm@ and \verb@xgboost@.
-The training set contains 350000 records and 30 features.
-
-\verb@xgboost@ can automatically do parallel computation. On a machine with Intel
-i7-4700MQ and 24GB memories, we found that \verb@xgboost@ costs about 35 seconds, which is about 20 times faster
-than \verb@gbm@. When we limited \verb@xgboost@ to use only one thread, it was
-still about two times faster than \verb@gbm@.
-
-Meanwhile, the result from \verb@xgboost@ reaches
-\href{http://www.kaggle.com/c/higgs-boson/details/evaluation}{3.60@AMS} with a
-single model. This results stands in the
-\href{http://www.kaggle.com/c/higgs-boson/leaderboard}{top 30\%} of the
-competition.
-
-\bibliographystyle{jss}
-\nocite{*} % list uncited references
-\bibliography{xgboost}
-
-\end{document}
-
-<>=
-file.remove("xgb.DMatrix")
-file.remove("model.dump")
-file.remove("model.save")
-@
diff --git a/ml-xgboost/R-package/vignettes/xgboost.bib b/ml-xgboost/R-package/vignettes/xgboost.bib
deleted file mode 100644
index f21bdae..0000000
--- a/ml-xgboost/R-package/vignettes/xgboost.bib
+++ /dev/null
@@ -1,30 +0,0 @@
-@article{friedman2001greedy,
- title={Greedy function approximation: a gradient boosting machine},
- author={Friedman, Jerome H},
- journal={Annals of Statistics},
- pages={1189--1232},
- year={2001},
- publisher={JSTOR}
-}
-
-@article{friedman2000additive,
- title={Additive logistic regression: a statistical view of boosting (with discussion and a rejoinder by the authors)},
- author={Friedman, Jerome and Hastie, Trevor and Tibshirani, Robert and others},
- journal={The annals of statistics},
- volume={28},
- number={2},
- pages={337--407},
- year={2000},
- publisher={Institute of Mathematical Statistics}
-}
-
-
-@misc{
- Bache+Lichman:2013 ,
- author = "K. Bache and M. Lichman",
- year = "2013",
- title = "{UCI} Machine Learning Repository",
- url = "http://archive.ics.uci.edu/ml",
- institution = "University of California, Irvine, School of Information and Computer Sciences"
-}
-
diff --git a/ml-xgboost/R-package/vignettes/xgboostPresentation.Rmd b/ml-xgboost/R-package/vignettes/xgboostPresentation.Rmd
deleted file mode 100644
index 6d1bab7..0000000
--- a/ml-xgboost/R-package/vignettes/xgboostPresentation.Rmd
+++ /dev/null
@@ -1,428 +0,0 @@
----
-title: "Xgboost presentation"
-output:
- rmarkdown::html_vignette:
- css: vignette.css
- number_sections: yes
- toc: yes
-bibliography: xgboost.bib
-author: Tianqi Chen, Tong He, Michaël Benesty
-vignette: >
- %\VignetteIndexEntry{Xgboost presentation}
- %\VignetteEngine{knitr::rmarkdown}
- \usepackage[utf8]{inputenc}
----
-
-XGBoost R Tutorial
-==================
-
-## Introduction
-
-
-**Xgboost** is short for e**X**treme **G**radient **Boost**ing package.
-
-The purpose of this Vignette is to show you how to use **Xgboost** to build a model and make predictions.
-
-It is an efficient and scalable implementation of gradient boosting framework by @friedman2000additive and @friedman2001greedy. Two solvers are included:
-
-- *linear* model ;
-- *tree learning* algorithm.
-
-It supports various objective functions, including *regression*, *classification* and *ranking*. The package is made to be extendible, so that users are also allowed to define their own objective functions easily.
-
-It has been [used](https://github.com/dmlc/xgboost) to win several [Kaggle](http://www.kaggle.com) competitions.
-
-It has several features:
-
-* Speed: it can automatically do parallel computation on *Windows* and *Linux*, with *OpenMP*. It is generally over 10 times faster than the classical `gbm`.
-* Input Type: it takes several types of input data:
- * *Dense* Matrix: *R*'s *dense* matrix, i.e. `matrix` ;
- * *Sparse* Matrix: *R*'s *sparse* matrix, i.e. `Matrix::dgCMatrix` ;
- * Data File: local data files ;
- * `xgb.DMatrix`: its own class (recommended).
-* Sparsity: it accepts *sparse* input for both *tree booster* and *linear booster*, and is optimized for *sparse* input ;
-* Customization: it supports customized objective functions and evaluation functions.
-
-## Installation
-
-
-### Github version
-
-
-For weekly updated version (highly recommended), install from *Github*:
-
-```{r installGithub, eval=FALSE}
-install.packages("drat", repos="https://cran.rstudio.com")
-drat:::addRepo("dmlc")
-install.packages("xgboost", repos="http://dmlc.ml/drat/", type = "source")
-```
-
-> *Windows* user will need to install [Rtools](https://cran.r-project.org/bin/windows/Rtools/) first.
-
-### CRAN version
-
-
-The version 0.4-2 is on CRAN, and you can install it by:
-
-```{r, eval=FALSE}
-install.packages("xgboost")
-```
-
-Formerly available versions can be obtained from the CRAN [archive](https://cran.r-project.org/src/contrib/Archive/xgboost)
-
-## Learning
-
-
-For the purpose of this tutorial we will load **XGBoost** package.
-
-```{r libLoading, results='hold', message=F, warning=F}
-require(xgboost)
-```
-
-### Dataset presentation
-
-
-In this example, we are aiming to predict whether a mushroom can be eaten or not (like in many tutorials, example data are the the same as you will use on in your every day life :-).
-
-Mushroom data is cited from UCI Machine Learning Repository. @Bache+Lichman:2013.
-
-### Dataset loading
-
-
-We will load the `agaricus` datasets embedded with the package and will link them to variables.
-
-The datasets are already split in:
-
-* `train`: will be used to build the model ;
-* `test`: will be used to assess the quality of our model.
-
-Why *split* the dataset in two parts?
-
-In the first part we will build our model. In the second part we will want to test it and assess its quality. Without dividing the dataset we would test the model on the data which the algorithm have already seen.
-
-```{r datasetLoading, results='hold', message=F, warning=F}
-data(agaricus.train, package='xgboost')
-data(agaricus.test, package='xgboost')
-train <- agaricus.train
-test <- agaricus.test
-```
-
-> In the real world, it would be up to you to make this division between `train` and `test` data. The way to do it is out of the purpose of this article, however `caret` package may [help](http://topepo.github.io/caret/data-splitting.html).
-
-Each variable is a `list` containing two things, `label` and `data`:
-
-```{r dataList, message=F, warning=F}
-str(train)
-```
-
-`label` is the outcome of our dataset meaning it is the binary *classification* we will try to predict.
-
-Let's discover the dimensionality of our datasets.
-
-```{r dataSize, message=F, warning=F}
-dim(train$data)
-dim(test$data)
-```
-
-This dataset is very small to not make the **R** package too heavy, however **XGBoost** is built to manage huge dataset very efficiently.
-
-As seen below, the `data` are stored in a `dgCMatrix` which is a *sparse* matrix and `label` vector is a `numeric` vector (`{0,1}`):
-
-```{r dataClass, message=F, warning=F}
-class(train$data)[1]
-class(train$label)
-```
-
-### Basic Training using XGBoost
-
-
-This step is the most critical part of the process for the quality of our model.
-
-#### Basic training
-
-We are using the `train` data. As explained above, both `data` and `label` are stored in a `list`.
-
-In a *sparse* matrix, cells containing `0` are not stored in memory. Therefore, in a dataset mainly made of `0`, memory size is reduced. It is very usual to have such dataset.
-
-We will train decision tree model using the following parameters:
-
-* `objective = "binary:logistic"`: we will train a binary classification model ;
-* `max_depth = 2`: the trees won't be deep, because our case is very simple ;
-* `nthread = 2`: the number of cpu threads we are going to use;
-* `nrounds = 2`: there will be two passes on the data, the second one will enhance the model by further reducing the difference between ground truth and prediction.
-
-```{r trainingSparse, message=F, warning=F}
-bstSparse <- xgboost(data = train$data, label = train$label, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-```
-
-> More complex the relationship between your features and your `label` is, more passes you need.
-
-#### Parameter variations
-
-##### Dense matrix
-
-Alternatively, you can put your dataset in a *dense* matrix, i.e. a basic **R** matrix.
-
-```{r trainingDense, message=F, warning=F}
-bstDense <- xgboost(data = as.matrix(train$data), label = train$label, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-```
-
-##### xgb.DMatrix
-
-**XGBoost** offers a way to group them in a `xgb.DMatrix`. You can even add other meta data in it. It will be useful for the most advanced features we will discover later.
-
-```{r trainingDmatrix, message=F, warning=F}
-dtrain <- xgb.DMatrix(data = train$data, label = train$label)
-bstDMatrix <- xgboost(data = dtrain, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic")
-```
-
-##### Verbose option
-
-**XGBoost** has several features to help you to view how the learning progress internally. The purpose is to help you to set the best parameters, which is the key of your model quality.
-
-One of the simplest way to see the training progress is to set the `verbose` option (see below for more advanced technics).
-
-```{r trainingVerbose0, message=T, warning=F}
-# verbose = 0, no message
-bst <- xgboost(data = dtrain, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", verbose = 0)
-```
-
-```{r trainingVerbose1, message=T, warning=F}
-# verbose = 1, print evaluation metric
-bst <- xgboost(data = dtrain, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", verbose = 1)
-```
-
-```{r trainingVerbose2, message=T, warning=F}
-# verbose = 2, also print information about tree
-bst <- xgboost(data = dtrain, max_depth = 2, eta = 1, nthread = 2, nrounds = 2, objective = "binary:logistic", verbose = 2)
-```
-
-## Basic prediction using XGBoost
-
-
-## Perform the prediction
-
-
-The purpose of the model we have built is to classify new data. As explained before, we will use the `test` dataset for this step.
-
-```{r predicting, message=F, warning=F}
-pred <- predict(bst, test$data)
-
-# size of the prediction vector
-print(length(pred))
-
-# limit display of predictions to the first 10
-print(head(pred))
-```
-
-These numbers doesn't look like *binary classification* `{0,1}`. We need to perform a simple transformation before being able to use these results.
-
-## Transform the regression in a binary classification
-
-
-The only thing that **XGBoost** does is a *regression*. **XGBoost** is using `label` vector to build its *regression* model.
-
-How can we use a *regression* model to perform a binary classification?
-
-If we think about the meaning of a regression applied to our data, the numbers we get are probabilities that a datum will be classified as `1`. Therefore, we will set the rule that if this probability for a specific datum is `> 0.5` then the observation is classified as `1` (or `0` otherwise).
-
-```{r predictingTest, message=F, warning=F}
-prediction <- as.numeric(pred > 0.5)
-print(head(prediction))
-```
-
-## Measuring model performance
-
-
-To measure the model performance, we will compute a simple metric, the *average error*.
-
-```{r predictingAverageError, message=F, warning=F}
-err <- mean(as.numeric(pred > 0.5) != test$label)
-print(paste("test-error=", err))
-```
-
-> Note that the algorithm has not seen the `test` data during the model construction.
-
-Steps explanation:
-
-1. `as.numeric(pred > 0.5)` applies our rule that when the probability (<=> regression <=> prediction) is `> 0.5` the observation is classified as `1` and `0` otherwise ;
-2. `probabilityVectorPreviouslyComputed != test$label` computes the vector of error between true data and computed probabilities ;
-3. `mean(vectorOfErrors)` computes the *average error* itself.
-
-The most important thing to remember is that **to do a classification, you just do a regression to the** `label` **and then apply a threshold**.
-
-*Multiclass* classification works in a similar way.
-
-This metric is **`r round(err, 2)`** and is pretty low: our yummly mushroom model works well!
-
-## Advanced features
-
-
-Most of the features below have been implemented to help you to improve your model by offering a better understanding of its content.
-
-
-### Dataset preparation
-
-
-For the following advanced features, we need to put data in `xgb.DMatrix` as explained above.
-
-```{r DMatrix, message=F, warning=F}
-dtrain <- xgb.DMatrix(data = train$data, label=train$label)
-dtest <- xgb.DMatrix(data = test$data, label=test$label)
-```
-
-### Measure learning progress with xgb.train
-
-
-Both `xgboost` (simple) and `xgb.train` (advanced) functions train models.
-
-One of the special feature of `xgb.train` is the capacity to follow the progress of the learning after each round. Because of the way boosting works, there is a time when having too many rounds lead to an overfitting. You can see this feature as a cousin of cross-validation method. The following techniques will help you to avoid overfitting or optimizing the learning time in stopping it as soon as possible.
-
-One way to measure progress in learning of a model is to provide to **XGBoost** a second dataset already classified. Therefore it can learn on the first dataset and test its model on the second one. Some metrics are measured after each round during the learning.
-
-> in some way it is similar to what we have done above with the average error. The main difference is that below it was after building the model, and now it is during the construction that we measure errors.
-
-For the purpose of this example, we use `watchlist` parameter. It is a list of `xgb.DMatrix`, each of them tagged with a name.
-
-```{r watchlist, message=F, warning=F}
-watchlist <- list(train=dtrain, test=dtest)
-
-bst <- xgb.train(data=dtrain, max_depth=2, eta=1, nthread = 2, nrounds=2, watchlist=watchlist, objective = "binary:logistic")
-```
-
-**XGBoost** has computed at each round the same average error metric than seen above (we set `nrounds` to 2, that is why we have two lines). Obviously, the `train-error` number is related to the training dataset (the one the algorithm learns from) and the `test-error` number to the test dataset.
-
-Both training and test error related metrics are very similar, and in some way, it makes sense: what we have learned from the training dataset matches the observations from the test dataset.
-
-If with your own dataset you have not such results, you should think about how you divided your dataset in training and test. May be there is something to fix. Again, `caret` package may [help](http://topepo.github.io/caret/data-splitting.html).
-
-For a better understanding of the learning progression, you may want to have some specific metric or even use multiple evaluation metrics.
-
-```{r watchlist2, message=F, warning=F}
-bst <- xgb.train(data=dtrain, max_depth=2, eta=1, nthread = 2, nrounds=2, watchlist=watchlist, eval_metric = "error", eval_metric = "logloss", objective = "binary:logistic")
-```
-
-> `eval_metric` allows us to monitor two new metrics for each round, `logloss` and `error`.
-
-### Linear boosting
-
-
-Until now, all the learnings we have performed were based on boosting trees. **XGBoost** implements a second algorithm, based on linear boosting. The only difference with previous command is `booster = "gblinear"` parameter (and removing `eta` parameter).
-
-```{r linearBoosting, message=F, warning=F}
-bst <- xgb.train(data=dtrain, booster = "gblinear", max_depth=2, nthread = 2, nrounds=2, watchlist=watchlist, eval_metric = "error", eval_metric = "logloss", objective = "binary:logistic")
-```
-
-In this specific case, *linear boosting* gets slightly better performance metrics than decision trees based algorithm.
-
-In simple cases, it will happen because there is nothing better than a linear algorithm to catch a linear link. However, decision trees are much better to catch a non linear link between predictors and outcome. Because there is no silver bullet, we advise you to check both algorithms with your own datasets to have an idea of what to use.
-
-### Manipulating xgb.DMatrix
-
-
-#### Save / Load
-
-Like saving models, `xgb.DMatrix` object (which groups both dataset and outcome) can also be saved using `xgb.DMatrix.save` function.
-
-```{r DMatrixSave, message=F, warning=F}
-xgb.DMatrix.save(dtrain, "dtrain.buffer")
-# to load it in, simply call xgb.DMatrix
-dtrain2 <- xgb.DMatrix("dtrain.buffer")
-bst <- xgb.train(data=dtrain2, max_depth=2, eta=1, nthread = 2, nrounds=2, watchlist=watchlist, objective = "binary:logistic")
-```
-
-```{r DMatrixDel, include=FALSE}
-file.remove("dtrain.buffer")
-```
-
-#### Information extraction
-
-Information can be extracted from `xgb.DMatrix` using `getinfo` function. Hereafter we will extract `label` data.
-
-```{r getinfo, message=F, warning=F}
-label = getinfo(dtest, "label")
-pred <- predict(bst, dtest)
-err <- as.numeric(sum(as.integer(pred > 0.5) != label))/length(label)
-print(paste("test-error=", err))
-```
-
-### View feature importance/influence from the learnt model
-
-
-Feature importance is similar to R gbm package's relative influence (rel.inf).
-
-```
-importance_matrix <- xgb.importance(model = bst)
-print(importance_matrix)
-xgb.plot.importance(importance_matrix = importance_matrix)
-```
-
-#### View the trees from a model
-
-
-You can dump the tree you learned using `xgb.dump` into a text file.
-
-```{r dump, message=T, warning=F}
-xgb.dump(bst, with_stats = T)
-```
-
-You can plot the trees from your model using ```xgb.plot.tree``
-
-```
-xgb.plot.tree(model = bst)
-```
-
-> if you provide a path to `fname` parameter you can save the trees to your hard drive.
-
-#### Save and load models
-
-
-Maybe your dataset is big, and it takes time to train a model on it? May be you are not a big fan of losing time in redoing the same task again and again? In these very rare cases, you will want to save your model and load it when required.
-
-Hopefully for you, **XGBoost** implements such functions.
-
-```{r saveModel, message=F, warning=F}
-# save model to binary local file
-xgb.save(bst, "xgboost.model")
-```
-
-> `xgb.save` function should return `r TRUE` if everything goes well and crashes otherwise.
-
-An interesting test to see how identical our saved model is to the original one would be to compare the two predictions.
-
-```{r loadModel, message=F, warning=F}
-# load binary model to R
-bst2 <- xgb.load("xgboost.model")
-pred2 <- predict(bst2, test$data)
-
-# And now the test
-print(paste("sum(abs(pred2-pred))=", sum(abs(pred2-pred))))
-```
-
-```{r clean, include=FALSE}
-# delete the created model
-file.remove("./xgboost.model")
-```
-
-> result is `0`? We are good!
-
-In some very specific cases, like when you want to pilot **XGBoost** from `caret` package, you will want to save the model as a *R* binary vector. See below how to do it.
-
-```{r saveLoadRBinVectorModel, message=F, warning=F}
-# save model to R's raw vector
-rawVec <- xgb.serialize(bst)
-
-# print class
-print(class(rawVec))
-
-# load binary model to R
-bst3 <- xgb.load(rawVec)
-pred3 <- predict(bst3, test$data)
-
-# pred2 should be identical to pred
-print(paste("sum(abs(pred3-pred))=", sum(abs(pred2-pred))))
-```
-
-> Again `0`? It seems that `XGBoost` works pretty well!
-
-## References
diff --git a/ml-xgboost/R-package/vignettes/xgboostfromJSON.Rmd b/ml-xgboost/R-package/vignettes/xgboostfromJSON.Rmd
deleted file mode 100644
index 492f3a7..0000000
--- a/ml-xgboost/R-package/vignettes/xgboostfromJSON.Rmd
+++ /dev/null
@@ -1,189 +0,0 @@
----
-title: "XGBoost from JSON"
-output:
- rmarkdown::html_vignette:
- number_sections: yes
- toc: yes
-author: Roland Stevenson
-vignette: >
- %\VignetteIndexEntry{XGBoost from JSON}
- %\VignetteEngine{knitr::rmarkdown}
- \usepackage[utf8]{inputenc}
----
-
-XGBoost from JSON
-=================
-
-## Introduction
-
-The purpose of this Vignette is to show you how to correctly load and work with an **Xgboost** model that has been dumped to JSON. **Xgboost** internally converts all data to [32-bit floats](https://en.wikipedia.org/wiki/Single-precision_floating-point_format), and the values dumped to JSON are decimal representations of these values. When working with a model that has been parsed from a JSON file, care must be taken to correctly treat:
-
-- the input data, which should be converted to 32-bit floats
-- any 32-bit floats that were stored in JSON as decimal representations
-- any calculations must be done with 32-bit mathematical operators
-
-## Setup
-
-For the purpose of this tutorial we will load the xgboost, jsonlite, and float packages. We'll also set `digits=22` in our options in case we want to inspect many digits of our results.
-
-```{r}
-require(xgboost)
-require(jsonlite)
-require(float)
-options(digits=22)
-```
-
-We will create a toy binary logistic model based on the example first provided [here](https://github.com/dmlc/xgboost/issues/3960), so that we can easily understand the structure of the dumped JSON model object. This will allow us to understand where discrepancies can occur and how they should be handled.
-
-```{r}
-dates <- c(20180130, 20180130, 20180130,
- 20180130, 20180130, 20180130,
- 20180131, 20180131, 20180131,
- 20180131, 20180131, 20180131,
- 20180131, 20180131, 20180131,
- 20180134, 20180134, 20180134)
-
-labels <- c(1, 1, 1,
- 1, 1, 1,
- 0, 0, 0,
- 0, 0, 0,
- 0, 0, 0,
- 0, 0, 0)
-
-data <- data.frame(dates = dates, labels=labels)
-
-bst <- xgboost(
- data = as.matrix(data$dates),
- label = labels,
- nthread = 2,
- nrounds = 1,
- objective = "binary:logistic",
- missing = NA,
- max_depth = 1
-)
-```
-
-## Comparing results
-We will now dump the model to JSON and attempt to illustrate a variety of issues that can arise, and how to properly deal with them.
-
-First let's dump the model to JSON:
-
-```{r}
-bst_json <- xgb.dump(bst, with_stats = FALSE, dump_format='json')
-bst_from_json <- fromJSON(bst_json, simplifyDataFrame = FALSE)
-node <- bst_from_json[[1]]
-cat(bst_json)
-```
-
-The tree JSON shown by the above code-chunk tells us that if the data is less than 20180132, the tree will output the value in the first leaf. Otherwise it will output the value in the second leaf. Let's try to reproduce this manually with the data we have and confirm that it matches the model predictions we've already calculated.
-
-```{r}
-bst_preds_logodds <- predict(bst,as.matrix(data$dates), outputmargin = TRUE)
-
-# calculate the logodds values using the JSON representation
-bst_from_json_logodds <- ifelse(data$dates When working with imported JSON, all data must be converted to 32-bit floats
-
-To explain this, let's repeat the comparison and round to two decimals:
-
-```{r}
-round(bst_preds_logodds,2) == round(bst_from_json_logodds,2)
-```
-
-If we round to two decimals, we see that only the elements related to data values of `20180131` don't agree. If we convert the data to floats, they agree:
-
-```{r}
-# now convert the dates to floats first
-bst_from_json_logodds <- ifelse(fl(data$dates) All JSON parameters stored as floats must be converted to floats.
-
-Let's now say we do care about numbers past the first two decimals.
-
-```{r}
-# test that values are equal
-bst_preds_logodds == bst_from_json_logodds
-```
-
-None are exactly equal. What happened? Although we've converted the data to 32-bit floats, we also need to convert the JSON parameters to 32-bit floats. Let's do this:
-
-```{r}
-# now convert the dates to floats first
-bst_from_json_logodds <- ifelse(fl(data$dates) Always use 32-bit numbers and operators
-
-We were able to get the log-odds to agree, so now let's manually calculate the sigmoid of the log-odds. This should agree with the xgboost predictions.
-
-
-```{r}
-bst_preds <- predict(bst,as.matrix(data$dates))
-
-# calculate the predictions casting doubles to floats
-bst_from_json_preds <- ifelse(fl(data$dates) eXtreme Gradient Boosting
-===========
-[![Build Status](https://xgboost-ci.net/job/xgboost/job/master/badge/icon?style=plastic)](https://xgboost-ci.net/blue/organizations/jenkins/xgboost/activity)
-[![Build Status](https://img.shields.io/travis/dmlc/xgboost.svg?label=build&logo=travis&branch=master)](https://travis-ci.org/dmlc/xgboost)
-[![Build Status](https://ci.appveyor.com/api/projects/status/5ypa8vaed6kpmli8?svg=true)](https://ci.appveyor.com/project/tqchen/xgboost)
-[![Documentation Status](https://readthedocs.org/projects/xgboost/badge/?version=latest)](https://xgboost.readthedocs.org)
-[![GitHub license](http://dmlc.github.io/img/apache2.svg)](./LICENSE)
-[![CRAN Status Badge](http://www.r-pkg.org/badges/version/xgboost)](http://cran.r-project.org/web/packages/xgboost)
-[![PyPI version](https://badge.fury.io/py/xgboost.svg)](https://pypi.python.org/pypi/xgboost/)
-[![Optuna](https://img.shields.io/badge/Optuna-integrated-blue)](https://optuna.org)
-
-[Community](https://xgboost.ai/community) |
-[Documentation](https://xgboost.readthedocs.org) |
-[Resources](demo/README.md) |
-[Contributors](CONTRIBUTORS.md) |
-[Release Notes](NEWS.md)
-
-XGBoost is an optimized distributed gradient boosting library designed to be highly ***efficient***, ***flexible*** and ***portable***.
-It implements machine learning algorithms under the [Gradient Boosting](https://en.wikipedia.org/wiki/Gradient_boosting) framework.
-XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and accurate way.
-The same code runs on major distributed environment (Kubernetes, Hadoop, SGE, MPI, Dask) and can solve problems beyond billions of examples.
-
-License
--------
-© Contributors, 2019. Licensed under an [Apache-2](https://github.com/dmlc/xgboost/blob/master/LICENSE) license.
-
-Contribute to XGBoost
----------------------
-XGBoost has been developed and used by a group of active community members. Your help is very valuable to make the package better for everyone.
-Checkout the [Community Page](https://xgboost.ai/community).
-
-Reference
----------
-- Tianqi Chen and Carlos Guestrin. [XGBoost: A Scalable Tree Boosting System](http://arxiv.org/abs/1603.02754). In 22nd SIGKDD Conference on Knowledge Discovery and Data Mining, 2016
-- XGBoost originates from research project at University of Washington.
-
-Sponsors
---------
-Become a sponsor and get a logo here. See details at [Sponsoring the XGBoost Project](https://xgboost.ai/sponsors). The funds are used to defray the cost of continuous integration and testing infrastructure (https://xgboost-ci.net).
-
-## Open Source Collective sponsors
-[![Backers on Open Collective](https://opencollective.com/xgboost/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/xgboost/sponsors/badge.svg)](#sponsors)
-
-### Sponsors
-[[Become a sponsor](https://opencollective.com/xgboost#sponsor)]
-
-
-
-
-
-
-
-
-
-
-
-
-
-### Backers
-[[Become a backer](https://opencollective.com/xgboost#backer)]
-
-
-
-## Other sponsors
-The sponsors in this list are donating cloud hours in lieu of cash donation.
-
-
diff --git a/ml-xgboost/amalgamation/dmlc-minimum0.cc b/ml-xgboost/amalgamation/dmlc-minimum0.cc
deleted file mode 100644
index d8594aa..0000000
--- a/ml-xgboost/amalgamation/dmlc-minimum0.cc
+++ /dev/null
@@ -1,16 +0,0 @@
-/*!
- * Copyright 2015 by Contributors.
- * \brief Mininum DMLC library Amalgamation, used for easy plugin of dmlc lib.
- * Normally this is not needed.
- */
-#include "../dmlc-core/src/io/line_split.cc"
-#include "../dmlc-core/src/io/recordio_split.cc"
-#include "../dmlc-core/src/io/input_split_base.cc"
-#include "../dmlc-core/src/io/local_filesys.cc"
-#include "../dmlc-core/src/io/filesys.cc"
-#include "../dmlc-core/src/io/indexed_recordio_split.cc"
-#include "../dmlc-core/src/data.cc"
-#include "../dmlc-core/src/io.cc"
-#include "../dmlc-core/src/recordio.cc"
-
-
diff --git a/ml-xgboost/amalgamation/xgboost-all0.cc b/ml-xgboost/amalgamation/xgboost-all0.cc
deleted file mode 100644
index 5f7e75f..0000000
--- a/ml-xgboost/amalgamation/xgboost-all0.cc
+++ /dev/null
@@ -1,83 +0,0 @@
-/*!
- * Copyright 2015-2019 by Contributors.
- * \brief XGBoost Amalgamation.
- * This offers an alternative way to compile the entire library from this single file.
- *
- * Example usage command.
- * - $(CXX) -std=c++0x -fopenmp -o -shared libxgboost.so xgboost-all0.cc -ldmlc -lrabit
- *
- * \author Tianqi Chen.
- */
-
-// metrics
-#include "../src/metric/metric.cc"
-#include "../src/metric/elementwise_metric.cc"
-#include "../src/metric/multiclass_metric.cc"
-#include "../src/metric/rank_metric.cc"
-#include "../src/metric/survival_metric.cc"
-
-// objectives
-#include "../src/objective/objective.cc"
-#include "../src/objective/regression_obj.cc"
-#include "../src/objective/multiclass_obj.cc"
-#include "../src/objective/rank_obj.cc"
-#include "../src/objective/hinge.cc"
-#include "../src/objective/aft_obj.cc"
-
-// gbms
-#include "../src/gbm/gbm.cc"
-#include "../src/gbm/gbtree.cc"
-#include "../src/gbm/gbtree_model.cc"
-#include "../src/gbm/gblinear.cc"
-#include "../src/gbm/gblinear_model.cc"
-
-// data
-#include "../src/data/data.cc"
-#include "../src/data/simple_dmatrix.cc"
-#include "../src/data/sparse_page_raw_format.cc"
-#include "../src/data/ellpack_page.cc"
-#include "../src/data/ellpack_page_source.cc"
-
-// prediction
-#include "../src/predictor/predictor.cc"
-#include "../src/predictor/cpu_predictor.cc"
-
-#if DMLC_ENABLE_STD_THREAD
-#include "../src/data/sparse_page_dmatrix.cc"
-#endif
-
-// trees
-#include "../src/tree/param.cc"
-#include "../src/tree/split_evaluator.cc"
-#include "../src/tree/tree_model.cc"
-#include "../src/tree/tree_updater.cc"
-#include "../src/tree/updater_colmaker.cc"
-#include "../src/tree/updater_quantile_hist.cc"
-#include "../src/tree/updater_prune.cc"
-#include "../src/tree/updater_refresh.cc"
-#include "../src/tree/updater_sync.cc"
-#include "../src/tree/updater_histmaker.cc"
-#include "../src/tree/updater_skmaker.cc"
-#include "../src/tree/constraints.cc"
-
-// linear
-#include "../src/linear/linear_updater.cc"
-#include "../src/linear/updater_coordinate.cc"
-#include "../src/linear/updater_shotgun.cc"
-
-// global
-#include "../src/learner.cc"
-#include "../src/logging.cc"
-#include "../src/common/common.cc"
-#include "../src/common/timer.cc"
-#include "../src/common/host_device_vector.cc"
-#include "../src/common/hist_util.cc"
-#include "../src/common/json.cc"
-#include "../src/common/io.cc"
-#include "../src/common/survival_util.cc"
-#include "../src/common/probability_distribution.cc"
-#include "../src/common/version.cc"
-
-// c_api
-#include "../src/c_api/c_api.cc"
-#include "../src/c_api/c_api_error.cc"
diff --git a/ml-xgboost/appveyor.yml b/ml-xgboost/appveyor.yml
deleted file mode 100644
index 68933db..0000000
--- a/ml-xgboost/appveyor.yml
+++ /dev/null
@@ -1,133 +0,0 @@
-environment:
- R_ARCH: x64
- USE_RTOOLS: true
- matrix:
- - target: msvc
- ver: 2015
- generator: "Visual Studio 14 2015 Win64"
- configuration: Debug
- - target: msvc
- ver: 2015
- generator: "Visual Studio 14 2015 Win64"
- configuration: Release
- - target: mingw
- generator: "Unix Makefiles"
- - target: jvm
- - target: rmsvc
- ver: 2015
- generator: "Visual Studio 14 2015 Win64"
- configuration: Release
- - target: rmingw
- generator: "Unix Makefiles"
-
-#matrix:
-# fast_finish: true
-
-platform:
- - x64
-
-install:
- - git submodule update --init --recursive
- # MinGW
- - set PATH=C:\msys64\mingw64\bin;C:\msys64\usr\bin;%PATH%
- - gcc -v
- - ls -l C:\
- # Miniconda3
- - call C:\Miniconda3-x64\Scripts\activate.bat
- - conda info
- - where python
- - python --version
- # do python build for mingw and one of the msvc jobs
- - set DO_PYTHON=off
- - if /i "%target%" == "mingw" set DO_PYTHON=on
- - if /i "%target%_%ver%_%configuration%" == "msvc_2015_Release" set DO_PYTHON=on
- - if /i "%DO_PYTHON%" == "on" (
- conda config --set always_yes true &&
- conda update -q conda &&
- conda install -y numpy scipy pandas matplotlib pytest scikit-learn graphviz python-graphviz
- )
- - set PATH=C:\Miniconda3-x64\Library\bin\graphviz;%PATH%
- # R: based on https://github.com/krlmlr/r-appveyor
- - ps: |
- if($env:target -eq 'rmingw' -or $env:target -eq 'rmsvc') {
- #$ErrorActionPreference = "Stop"
- Invoke-WebRequest https://raw.githubusercontent.com/krlmlr/r-appveyor/master/scripts/appveyor-tool.ps1 -OutFile "$Env:TEMP\appveyor-tool.ps1"
- Import-Module "$Env:TEMP\appveyor-tool.ps1"
- Bootstrap
- $BINARY_DEPS = "c('XML','igraph')"
- cmd.exe /c "R.exe -q -e ""install.packages($BINARY_DEPS, repos='$CRAN', type='win.binary')"" 2>&1"
- $DEPS = "c('data.table','magrittr','stringi','ggplot2','DiagrammeR','Ckmeans.1d.dp','vcd','testthat','lintr','knitr','rmarkdown')"
- cmd.exe /c "R.exe -q -e ""install.packages($DEPS, repos='$CRAN', type='both')"" 2>&1"
- }
-
-build_script:
- - cd %APPVEYOR_BUILD_FOLDER%
- - if /i "%target%" == "msvc" (
- mkdir build_msvc%ver% &&
- cd build_msvc%ver% &&
- cmake .. -G"%generator%" -DCMAKE_CONFIGURATION_TYPES="Release;Debug;" &&
- msbuild xgboost.sln
- )
- - if /i "%target%" == "mingw" (
- mkdir build_mingw &&
- cd build_mingw &&
- cmake .. -G"%generator%" &&
- make -j2
- )
- # Python package
- - if /i "%DO_PYTHON%" == "on" (
- cd %APPVEYOR_BUILD_FOLDER%\python-package &&
- python setup.py install &&
- mkdir wheel &&
- python setup.py bdist_wheel --universal --plat-name win-amd64 -d wheel
- )
- # R package: make + mingw standard CRAN packaging (only x64 for now)
- - if /i "%target%" == "rmingw" (
- make Rbuild &&
- ls -l &&
- R.exe CMD INSTALL xgboost*.tar.gz
- )
- # R package: cmake + VC2015
- - if /i "%target%" == "rmsvc" (
- mkdir build_rmsvc%ver% &&
- cd build_rmsvc%ver% &&
- cmake .. -G"%generator%" -DCMAKE_CONFIGURATION_TYPES="Release" -DR_LIB=ON &&
- cmake --build . --target install --config Release
- )
- - if /i "%target%" == "jvm" cd jvm-packages && mvn test -pl :boostkit-xgboost4j_2.11
-
-test_script:
- - cd %APPVEYOR_BUILD_FOLDER%
- - if /i "%DO_PYTHON%" == "on" python -m pytest tests/python
- # mingw R package: run the R check (which includes unit tests), and also keep the built binary package
- - if /i "%target%" == "rmingw" (
- set _R_CHECK_CRAN_INCOMING_=FALSE&&
- set _R_CHECK_FORCE_SUGGESTS_=FALSE&&
- R.exe CMD check xgboost*.tar.gz --no-manual --no-build-vignettes --as-cran --install-args=--build
- )
- # MSVC R package: run only the unit tests
- - if /i "%target%" == "rmsvc" (
- cd build_rmsvc%ver%\R-package &&
- R.exe -q -e "library(testthat); setwd('tests'); source('testthat.R')"
- )
-
-on_failure:
- # keep the whole output of R check
- - if /i "%target%" == "rmingw" (
- 7z a failure.zip *.Rcheck\* &&
- appveyor PushArtifact failure.zip
- )
-
-artifacts:
- # log from R check
- - path: '*.Rcheck\**\*.log'
- name: Logs
- # source R-package
- - path: '\xgboost_*.tar.gz'
- name: Bits
- # binary R-package
- - path: '**\xgboost_*.zip'
- name: Bits
- # binary Python wheel package
- - path: '**\*.whl'
- name: Bits
diff --git a/ml-xgboost/cmake/Doc.cmake b/ml-xgboost/cmake/Doc.cmake
deleted file mode 100644
index 2ffa005..0000000
--- a/ml-xgboost/cmake/Doc.cmake
+++ /dev/null
@@ -1,16 +0,0 @@
-function (run_doxygen)
- find_package(Doxygen REQUIRED)
-
- if (NOT DOXYGEN_DOT_FOUND)
- message(FATAL_ERROR "Command `dot` not found. Please install graphviz.")
- endif (NOT DOXYGEN_DOT_FOUND)
-
- configure_file(
- ${xgboost_SOURCE_DIR}/doc/Doxyfile.in
- ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile @ONLY)
- add_custom_target( doc_doxygen ALL
- COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile
- WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
- COMMENT "Generate C APIs documentation."
- VERBATIM)
-endfunction (run_doxygen)
diff --git a/ml-xgboost/cmake/FindPrefetchIntrinsics.cmake b/ml-xgboost/cmake/FindPrefetchIntrinsics.cmake
deleted file mode 100644
index b00ff57..0000000
--- a/ml-xgboost/cmake/FindPrefetchIntrinsics.cmake
+++ /dev/null
@@ -1,22 +0,0 @@
-function (find_prefetch_intrinsics)
- include(CheckCXXSourceCompiles)
- check_cxx_source_compiles("
- #include
- int main() {
- char data = 0;
- const char* address = &data;
- _mm_prefetch(address, _MM_HINT_NTA);
- return 0;
- }
- " XGBOOST_MM_PREFETCH_PRESENT)
- check_cxx_source_compiles("
- int main() {
- char data = 0;
- const char* address = &data;
- __builtin_prefetch(address, 0, 0);
- return 0;
- }
- " XGBOOST_BUILTIN_PREFETCH_PRESENT)
- set(XGBOOST_MM_PREFETCH_PRESENT ${XGBOOST_MM_PREFETCH_PRESENT} PARENT_SCOPE)
- set(XGBOOST_BUILTIN_PREFETCH_PRESENT ${XGBOOST_BUILTIN_PREFETCH_PRESENT} PARENT_SCOPE)
-endfunction (find_prefetch_intrinsics)
diff --git a/ml-xgboost/cmake/Python_version.in b/ml-xgboost/cmake/Python_version.in
deleted file mode 100644
index c55458e..0000000
--- a/ml-xgboost/cmake/Python_version.in
+++ /dev/null
@@ -1 +0,0 @@
-@xgboost_VERSION_MAJOR@.@xgboost_VERSION_MINOR@.@xgboost_VERSION_PATCH@
diff --git a/ml-xgboost/cmake/Sanitizer.cmake b/ml-xgboost/cmake/Sanitizer.cmake
deleted file mode 100644
index c1afb14..0000000
--- a/ml-xgboost/cmake/Sanitizer.cmake
+++ /dev/null
@@ -1,63 +0,0 @@
-# Set appropriate compiler and linker flags for sanitizers.
-#
-# Usage of this module:
-# enable_sanitizers("address;leak")
-
-# Add flags
-macro(enable_sanitizer sanitizer)
- if(${sanitizer} MATCHES "address")
- find_package(ASan REQUIRED)
- set(SAN_COMPILE_FLAGS "${SAN_COMPILE_FLAGS} -fsanitize=address")
- link_libraries(${ASan_LIBRARY})
-
- elseif(${sanitizer} MATCHES "thread")
- find_package(TSan REQUIRED)
- set(SAN_COMPILE_FLAGS "${SAN_COMPILE_FLAGS} -fsanitize=thread")
- link_libraries(${TSan_LIBRARY})
-
- elseif(${sanitizer} MATCHES "leak")
- find_package(LSan REQUIRED)
- set(SAN_COMPILE_FLAGS "${SAN_COMPILE_FLAGS} -fsanitize=leak")
- link_libraries(${LSan_LIBRARY})
-
- elseif(${sanitizer} MATCHES "undefined")
- find_package(UBSan REQUIRED)
- set(SAN_COMPILE_FLAGS "${SAN_COMPILE_FLAGS} -fsanitize=undefined -fno-sanitize-recover=undefined")
- link_libraries(${UBSan_LIBRARY})
-
- else()
- message(FATAL_ERROR "Santizer ${sanitizer} not supported.")
- endif()
-endmacro()
-
-macro(enable_sanitizers SANITIZERS)
- # Check sanitizers compatibility.
- # Idealy, we should use if(san IN_LIST SANITIZERS) ... endif()
- # But I haven't figure out how to make it work.
- foreach ( _san ${SANITIZERS} )
- string(TOLOWER ${_san} _san)
- if (_san MATCHES "thread")
- if (${_use_other_sanitizers})
- message(FATAL_ERROR
- "thread sanitizer is not compatible with ${_san} sanitizer.")
- endif()
- set(_use_thread_sanitizer 1)
- else ()
- if (${_use_thread_sanitizer})
- message(FATAL_ERROR
- "${_san} sanitizer is not compatible with thread sanitizer.")
- endif()
- set(_use_other_sanitizers 1)
- endif()
- endforeach()
-
- message("Sanitizers: ${SANITIZERS}")
-
- foreach( _san ${SANITIZERS} )
- string(TOLOWER ${_san} _san)
- enable_sanitizer(${_san})
- endforeach()
- message("Sanitizers compile flags: ${SAN_COMPILE_FLAGS}")
- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SAN_COMPILE_FLAGS}")
- set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SAN_COMPILE_FLAGS}")
-endmacro()
diff --git a/ml-xgboost/cmake/Utils.cmake b/ml-xgboost/cmake/Utils.cmake
deleted file mode 100644
index 4a9e63a..0000000
--- a/ml-xgboost/cmake/Utils.cmake
+++ /dev/null
@@ -1,143 +0,0 @@
-# Automatically set source group based on folder
-function(auto_source_group SOURCES)
-
- foreach(FILE ${SOURCES})
- get_filename_component(PARENT_DIR "${FILE}" PATH)
-
- # skip src or include and changes /'s to \\'s
- string(REPLACE "${CMAKE_CURRENT_LIST_DIR}" "" GROUP "${PARENT_DIR}")
- string(REPLACE "/" "\\\\" GROUP "${GROUP}")
- string(REGEX REPLACE "^\\\\" "" GROUP "${GROUP}")
-
- source_group("${GROUP}" FILES "${FILE}")
- endforeach()
-endfunction(auto_source_group)
-
-# Force static runtime for MSVC
-function(msvc_use_static_runtime)
- if(MSVC)
- set(variables
- CMAKE_C_FLAGS_DEBUG
- CMAKE_C_FLAGS_MINSIZEREL
- CMAKE_C_FLAGS_RELEASE
- CMAKE_C_FLAGS_RELWITHDEBINFO
- CMAKE_CXX_FLAGS_DEBUG
- CMAKE_CXX_FLAGS_MINSIZEREL
- CMAKE_CXX_FLAGS_RELEASE
- CMAKE_CXX_FLAGS_RELWITHDEBINFO
- )
- foreach(variable ${variables})
- if(${variable} MATCHES "/MD")
- string(REGEX REPLACE "/MD" "/MT" ${variable} "${${variable}}")
- set(${variable} "${${variable}}" PARENT_SCOPE)
- endif()
- endforeach()
- set(variables
- CMAKE_CUDA_FLAGS
- CMAKE_CUDA_FLAGS_DEBUG
- CMAKE_CUDA_FLAGS_MINSIZEREL
- CMAKE_CUDA_FLAGS_RELEASE
- CMAKE_CUDA_FLAGS_RELWITHDEBINFO
- )
- foreach(variable ${variables})
- if(${variable} MATCHES "-MD")
- string(REGEX REPLACE "-MD" "-MT" ${variable} "${${variable}}")
- set(${variable} "${${variable}}" PARENT_SCOPE)
- endif()
- if(${variable} MATCHES "/MD")
- string(REGEX REPLACE "/MD" "/MT" ${variable} "${${variable}}")
- set(${variable} "${${variable}}" PARENT_SCOPE)
- endif()
- endforeach()
- endif()
-endfunction(msvc_use_static_runtime)
-
-# Set output directory of target, ignoring debug or release
-function(set_output_directory target dir)
- set_target_properties(${target} PROPERTIES
- RUNTIME_OUTPUT_DIRECTORY ${dir}
- RUNTIME_OUTPUT_DIRECTORY_DEBUG ${dir}
- RUNTIME_OUTPUT_DIRECTORY_RELEASE ${dir}
- RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${dir}
- RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${dir}
- LIBRARY_OUTPUT_DIRECTORY ${dir}
- LIBRARY_OUTPUT_DIRECTORY_DEBUG ${dir}
- LIBRARY_OUTPUT_DIRECTORY_RELEASE ${dir}
- LIBRARY_OUTPUT_DIRECTORY_RELWITHDEBINFO ${dir}
- LIBRARY_OUTPUT_DIRECTORY_MINSIZEREL ${dir}
- ARCHIVE_OUTPUT_DIRECTORY ${dir}
- ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${dir}
- ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${dir}
- ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO ${dir}
- ARCHIVE_OUTPUT_DIRECTORY_MINSIZEREL ${dir}
- )
-endfunction(set_output_directory)
-
-# Set a default build type to release if none was specified
-function(set_default_configuration_release)
- if(CMAKE_CONFIGURATION_TYPES STREQUAL "Debug;Release;MinSizeRel;RelWithDebInfo") # multiconfig generator?
- set(CMAKE_CONFIGURATION_TYPES Release CACHE STRING "" FORCE)
- elseif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
- message(STATUS "Setting build type to 'Release' as none was specified.")
- set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE )
- endif()
-endfunction(set_default_configuration_release)
-
-# Generate nvcc compiler flags given a list of architectures
-# Also generates PTX for the most recent architecture for forwards compatibility
-function(format_gencode_flags flags out)
- if(CMAKE_CUDA_COMPILER_VERSION MATCHES "^([0-9]+\\.[0-9]+)")
- set(CUDA_VERSION "${CMAKE_MATCH_1}")
- endif()
- # Set up architecture flags
- if(NOT flags)
- if(CUDA_VERSION VERSION_GREATER_EQUAL "10.0")
- set(flags "35;50;52;60;61;70;75")
- elseif(CUDA_VERSION VERSION_GREATER_EQUAL "9.0")
- set(flags "35;50;52;60;61;70")
- else()
- set(flags "35;50;52;60;61")
- endif()
- endif()
- # Generate SASS
- foreach(ver ${flags})
- set(${out} "${${out}}--generate-code=arch=compute_${ver},code=sm_${ver};")
- endforeach()
- # Generate PTX for last architecture
- list(GET flags -1 ver)
- set(${out} "${${out}}--generate-code=arch=compute_${ver},code=compute_${ver};")
-
- set(${out} "${${out}}" PARENT_SCOPE)
-endfunction(format_gencode_flags flags)
-
-# Assembles the R-package files in build_dir;
-# if necessary, installs the main R package dependencies;
-# runs R CMD INSTALL.
-function(setup_rpackage_install_target rlib_target build_dir)
- # backup cmake_install.cmake
- install(CODE "file(COPY \"${build_dir}/R-package/cmake_install.cmake\"
-DESTINATION \"${build_dir}/bak\")")
-
- install(CODE "file(REMOVE_RECURSE \"${build_dir}/R-package\")")
- install(
- DIRECTORY "${xgboost_SOURCE_DIR}/R-package"
- DESTINATION "${build_dir}"
- REGEX "src/*" EXCLUDE
- REGEX "R-package/configure" EXCLUDE
- )
- install(TARGETS ${rlib_target}
- LIBRARY DESTINATION "${build_dir}/R-package/src/"
- RUNTIME DESTINATION "${build_dir}/R-package/src/")
- install(CODE "file(WRITE \"${build_dir}/R-package/src/Makevars\" \"all:\")")
- install(CODE "file(WRITE \"${build_dir}/R-package/src/Makevars.win\" \"all:\")")
- set(XGB_DEPS_SCRIPT
- "deps = setdiff(c('data.table', 'magrittr', 'stringi'), rownames(installed.packages()));\
- if(length(deps)>0) install.packages(deps, repo = 'https://cloud.r-project.org/')")
- install(CODE "execute_process(COMMAND \"${LIBR_EXECUTABLE}\" \"-q\" \"-e\" \"${XGB_DEPS_SCRIPT}\")")
- install(CODE "execute_process(COMMAND \"${LIBR_EXECUTABLE}\" CMD INSTALL\
- \"--no-multiarch\" \"--build\" \"${build_dir}/R-package\")")
-
- # restore cmake_install.cmake
- install(CODE "file(RENAME \"${build_dir}/bak/cmake_install.cmake\"
- \"${build_dir}/R-package/cmake_install.cmake\")")
-endfunction(setup_rpackage_install_target)
diff --git a/ml-xgboost/cmake/Version.cmake b/ml-xgboost/cmake/Version.cmake
deleted file mode 100644
index f38ce3c..0000000
--- a/ml-xgboost/cmake/Version.cmake
+++ /dev/null
@@ -1,9 +0,0 @@
-function (write_version)
- message(STATUS "xgboost VERSION: ${xgboost_VERSION}")
- configure_file(
- ${xgboost_SOURCE_DIR}/cmake/version_config.h.in
- ${xgboost_SOURCE_DIR}/include/xgboost/version_config.h @ONLY)
- configure_file(
- ${xgboost_SOURCE_DIR}/cmake/Python_version.in
- ${xgboost_SOURCE_DIR}/python-package/xgboost/VERSION @ONLY)
-endfunction (write_version)
diff --git a/ml-xgboost/cmake/modules/FindASan.cmake b/ml-xgboost/cmake/modules/FindASan.cmake
deleted file mode 100644
index e7b2738..0000000
--- a/ml-xgboost/cmake/modules/FindASan.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-set(ASan_LIB_NAME ASan)
-
-find_library(ASan_LIBRARY
- NAMES libasan.so libasan.so.5 libasan.so.4 libasan.so.3 libasan.so.2 libasan.so.1 libasan.so.0
- PATHS ${SANITIZER_PATH} /usr/lib64 /usr/lib /usr/local/lib64 /usr/local/lib ${CMAKE_PREFIX_PATH}/lib)
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(ASan DEFAULT_MSG
- ASan_LIBRARY)
-
-mark_as_advanced(
- ASan_LIBRARY
- ASan_LIB_NAME)
diff --git a/ml-xgboost/cmake/modules/FindLSan.cmake b/ml-xgboost/cmake/modules/FindLSan.cmake
deleted file mode 100644
index 3f68fb0..0000000
--- a/ml-xgboost/cmake/modules/FindLSan.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-set(LSan_LIB_NAME lsan)
-
-find_library(LSan_LIBRARY
- NAMES liblsan.so liblsan.so.0 liblsan.so.0.0.0
- PATHS ${SANITIZER_PATH} /usr/lib64 /usr/lib /usr/local/lib64 /usr/local/lib ${CMAKE_PREFIX_PATH}/lib)
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(LSan DEFAULT_MSG
- LSan_LIBRARY)
-
-mark_as_advanced(
- LSan_LIBRARY
- LSan_LIB_NAME)
diff --git a/ml-xgboost/cmake/modules/FindLibR.cmake b/ml-xgboost/cmake/modules/FindLibR.cmake
deleted file mode 100644
index 0110439..0000000
--- a/ml-xgboost/cmake/modules/FindLibR.cmake
+++ /dev/null
@@ -1,183 +0,0 @@
-# CMake module for R
-# Borrows ideas from RStudio's FindLibR.cmake
-#
-# Defines the following:
-# LIBR_FOUND
-# LIBR_HOME
-# LIBR_EXECUTABLE
-# LIBR_INCLUDE_DIRS
-# LIBR_LIB_DIR
-# LIBR_CORE_LIBRARY
-# and a cmake function to create R.lib for MSVC
-#
-# The following could be provided by user through cmake's -D options:
-# LIBR_EXECUTABLE (for unix and win)
-# R_VERSION (for win)
-# R_ARCH (for win 64 when want 32 bit build)
-#
-# TODO:
-# - someone to verify OSX detection,
-# - possibly, add OSX detection based on current R in PATH or LIBR_EXECUTABLE
-# - improve registry-based R_HOME detection in Windows (from a set of R_VERSION's)
-
-
-# Windows users might want to change this to their R version:
-if(NOT R_VERSION)
- set(R_VERSION "3.4.1")
-endif()
-if(NOT R_ARCH)
- if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "4")
- set(R_ARCH "i386")
- else()
- set(R_ARCH "x64")
- endif()
-endif()
-
-
-# Creates R.lib and R.def in the build directory for linking with MSVC
-function(create_rlib_for_msvc)
- # various checks and warnings
- if(NOT WIN32 OR NOT MSVC)
- message(FATAL_ERROR "create_rlib_for_msvc() can only be used with MSVC")
- endif()
- if(NOT EXISTS "${LIBR_LIB_DIR}")
- message(FATAL_ERROR "LIBR_LIB_DIR was not set!")
- endif()
- find_program(GENDEF_EXE gendef)
- find_program(DLLTOOL_EXE dlltool)
- if(NOT GENDEF_EXE OR NOT DLLTOOL_EXE)
- message(FATAL_ERROR "\nEither gendef.exe or dlltool.exe not found!\
- \nDo you have Rtools installed with its MinGW's bin/ in PATH?")
- endif()
- # extract symbols from R.dll into R.def and R.lib import library
- execute_process(COMMAND ${GENDEF_EXE}
- "-" "${LIBR_LIB_DIR}/R.dll"
- OUTPUT_FILE "${CMAKE_CURRENT_BINARY_DIR}/R.def")
- execute_process(COMMAND ${DLLTOOL_EXE}
- "--input-def" "${CMAKE_CURRENT_BINARY_DIR}/R.def"
- "--output-lib" "${CMAKE_CURRENT_BINARY_DIR}/R.lib")
-endfunction(create_rlib_for_msvc)
-
-
-# detection for OSX
-if(APPLE)
-
- find_library(LIBR_LIBRARIES R)
-
- if(LIBR_LIBRARIES MATCHES ".*\\.framework")
- set(LIBR_HOME "${LIBR_LIBRARIES}/Resources" CACHE PATH "R home directory")
- set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory")
- set(LIBR_EXECUTABLE "${LIBR_HOME}/R" CACHE PATH "R executable")
- set(LIBR_LIB_DIR "${LIBR_HOME}/lib" CACHE PATH "R lib directory")
- else()
- get_filename_component(_LIBR_LIBRARIES "${LIBR_LIBRARIES}" REALPATH)
- get_filename_component(_LIBR_LIBRARIES_DIR "${_LIBR_LIBRARIES}" DIRECTORY)
- set(LIBR_EXECUTABLE "${_LIBR_LIBRARIES_DIR}/../bin/R")
- execute_process(
- COMMAND ${LIBR_EXECUTABLE} "--slave" "--vanilla" "-e" "cat(R.home())"
- OUTPUT_VARIABLE LIBR_HOME)
- set(LIBR_HOME ${LIBR_HOME} CACHE PATH "R home directory")
- set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include" CACHE PATH "R include directory")
- set(LIBR_LIB_DIR "${LIBR_HOME}/lib" CACHE PATH "R lib directory")
- endif()
-
-# detection for UNIX & Win32
-else()
-
- # attempt to find R executable
- if(NOT LIBR_EXECUTABLE)
- find_program(LIBR_EXECUTABLE NAMES R R.exe)
- endif()
-
- if(UNIX)
-
- if(NOT LIBR_EXECUTABLE)
- message(FATAL_ERROR "Unable to locate R executable.\
- \nEither add its location to PATH or provide it through the LIBR_EXECUTABLE cmake variable")
- endif()
-
- # ask R for the home path
- execute_process(
- COMMAND ${LIBR_EXECUTABLE} "--slave" "--vanilla" "-e" "cat(R.home())"
- OUTPUT_VARIABLE LIBR_HOME
- )
- # ask R for the include dir
- execute_process(
- COMMAND ${LIBR_EXECUTABLE} "--slave" "--vanilla" "-e" "cat(R.home('include'))"
- OUTPUT_VARIABLE LIBR_INCLUDE_DIRS
- )
- # ask R for the lib dir
- execute_process(
- COMMAND ${LIBR_EXECUTABLE} "--slave" "--vanilla" "-e" "cat(R.home('lib'))"
- OUTPUT_VARIABLE LIBR_LIB_DIR
- )
-
- # Windows
- else()
- # ask R for R_HOME
- if(LIBR_EXECUTABLE)
- execute_process(
- COMMAND ${LIBR_EXECUTABLE} "--slave" "--no-save" "-e" "cat(normalizePath(R.home(),winslash='/'))"
- OUTPUT_VARIABLE LIBR_HOME)
- endif()
- # if R executable not available, query R_HOME path from registry
- if(NOT LIBR_HOME)
- get_filename_component(LIBR_HOME
- "[HKEY_LOCAL_MACHINE\\SOFTWARE\\R-core\\R\\${R_VERSION};InstallPath]"
- ABSOLUTE)
- if(NOT LIBR_HOME)
- message(FATAL_ERROR "\nUnable to locate R executable.\
- \nEither add its location to PATH or provide it through the LIBR_EXECUTABLE cmake variable")
- endif()
- endif()
- # set exe location based on R_ARCH
- if(NOT LIBR_EXECUTABLE)
- set(LIBR_EXECUTABLE "${LIBR_HOME}/bin/${R_ARCH}/R.exe")
- endif()
- # set other R paths based on home path
- set(LIBR_INCLUDE_DIRS "${LIBR_HOME}/include")
- set(LIBR_LIB_DIR "${LIBR_HOME}/bin/${R_ARCH}")
-
-message(STATUS "LIBR_HOME [${LIBR_HOME}]")
-message(STATUS "LIBR_EXECUTABLE [${LIBR_EXECUTABLE}]")
-message(STATUS "LIBR_INCLUDE_DIRS [${LIBR_INCLUDE_DIRS}]")
-message(STATUS "LIBR_LIB_DIR [${LIBR_LIB_DIR}]")
-message(STATUS "LIBR_CORE_LIBRARY [${LIBR_CORE_LIBRARY}]")
-
- endif()
-
-endif()
-
-if(WIN32 AND MSVC)
- # create a local R.lib import library for R.dll if it doesn't exist
- if(NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/R.lib")
- create_rlib_for_msvc()
- endif()
-endif()
-
-# look for the core R library
-find_library(LIBR_CORE_LIBRARY NAMES R
- HINTS "${CMAKE_CURRENT_BINARY_DIR}" "${LIBR_LIB_DIR}" "${LIBR_HOME}/bin" "${LIBR_LIBRARIES}")
-if(LIBR_CORE_LIBRARY-NOTFOUND)
- message(STATUS "Could not find R core shared library.")
-endif()
-
-set(LIBR_HOME ${LIBR_HOME} CACHE PATH "R home directory")
-set(LIBR_EXECUTABLE ${LIBR_EXECUTABLE} CACHE PATH "R executable")
-set(LIBR_INCLUDE_DIRS ${LIBR_INCLUDE_DIRS} CACHE PATH "R include directory")
-set(LIBR_LIB_DIR ${LIBR_LIB_DIR} CACHE PATH "R shared libraries directory")
-set(LIBR_CORE_LIBRARY ${LIBR_CORE_LIBRARY} CACHE PATH "R core shared library")
-
-# define find requirements
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(LibR DEFAULT_MSG
- LIBR_HOME
- LIBR_EXECUTABLE
- LIBR_INCLUDE_DIRS
- LIBR_LIB_DIR
- LIBR_CORE_LIBRARY
-)
-
-if(LIBR_FOUND)
- message(STATUS "Found R: ${LIBR_EXECUTABLE}")
-endif()
diff --git a/ml-xgboost/cmake/modules/FindNVML.cmake b/ml-xgboost/cmake/modules/FindNVML.cmake
deleted file mode 100644
index a4bed00..0000000
--- a/ml-xgboost/cmake/modules/FindNVML.cmake
+++ /dev/null
@@ -1,23 +0,0 @@
-if (NVML_LIBRARY)
- unset(NVML_LIBRARY CACHE)
-endif(NVML_LIBRARY)
-
-set(NVML_LIB_NAME nvml)
-
-find_path(NVML_INCLUDE_DIR
- NAMES nvml.h
- PATHS ${CUDA_HOME}/include ${CUDA_INCLUDE} /usr/local/cuda/include)
-
-find_library(NVML_LIBRARY
- NAMES nvidia-ml)
-
-message(STATUS "Using nvml library: ${NVML_LIBRARY}")
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(NVML DEFAULT_MSG
- NVML_INCLUDE_DIR NVML_LIBRARY)
-
-mark_as_advanced(
- NVML_INCLUDE_DIR
- NVML_LIBRARY
-)
diff --git a/ml-xgboost/cmake/modules/FindNccl.cmake b/ml-xgboost/cmake/modules/FindNccl.cmake
deleted file mode 100644
index 643c45f..0000000
--- a/ml-xgboost/cmake/modules/FindNccl.cmake
+++ /dev/null
@@ -1,65 +0,0 @@
-#
-# Licensed 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.
-#
-# Tries to find NCCL headers and libraries.
-#
-# Usage of this module as follows:
-#
-# find_package(NCCL)
-#
-# Variables used by this module, they can change the default behaviour and need
-# to be set before calling find_package:
-#
-# NCCL_ROOT - When set, this path is inspected instead of standard library
-# locations as the root of the NCCL installation.
-# The environment variable NCCL_ROOT overrides this veriable.
-#
-# This module defines
-# Nccl_FOUND, whether nccl has been found
-# NCCL_INCLUDE_DIR, directory containing header
-# NCCL_LIBRARY, directory containing nccl library
-# NCCL_LIB_NAME, nccl library name
-#
-# This module assumes that the user has already called find_package(CUDA)
-
-if (NCCL_LIBRARY)
- # Don't cache NCCL_LIBRARY to enable switching between static and shared.
- unset(NCCL_LIBRARY CACHE)
-endif()
-
-if (BUILD_WITH_SHARED_NCCL)
- # libnccl.so
- set(NCCL_LIB_NAME nccl)
-else ()
- # libnccl_static.a
- set(NCCL_LIB_NAME nccl_static)
-endif (BUILD_WITH_SHARED_NCCL)
-
-find_path(NCCL_INCLUDE_DIR
- NAMES nccl.h
- PATHS $ENV{NCCL_ROOT}/include ${NCCL_ROOT}/include)
-
-find_library(NCCL_LIBRARY
- NAMES ${NCCL_LIB_NAME}
- PATHS $ENV{NCCL_ROOT}/lib/ ${NCCL_ROOT}/lib)
-
-message(STATUS "Using nccl library: ${NCCL_LIBRARY}")
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(Nccl DEFAULT_MSG
- NCCL_INCLUDE_DIR NCCL_LIBRARY)
-
-mark_as_advanced(
- NCCL_INCLUDE_DIR
- NCCL_LIBRARY
-)
diff --git a/ml-xgboost/cmake/modules/FindTSan.cmake b/ml-xgboost/cmake/modules/FindTSan.cmake
deleted file mode 100644
index aa01802..0000000
--- a/ml-xgboost/cmake/modules/FindTSan.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-set(TSan_LIB_NAME tsan)
-
-find_library(TSan_LIBRARY
- NAMES libtsan.so libtsan.so.0 libtsan.so.0.0.0
- PATHS ${SANITIZER_PATH} /usr/lib64 /usr/lib /usr/local/lib64 /usr/local/lib ${CMAKE_PREFIX_PATH}/lib)
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(TSan DEFAULT_MSG
- TSan_LIBRARY)
-
-mark_as_advanced(
- TSan_LIBRARY
- TSan_LIB_NAME)
diff --git a/ml-xgboost/cmake/modules/FindUBSan.cmake b/ml-xgboost/cmake/modules/FindUBSan.cmake
deleted file mode 100644
index e1b72eb..0000000
--- a/ml-xgboost/cmake/modules/FindUBSan.cmake
+++ /dev/null
@@ -1,13 +0,0 @@
-set(UBSan_LIB_NAME UBSan)
-
-find_library(UBSan_LIBRARY
- NAMES libubsan.so libubsan.so.5 libubsan.so.4 libubsan.so.3 libubsan.so.2 libubsan.so.1 libubsan.so.0
- PATHS ${SANITIZER_PATH} /usr/lib64 /usr/lib /usr/local/lib64 /usr/local/lib ${CMAKE_PREFIX_PATH}/lib)
-
-include(FindPackageHandleStandardArgs)
-find_package_handle_standard_args(UBSan DEFAULT_MSG
- UBSan_LIBRARY)
-
-mark_as_advanced(
- UBSan_LIBRARY
- UBSan_LIB_NAME)
diff --git a/ml-xgboost/cmake/version_config.h.in b/ml-xgboost/cmake/version_config.h.in
deleted file mode 100644
index dfde79a..0000000
--- a/ml-xgboost/cmake/version_config.h.in
+++ /dev/null
@@ -1,11 +0,0 @@
-/*!
- * Copyright 2019 XGBoost contributors
- */
-#ifndef XGBOOST_VERSION_CONFIG_H_
-#define XGBOOST_VERSION_CONFIG_H_
-
-#define XGBOOST_VER_MAJOR @xgboost_VERSION_MAJOR@
-#define XGBOOST_VER_MINOR @xgboost_VERSION_MINOR@
-#define XGBOOST_VER_PATCH @xgboost_VERSION_PATCH@
-
-#endif // XGBOOST_VERSION_CONFIG_H_
diff --git a/ml-xgboost/cmake/xgboost-config.cmake.in b/ml-xgboost/cmake/xgboost-config.cmake.in
deleted file mode 100644
index 6a155f0..0000000
--- a/ml-xgboost/cmake/xgboost-config.cmake.in
+++ /dev/null
@@ -1,5 +0,0 @@
-@PACKAGE_INIT@
-
-if(NOT TARGET xgboost::xgboost)
- include(${CMAKE_CURRENT_LIST_DIR}/XGBoostTargets.cmake)
-endif()
diff --git a/ml-xgboost/cub/.cproject b/ml-xgboost/cub/.cproject
deleted file mode 100644
index 5e970a7..0000000
--- a/ml-xgboost/cub/.cproject
+++ /dev/null
@@ -1,1211 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/ml-xgboost/cub/CHANGE_LOG.TXT b/ml-xgboost/cub/CHANGE_LOG.TXT
deleted file mode 100644
index 837dcc2..0000000
--- a/ml-xgboost/cub/CHANGE_LOG.TXT
+++ /dev/null
@@ -1,346 +0,0 @@
-1.7.0 06/07/2017
- - Compatible with CUDA9 and SM7.x (Volta) independent thread scheduling
- - API change: remove cub::WarpAll() and cub::WarpAny(). These functions served to
- emulate __all and __any functionality for SM1.x devices, which did not have those
- operations. However, the SM1.x devices are now deprecated in CUDA, and the
- interfaces of the these two functions are now lacking the lane-mask needed
- for collectives to run on Volta SMs having independent thread scheduling.
- - Bug fixes:
- - Issue #86 Incorrect results with ReduceByKey
-
-//-----------------------------------------------------------------------------
-
-1.6.4 12/06/2016
- - Updated sm_5x, sm_6x tuning policies for radix sorting (3.5B and 3.4B
- 32b keys/s on TitanX and GTX 1080, respectively)
- - Bug fixes:
- - Restore fence work-around for scan (reduce-by-key, etc.) hangs
- in CUDA 8.5
- - Issue 65: DeviceSegmentedRadixSort should allow inputs to have
- pointer-to-const type
- - Mollify Clang device-side warnings
- - Remove out-dated VC project files
-
-//-----------------------------------------------------------------------------
-
-1.6.3 11/20/2016
- - API change: BlockLoad and BlockStore are now templated by the local
- data type, instead of the Iterator type. This allows for output iterators
- having \p void as their \p value_type (e.g., discard iterators).
- - Updated GP100 tuning policies for radix sorting (6.2B 32b keys/s)
- - Bug fixes:
- - Issue #74: Warpreduce executes reduction operator for out-of-bounds items
- - Issue #72 (cub:InequalityWrapper::operator() should be non-const)
- - Issue #71 (KeyVairPair won't work if Key has non-trivial ctor)
- - Issue #70 1.5.3 breaks BlockScan API. Retroactively reversioned
- from v1.5.3 -> v1.6 to appropriately indicate API change.
- - Issue #69 cub::BlockStore::Store doesn't compile if OutputIteratorT::value_type != T
- - Issue #68 (cub::TilePrefixCallbackOp::WarpReduce doesn't permit ptx
- arch specialization)
- - Improved support for Win32 platforms (warnings, alignment, etc)
-
-//-----------------------------------------------------------------------------
-
-1.6.2 (was 1.5.5) 10/25/2016
- - Updated Pascal tuning policies for radix sorting
- - Bug fixes:
- - Fix for arm64 compilation of caching allocator
-
-//-----------------------------------------------------------------------------
-
-1.6.1 (was 1.5.4) 10/14/2016
- - Bug fixes:
- - Fix for radix sorting bug introduced by scan refactorization
-
-//-----------------------------------------------------------------------------
-
-1.6.0 (was 1.5.3) 10/11/2016
- - API change: Device/block/warp-wide exclusive scans have been revised to now
- accept an "initial value" (instead of an "identity value") for seeding the
- computation with an arbitrary prefix.
- - API change: Device-wide reductions and scans can now have input sequence types that are
- different from output sequence types (as long as they are coercible)
- value") for seeding the computation with an arbitrary prefix
- - Reduce repository size (move doxygen binary to doc repository)
- - Minor reductions in block-scan instruction count
- - Bug fixes:
- - Issue #55: warning in cub/device/dispatch/dispatch_reduce_by_key.cuh
- - Issue #59: cub::DeviceScan::ExclusiveSum can't prefix sum of float into double
- - Issue #58: Infinite loop in cub::CachingDeviceAllocator::NearestPowerOf
- - Issue #47: Caching allocator needs to clean up cuda error upon successful retry
- - Issue #46: Very high amount of needed memory from the cub::DeviceHistogram::HistogramEven routine
- - Issue #45: Caching Device Allocator fails with debug output enabled
- - Fix for generic-type reduce-by-key warpscan (sm3.x and newer)
-
-//-----------------------------------------------------------------------------
-
-1.5.2 03/21/2016
- - Improved medium-size scan performance for sm5x (Maxwell)
- - Refactored caching allocator for device memory
- - Spends less time locked
- - Failure to allocate a block from the runtime will retry once after
- freeing cached allocations
- - Now respects max-bin (issue where blocks in excess of max-bin were
- still being retained in free cache)
- - Uses C++11 mutex when available
- - Bug fixes:
- - Fix for generic-type reduce-by-key warpscan (sm3.x and newer)
-
-//-----------------------------------------------------------------------------
-
-1.5.1 12/28/2015
- - Bug fixes:
- - Fix for incorrect DeviceRadixSort output for some small problems on
- Maxwell SM52 architectures
- - Fix for macro redefinition warnings when compiling with Thrust sort
-
-//-----------------------------------------------------------------------------
-
-1.5.0 12/14/2015
- - New Features:
- - Added new segmented device-wide operations for device-wide sort and
- reduction primitives.
- - Bug fixes:
- - Fix for Git Issue 36 (Compilation error with GCC 4.8.4 nvcc 7.0.27) and
- Forums thread (ThreadLoad generates compiler errors when loading from
- pointer-to-const)
- - Fix for Git Issue 29 (DeviceRadixSort::SortKeys yields compiler
- errors)
- - Fix for Git Issue 26 (CUDA error: misaligned address after
- cub::DeviceRadixSort::SortKeys())
- - Fix for incorrect/crash on 0-length problems, e.g., Git Issue 25 (Floating
- point exception (core dumped) during cub::DeviceRadixSort::SortKeys)
- - Fix for CUDA 7.5 issues on SM 5.2 with SHFL-based warp-scan and warp-reduction
- on non-primitive data types (e.g., user-defined structs)
- - Fix for small radix sorting problems where 0 temporary bytes were
- required and users code was invoking malloc(0) on some systems where
- that returns NULL. (Impl assumed was asking for size again and was not
- running the sort.)
-
-//-----------------------------------------------------------------------------
-
-1.4.1 04/13/2015
- - Bug fixes:
- - Fixes for CUDA 7.0 issues with SHFL-based warp-scan and warp-reduction
- on non-primitive data types (e.g., user-defined structs)
- - Fixes for minor CUDA 7.0 performance regressions in cub::DeviceScan,
- DeviceReduceByKey
- - Fixes to allow cub::DeviceRadixSort and cub::BlockRadixSort on bool types
- - Remove requirement for callers to define the CUB_CDP macro
- when invoking CUB device-wide rountines using CUDA dynamic parallelism
- - Fix for headers not being included in the proper order (or missing includes)
- for some block-wide functions
-
-//-----------------------------------------------------------------------------
-
-1.4.0 03/18/2015
- - New Features:
- - Support and performance tuning for new Maxwell GPU architectures
- - Updated cub::DeviceHistogram implementation that provides the same
- "histogram-even" and "histogram-range" functionality as IPP/NPP.
- Provides extremely fast and, perhaps more importantly, very
- uniform performance response across diverse real-world datasets,
- including pathological (homogeneous) sample distributions (resilience)
- - New cub::DeviceSpmv methods for multiplying sparse matrices by
- dense vectors, load-balanced using a merge-based parallel decomposition.
- - New cub::DeviceRadixSort sorting entry-points that always return
- the sorted output into the specified buffer (as opposed to the
- cub::DoubleBuffer in which it could end up in either buffer)
- - New cub::DeviceRunLengthEncode::NonTrivialRuns for finding the starting
- offsets and lengths of all non-trivial runs (i.e., length > 1) of keys in
- a given sequence. (Useful for top-down partitioning algorithms like
- MSD sorting of very-large keys.)
-
-//-----------------------------------------------------------------------------
-
-1.3.2 07/28/2014
- - Bug fixes:
- - Fix for cub::DeviceReduce where reductions of small problems
- (small enough to only dispatch a single threadblock) would run in
- the default stream (stream zero) regardless of whether an alternate
- stream was specified.
-
-//-----------------------------------------------------------------------------
-
-1.3.1 05/23/2014
- - Bug fixes:
- - Workaround for a benign WAW race warning reported by cuda-memcheck
- in BlockScan specialized for BLOCK_SCAN_WARP_SCANS algorithm.
- - Fix for bug in DeviceRadixSort where the algorithm may sort more
- key bits than the caller specified (up to the nearest radix digit).
- - Fix for ~3% DeviceRadixSort performance regression on Kepler and
- Fermi that was introduced in v1.3.0.
-
-//-----------------------------------------------------------------------------
-
-1.3.0 05/12/2014
- - New features:
- - CUB's collective (block-wide, warp-wide) primitives underwent a minor
- interface refactoring:
- - To provide the appropriate support for multidimensional thread blocks,
- The interfaces for collective classes are now template-parameterized
- by X, Y, and Z block dimensions (with BLOCK_DIM_Y and BLOCK_DIM_Z being
- optional, and BLOCK_DIM_X replacing BLOCK_THREADS). Furthermore, the
- constructors that accept remapped linear thread-identifiers have been
- removed: all primitives now assume a row-major thread-ranking for
- multidimensional thread blocks.
- - To allow the host program (compiled by the host-pass) to
- accurately determine the device-specific storage requirements for
- a given collective (compiled for each device-pass), the interfaces
- for collective classes are now (optionally) template-parameterized
- by the desired PTX compute capability. This is useful when
- aliasing collective storage to shared memory that has been
- allocated dynamically by the host at the kernel call site.
- - Most CUB programs having typical 1D usage should not require any
- changes to accomodate these updates.
- - Added new "combination" WarpScan methods for efficiently computing
- both inclusive and exclusive prefix scans (and sums).
- - Bug fixes:
- - Fixed bug in cub::WarpScan (which affected cub::BlockScan and
- cub::DeviceScan) where incorrect results (e.g., NAN) would often be
- returned when parameterized for floating-point types (fp32, fp64).
- - Workaround-fix for ptxas error when compiling with with -G flag on Linux
- (for debug instrumentation)
- - Misc. workaround-fixes for certain scan scenarios (using custom
- scan operators) where code compiled for SM1x is run on newer
- GPUs of higher compute-capability: the compiler could not tell
- which memory space was being used collective operations and was
- mistakenly using global ops instead of shared ops.
-
-//-----------------------------------------------------------------------------
-
-1.2.3 04/01/2014
- - Bug fixes:
- - Fixed access violation bug in DeviceReduce::ReduceByKey for non-primitive value types
- - Fixed code-snippet bug in ArgIndexInputIteratorT documentation
-
-//-----------------------------------------------------------------------------
-
-1.2.2 03/03/2014
- - New features:
- - Added MS VC++ project solutions for device-wide and block-wide examples
- - Performance:
- - Added a third algorithmic variant of cub::BlockReduce for improved performance
- when using commutative operators (e.g., numeric addition)
- - Bug fixes:
- - Fixed bug where inclusion of Thrust headers in a certain order prevented CUB device-wide primitives from working properly
-
-//-----------------------------------------------------------------------------
-
-1.2.0 02/25/2014
- - New features:
- - Added device-wide reduce-by-key (DeviceReduce::ReduceByKey, DeviceReduce::RunLengthEncode)
- - Performance
- - Improved DeviceScan, DeviceSelect, DevicePartition performance
- - Documentation and testing:
- - Compatible with CUDA 6.0
- - Added performance-portability plots for many device-wide primitives to doc
- - Update doc and tests to reflect iterator (in)compatibilities with CUDA 5.0 (and older) and Thrust 1.6 (and older).
- - Bug fixes
- - Revised the operation of temporary tile status bookkeeping for DeviceScan (and similar) to be safe for current code run on future platforms (now uses proper fences)
- - Fixed DeviceScan bug where Win32 alignment disagreements between host and device regarding user-defined data types would corrupt tile status
- - Fixed BlockScan bug where certain exclusive scans on custom data types for the BLOCK_SCAN_WARP_SCANS variant would return incorrect results for the first thread in the block
- - Added workaround for TexRefInputIteratorTto work with CUDA 6.0
-
-//-----------------------------------------------------------------------------
-
-1.1.1 12/11/2013
- - New features:
- - Added TexObjInputIteratorT, TexRefInputIteratorT, CacheModifiedInputIteratorT, and CacheModifiedOutputIterator types for loading & storing arbitrary types through the cache hierarchy. Compatible with Thrust API.
- - Added descending sorting to DeviceRadixSort and BlockRadixSort
- - Added min, max, arg-min, and arg-max to DeviceReduce
- - Added DeviceSelect (select-unique, select-if, and select-flagged)
- - Added DevicePartition (partition-if, partition-flagged)
- - Added generic cub::ShuffleUp(), cub::ShuffleDown(), and cub::ShuffleIndex() for warp-wide communication of arbitrary data types (SM3x+)
- - Added cub::MaxSmOccupancy() for accurately determining SM occupancy for any given kernel function pointer
- - Performance
- - Improved DeviceScan and DeviceRadixSort performance for older architectures (SM10-SM30)
- - Interface changes:
- - Refactored block-wide I/O (BlockLoad and BlockStore), removing cache-modifiers from their interfaces. The CacheModifiedInputIteratorTand CacheModifiedOutputIterator should now be used with BlockLoad and BlockStore to effect that behavior.
- - Rename device-wide "stream_synchronous" param to "debug_synchronous" to avoid confusion about usage
- - Documentation and testing:
- - Added simple examples of device-wide methods
- - Improved doxygen documentation and example snippets
- - Improved test coverege to include up to 21,000 kernel variants and 851,000 unit tests (per architecture, per platform)
- - Bug fixes
- - Fixed misc DeviceScan, BlockScan, DeviceReduce, and BlockReduce bugs when operating on non-primitive types for older architectures SM10-SM13
- - Fixed DeviceScan / WarpReduction bug: SHFL-based segmented reduction producting incorrect results for multi-word types (size > 4B) on Linux
- - Fixed BlockScan bug: For warpscan-based scans, not all threads in the first warp were entering the prefix callback functor
- - Fixed DeviceRadixSort bug: race condition with key-value pairs for pre-SM35 architectures
- - Fixed DeviceRadixSort bug: incorrect bitfield-extract behavior with long keys on 64bit Linux
- - Fixed BlockDiscontinuity bug: complation error in for types other than int32/uint32
- - CDP (device-callable) versions of device-wide methods now report the same temporary storage allocation size requirement as their host-callable counterparts
-
-
-//-----------------------------------------------------------------------------
-
-1.0.2 08/23/2013
- - Corrections to code snippet examples for BlockLoad, BlockStore, and BlockDiscontinuity
- - Cleaned up unnecessary/missing header includes. You can now safely #inlude a specific .cuh (instead of cub.cuh)
- - Bug/compilation fixes for BlockHistogram
-
-//-----------------------------------------------------------------------------
-
-1.0.1 08/08/2013
- - New collective interface idiom (specialize::construct::invoke).
- - Added best-in-class DeviceRadixSort. Implements short-circuiting for homogenous digit passes.
- - Added best-in-class DeviceScan. Implements single-pass "adaptive-lookback" strategy.
- - Significantly improved documentation (with example code snippets)
- - More extensive regression test suit for aggressively testing collective variants
- - Allow non-trially-constructed types (previously unions had prevented aliasing temporary storage of those types)
- - Improved support for Kepler SHFL (collective ops now use SHFL for types larger than 32b)
- - Better code generation for 64-bit addressing within BlockLoad/BlockStore
- - DeviceHistogram now supports histograms of arbitrary bins
- - Misc. fixes
- - Workarounds for SM10 codegen issues in uncommonly-used WarpScan/Reduce specializations
- - Updates to accommodate CUDA 5.5 dynamic parallelism
-
-
-//-----------------------------------------------------------------------------
-
-0.9.4 05/07/2013
-
- - Fixed compilation errors for SM10-SM13
- - Fixed compilation errors for some WarpScan entrypoints on SM30+
- - Added block-wide histogram (BlockHistogram256)
- - Added device-wide histogram (DeviceHistogram256)
- - Added new BlockScan algorithm variant BLOCK_SCAN_RAKING_MEMOIZE, which
- trades more register consumption for less shared memory I/O)
- - Updates to BlockRadixRank to use BlockScan (which improves performance
- on Kepler due to SHFL instruction)
- - Allow types other than C++ primitives to be used in WarpScan::*Sum methods
- if they only have operator + overloaded. (Previously they also required
- to support assignment from int(0).)
- - Update BlockReduce's BLOCK_REDUCE_WARP_REDUCTIONS algorithm to work even
- when block size is not an even multiple of warp size
- - Added work management utility descriptors (GridQueue, GridEvenShare)
- - Refactoring of DeviceAllocator interface and CachingDeviceAllocator
- implementation
- - Misc. documentation updates and corrections.
-
-//-----------------------------------------------------------------------------
-
-0.9.2 04/04/2013
-
- - Added WarpReduce. WarpReduce uses the SHFL instruction when applicable.
- BlockReduce now uses this WarpReduce instead of implementing its own.
- - Misc. fixes for 64-bit Linux compilation warnings and errors.
- - Misc. documentation updates and corrections.
-
-//-----------------------------------------------------------------------------
-
-0.9.1 03/09/2013
-
- - Fix for ambiguity in BlockScan::Reduce() between generic reduction and
- summation. Summation entrypoints are now called ::Sum(), similar to the
- convention in BlockScan.
- - Small edits to mainpage documentation and download tracking
-
-//-----------------------------------------------------------------------------
-
-0.9.0 03/07/2013
-
- - Intial "preview" release. CUB is the first durable, high-performance library
- of cooperative block-level, warp-level, and thread-level primitives for CUDA
- kernel programming. More primitives and examples coming soon!
-
\ No newline at end of file
diff --git a/ml-xgboost/cub/LICENSE.TXT b/ml-xgboost/cub/LICENSE.TXT
deleted file mode 100644
index 9ba3b78..0000000
--- a/ml-xgboost/cub/LICENSE.TXT
+++ /dev/null
@@ -1,24 +0,0 @@
-Copyright (c) 2010-2011, Duane Merrill. All rights reserved.
-Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- * Neither the name of the NVIDIA CORPORATION nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
-DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/ml-xgboost/cub/README.md b/ml-xgboost/cub/README.md
deleted file mode 100644
index 1ffcf84..0000000
--- a/ml-xgboost/cub/README.md
+++ /dev/null
@@ -1,128 +0,0 @@
-
-About CUB
-
-Current release: v1.6.4 (12/06/2016)
-
-We recommend the [CUB Project Website](http://nvlabs.github.com/cub) and the [cub-users discussion forum](http://groups.google.com/group/cub-users) for further information and examples.
-
-CUB provides state-of-the-art, reusable software components for every layer
-of the CUDA programming model:
-- [Device-wide primitives ] (https://nvlabs.github.com/cub/group___device_module.html)
- - Sort, prefix scan, reduction, histogram, etc.
- - Compatible with CUDA dynamic parallelism
-- [Block-wide "collective" primitives ] (https://nvlabs.github.com/cub/group___block_module.html)
- - I/O, sort, prefix scan, reduction, histogram, etc.
- - Compatible with arbitrary thread block sizes and types
-- [Warp-wide "collective" primitives ] (https://nvlabs.github.com/cub/group___warp_module.html)
- - Warp-wide prefix scan, reduction, etc.
- - Safe and architecture-specific
-- [Thread and resource utilities ](https://nvlabs.github.com/cub/group___thread_module.html)
- - PTX intrinsics, device reflection, texture-caching iterators, caching memory allocators, etc.
-
-![Orientation of collective primitives within the CUDA software stack](http://nvlabs.github.com/cub/cub_overview.png)
-
-
-A Simple Example
-
-```C++
-#include
-
-// Block-sorting CUDA kernel
-__global__ void BlockSortKernel(int *d_in, int *d_out)
-{
- using namespace cub;
-
- // Specialize BlockRadixSort, BlockLoad, and BlockStore for 128 threads
- // owning 16 integer items each
- typedef BlockRadixSort BlockRadixSort;
- typedef BlockLoad BlockLoad;
- typedef BlockStore BlockStore;
-
- // Allocate shared memory
- __shared__ union {
- typename BlockRadixSort::TempStorage sort;
- typename BlockLoad::TempStorage load;
- typename BlockStore::TempStorage store;
- } temp_storage;
-
- int block_offset = blockIdx.x * (128 * 16); // OffsetT for this block's ment
-
- // Obtain a segment of 2048 consecutive keys that are blocked across threads
- int thread_keys[16];
- BlockLoad(temp_storage.load).Load(d_in + block_offset, thread_keys);
- __syncthreads();
-
- // Collectively sort the keys
- BlockRadixSort(temp_storage.sort).Sort(thread_keys);
- __syncthreads();
-
- // Store the sorted segment
- BlockStore(temp_storage.store).Store(d_out + block_offset, thread_keys);
-}
-```
-
-Each thread block uses cub::BlockRadixSort to collectively sort
-its own input segment. The class is specialized by the
-data type being sorted, by the number of threads per block, by the number of
-keys per thread, and implicitly by the targeted compilation architecture.
-
-The cub::BlockLoad and cub::BlockStore classes are similarly specialized.
-Furthermore, to provide coalesced accesses to device memory, these primitives are
-configured to access memory using a striped access pattern (where consecutive threads
-simultaneously access consecutive items) and then transpose the keys into
-a [blocked arrangement ](index.html#sec4sec3) of elements across threads.
-
-Once specialized, these classes expose opaque \p TempStorage member types.
-The thread block uses these storage types to statically allocate the union of
-shared memory needed by the thread block. (Alternatively these storage types
-could be aliased to global memory allocations).
-
-
-Stable Releases
-
-CUB releases are labeled using version identifiers having three fields:
-*epoch.feature.update*. The *epoch* field corresponds to support for
-a major change in the CUDA programming model. The *feature* field
-corresponds to a stable set of features, functionality, and interface. The
-*update* field corresponds to a bug-fix or performance update for that
-feature set. At the moment, we do not publicly provide non-stable releases
-such as development snapshots, beta releases or rolling releases. (Feel free
-to contact us if you would like such things.) See the
-[CUB Project Website](http://nvlabs.github.com/cub) for more information.
-
-
-Contributors
-
-CUB is developed as an open-source project by [NVIDIA Research](http://research.nvidia.com). The primary contributor is [Duane Merrill](http://github.com/dumerrill).
-
-
-Open Source License
-
-CUB is available under the "New BSD" open-source license:
-
-```
-Copyright (c) 2010-2011, Duane Merrill. All rights reserved.
-Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
- * Neither the name of the NVIDIA CORPORATION nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
-DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-```
diff --git a/ml-xgboost/cub/common.mk b/ml-xgboost/cub/common.mk
deleted file mode 100644
index 8154850..0000000
--- a/ml-xgboost/cub/common.mk
+++ /dev/null
@@ -1,233 +0,0 @@
-#/******************************************************************************
-# * Copyright (c) 2011, Duane Merrill. All rights reserved.
-# * Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved.
-# *
-# * Redistribution and use in source and binary forms, with or without
-# * modification, are permitted provided that the following conditions are met:
-# * * Redistributions of source code must retain the above copyright
-# * notice, this list of conditions and the following disclaimer.
-# * * Redistributions in binary form must reproduce the above copyright
-# * notice, this list of conditions and the following disclaimer in the
-# * documentation and/or other materials provided with the distribution.
-# * * Neither the name of the NVIDIA CORPORATION nor the
-# * names of its contributors may be used to endorse or promote products
-# * derived from this software without specific prior written permission.
-# *
-# * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-# * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
-# * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-# * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-# * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-# *
-#******************************************************************************/
-
-
-#-------------------------------------------------------------------------------
-# Commandline Options
-#-------------------------------------------------------------------------------
-
-# [sm=] Compute-capability to compile for, e.g., "sm=200,300,350" (SM20 by default).
-
-COMMA = ,
-ifdef sm
- SM_ARCH = $(subst $(COMMA),-,$(sm))
-else
- SM_ARCH = 200
-endif
-
-ifeq (700, $(findstring 700, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_70,code=\"sm_70,compute_70\"
- SM_DEF += -DSM700
- TEST_ARCH = 700
-endif
-ifeq (620, $(findstring 620, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_62,code=\"sm_62,compute_62\"
- SM_DEF += -DSM620
- TEST_ARCH = 620
-endif
-ifeq (610, $(findstring 610, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_61,code=\"sm_61,compute_61\"
- SM_DEF += -DSM610
- TEST_ARCH = 610
-endif
-ifeq (600, $(findstring 600, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_60,code=\"sm_60,compute_60\"
- SM_DEF += -DSM600
- TEST_ARCH = 600
-endif
-ifeq (520, $(findstring 520, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_52,code=\"sm_52,compute_52\"
- SM_DEF += -DSM520
- TEST_ARCH = 520
-endif
-ifeq (370, $(findstring 370, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_37,code=\"sm_37,compute_37\"
- SM_DEF += -DSM370
- TEST_ARCH = 370
-endif
-ifeq (350, $(findstring 350, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_35,code=\"sm_35,compute_35\"
- SM_DEF += -DSM350
- TEST_ARCH = 350
-endif
-ifeq (300, $(findstring 300, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_30,code=\"sm_30,compute_30\"
- SM_DEF += -DSM300
- TEST_ARCH = 300
-endif
-ifeq (210, $(findstring 210, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_20,code=\"sm_21,compute_20\"
- SM_DEF += -DSM210
- TEST_ARCH = 210
-endif
-ifeq (200, $(findstring 200, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_20,code=\"sm_20,compute_20\"
- SM_DEF += -DSM200
- TEST_ARCH = 200
-endif
-ifeq (130, $(findstring 130, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_13,code=\"sm_13,compute_13\"
- SM_DEF += -DSM130
- TEST_ARCH = 130
-endif
-ifeq (120, $(findstring 120, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_12,code=\"sm_12,compute_12\"
- SM_DEF += -DSM120
- TEST_ARCH = 120
-endif
-ifeq (110, $(findstring 110, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_11,code=\"sm_11,compute_11\"
- SM_DEF += -DSM110
- TEST_ARCH = 110
-endif
-ifeq (100, $(findstring 100, $(SM_ARCH)))
- SM_TARGETS += -gencode=arch=compute_10,code=\"sm_10,compute_10\"
- SM_DEF += -DSM100
- TEST_ARCH = 100
-endif
-
-
-# [cdp=<0|1>] CDP enable option (default: no)
-ifeq ($(cdp), 1)
- DEFINES += -DCUB_CDP
- CDP_SUFFIX = cdp
- NVCCFLAGS += -rdc=true -lcudadevrt
-else
- CDP_SUFFIX = nocdp
-endif
-
-
-# [force32=<0|1>] Device addressing mode option (64-bit device pointers by default)
-ifeq ($(force32), 1)
- CPU_ARCH = -m32
- CPU_ARCH_SUFFIX = i386
-else
- CPU_ARCH = -m64
- CPU_ARCH_SUFFIX = x86_64
- NPPI = -lnppi
-endif
-
-
-# [abi=<0|1>] CUDA ABI option (enabled by default)
-ifneq ($(abi), 0)
- ABI_SUFFIX = abi
-else
- NVCCFLAGS += -Xptxas -abi=no
- ABI_SUFFIX = noabi
-endif
-
-
-# [open64=<0|1>] Middle-end compiler option (nvvm by default)
-ifeq ($(open64), 1)
- NVCCFLAGS += -open64
- PTX_SUFFIX = open64
-else
- PTX_SUFFIX = nvvm
-endif
-
-
-# [verbose=<0|1>] Verbose toolchain output from nvcc option
-ifeq ($(verbose), 1)
- NVCCFLAGS += -v
-endif
-
-
-# [keep=<0|1>] Keep intermediate compilation artifacts option
-ifeq ($(keep), 1)
- NVCCFLAGS += -keep
-endif
-
-# [debug=<0|1>] Generate debug mode code
-ifeq ($(debug), 1)
- NVCCFLAGS += -G
-endif
-
-
-#-------------------------------------------------------------------------------
-# Compiler and compilation platform
-#-------------------------------------------------------------------------------
-
-CUB_DIR = $(dir $(lastword $(MAKEFILE_LIST)))
-
-NVCC = "$(shell which nvcc)"
-ifdef nvccver
- NVCC_VERSION = $(nvccver)
-else
- NVCC_VERSION = $(strip $(shell nvcc --version | grep release | sed 's/.*release //' | sed 's/,.*//'))
-endif
-
-# detect OS
-OSUPPER = $(shell uname -s 2>/dev/null | tr [:lower:] [:upper:])
-
-# Default flags: verbose kernel properties (regs, smem, cmem, etc.); runtimes for compilation phases
-NVCCFLAGS += $(SM_DEF) -Xptxas -v -Xcudafe -\#
-
-ifeq (WIN_NT, $(findstring WIN_NT, $(OSUPPER)))
- # For MSVC
- # Enable more warnings and treat as errors
- NVCCFLAGS += -Xcompiler /W3 -Xcompiler /WX
- # Disable excess x86 floating point precision that can lead to results being labeled incorrectly
- NVCCFLAGS += -Xcompiler /fp:strict
- # Help the compiler/linker work with huge numbers of kernels on Windows
- NVCCFLAGS += -Xcompiler /bigobj -Xcompiler /Zm500
- CC = cl
-
- # Multithreaded runtime
- NVCCFLAGS += -Xcompiler /MT
-
-ifneq ($(force32), 1)
- CUDART_CYG = "$(shell dirname $(NVCC))/../lib/Win32/cudart.lib"
-else
- CUDART_CYG = "$(shell dirname $(NVCC))/../lib/x64/cudart.lib"
-endif
- CUDART = "$(shell cygpath -w $(CUDART_CYG))"
-else
- # For g++
- # Disable excess x86 floating point precision that can lead to results being labeled incorrectly
- NVCCFLAGS += -Xcompiler -ffloat-store
- CC = g++
-ifneq ($(force32), 1)
- CUDART = "$(shell dirname $(NVCC))/../lib/libcudart_static.a"
-else
- CUDART = "$(shell dirname $(NVCC))/../lib64/libcudart_static.a"
-endif
-endif
-
-# Suffix to append to each binary
-BIN_SUFFIX = sm$(SM_ARCH)_$(PTX_SUFFIX)_$(NVCC_VERSION)_$(ABI_SUFFIX)_$(CDP_SUFFIX)_$(CPU_ARCH_SUFFIX)
-
-
-#-------------------------------------------------------------------------------
-# Dependency Lists
-#-------------------------------------------------------------------------------
-
-rwildcard=$(foreach d,$(wildcard $1*),$(call rwildcard,$d/,$2) $(filter $(subst *,%,$2),$d))
-
-CUB_DEPS = $(call rwildcard, $(CUB_DIR),*.cuh) \
- $(CUB_DIR)common.mk
-
diff --git a/ml-xgboost/cub/cub/agent/agent_histogram.cuh b/ml-xgboost/cub/cub/agent/agent_histogram.cuh
deleted file mode 100644
index e42ffe2..0000000
--- a/ml-xgboost/cub/cub/agent/agent_histogram.cuh
+++ /dev/null
@@ -1,783 +0,0 @@
-/******************************************************************************
- * Copyright (c) 2011, Duane Merrill. All rights reserved.
- * Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the NVIDIA CORPORATION nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- ******************************************************************************/
-
-/**
- * \file
- * cub::AgentHistogram implements a stateful abstraction of CUDA thread blocks for participating in device-wide histogram .
- */
-
-#pragma once
-
-#include
-
-#include "../util_type.cuh"
-#include "../block/block_load.cuh"
-#include "../grid/grid_queue.cuh"
-#include "../iterator/cache_modified_input_iterator.cuh"
-#include "../util_namespace.cuh"
-
-/// Optional outer namespace(s)
-CUB_NS_PREFIX
-
-/// CUB namespace
-namespace cub {
-
-
-/******************************************************************************
- * Tuning policy
- ******************************************************************************/
-
-/**
- *
- */
-enum BlockHistogramMemoryPreference
-{
- GMEM,
- SMEM,
- BLEND
-};
-
-
-/**
- * Parameterizable tuning policy type for AgentHistogram
- */
-template <
- int _BLOCK_THREADS, ///< Threads per thread block
- int _PIXELS_PER_THREAD, ///< Pixels per thread (per tile of input)
- BlockLoadAlgorithm _LOAD_ALGORITHM, ///< The BlockLoad algorithm to use
- CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading input elements
- bool _RLE_COMPRESS, ///< Whether to perform localized RLE to compress samples before histogramming
- BlockHistogramMemoryPreference _MEM_PREFERENCE, ///< Whether to prefer privatized shared-memory bins (versus privatized global-memory bins)
- bool _WORK_STEALING> ///< Whether to dequeue tiles from a global work queue
-struct AgentHistogramPolicy
-{
- enum
- {
- BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block
- PIXELS_PER_THREAD = _PIXELS_PER_THREAD, ///< Pixels per thread (per tile of input)
- IS_RLE_COMPRESS = _RLE_COMPRESS, ///< Whether to perform localized RLE to compress samples before histogramming
- MEM_PREFERENCE = _MEM_PREFERENCE, ///< Whether to prefer privatized shared-memory bins (versus privatized global-memory bins)
- IS_WORK_STEALING = _WORK_STEALING, ///< Whether to dequeue tiles from a global work queue
- };
-
- static const BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; ///< The BlockLoad algorithm to use
- static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading input elements
-};
-
-
-/******************************************************************************
- * Thread block abstractions
- ******************************************************************************/
-
-/**
- * \brief AgentHistogram implements a stateful abstraction of CUDA thread blocks for participating in device-wide histogram .
- */
-template <
- typename AgentHistogramPolicyT, ///< Parameterized AgentHistogramPolicy tuning policy type
- int PRIVATIZED_SMEM_BINS, ///< Number of privatized shared-memory histogram bins of any channel. Zero indicates privatized counters to be maintained in device-accessible memory.
- int NUM_CHANNELS, ///< Number of channels interleaved in the input data. Supports up to four channels.
- int NUM_ACTIVE_CHANNELS, ///< Number of channels actively being histogrammed
- typename SampleIteratorT, ///< Random-access input iterator type for reading samples
- typename CounterT, ///< Integer type for counting sample occurrences per histogram bin
- typename PrivatizedDecodeOpT, ///< The transform operator type for determining privatized counter indices from samples, one for each channel
- typename OutputDecodeOpT, ///< The transform operator type for determining output bin-ids from privatized counter indices, one for each channel
- typename OffsetT, ///< Signed integer type for global offsets
- int PTX_ARCH = CUB_PTX_ARCH> ///< PTX compute capability
-struct AgentHistogram
-{
- //---------------------------------------------------------------------
- // Types and constants
- //---------------------------------------------------------------------
-
- /// The sample type of the input iterator
- typedef typename std::iterator_traits::value_type SampleT;
-
- /// The pixel type of SampleT
- typedef typename CubVector::Type PixelT;
-
- /// The quad type of SampleT
- typedef typename CubVector::Type QuadT;
-
- /// Constants
- enum
- {
- BLOCK_THREADS = AgentHistogramPolicyT::BLOCK_THREADS,
-
- PIXELS_PER_THREAD = AgentHistogramPolicyT::PIXELS_PER_THREAD,
- SAMPLES_PER_THREAD = PIXELS_PER_THREAD * NUM_CHANNELS,
- QUADS_PER_THREAD = SAMPLES_PER_THREAD / 4,
-
- TILE_PIXELS = PIXELS_PER_THREAD * BLOCK_THREADS,
- TILE_SAMPLES = SAMPLES_PER_THREAD * BLOCK_THREADS,
-
- IS_RLE_COMPRESS = AgentHistogramPolicyT::IS_RLE_COMPRESS,
-
- MEM_PREFERENCE = (PRIVATIZED_SMEM_BINS > 0) ?
- AgentHistogramPolicyT::MEM_PREFERENCE :
- GMEM,
-
- IS_WORK_STEALING = AgentHistogramPolicyT::IS_WORK_STEALING,
- };
-
- /// Cache load modifier for reading input elements
- static const CacheLoadModifier LOAD_MODIFIER = AgentHistogramPolicyT::LOAD_MODIFIER;
-
-
- /// Input iterator wrapper type (for applying cache modifier)
- typedef typename If::VALUE,
- CacheModifiedInputIterator, // Wrap the native input pointer with CacheModifiedInputIterator
- SampleIteratorT>::Type // Directly use the supplied input iterator type
- WrappedSampleIteratorT;
-
- /// Pixel input iterator type (for applying cache modifier)
- typedef CacheModifiedInputIterator
- WrappedPixelIteratorT;
-
- /// Qaud input iterator type (for applying cache modifier)
- typedef CacheModifiedInputIterator
- WrappedQuadIteratorT;
-
- /// Parameterized BlockLoad type for samples
- typedef BlockLoad<
- SampleT,
- BLOCK_THREADS,
- SAMPLES_PER_THREAD,
- AgentHistogramPolicyT::LOAD_ALGORITHM>
- BlockLoadSampleT;
-
- /// Parameterized BlockLoad type for pixels
- typedef BlockLoad<
- PixelT,
- BLOCK_THREADS,
- PIXELS_PER_THREAD,
- AgentHistogramPolicyT::LOAD_ALGORITHM>
- BlockLoadPixelT;
-
- /// Parameterized BlockLoad type for quads
- typedef BlockLoad<
- QuadT,
- BLOCK_THREADS,
- QUADS_PER_THREAD,
- AgentHistogramPolicyT::LOAD_ALGORITHM>
- BlockLoadQuadT;
-
- /// Shared memory type required by this thread block
- struct _TempStorage
- {
- CounterT histograms[NUM_ACTIVE_CHANNELS][PRIVATIZED_SMEM_BINS + 1]; // Smem needed for block-privatized smem histogram (with 1 word of padding)
-
- int tile_idx;
-
- union
- {
- typename BlockLoadSampleT::TempStorage sample_load; // Smem needed for loading a tile of samples
- typename BlockLoadPixelT::TempStorage pixel_load; // Smem needed for loading a tile of pixels
- typename BlockLoadQuadT::TempStorage quad_load; // Smem needed for loading a tile of quads
- };
- };
-
-
- /// Temporary storage type (unionable)
- struct TempStorage : Uninitialized<_TempStorage> {};
-
-
- //---------------------------------------------------------------------
- // Per-thread fields
- //---------------------------------------------------------------------
-
- /// Reference to temp_storage
- _TempStorage &temp_storage;
-
- /// Sample input iterator (with cache modifier applied, if possible)
- WrappedSampleIteratorT d_wrapped_samples;
-
- /// Native pointer for input samples (possibly NULL if unavailable)
- SampleT* d_native_samples;
-
- /// The number of output bins for each channel
- int (&num_output_bins)[NUM_ACTIVE_CHANNELS];
-
- /// The number of privatized bins for each channel
- int (&num_privatized_bins)[NUM_ACTIVE_CHANNELS];
-
- /// Reference to gmem privatized histograms for each channel
- CounterT* d_privatized_histograms[NUM_ACTIVE_CHANNELS];
-
- /// Reference to final output histograms (gmem)
- CounterT* (&d_output_histograms)[NUM_ACTIVE_CHANNELS];
-
- /// The transform operator for determining output bin-ids from privatized counter indices, one for each channel
- OutputDecodeOpT (&output_decode_op)[NUM_ACTIVE_CHANNELS];
-
- /// The transform operator for determining privatized counter indices from samples, one for each channel
- PrivatizedDecodeOpT (&privatized_decode_op)[NUM_ACTIVE_CHANNELS];
-
- /// Whether to prefer privatized smem counters vs privatized global counters
- bool prefer_smem;
-
-
- //---------------------------------------------------------------------
- // Initialize privatized bin counters
- //---------------------------------------------------------------------
-
- // Initialize privatized bin counters
- __device__ __forceinline__ void InitBinCounters(CounterT* privatized_histograms[NUM_ACTIVE_CHANNELS])
- {
- // Initialize histogram bin counts to zeros
- #pragma unroll
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- {
- for (int privatized_bin = threadIdx.x; privatized_bin < num_privatized_bins[CHANNEL]; privatized_bin += BLOCK_THREADS)
- {
- privatized_histograms[CHANNEL][privatized_bin] = 0;
- }
- }
-
- // Barrier to make sure all threads are done updating counters
- CTA_SYNC();
- }
-
-
- // Initialize privatized bin counters. Specialized for privatized shared-memory counters
- __device__ __forceinline__ void InitSmemBinCounters()
- {
- CounterT* privatized_histograms[NUM_ACTIVE_CHANNELS];
-
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- privatized_histograms[CHANNEL] = temp_storage.histograms[CHANNEL];
-
- InitBinCounters(privatized_histograms);
- }
-
-
- // Initialize privatized bin counters. Specialized for privatized global-memory counters
- __device__ __forceinline__ void InitGmemBinCounters()
- {
- InitBinCounters(d_privatized_histograms);
- }
-
-
- //---------------------------------------------------------------------
- // Update final output histograms
- //---------------------------------------------------------------------
-
- // Update final output histograms from privatized histograms
- __device__ __forceinline__ void StoreOutput(CounterT* privatized_histograms[NUM_ACTIVE_CHANNELS])
- {
- // Barrier to make sure all threads are done updating counters
- CTA_SYNC();
-
- // Apply privatized bin counts to output bin counts
- #pragma unroll
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- {
- int channel_bins = num_privatized_bins[CHANNEL];
- for (int privatized_bin = threadIdx.x;
- privatized_bin < channel_bins;
- privatized_bin += BLOCK_THREADS)
- {
- int output_bin = -1;
- CounterT count = privatized_histograms[CHANNEL][privatized_bin];
- bool is_valid = count > 0;
-
- output_decode_op[CHANNEL].BinSelect((SampleT) privatized_bin, output_bin, is_valid);
-
- if (output_bin >= 0)
- {
- atomicAdd(&d_output_histograms[CHANNEL][output_bin], count);
- }
-
- }
- }
- }
-
-
- // Update final output histograms from privatized histograms. Specialized for privatized shared-memory counters
- __device__ __forceinline__ void StoreSmemOutput()
- {
- CounterT* privatized_histograms[NUM_ACTIVE_CHANNELS];
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- privatized_histograms[CHANNEL] = temp_storage.histograms[CHANNEL];
-
- StoreOutput(privatized_histograms);
- }
-
-
- // Update final output histograms from privatized histograms. Specialized for privatized global-memory counters
- __device__ __forceinline__ void StoreGmemOutput()
- {
- StoreOutput(d_privatized_histograms);
- }
-
-
- //---------------------------------------------------------------------
- // Tile accumulation
- //---------------------------------------------------------------------
-
- // Accumulate pixels. Specialized for RLE compression.
- __device__ __forceinline__ void AccumulatePixels(
- SampleT samples[PIXELS_PER_THREAD][NUM_CHANNELS],
- bool is_valid[PIXELS_PER_THREAD],
- CounterT* privatized_histograms[NUM_ACTIVE_CHANNELS],
- Int2Type is_rle_compress)
- {
-
- #pragma unroll
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- {
- // Bin pixels
- int bins[PIXELS_PER_THREAD];
-
- #pragma unroll
- for (int PIXEL = 0; PIXEL < PIXELS_PER_THREAD; ++PIXEL)
- {
- bins[PIXEL] = -1;
- privatized_decode_op[CHANNEL].BinSelect(samples[PIXEL][CHANNEL], bins[PIXEL], is_valid[PIXEL]);
- }
-
- CounterT accumulator = 1;
-
- #pragma unroll
- for (int PIXEL = 0; PIXEL < PIXELS_PER_THREAD - 1; ++PIXEL)
- {
- if (bins[PIXEL] == bins[PIXEL + 1])
- {
- accumulator++;
- }
- else
- {
- if (bins[PIXEL] >= 0)
- atomicAdd(privatized_histograms[CHANNEL] + bins[PIXEL], accumulator);
-
- accumulator = 1;
- }
- }
- // Last pixel
- if (bins[PIXELS_PER_THREAD - 1] >= 0)
- atomicAdd(privatized_histograms[CHANNEL] + bins[PIXELS_PER_THREAD - 1], accumulator);
- }
- }
-
-
- // Accumulate pixels. Specialized for individual accumulation of each pixel.
- __device__ __forceinline__ void AccumulatePixels(
- SampleT samples[PIXELS_PER_THREAD][NUM_CHANNELS],
- bool is_valid[PIXELS_PER_THREAD],
- CounterT* privatized_histograms[NUM_ACTIVE_CHANNELS],
- Int2Type is_rle_compress)
- {
- #pragma unroll
- for (int PIXEL = 0; PIXEL < PIXELS_PER_THREAD; ++PIXEL)
- {
- #pragma unroll
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- {
- int bin = -1;
- privatized_decode_op[CHANNEL].BinSelect(samples[PIXEL][CHANNEL], bin, is_valid[PIXEL]);
- if (bin >= 0)
- atomicAdd(privatized_histograms[CHANNEL] + bin, 1);
- }
- }
- }
-
-
- /**
- * Accumulate pixel, specialized for smem privatized histogram
- */
- __device__ __forceinline__ void AccumulateSmemPixels(
- SampleT samples[PIXELS_PER_THREAD][NUM_CHANNELS],
- bool is_valid[PIXELS_PER_THREAD])
- {
- CounterT* privatized_histograms[NUM_ACTIVE_CHANNELS];
-
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- privatized_histograms[CHANNEL] = temp_storage.histograms[CHANNEL];
-
- AccumulatePixels(samples, is_valid, privatized_histograms, Int2Type());
- }
-
-
- /**
- * Accumulate pixel, specialized for gmem privatized histogram
- */
- __device__ __forceinline__ void AccumulateGmemPixels(
- SampleT samples[PIXELS_PER_THREAD][NUM_CHANNELS],
- bool is_valid[PIXELS_PER_THREAD])
- {
- AccumulatePixels(samples, is_valid, d_privatized_histograms, Int2Type());
- }
-
-
-
- //---------------------------------------------------------------------
- // Tile loading
- //---------------------------------------------------------------------
-
- // Load full, aligned tile using pixel iterator (multi-channel)
- template
- __device__ __forceinline__ void LoadFullAlignedTile(
- OffsetT block_offset,
- int valid_samples,
- SampleT (&samples)[PIXELS_PER_THREAD][NUM_CHANNELS],
- Int2Type<_NUM_ACTIVE_CHANNELS> num_active_channels)
- {
- typedef PixelT AliasedPixels[PIXELS_PER_THREAD];
-
- WrappedPixelIteratorT d_wrapped_pixels((PixelT*) (d_native_samples + block_offset));
-
- // Load using a wrapped pixel iterator
- BlockLoadPixelT(temp_storage.pixel_load).Load(
- d_wrapped_pixels,
- reinterpret_cast(samples));
- }
-
- // Load full, aligned tile using quad iterator (single-channel)
- __device__ __forceinline__ void LoadFullAlignedTile(
- OffsetT block_offset,
- int valid_samples,
- SampleT (&samples)[PIXELS_PER_THREAD][NUM_CHANNELS],
- Int2Type<1> num_active_channels)
- {
- typedef QuadT AliasedQuads[QUADS_PER_THREAD];
-
- WrappedQuadIteratorT d_wrapped_quads((QuadT*) (d_native_samples + block_offset));
-
- // Load using a wrapped quad iterator
- BlockLoadQuadT(temp_storage.quad_load).Load(
- d_wrapped_quads,
- reinterpret_cast(samples));
- }
-
- // Load full, aligned tile
- __device__ __forceinline__ void LoadTile(
- OffsetT block_offset,
- int valid_samples,
- SampleT (&samples)[PIXELS_PER_THREAD][NUM_CHANNELS],
- Int2Type is_full_tile,
- Int2Type is_aligned)
- {
- LoadFullAlignedTile(block_offset, valid_samples, samples, Int2Type());
- }
-
- // Load full, mis-aligned tile using sample iterator
- __device__ __forceinline__ void LoadTile(
- OffsetT block_offset,
- int valid_samples,
- SampleT (&samples)[PIXELS_PER_THREAD][NUM_CHANNELS],
- Int2Type is_full_tile,
- Int2Type is_aligned)
- {
- typedef SampleT AliasedSamples[SAMPLES_PER_THREAD];
-
- // Load using sample iterator
- BlockLoadSampleT(temp_storage.sample_load).Load(
- d_wrapped_samples + block_offset,
- reinterpret_cast(samples));
- }
-
- // Load partially-full, aligned tile using the pixel iterator
- __device__ __forceinline__ void LoadTile(
- OffsetT block_offset,
- int valid_samples,
- SampleT (&samples)[PIXELS_PER_THREAD][NUM_CHANNELS],
- Int2Type is_full_tile,
- Int2Type is_aligned)
- {
- typedef PixelT AliasedPixels[PIXELS_PER_THREAD];
-
- WrappedPixelIteratorT d_wrapped_pixels((PixelT*) (d_native_samples + block_offset));
-
- int valid_pixels = valid_samples / NUM_CHANNELS;
-
- // Load using a wrapped pixel iterator
- BlockLoadPixelT(temp_storage.pixel_load).Load(
- d_wrapped_pixels,
- reinterpret_cast(samples),
- valid_pixels);
- }
-
- // Load partially-full, mis-aligned tile using sample iterator
- __device__ __forceinline__ void LoadTile(
- OffsetT block_offset,
- int valid_samples,
- SampleT (&samples)[PIXELS_PER_THREAD][NUM_CHANNELS],
- Int2Type is_full_tile,
- Int2Type is_aligned)
- {
- typedef SampleT AliasedSamples[SAMPLES_PER_THREAD];
-
- BlockLoadSampleT(temp_storage.sample_load).Load(
- d_wrapped_samples + block_offset,
- reinterpret_cast(samples),
- valid_samples);
- }
-
-
- //---------------------------------------------------------------------
- // Tile processing
- //---------------------------------------------------------------------
-
- // Consume a tile of data samples
- template <
- bool IS_ALIGNED, // Whether the tile offset is aligned (quad-aligned for single-channel, pixel-aligned for multi-channel)
- bool IS_FULL_TILE> // Whether the tile is full
- __device__ __forceinline__ void ConsumeTile(OffsetT block_offset, int valid_samples)
- {
- SampleT samples[PIXELS_PER_THREAD][NUM_CHANNELS];
- bool is_valid[PIXELS_PER_THREAD];
-
- // Load tile
- LoadTile(
- block_offset,
- valid_samples,
- samples,
- Int2Type(),
- Int2Type());
-
- // Set valid flags
- #pragma unroll
- for (int PIXEL = 0; PIXEL < PIXELS_PER_THREAD; ++PIXEL)
- is_valid[PIXEL] = IS_FULL_TILE || (((threadIdx.x * PIXELS_PER_THREAD + PIXEL) * NUM_CHANNELS) < valid_samples);
-
- // Accumulate samples
-#if CUB_PTX_ARCH >= 120
- if (prefer_smem)
- AccumulateSmemPixels(samples, is_valid);
- else
- AccumulateGmemPixels(samples, is_valid);
-#else
- AccumulateGmemPixels(samples, is_valid);
-#endif
-
- }
-
-
- // Consume row tiles. Specialized for work-stealing from queue
- template
- __device__ __forceinline__ void ConsumeTiles(
- OffsetT num_row_pixels, ///< The number of multi-channel pixels per row in the region of interest
- OffsetT num_rows, ///< The number of rows in the region of interest
- OffsetT row_stride_samples, ///< The number of samples between starts of consecutive rows in the region of interest
- int tiles_per_row, ///< Number of image tiles per row
- GridQueue tile_queue,
- Int2Type is_work_stealing)
- {
-
- int num_tiles = num_rows * tiles_per_row;
- int tile_idx = (blockIdx.y * gridDim.x) + blockIdx.x;
- OffsetT num_even_share_tiles = gridDim.x * gridDim.y;
-
- while (tile_idx < num_tiles)
- {
- int row = tile_idx / tiles_per_row;
- int col = tile_idx - (row * tiles_per_row);
- OffsetT row_offset = row * row_stride_samples;
- OffsetT col_offset = (col * TILE_SAMPLES);
- OffsetT tile_offset = row_offset + col_offset;
-
- if (col == tiles_per_row - 1)
- {
- // Consume a partially-full tile at the end of the row
- OffsetT num_remaining = (num_row_pixels * NUM_CHANNELS) - col_offset;
- ConsumeTile(tile_offset, num_remaining);
- }
- else
- {
- // Consume full tile
- ConsumeTile(tile_offset, TILE_SAMPLES);
- }
-
- CTA_SYNC();
-
- // Get next tile
- if (threadIdx.x == 0)
- temp_storage.tile_idx = tile_queue.Drain(1) + num_even_share_tiles;
-
- CTA_SYNC();
-
- tile_idx = temp_storage.tile_idx;
- }
- }
-
-
- // Consume row tiles. Specialized for even-share (striped across thread blocks)
- template
- __device__ __forceinline__ void ConsumeTiles(
- OffsetT num_row_pixels, ///< The number of multi-channel pixels per row in the region of interest
- OffsetT num_rows, ///< The number of rows in the region of interest
- OffsetT row_stride_samples, ///< The number of samples between starts of consecutive rows in the region of interest
- int tiles_per_row, ///< Number of image tiles per row
- GridQueue tile_queue,
- Int2Type is_work_stealing)
- {
- for (int row = blockIdx.y; row < num_rows; row += gridDim.y)
- {
- OffsetT row_begin = row * row_stride_samples;
- OffsetT row_end = row_begin + (num_row_pixels * NUM_CHANNELS);
- OffsetT tile_offset = row_begin + (blockIdx.x * TILE_SAMPLES);
-
- while (tile_offset < row_end)
- {
- OffsetT num_remaining = row_end - tile_offset;
-
- if (num_remaining < TILE_SAMPLES)
- {
- // Consume partial tile
- ConsumeTile(tile_offset, num_remaining);
- break;
- }
-
- // Consume full tile
- ConsumeTile(tile_offset, TILE_SAMPLES);
- tile_offset += gridDim.x * TILE_SAMPLES;
- }
- }
- }
-
-
- //---------------------------------------------------------------------
- // Parameter extraction
- //---------------------------------------------------------------------
-
- // Return a native pixel pointer (specialized for CacheModifiedInputIterator types)
- template <
- CacheLoadModifier _MODIFIER,
- typename _ValueT,
- typename _OffsetT>
- __device__ __forceinline__ SampleT* NativePointer(CacheModifiedInputIterator<_MODIFIER, _ValueT, _OffsetT> itr)
- {
- return itr.ptr;
- }
-
- // Return a native pixel pointer (specialized for other types)
- template
- __device__ __forceinline__ SampleT* NativePointer(IteratorT itr)
- {
- return NULL;
- }
-
-
-
- //---------------------------------------------------------------------
- // Interface
- //---------------------------------------------------------------------
-
-
- /**
- * Constructor
- */
- __device__ __forceinline__ AgentHistogram(
- TempStorage &temp_storage, ///< Reference to temp_storage
- SampleIteratorT d_samples, ///< Input data to reduce
- int (&num_output_bins)[NUM_ACTIVE_CHANNELS], ///< The number bins per final output histogram
- int (&num_privatized_bins)[NUM_ACTIVE_CHANNELS], ///< The number bins per privatized histogram
- CounterT* (&d_output_histograms)[NUM_ACTIVE_CHANNELS], ///< Reference to final output histograms
- CounterT* (&d_privatized_histograms)[NUM_ACTIVE_CHANNELS], ///< Reference to privatized histograms
- OutputDecodeOpT (&output_decode_op)[NUM_ACTIVE_CHANNELS], ///< The transform operator for determining output bin-ids from privatized counter indices, one for each channel
- PrivatizedDecodeOpT (&privatized_decode_op)[NUM_ACTIVE_CHANNELS]) ///< The transform operator for determining privatized counter indices from samples, one for each channel
- :
- temp_storage(temp_storage.Alias()),
- d_wrapped_samples(d_samples),
- num_output_bins(num_output_bins),
- num_privatized_bins(num_privatized_bins),
- d_output_histograms(d_output_histograms),
- privatized_decode_op(privatized_decode_op),
- output_decode_op(output_decode_op),
- d_native_samples(NativePointer(d_wrapped_samples)),
- prefer_smem((MEM_PREFERENCE == SMEM) ?
- true : // prefer smem privatized histograms
- (MEM_PREFERENCE == GMEM) ?
- false : // prefer gmem privatized histograms
- blockIdx.x & 1) // prefer blended privatized histograms
- {
- int blockId = (blockIdx.y * gridDim.x) + blockIdx.x;
-
- // Initialize the locations of this block's privatized histograms
- for (int CHANNEL = 0; CHANNEL < NUM_ACTIVE_CHANNELS; ++CHANNEL)
- this->d_privatized_histograms[CHANNEL] = d_privatized_histograms[CHANNEL] + (blockId * num_privatized_bins[CHANNEL]);
- }
-
-
- /**
- * Consume image
- */
- __device__ __forceinline__ void ConsumeTiles(
- OffsetT num_row_pixels, ///< The number of multi-channel pixels per row in the region of interest
- OffsetT num_rows, ///< The number of rows in the region of interest
- OffsetT row_stride_samples, ///< The number of samples between starts of consecutive rows in the region of interest
- int tiles_per_row, ///< Number of image tiles per row
- GridQueue tile_queue) ///< Queue descriptor for assigning tiles of work to thread blocks
- {
- // Check whether all row starting offsets are quad-aligned (in single-channel) or pixel-aligned (in multi-channel)
- size_t row_bytes = sizeof(SampleT) * row_stride_samples;
- size_t offset_mask = size_t(d_native_samples) | row_bytes;
- int quad_mask = sizeof(SampleT) * 4 - 1;
- int pixel_mask = AlignBytes::ALIGN_BYTES - 1;
- bool quad_aligned_rows = (NUM_CHANNELS == 1) && ((offset_mask & quad_mask) == 0);
- bool pixel_aligned_rows = (NUM_CHANNELS > 1) && ((offset_mask & pixel_mask) == 0);
-
- // Whether rows are aligned and can be vectorized
- if (quad_aligned_rows || pixel_aligned_rows)
- ConsumeTiles(num_row_pixels, num_rows, row_stride_samples, tiles_per_row, tile_queue, Int2Type());
- else
- ConsumeTiles(num_row_pixels, num_rows, row_stride_samples, tiles_per_row, tile_queue, Int2Type());
- }
-
-
- /**
- * Initialize privatized bin counters. Specialized for privatized shared-memory counters
- */
- __device__ __forceinline__ void InitBinCounters()
- {
- if (prefer_smem)
- InitSmemBinCounters();
- else
- InitGmemBinCounters();
- }
-
-
- /**
- * Store privatized histogram to device-accessible memory. Specialized for privatized shared-memory counters
- */
- __device__ __forceinline__ void StoreOutput()
- {
- if (prefer_smem)
- StoreSmemOutput();
- else
- StoreGmemOutput();
- }
-
-
-};
-
-
-
-
-} // CUB namespace
-CUB_NS_POSTFIX // Optional outer namespace(s)
-
diff --git a/ml-xgboost/cub/cub/agent/agent_radix_sort_downsweep.cuh b/ml-xgboost/cub/cub/agent/agent_radix_sort_downsweep.cuh
deleted file mode 100644
index 9b9931a..0000000
--- a/ml-xgboost/cub/cub/agent/agent_radix_sort_downsweep.cuh
+++ /dev/null
@@ -1,753 +0,0 @@
-/******************************************************************************
- * Copyright (c) 2011, Duane Merrill. All rights reserved.
- * Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the NVIDIA CORPORATION nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- ******************************************************************************/
-
-/**
- * \file
- * AgentRadixSortDownsweep implements a stateful abstraction of CUDA thread blocks for participating in device-wide radix sort downsweep .
- */
-
-
-#pragma once
-
-#include "../thread/thread_load.cuh"
-#include "../block/block_load.cuh"
-#include "../block/block_store.cuh"
-#include "../block/block_radix_rank.cuh"
-#include "../block/block_exchange.cuh"
-#include "../util_type.cuh"
-#include "../iterator/cache_modified_input_iterator.cuh"
-#include "../util_namespace.cuh"
-
-/// Optional outer namespace(s)
-CUB_NS_PREFIX
-
-/// CUB namespace
-namespace cub {
-
-
-/******************************************************************************
- * Tuning policy types
- ******************************************************************************/
-
-/**
- * Types of scattering strategies
- */
-enum RadixSortScatterAlgorithm
-{
- RADIX_SORT_SCATTER_DIRECT, ///< Scatter directly from registers to global bins
- RADIX_SORT_SCATTER_TWO_PHASE, ///< First scatter from registers into shared memory bins, then into global bins
-};
-
-
-/**
- * Parameterizable tuning policy type for AgentRadixSortDownsweep
- */
-template <
- int _BLOCK_THREADS, ///< Threads per thread block
- int _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
- BlockLoadAlgorithm _LOAD_ALGORITHM, ///< The BlockLoad algorithm to use
- CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading keys (and values)
- bool _MEMOIZE_OUTER_SCAN, ///< Whether or not to buffer outer raking scan partials to incur fewer shared memory reads at the expense of higher register pressure. See BlockScanAlgorithm::BLOCK_SCAN_RAKING_MEMOIZE for more details.
- BlockScanAlgorithm _INNER_SCAN_ALGORITHM, ///< The BlockScan algorithm algorithm to use
- RadixSortScatterAlgorithm _SCATTER_ALGORITHM, ///< The scattering strategy to use
- int _RADIX_BITS> ///< The number of radix bits, i.e., log2(bins)
-struct AgentRadixSortDownsweepPolicy
-{
- enum
- {
- BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block
- ITEMS_PER_THREAD = _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
- RADIX_BITS = _RADIX_BITS, ///< The number of radix bits, i.e., log2(bins)
- MEMOIZE_OUTER_SCAN = _MEMOIZE_OUTER_SCAN, ///< Whether or not to buffer outer raking scan partials to incur fewer shared memory reads at the expense of higher register pressure. See BlockScanAlgorithm::BLOCK_SCAN_RAKING_MEMOIZE for more details.
- };
-
- static const BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; ///< The BlockLoad algorithm to use
- static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading keys (and values)
- static const BlockScanAlgorithm INNER_SCAN_ALGORITHM = _INNER_SCAN_ALGORITHM; ///< The BlockScan algorithm algorithm to use
- static const RadixSortScatterAlgorithm SCATTER_ALGORITHM = _SCATTER_ALGORITHM; ///< The scattering strategy to use
-};
-
-
-/******************************************************************************
- * Thread block abstractions
- ******************************************************************************/
-
-/**
- * \brief AgentRadixSortDownsweep implements a stateful abstraction of CUDA thread blocks for participating in device-wide radix sort downsweep .
- */
-template <
- typename AgentRadixSortDownsweepPolicy, ///< Parameterized AgentRadixSortDownsweepPolicy tuning policy type
- bool IS_DESCENDING, ///< Whether or not the sorted-order is high-to-low
- typename KeyT, ///< KeyT type
- typename ValueT, ///< ValueT type
- typename OffsetT> ///< Signed integer type for global offsets
-struct AgentRadixSortDownsweep
-{
- //---------------------------------------------------------------------
- // Type definitions and constants
- //---------------------------------------------------------------------
-
- // Appropriate unsigned-bits representation of KeyT
- typedef typename Traits::UnsignedBits UnsignedBits;
-
- static const UnsignedBits LOWEST_KEY = Traits::LOWEST_KEY;
- static const UnsignedBits MAX_KEY = Traits::MAX_KEY;
-
- static const BlockLoadAlgorithm LOAD_ALGORITHM = AgentRadixSortDownsweepPolicy::LOAD_ALGORITHM;
- static const CacheLoadModifier LOAD_MODIFIER = AgentRadixSortDownsweepPolicy::LOAD_MODIFIER;
- static const BlockScanAlgorithm INNER_SCAN_ALGORITHM = AgentRadixSortDownsweepPolicy::INNER_SCAN_ALGORITHM;
- static const RadixSortScatterAlgorithm SCATTER_ALGORITHM = AgentRadixSortDownsweepPolicy::SCATTER_ALGORITHM;
-
- enum
- {
- BLOCK_THREADS = AgentRadixSortDownsweepPolicy::BLOCK_THREADS,
- ITEMS_PER_THREAD = AgentRadixSortDownsweepPolicy::ITEMS_PER_THREAD,
- RADIX_BITS = AgentRadixSortDownsweepPolicy::RADIX_BITS,
- MEMOIZE_OUTER_SCAN = AgentRadixSortDownsweepPolicy::MEMOIZE_OUTER_SCAN,
- TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD,
-
- RADIX_DIGITS = 1 << RADIX_BITS,
- KEYS_ONLY = Equals::VALUE,
-
- WARP_THREADS = CUB_PTX_LOG_WARP_THREADS,
- WARPS = (BLOCK_THREADS + WARP_THREADS - 1) / WARP_THREADS,
-
- BYTES_PER_SIZET = sizeof(OffsetT),
- LOG_BYTES_PER_SIZET = Log2::VALUE,
-
- LOG_SMEM_BANKS = CUB_PTX_LOG_SMEM_BANKS,
- SMEM_BANKS = 1 << LOG_SMEM_BANKS,
-
- DIGITS_PER_SCATTER_PASS = BLOCK_THREADS / SMEM_BANKS,
- SCATTER_PASSES = RADIX_DIGITS / DIGITS_PER_SCATTER_PASS,
-
- LOG_STORE_TXN_THREADS = LOG_SMEM_BANKS,
- STORE_TXN_THREADS = 1 << LOG_STORE_TXN_THREADS,
- };
-
- // Input iterator wrapper type (for applying cache modifier)s
- typedef CacheModifiedInputIterator KeysItr;
- typedef CacheModifiedInputIterator ValuesItr;
-
- // BlockRadixRank type
- typedef BlockRadixRank<
- BLOCK_THREADS,
- RADIX_BITS,
- IS_DESCENDING,
- MEMOIZE_OUTER_SCAN,
- INNER_SCAN_ALGORITHM> BlockRadixRank;
-
- // BlockLoad type (keys)
- typedef BlockLoad<
- UnsignedBits,
- BLOCK_THREADS,
- ITEMS_PER_THREAD,
- LOAD_ALGORITHM> BlockLoadKeys;
-
- // BlockLoad type (values)
- typedef BlockLoad<
- ValueT,
- BLOCK_THREADS,
- ITEMS_PER_THREAD,
- LOAD_ALGORITHM> BlockLoadValues;
-
- // BlockExchange type (keys)
- typedef BlockExchange<
- UnsignedBits,
- BLOCK_THREADS,
- ITEMS_PER_THREAD> BlockExchangeKeys;
-
- // BlockExchange type (values)
- typedef BlockExchange<
- ValueT,
- BLOCK_THREADS,
- ITEMS_PER_THREAD> BlockExchangeValues;
-
-
- /**
- * Shared memory storage layout
- */
- union __align__(16) _TempStorage
- {
- typename BlockLoadKeys::TempStorage load_keys;
- typename BlockRadixRank::TempStorage ranking;
- typename BlockLoadValues::TempStorage load_values;
- typename BlockExchangeValues::TempStorage exchange_values;
-
- OffsetT exclusive_digit_prefix[RADIX_DIGITS];
-
- struct
- {
- typename BlockExchangeKeys::TempStorage exchange_keys;
- OffsetT relative_bin_offsets[RADIX_DIGITS + 1];
- };
-
- };
-
-
- /// Alias wrapper allowing storage to be unioned
- struct TempStorage : Uninitialized<_TempStorage> {};
-
-
- //---------------------------------------------------------------------
- // Thread fields
- //---------------------------------------------------------------------
-
- // Shared storage for this CTA
- _TempStorage &temp_storage;
-
- // Input and output device pointers
- KeysItr d_keys_in;
- ValuesItr d_values_in;
- UnsignedBits *d_keys_out;
- ValueT *d_values_out;
-
- // The global scatter base offset for each digit (valid in the first RADIX_DIGITS threads)
- OffsetT bin_offset;
-
- // The least-significant bit position of the current digit to extract
- int current_bit;
-
- // Number of bits in current digit
- int num_bits;
-
- // Whether to short-cirucit
- int short_circuit;
-
- //---------------------------------------------------------------------
- // Utility methods
- //---------------------------------------------------------------------
-
- /**
- * Scatter ranked keys directly to device-accessible memory
- */
- template
- __device__ __forceinline__ void ScatterKeys(
- UnsignedBits (&twiddled_keys)[ITEMS_PER_THREAD],
- OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD],
- int (&ranks)[ITEMS_PER_THREAD],
- OffsetT valid_items,
- Int2Type /*scatter_algorithm*/)
- {
- #pragma unroll
- for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
- {
- UnsignedBits digit = BFE(twiddled_keys[ITEM], current_bit, num_bits);
- relative_bin_offsets[ITEM] = temp_storage.relative_bin_offsets[digit];
-
- // Un-twiddle
- UnsignedBits key = Traits::TwiddleOut(twiddled_keys[ITEM]);
-
- if (FULL_TILE || (ranks[ITEM] < valid_items))
- {
- d_keys_out[relative_bin_offsets[ITEM] + ranks[ITEM]] = key;
- }
- }
- }
-
-
- /**
- * Scatter ranked keys through shared memory, then to device-accessible memory
- */
- template
- __device__ __forceinline__ void ScatterKeys(
- UnsignedBits (&twiddled_keys)[ITEMS_PER_THREAD],
- OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD],
- int (&ranks)[ITEMS_PER_THREAD],
- OffsetT valid_items,
- Int2Type /*scatter_algorithm*/)
- {
- UnsignedBits *smem = reinterpret_cast(&temp_storage.exchange_keys);
-
- #pragma unroll
- for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
- {
- smem[ranks[ITEM]] = twiddled_keys[ITEM];
- }
-
- CTA_SYNC();
-
- #pragma unroll
- for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
- {
- UnsignedBits key = smem[threadIdx.x + (ITEM * BLOCK_THREADS)];
-
- UnsignedBits digit = BFE(key, current_bit, num_bits);
-
- relative_bin_offsets[ITEM] = temp_storage.relative_bin_offsets[digit];
-
- // Un-twiddle
- key = Traits::TwiddleOut(key);
-
- if (FULL_TILE ||
- (static_cast(threadIdx.x + (ITEM * BLOCK_THREADS)) < valid_items))
- {
- d_keys_out[relative_bin_offsets[ITEM] + threadIdx.x + (ITEM * BLOCK_THREADS)] = key;
- }
- }
- }
-
-
-
- /**
- * Scatter ranked values directly to device-accessible memory
- */
- template
- __device__ __forceinline__ void ScatterValues(
- ValueT (&values)[ITEMS_PER_THREAD],
- OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD],
- int (&ranks)[ITEMS_PER_THREAD],
- OffsetT valid_items,
- Int2Type /*scatter_algorithm*/)
- {
- #pragma unroll
- for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
- {
- if (FULL_TILE || (ranks[ITEM] < valid_items))
- {
- d_values_out[relative_bin_offsets[ITEM] + ranks[ITEM]] = values[ITEM];
- }
- }
- }
-
-
- /**
- * Scatter ranked values through shared memory, then to device-accessible memory
- */
- template
- __device__ __forceinline__ void ScatterValues(
- ValueT (&values)[ITEMS_PER_THREAD],
- OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD],
- int (&ranks)[ITEMS_PER_THREAD],
- OffsetT valid_items,
- Int2Type /*scatter_algorithm*/)
- {
- CTA_SYNC();
-
- ValueT *smem = reinterpret_cast(&temp_storage.exchange_values);
-
- #pragma unroll
- for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
- {
- smem[ranks[ITEM]] = values[ITEM];
- }
-
- CTA_SYNC();
-
- #pragma unroll
- for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
- {
- ValueT value = smem[threadIdx.x + (ITEM * BLOCK_THREADS)];
-
- if (FULL_TILE ||
- (static_cast(threadIdx.x + (ITEM * BLOCK_THREADS)) < valid_items))
- {
- d_values_out[relative_bin_offsets[ITEM] + threadIdx.x + (ITEM * BLOCK_THREADS)] = value;
- }
- }
- }
-
-
- /**
- * Load a tile of items (specialized for full tile)
- */
- template
- __device__ __forceinline__ void LoadItems(
- BlockLoadT &block_loader,
- T (&items)[ITEMS_PER_THREAD],
- InputIteratorT d_in,
- OffsetT /*valid_items*/,
- Int2Type /*is_full_tile*/)
- {
- block_loader.Load(d_in, items);
- }
-
-
- /**
- * Load a tile of items (specialized for full tile)
- */
- template
- __device__ __forceinline__ void LoadItems(
- BlockLoadT &block_loader,
- T (&items)[ITEMS_PER_THREAD],
- InputIteratorT d_in,
- OffsetT /*valid_items*/,
- T /*oob_item*/,
- Int2Type /*is_full_tile*/)
- {
- block_loader.Load(d_in, items);
- }
-
-
- /**
- * Load a tile of items (specialized for partial tile)
- */
- template
- __device__ __forceinline__ void LoadItems(
- BlockLoadT &block_loader,
- T (&items)[ITEMS_PER_THREAD],
- InputIteratorT d_in,
- OffsetT valid_items,
- Int2Type /*is_full_tile*/)
- {
- block_loader.Load(d_in, items, valid_items);
- }
-
- /**
- * Load a tile of items (specialized for partial tile)
- */
- template
- __device__ __forceinline__ void LoadItems(
- BlockLoadT &block_loader,
- T (&items)[ITEMS_PER_THREAD],
- InputIteratorT d_in,
- OffsetT valid_items,
- T oob_item,
- Int2Type /*is_full_tile*/)
- {
- block_loader.Load(d_in, items, valid_items, oob_item);
- }
-
-
- /**
- * Truck along associated values
- */
- template
- __device__ __forceinline__ void GatherScatterValues(
- OffsetT (&relative_bin_offsets)[ITEMS_PER_THREAD],
- int (&ranks)[ITEMS_PER_THREAD],
- OffsetT block_offset,
- OffsetT valid_items,
- Int2Type /*is_keys_only*/)
- {
- CTA_SYNC();
-
- ValueT values[ITEMS_PER_THREAD];
-
- BlockLoadValues loader(temp_storage.load_values);
- LoadItems(
- loader,
- values,
- d_values_in + block_offset,
- valid_items,
- Int2Type());
-
- ScatterValues(
- values,
- relative_bin_offsets,
- ranks,
- valid_items,
- Int2Type());
- }
-
-
- /**
- * Truck along associated values (specialized for key-only sorting)
- */
- template
- __device__ __forceinline__ void GatherScatterValues(
- OffsetT (&/*relative_bin_offsets*/)[ITEMS_PER_THREAD],
- int (&/*ranks*/)[ITEMS_PER_THREAD],
- OffsetT /*block_offset*/,
- OffsetT /*valid_items*/,
- Int2Type /*is_keys_only*/)
- {}
-
-
- /**
- * Process tile
- */
- template
- __device__ __forceinline__ void ProcessTile(
- OffsetT block_offset,
- const OffsetT &valid_items = TILE_ITEMS)
- {
- // Per-thread tile data
- UnsignedBits keys[ITEMS_PER_THREAD]; // Keys
- UnsignedBits twiddled_keys[ITEMS_PER_THREAD]; // Twiddled keys
- int ranks[ITEMS_PER_THREAD]; // For each key, the local rank within the CTA
- OffsetT relative_bin_offsets[ITEMS_PER_THREAD]; // For each key, the global scatter base offset of the corresponding digit
-
- // Assign default (min/max) value to all keys
- UnsignedBits default_key = (IS_DESCENDING) ? LOWEST_KEY : MAX_KEY;
-
- // Load tile of keys
- BlockLoadKeys loader(temp_storage.load_keys);
- LoadItems(
- loader,
- keys,
- d_keys_in + block_offset,
- valid_items,
- default_key,
- Int2Type());
-
- CTA_SYNC();
-
- // Twiddle key bits if necessary
- #pragma unroll
- for (int KEY = 0; KEY < ITEMS_PER_THREAD; KEY++)
- {
- twiddled_keys[KEY] = Traits::TwiddleIn(keys[KEY]);
- }
-
- // Rank the twiddled keys
- int exclusive_digit_prefix;
- BlockRadixRank(temp_storage.ranking).RankKeys(
- twiddled_keys,
- ranks,
- current_bit,
- num_bits,
- exclusive_digit_prefix);
-
- CTA_SYNC();
-
- // Share exclusive digit prefix
- if (threadIdx.x < RADIX_DIGITS)
- {
- // Store exclusive prefix
- temp_storage.exclusive_digit_prefix[threadIdx.x] = exclusive_digit_prefix;
- }
-
- CTA_SYNC();
-
- // Get inclusive digit prefix
- int inclusive_digit_prefix;
- if (threadIdx.x < RADIX_DIGITS)
- {
- if (IS_DESCENDING)
- {
- // Get inclusive digit prefix from exclusive prefix (higher bins come first)
- inclusive_digit_prefix = (threadIdx.x == 0) ?
- (BLOCK_THREADS * ITEMS_PER_THREAD) :
- temp_storage.exclusive_digit_prefix[threadIdx.x - 1];
- }
- else
- {
- // Get inclusive digit prefix from exclusive prefix (lower bins come first)
- inclusive_digit_prefix = (threadIdx.x == RADIX_DIGITS - 1) ?
- (BLOCK_THREADS * ITEMS_PER_THREAD) :
- temp_storage.exclusive_digit_prefix[threadIdx.x + 1];
- }
- }
-
- CTA_SYNC();
-
- // Update global scatter base offsets for each digit
- if (threadIdx.x < RADIX_DIGITS)
- {
-
-
- bin_offset -= exclusive_digit_prefix;
- temp_storage.relative_bin_offsets[threadIdx.x] = bin_offset;
- bin_offset += inclusive_digit_prefix;
- }
-
- CTA_SYNC();
-
- // Scatter keys
- ScatterKeys(twiddled_keys, relative_bin_offsets, ranks, valid_items, Int2Type());
-
- // Gather/scatter values
- GatherScatterValues(relative_bin_offsets , ranks, block_offset, valid_items, Int2Type());
- }
-
- //---------------------------------------------------------------------
- // Copy shortcut
- //---------------------------------------------------------------------
-
- /**
- * Copy tiles within the range of input
- */
- template <
- typename InputIteratorT,
- typename T>
- __device__ __forceinline__ void Copy(
- InputIteratorT d_in,
- T *d_out,
- OffsetT block_offset,
- OffsetT block_end)
- {
- // Simply copy the input
- while (block_offset + TILE_ITEMS <= block_end)
- {
- T items[ITEMS_PER_THREAD];
-
- LoadDirectStriped(threadIdx.x, d_in + block_offset, items);
- CTA_SYNC();
- StoreDirectStriped(threadIdx.x, d_out + block_offset, items);
-
- block_offset += TILE_ITEMS;
- }
-
- // Clean up last partial tile with guarded-I/O
- if (block_offset < block_end)
- {
- OffsetT valid_items = block_end - block_offset;
-
- T items[ITEMS_PER_THREAD];
-
- LoadDirectStriped(threadIdx.x, d_in + block_offset, items, valid_items);
- CTA_SYNC();
- StoreDirectStriped(threadIdx.x, d_out + block_offset, items, valid_items);
- }
- }
-
-
- /**
- * Copy tiles within the range of input (specialized for NullType)
- */
- template
- __device__ __forceinline__ void Copy(
- InputIteratorT /*d_in*/,
- NullType * /*d_out*/,
- OffsetT /*block_offset*/,
- OffsetT /*block_end*/)
- {}
-
-
- //---------------------------------------------------------------------
- // Interface
- //---------------------------------------------------------------------
-
- /**
- * Constructor
- */
- __device__ __forceinline__ AgentRadixSortDownsweep(
- TempStorage &temp_storage,
- OffsetT num_items,
- OffsetT bin_offset,
- const KeyT *d_keys_in,
- KeyT *d_keys_out,
- const ValueT *d_values_in,
- ValueT *d_values_out,
- int current_bit,
- int num_bits)
- :
- temp_storage(temp_storage.Alias()),
- bin_offset(bin_offset),
- d_keys_in(reinterpret_cast(d_keys_in)),
- d_values_in(d_values_in),
- d_keys_out(reinterpret_cast(d_keys_out)),
- d_values_out(d_values_out),
- current_bit(current_bit),
- num_bits(num_bits),
- short_circuit(1)
- {
- if (threadIdx.x < RADIX_DIGITS)
- {
- // Short circuit if the histogram has only bin counts of only zeros or problem-size
- short_circuit = ((bin_offset == 0) || (bin_offset == num_items));
- }
-
- short_circuit = CTA_SYNC_AND(short_circuit);
- }
-
-
- /**
- * Constructor
- */
- __device__ __forceinline__ AgentRadixSortDownsweep(
- TempStorage &temp_storage,
- OffsetT num_items,
- OffsetT *d_spine,
- const KeyT *d_keys_in,
- KeyT *d_keys_out,
- const ValueT *d_values_in,
- ValueT *d_values_out,
- int current_bit,
- int num_bits)
- :
- temp_storage(temp_storage.Alias()),
- d_keys_in(reinterpret_cast(d_keys_in)),
- d_values_in(d_values_in),
- d_keys_out(reinterpret_cast(d_keys_out)),
- d_values_out(d_values_out),
- current_bit(current_bit),
- num_bits(num_bits),
- short_circuit(1)
- {
- // Load digit bin offsets (each of the first RADIX_DIGITS threads will load an offset for that digit)
- if (threadIdx.x < RADIX_DIGITS)
- {
- int bin_idx = (IS_DESCENDING) ?
- RADIX_DIGITS - threadIdx.x - 1 :
- threadIdx.x;
-
- // Short circuit if the first block's histogram has only bin counts of only zeros or problem-size
- OffsetT first_block_bin_offset = d_spine[gridDim.x * bin_idx];
- short_circuit = ((first_block_bin_offset == 0) || (first_block_bin_offset == num_items));
-
- // Load my block's bin offset for my bin
- bin_offset = d_spine[(gridDim.x * bin_idx) + blockIdx.x];
- }
-
- short_circuit = CTA_SYNC_AND(short_circuit);
- }
-
-
- /**
- * Distribute keys from a segment of input tiles.
- */
- __device__ __forceinline__ void ProcessRegion(
- OffsetT block_offset,
- OffsetT block_end)
- {
- if (short_circuit)
- {
- // Copy keys
- Copy(d_keys_in, d_keys_out, block_offset, block_end);
-
- // Copy values
- Copy(d_values_in, d_values_out, block_offset, block_end);
- }
- else
- {
- // Process full tiles of tile_items
- while (block_offset + TILE_ITEMS <= block_end)
- {
- ProcessTile(block_offset);
- block_offset += TILE_ITEMS;
-
- CTA_SYNC();
- }
-
- // Clean up last partial tile with guarded-I/O
- if (block_offset < block_end)
- {
- ProcessTile(block_offset, block_end - block_offset);
- }
- }
- }
-
-};
-
-
-
-} // CUB namespace
-CUB_NS_POSTFIX // Optional outer namespace(s)
-
diff --git a/ml-xgboost/cub/cub/agent/agent_radix_sort_upsweep.cuh b/ml-xgboost/cub/cub/agent/agent_radix_sort_upsweep.cuh
deleted file mode 100644
index 88e27d3..0000000
--- a/ml-xgboost/cub/cub/agent/agent_radix_sort_upsweep.cuh
+++ /dev/null
@@ -1,449 +0,0 @@
-/******************************************************************************
- * Copyright (c) 2011, Duane Merrill. All rights reserved.
- * Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the NVIDIA CORPORATION nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- ******************************************************************************/
-
-/**
- * \file
- * AgentRadixSortUpsweep implements a stateful abstraction of CUDA thread blocks for participating in device-wide radix sort upsweep .
- */
-
-#pragma once
-
-#include "../thread/thread_reduce.cuh"
-#include "../thread/thread_load.cuh"
-#include "../block/block_load.cuh"
-#include "../util_type.cuh"
-#include "../iterator/cache_modified_input_iterator.cuh"
-#include "../util_namespace.cuh"
-
-/// Optional outer namespace(s)
-CUB_NS_PREFIX
-
-/// CUB namespace
-namespace cub {
-
-/******************************************************************************
- * Tuning policy types
- ******************************************************************************/
-
-/**
- * Parameterizable tuning policy type for AgentRadixSortUpsweep
- */
-template <
- int _BLOCK_THREADS, ///< Threads per thread block
- int _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
- CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading keys
- int _RADIX_BITS> ///< The number of radix bits, i.e., log2(bins)
-struct AgentRadixSortUpsweepPolicy
-{
- enum
- {
- BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block
- ITEMS_PER_THREAD = _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
- RADIX_BITS = _RADIX_BITS, ///< The number of radix bits, i.e., log2(bins)
- };
-
- static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading keys
-};
-
-
-/******************************************************************************
- * Thread block abstractions
- ******************************************************************************/
-
-/**
- * \brief AgentRadixSortUpsweep implements a stateful abstraction of CUDA thread blocks for participating in device-wide radix sort upsweep .
- */
-template <
- typename AgentRadixSortUpsweepPolicy, ///< Parameterized AgentRadixSortUpsweepPolicy tuning policy type
- typename KeyT, ///< KeyT type
- typename OffsetT> ///< Signed integer type for global offsets
-struct AgentRadixSortUpsweep
-{
-
- //---------------------------------------------------------------------
- // Type definitions and constants
- //---------------------------------------------------------------------
-
- typedef typename Traits::UnsignedBits UnsignedBits;
-
- // Integer type for digit counters (to be packed into words of PackedCounters)
- typedef unsigned char DigitCounter;
-
- // Integer type for packing DigitCounters into columns of shared memory banks
- typedef unsigned int PackedCounter;
-
- static const CacheLoadModifier LOAD_MODIFIER = AgentRadixSortUpsweepPolicy::LOAD_MODIFIER;
-
- enum
- {
- RADIX_BITS = AgentRadixSortUpsweepPolicy::RADIX_BITS,
- BLOCK_THREADS = AgentRadixSortUpsweepPolicy::BLOCK_THREADS,
- KEYS_PER_THREAD = AgentRadixSortUpsweepPolicy::ITEMS_PER_THREAD,
-
- RADIX_DIGITS = 1 << RADIX_BITS,
-
- LOG_WARP_THREADS = CUB_PTX_LOG_WARP_THREADS,
- WARP_THREADS = 1 << LOG_WARP_THREADS,
- WARPS = (BLOCK_THREADS + WARP_THREADS - 1) / WARP_THREADS,
-
- TILE_ITEMS = BLOCK_THREADS * KEYS_PER_THREAD,
-
- BYTES_PER_COUNTER = sizeof(DigitCounter),
- LOG_BYTES_PER_COUNTER = Log2::VALUE,
-
- PACKING_RATIO = sizeof(PackedCounter) / sizeof(DigitCounter),
- LOG_PACKING_RATIO = Log2::VALUE,
-
- LOG_COUNTER_LANES = CUB_MAX(0, RADIX_BITS - LOG_PACKING_RATIO),
- COUNTER_LANES = 1 << LOG_COUNTER_LANES,
-
- // To prevent counter overflow, we must periodically unpack and aggregate the
- // digit counters back into registers. Each counter lane is assigned to a
- // warp for aggregation.
-
- LANES_PER_WARP = CUB_MAX(1, (COUNTER_LANES + WARPS - 1) / WARPS),
-
- // Unroll tiles in batches without risk of counter overflow
- UNROLL_COUNT = CUB_MIN(64, 255 / KEYS_PER_THREAD),
- UNROLLED_ELEMENTS = UNROLL_COUNT * TILE_ITEMS,
- };
-
-
- // Input iterator wrapper type (for applying cache modifier)s
- typedef CacheModifiedInputIterator KeysItr;
-
- /**
- * Shared memory storage layout
- */
- struct _TempStorage
- {
- union
- {
- DigitCounter digit_counters[COUNTER_LANES][BLOCK_THREADS][PACKING_RATIO];
- PackedCounter packed_counters[COUNTER_LANES][BLOCK_THREADS];
- OffsetT digit_partials[RADIX_DIGITS][WARP_THREADS + 1];
- };
- };
-
-
- /// Alias wrapper allowing storage to be unioned
- struct TempStorage : Uninitialized<_TempStorage> {};
-
-
- //---------------------------------------------------------------------
- // Thread fields (aggregate state bundle)
- //---------------------------------------------------------------------
-
- // Shared storage for this CTA
- _TempStorage &temp_storage;
-
- // Thread-local counters for periodically aggregating composite-counter lanes
- OffsetT local_counts[LANES_PER_WARP][PACKING_RATIO];
-
- // Input and output device pointers
- KeysItr d_keys_in;
-
- // The least-significant bit position of the current digit to extract
- int current_bit;
-
- // Number of bits in current digit
- int num_bits;
-
-
-
- //---------------------------------------------------------------------
- // Helper structure for templated iteration
- //---------------------------------------------------------------------
-
- // Iterate
- template
- struct Iterate
- {
- // BucketKeys
- static __device__ __forceinline__ void BucketKeys(
- AgentRadixSortUpsweep &cta,
- UnsignedBits keys[KEYS_PER_THREAD])
- {
- cta.Bucket(keys[COUNT]);
-
- // Next
- Iterate::BucketKeys(cta, keys);
- }
- };
-
- // Terminate
- template
- struct Iterate
- {
- // BucketKeys
- static __device__ __forceinline__ void BucketKeys(AgentRadixSortUpsweep &/*cta*/, UnsignedBits /*keys*/[KEYS_PER_THREAD]) {}
- };
-
-
- //---------------------------------------------------------------------
- // Utility methods
- //---------------------------------------------------------------------
-
- /**
- * Decode a key and increment corresponding smem digit counter
- */
- __device__ __forceinline__ void Bucket(UnsignedBits key)
- {
- // Perform transform op
- UnsignedBits converted_key = Traits::TwiddleIn(key);
-
- // Extract current digit bits
- UnsignedBits digit = BFE(converted_key, current_bit, num_bits);
-
- // Get sub-counter offset
- UnsignedBits sub_counter = digit & (PACKING_RATIO - 1);
-
- // Get row offset
- UnsignedBits row_offset = digit >> LOG_PACKING_RATIO;
-
- // Increment counter
- temp_storage.digit_counters[row_offset][threadIdx.x][sub_counter]++;
- }
-
-
- /**
- * Reset composite counters
- */
- __device__ __forceinline__ void ResetDigitCounters()
- {
- #pragma unroll
- for (int LANE = 0; LANE < COUNTER_LANES; LANE++)
- {
- temp_storage.packed_counters[LANE][threadIdx.x] = 0;
- }
- }
-
-
- /**
- * Reset the unpacked counters in each thread
- */
- __device__ __forceinline__ void ResetUnpackedCounters()
- {
- #pragma unroll
- for (int LANE = 0; LANE < LANES_PER_WARP; LANE++)
- {
- #pragma unroll
- for (int UNPACKED_COUNTER = 0; UNPACKED_COUNTER < PACKING_RATIO; UNPACKED_COUNTER++)
- {
- local_counts[LANE][UNPACKED_COUNTER] = 0;
- }
- }
- }
-
-
- /**
- * Extracts and aggregates the digit counters for each counter lane
- * owned by this warp
- */
- __device__ __forceinline__ void UnpackDigitCounts()
- {
- unsigned int warp_id = threadIdx.x >> LOG_WARP_THREADS;
- unsigned int warp_tid = threadIdx.x & (WARP_THREADS - 1);
-
- #pragma unroll
- for (int LANE = 0; LANE < LANES_PER_WARP; LANE++)
- {
- const int counter_lane = (LANE * WARPS) + warp_id;
- if (counter_lane < COUNTER_LANES)
- {
- #pragma unroll
- for (int PACKED_COUNTER = 0; PACKED_COUNTER < BLOCK_THREADS; PACKED_COUNTER += WARP_THREADS)
- {
- #pragma unroll
- for (int UNPACKED_COUNTER = 0; UNPACKED_COUNTER < PACKING_RATIO; UNPACKED_COUNTER++)
- {
- OffsetT counter = temp_storage.digit_counters[counter_lane][warp_tid + PACKED_COUNTER][UNPACKED_COUNTER];
- local_counts[LANE][UNPACKED_COUNTER] += counter;
- }
- }
- }
- }
- }
-
-
- /**
- * Places unpacked counters into smem for final digit reduction
- */
- __device__ __forceinline__ void ReduceUnpackedCounts(OffsetT &bin_count)
- {
- unsigned int warp_id = threadIdx.x >> LOG_WARP_THREADS;
- unsigned int warp_tid = threadIdx.x & (WARP_THREADS - 1);
-
- // Place unpacked digit counters in shared memory
- #pragma unroll
- for (int LANE = 0; LANE < LANES_PER_WARP; LANE++)
- {
- int counter_lane = (LANE * WARPS) + warp_id;
- if (counter_lane < COUNTER_LANES)
- {
- int digit_row = counter_lane << LOG_PACKING_RATIO;
-
- #pragma unroll
- for (int UNPACKED_COUNTER = 0; UNPACKED_COUNTER < PACKING_RATIO; UNPACKED_COUNTER++)
- {
- temp_storage.digit_partials[digit_row + UNPACKED_COUNTER][warp_tid] =
- local_counts[LANE][UNPACKED_COUNTER];
- }
- }
- }
-
- CTA_SYNC();
-
- // Rake-reduce bin_count reductions
- if (threadIdx.x < RADIX_DIGITS)
- {
- bin_count = ThreadReduce(
- temp_storage.digit_partials[threadIdx.x],
- Sum());
- }
- }
-
-
- /**
- * Processes a single, full tile
- */
- __device__ __forceinline__ void ProcessFullTile(OffsetT block_offset)
- {
- // Tile of keys
- UnsignedBits keys[KEYS_PER_THREAD];
-
- LoadDirectStriped(threadIdx.x, d_keys_in + block_offset, keys);
-
- // Prevent hoisting
- CTA_SYNC();
-
- // Bucket tile of keys
- Iterate<0, KEYS_PER_THREAD>::BucketKeys(*this, keys);
- }
-
-
- /**
- * Processes a single load (may have some threads masked off)
- */
- __device__ __forceinline__ void ProcessPartialTile(
- OffsetT block_offset,
- const OffsetT &block_end)
- {
- // Process partial tile if necessary using single loads
- block_offset += threadIdx.x;
- while (block_offset < block_end)
- {
- // Load and bucket key
- UnsignedBits key = d_keys_in[block_offset];
- Bucket(key);
- block_offset += BLOCK_THREADS;
- }
- }
-
-
- //---------------------------------------------------------------------
- // Interface
- //---------------------------------------------------------------------
-
- /**
- * Constructor
- */
- __device__ __forceinline__ AgentRadixSortUpsweep(
- TempStorage &temp_storage,
- const KeyT *d_keys_in,
- int current_bit,
- int num_bits)
- :
- temp_storage(temp_storage.Alias()),
- d_keys_in(reinterpret_cast(d_keys_in)),
- current_bit(current_bit),
- num_bits(num_bits)
- {}
-
-
- /**
- * Compute radix digit histograms from a segment of input tiles.
- */
- __device__ __forceinline__ void ProcessRegion(
- OffsetT block_offset,
- const OffsetT &block_end,
- OffsetT &bin_count) ///< [out] The digit count for tid'th bin (output param, valid in the first RADIX_DIGITS threads)
- {
- // Reset digit counters in smem and unpacked counters in registers
- ResetDigitCounters();
- ResetUnpackedCounters();
-
- // Unroll batches of full tiles
- while (block_offset + UNROLLED_ELEMENTS <= block_end)
- {
- for (int i = 0; i < UNROLL_COUNT; ++i)
- {
- ProcessFullTile(block_offset);
- block_offset += TILE_ITEMS;
- }
-
- CTA_SYNC();
-
- // Aggregate back into local_count registers to prevent overflow
- UnpackDigitCounts();
-
- CTA_SYNC();
-
- // Reset composite counters in lanes
- ResetDigitCounters();
- }
-
- // Unroll single full tiles
- while (block_offset + TILE_ITEMS <= block_end)
- {
- ProcessFullTile(block_offset);
- block_offset += TILE_ITEMS;
- }
-
- // Process partial tile if necessary
- ProcessPartialTile(
- block_offset,
- block_end);
-
- CTA_SYNC();
-
- // Aggregate back into local_count registers
- UnpackDigitCounts();
-
- CTA_SYNC();
-
- // Final raking reduction of counts by bin
- ReduceUnpackedCounts(bin_count);
- }
-
-};
-
-
-} // CUB namespace
-CUB_NS_POSTFIX // Optional outer namespace(s)
-
diff --git a/ml-xgboost/cub/cub/agent/agent_reduce.cuh b/ml-xgboost/cub/cub/agent/agent_reduce.cuh
deleted file mode 100644
index ad8fbcf..0000000
--- a/ml-xgboost/cub/cub/agent/agent_reduce.cuh
+++ /dev/null
@@ -1,475 +0,0 @@
-/******************************************************************************
- * Copyright (c) 2011, Duane Merrill. All rights reserved.
- * Copyright (c) 2011-2016, NVIDIA CORPORATION. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the NVIDIA CORPORATION nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- ******************************************************************************/
-
-/**
- * \file
- * cub::AgentReduce implements a stateful abstraction of CUDA thread blocks for participating in device-wide reduction .
- */
-
-#pragma once
-
-#include
-
-#include "../block/block_load.cuh"
-#include "../block/block_reduce.cuh"
-#include "../grid/grid_mapping.cuh"
-#include "../grid/grid_queue.cuh"
-#include "../grid/grid_even_share.cuh"
-#include "../util_type.cuh"
-#include "../iterator/cache_modified_input_iterator.cuh"
-#include "../util_namespace.cuh"
-
-
-/// Optional outer namespace(s)
-CUB_NS_PREFIX
-
-/// CUB namespace
-namespace cub {
-
-
-/******************************************************************************
- * Tuning policy types
- ******************************************************************************/
-
-/**
- * Parameterizable tuning policy type for AgentReduce
- */
-template <
- int _BLOCK_THREADS, ///< Threads per thread block
- int _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
- int _VECTOR_LOAD_LENGTH, ///< Number of items per vectorized load
- BlockReduceAlgorithm _BLOCK_ALGORITHM, ///< Cooperative block-wide reduction algorithm to use
- CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading input elements
- GridMappingStrategy _GRID_MAPPING> ///< How to map tiles of input onto thread blocks
-struct AgentReducePolicy
-{
- enum
- {
- BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block
- ITEMS_PER_THREAD = _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
- VECTOR_LOAD_LENGTH = _VECTOR_LOAD_LENGTH, ///< Number of items per vectorized load
- };
-
- static const BlockReduceAlgorithm BLOCK_ALGORITHM = _BLOCK_ALGORITHM; ///< Cooperative block-wide reduction algorithm to use
- static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading input elements
- static const GridMappingStrategy GRID_MAPPING = _GRID_MAPPING; ///< How to map tiles of input onto thread blocks
-};
-
-
-
-/******************************************************************************
- * Thread block abstractions
- ******************************************************************************/
-
-/**
- * \brief AgentReduce implements a stateful abstraction of CUDA thread blocks for participating in device-wide reduction .
- *
- * Each thread reduces only the values it loads. If \p FIRST_TILE, this
- * partial reduction is stored into \p thread_aggregate. Otherwise it is
- * accumulated into \p thread_aggregate.
- */
-template <
- typename AgentReducePolicy, ///< Parameterized AgentReducePolicy tuning policy type
- typename InputIteratorT, ///< Random-access iterator type for input
- typename OutputIteratorT, ///< Random-access iterator type for output
- typename OffsetT, ///< Signed integer type for global offsets
- typename ReductionOp> ///< Binary reduction operator type having member T operator()(const T &a, const T &b)
-struct AgentReduce
-{
-
- //---------------------------------------------------------------------
- // Types and constants
- //---------------------------------------------------------------------
-
- /// The input value type
- typedef typename std::iterator_traits::value_type InputT;
-
- /// The output value type
- typedef typename If<(Equals::value_type, void>::VALUE), // OutputT = (if output iterator's value type is void) ?
- typename std::iterator_traits::value_type, // ... then the input iterator's value type,
- typename std::iterator_traits::value_type>::Type OutputT; // ... else the output iterator's value type
-
- /// Vector type of InputT for data movement
- typedef typename CubVector::Type VectorT;
-
- /// Input iterator wrapper type (for applying cache modifier)
- typedef typename If::VALUE,
- CacheModifiedInputIterator, // Wrap the native input pointer with CacheModifiedInputIterator
- InputIteratorT>::Type // Directly use the supplied input iterator type
- WrappedInputIteratorT;
-
- /// Constants
- enum
- {
- BLOCK_THREADS = AgentReducePolicy::BLOCK_THREADS,
- ITEMS_PER_THREAD = AgentReducePolicy::ITEMS_PER_THREAD,
- VECTOR_LOAD_LENGTH = CUB_MIN(ITEMS_PER_THREAD, AgentReducePolicy::VECTOR_LOAD_LENGTH),
- TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD,
-
- // Can vectorize according to the policy if the input iterator is a native pointer to a primitive type
- ATTEMPT_VECTORIZATION = (VECTOR_LOAD_LENGTH > 1) &&
- (ITEMS_PER_THREAD % VECTOR_LOAD_LENGTH == 0) &&
- (IsPointer::VALUE) && Traits::PRIMITIVE,
-
- };
-
- static const CacheLoadModifier LOAD_MODIFIER = AgentReducePolicy::LOAD_MODIFIER;
- static const BlockReduceAlgorithm BLOCK_ALGORITHM = AgentReducePolicy::BLOCK_ALGORITHM;
-
- /// Parameterized BlockReduce primitive
- typedef BlockReduce BlockReduceT;
-
- /// Shared memory type required by this thread block
- struct _TempStorage
- {
- typename BlockReduceT::TempStorage reduce;
- OffsetT dequeue_offset;
- };
-
- /// Alias wrapper allowing storage to be unioned
- struct TempStorage : Uninitialized<_TempStorage> {};
-
-
- //---------------------------------------------------------------------
- // Per-thread fields
- //---------------------------------------------------------------------
-
- _TempStorage& temp_storage; ///< Reference to temp_storage
- InputIteratorT d_in; ///< Input data to reduce
- WrappedInputIteratorT d_wrapped_in; ///< Wrapped input data to reduce
- ReductionOp reduction_op; ///< Binary reduction operator
-
-
- //---------------------------------------------------------------------
- // Utility
- //---------------------------------------------------------------------
-
-
- // Whether or not the input is aligned with the vector type (specialized for types we can vectorize)
- template
- static __device__ __forceinline__ bool IsAligned(
- Iterator d_in,
- Int2Type /*can_vectorize*/)
- {
- return (size_t(d_in) & (sizeof(VectorT) - 1)) == 0;
- }
-
- // Whether or not the input is aligned with the vector type (specialized for types we cannot vectorize)
- template
- static __device__ __forceinline__ bool IsAligned(
- Iterator /*d_in*/,
- Int2Type /*can_vectorize*/)
- {
- return false;
- }
-
-
- //---------------------------------------------------------------------
- // Constructor
- //---------------------------------------------------------------------
-
- /**
- * Constructor
- */
- __device__ __forceinline__ AgentReduce(
- TempStorage& temp_storage, ///< Reference to temp_storage
- InputIteratorT d_in, ///< Input data to reduce
- ReductionOp reduction_op) ///< Binary reduction operator
- :
- temp_storage(temp_storage.Alias()),
- d_in(d_in),
- d_wrapped_in(d_in),
- reduction_op(reduction_op)
- {}
-
-
- //---------------------------------------------------------------------
- // Tile consumption
- //---------------------------------------------------------------------
-
- /**
- * Consume a full tile of input (non-vectorized)
- */
- template
- __device__ __forceinline__ void ConsumeTile(
- OutputT &thread_aggregate,
- OffsetT block_offset, ///< The offset the tile to consume
- int /*valid_items*/, ///< The number of valid items in the tile
- Int2Type /*is_full_tile*/, ///< Whether or not this is a full tile
- Int2Type /*can_vectorize*/) ///< Whether or not we can vectorize loads
- {
- OutputT items[ITEMS_PER_THREAD];
-
- // Load items in striped fashion
- LoadDirectStriped(threadIdx.x, d_wrapped_in + block_offset, items);
-
- // Reduce items within each thread stripe
- thread_aggregate = (IS_FIRST_TILE) ?
- ThreadReduce(items, reduction_op) :
- ThreadReduce(items, reduction_op, thread_aggregate);
- }
-
-
- /**
- * Consume a full tile of input (vectorized)
- */
- template
- __device__ __forceinline__ void ConsumeTile(
- OutputT &thread_aggregate,
- OffsetT block_offset, ///< The offset the tile to consume
- int /*valid_items*/, ///< The number of valid items in the tile
- Int2Type /*is_full_tile*/, ///< Whether or not this is a full tile
- Int2Type /*can_vectorize*/) ///< Whether or not we can vectorize loads
- {
- // Alias items as an array of VectorT and load it in striped fashion
- enum { WORDS = ITEMS_PER_THREAD / VECTOR_LOAD_LENGTH };
-
- // Fabricate a vectorized input iterator
- InputT *d_in_unqualified = const_cast(d_in) + block_offset + (threadIdx.x * VECTOR_LOAD_LENGTH);
- CacheModifiedInputIterator d_vec_in(
- reinterpret_cast(d_in_unqualified));
-
- // Load items as vector items
- InputT input_items[ITEMS_PER_THREAD];
- VectorT *vec_items = reinterpret_cast(input_items);
- #pragma unroll
- for (int i = 0; i < WORDS; ++i)
- vec_items[i] = d_vec_in[BLOCK_THREADS * i];
-
- // Convert from input type to output type
- OutputT items[ITEMS_PER_THREAD];
- #pragma unroll
- for (int i = 0; i < ITEMS_PER_THREAD; ++i)
- items[i] = input_items[i];
-
- // Reduce items within each thread stripe
- thread_aggregate = (IS_FIRST_TILE) ?
- ThreadReduce(items, reduction_op) :
- ThreadReduce(items, reduction_op, thread_aggregate);
- }
-
-
- /**
- * Consume a partial tile of input
- */
- template
- __device__ __forceinline__ void ConsumeTile(
- OutputT &thread_aggregate,
- OffsetT block_offset, ///< The offset the tile to consume
- int valid_items, ///< The number of valid items in the tile
- Int2Type /*is_full_tile*/, ///< Whether or not this is a full tile
- Int2Type /*can_vectorize*/) ///< Whether or not we can vectorize loads
- {
- // Partial tile
- int thread_offset = threadIdx.x;
-
- // Read first item
- if ((IS_FIRST_TILE) && (thread_offset < valid_items))
- {
- thread_aggregate = d_wrapped_in[block_offset + thread_offset];
- thread_offset += BLOCK_THREADS;
- }
-
- // Continue reading items (block-striped)
- while (thread_offset < valid_items)
- {
- OutputT item = d_wrapped_in[block_offset + thread_offset];
- thread_aggregate = reduction_op(thread_aggregate, item);
- thread_offset += BLOCK_THREADS;
- }
- }
-
-
- //---------------------------------------------------------------
- // Consume a contiguous segment of tiles
- //---------------------------------------------------------------------
-
- /**
- * \brief Reduce a contiguous segment of input tiles
- */
- template
- __device__ __forceinline__ OutputT ConsumeRange(
- OffsetT block_offset, ///< [in] Threadblock begin offset (inclusive)
- OffsetT block_end, ///< [in] Threadblock end offset (exclusive)
- Int2Type can_vectorize) ///< Whether or not we can vectorize loads
- {
- OutputT thread_aggregate;
-
- if (block_offset + TILE_ITEMS > block_end)
- {
- // First tile isn't full (not all threads have valid items)
- int valid_items = block_end - block_offset;
- ConsumeTile(thread_aggregate, block_offset, valid_items, Int2Type(), can_vectorize);
- return BlockReduceT(temp_storage.reduce).Reduce(thread_aggregate, reduction_op, valid_items);
- }
-
- // At least one full block
- ConsumeTile(thread_aggregate, block_offset, TILE_ITEMS, Int2Type(), can_vectorize);
- block_offset += TILE_ITEMS;
-
- // Consume subsequent full tiles of input
- while (block_offset + TILE_ITEMS <= block_end)
- {
- ConsumeTile(thread_aggregate, block_offset, TILE_ITEMS, Int2Type(), can_vectorize);
- block_offset += TILE_ITEMS;
- }
-
- // Consume a partially-full tile
- if (block_offset < block_end)
- {
- int valid_items = block_end - block_offset;
- ConsumeTile(thread_aggregate, block_offset, valid_items, Int2Type(), can_vectorize);
- }
-
- // Compute block-wide reduction (all threads have valid items)
- return BlockReduceT(temp_storage.reduce).Reduce(thread_aggregate, reduction_op);
- }
-
-
- /**
- * \brief Reduce a contiguous segment of input tiles
- */
- __device__ __forceinline__ OutputT ConsumeRange(
- OffsetT block_offset, ///< [in] Threadblock begin offset (inclusive)
- OffsetT block_end) ///< [in] Threadblock end offset (exclusive)
- {
- return (IsAligned(d_in + block_offset, Int2Type())) ?
- ConsumeRange(block_offset, block_end, Int2Type()) :
- ConsumeRange(block_offset, block_end, Int2Type());
- }
-
-
- /**
- * Reduce a contiguous segment of input tiles
- */
- __device__ __forceinline__ OutputT ConsumeTiles(
- OffsetT /*num_items*/, ///< [in] Total number of global input items
- GridEvenShare &even_share, ///< [in] GridEvenShare descriptor
- GridQueue &/*queue*/, ///< [in,out] GridQueue descriptor
- Int2Type /*is_even_share*/) ///< [in] Marker type indicating this is an even-share mapping
- {
- // Initialize even-share descriptor for this thread block
- even_share.BlockInit();
-
- return (IsAligned(d_in, Int2Type())) ?
- ConsumeRange(even_share.block_offset, even_share.block_end, Int2Type()) :
- ConsumeRange(even_share.block_offset, even_share.block_end, Int2Type());
-
- }
-
-
- //---------------------------------------------------------------------
- // Dynamically consume tiles
- //---------------------------------------------------------------------
-
- /**
- * Dequeue and reduce tiles of items as part of a inter-block reduction
- */
- template
- __device__ __forceinline__ OutputT ConsumeTiles(
- int num_items, ///< Total number of input items
- GridQueue queue, ///< Queue descriptor for assigning tiles of work to thread blocks
- Int2Type