|
| 1 | +package org.apache.spark.ml.classification |
| 2 | + |
| 3 | +import scala.collection.mutable.ArrayBuffer |
| 4 | + |
| 5 | +import org.apache.spark.rdd.RDD |
| 6 | +import org.apache.spark.sql._ |
| 7 | +import org.apache.spark.mllib.linalg.{Vectors, Vector} |
| 8 | +import org.apache.spark.ml.LabeledPoint |
| 9 | +import org.apache.spark.ml.evaluation.ClassificationEvaluator |
| 10 | +import org.apache.spark.ml.param.{HasWeightCol, Param, ParamMap, HasMaxIter} |
| 11 | +import org.apache.spark.ml.impl.estimator.{ProbabilisticClassificationModel, WeakLearner, |
| 12 | + IterativeEstimator, IterativeSolver} |
| 13 | + |
| 14 | + |
| 15 | +private[classification] trait AdaBoostParams extends ClassifierParams |
| 16 | + with HasMaxIter with HasWeightCol { |
| 17 | + |
| 18 | + /** param for weak learner type */ |
| 19 | + val weakLearner: Param[Classifier[_, _]] = |
| 20 | + new Param(this, "weakLearner", "weak learning algorithm") |
| 21 | + def getWeakLearner: Classifier[_, _] = get(weakLearner) |
| 22 | + |
| 23 | + /** param for weak learner param maps */ |
| 24 | + val weakLearnerParamMap: Param[ParamMap] = |
| 25 | + new Param(this, "weakLearnerParamMap", "param map for the weak learner") |
| 26 | + def getWeakLearnerParamMap: ParamMap = get(weakLearnerParamMap) |
| 27 | + |
| 28 | + override def validate(paramMap: ParamMap): Unit = { |
| 29 | + // TODO: Check maxIter, weakLearner, weakLearnerParamMap, weightCol |
| 30 | + // Check: If the weak learner does not extend WeakLearner, then featuresColName should be |
| 31 | + // castable to FeaturesType. |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +/** |
| 37 | + * AdaBoost |
| 38 | + * |
| 39 | + * Developer notes: |
| 40 | + * - If the weak learner implements the [[WeakLearner]] |
| 41 | + */ |
| 42 | +class AdaBoost extends Classifier[AdaBoost, AdaBoostModel] |
| 43 | + with AdaBoostParams |
| 44 | + with IterativeEstimator[AdaBoostModel] { |
| 45 | + |
| 46 | + def setMaxIter(value: Int): this.type = set(maxIter, value) |
| 47 | + def setWeightCol(value: String): this.type = set(weightCol, value) |
| 48 | + def setWeakLearner(value: Classifier[_, _]): this.type = set(weakLearner, value) |
| 49 | + def setWeakLearnerParamMap(value: ParamMap): this.type = set(weakLearnerParamMap, value) |
| 50 | + |
| 51 | + /** |
| 52 | + * Extract LabeledPoints, using the weak learner's native feature representation if possible. |
| 53 | + * @param paramMap Complete paramMap (after combining with the internal paramMap) |
| 54 | + */ |
| 55 | + private def extractLabeledPoints(dataset: SchemaRDD, paramMap: ParamMap): RDD[LabeledPoint] = { |
| 56 | + import dataset.sqlContext._ |
| 57 | + val featuresColName = paramMap(featuresCol) |
| 58 | + val wl = paramMap(weakLearner) |
| 59 | + val featuresRDD: RDD[Vector] = wl match { |
| 60 | + case wlTagged: WeakLearner => |
| 61 | + val wlParamMap = paramMap(weakLearnerParamMap) |
| 62 | + val wlFeaturesColName = wlParamMap(wl.featuresCol) |
| 63 | + val origFeaturesRDD = dataset.select(featuresColName.attr).as(wlFeaturesColName.attr) |
| 64 | + wlTagged.getNativeFeatureRDD(origFeaturesRDD, wlParamMap) |
| 65 | + case _ => |
| 66 | + dataset.select(featuresColName.attr).map { case Row(features: Vector) => features } |
| 67 | + } |
| 68 | + |
| 69 | + val labelColName = paramMap(labelCol) |
| 70 | + if (paramMap.contains(weightCol)) { |
| 71 | + val weightColName = paramMap(weightCol) |
| 72 | + dataset.select(labelColName.attr, weightColName.attr) |
| 73 | + .zip(featuresRDD).map { case (Row(label: Double, weight: Double), features: Vector) => |
| 74 | + LabeledPoint(label, features, weight) |
| 75 | + } |
| 76 | + } else { |
| 77 | + dataset.select(labelColName.attr) |
| 78 | + .zip(featuresRDD).map { case (Row(label: Double), features: Vector) => |
| 79 | + LabeledPoint(label, features) |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + // From Classifier |
| 85 | + override def fit(dataset: SchemaRDD, paramMap: ParamMap): AdaBoostModel = { |
| 86 | + val map = this.paramMap ++ paramMap |
| 87 | + val labeledPoints: RDD[LabeledPoint] = extractLabeledPoints(dataset, map) |
| 88 | + train(labeledPoints, paramMap) |
| 89 | + } |
| 90 | + |
| 91 | + // From IterativeEstimator |
| 92 | + override private[ml] def createSolver(dataset: SchemaRDD, paramMap: ParamMap): AdaBoostSolver = { |
| 93 | + val map = this.paramMap ++ paramMap |
| 94 | + val labeledPoints: RDD[LabeledPoint] = extractLabeledPoints(dataset, map) |
| 95 | + new AdaBoostSolver(labeledPoints, this, map) |
| 96 | + } |
| 97 | + |
| 98 | + // From Predictor |
| 99 | + override def train(dataset: RDD[LabeledPoint], paramMap: ParamMap): AdaBoostModel = { |
| 100 | + val map = this.paramMap ++ paramMap |
| 101 | + val solver = new AdaBoostSolver(dataset, this, map) |
| 102 | + while (solver.step()) { } |
| 103 | + solver.currentModel |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | + |
| 108 | +class AdaBoostModel private[ml] ( |
| 109 | + val weakHypotheses: Array[ClassificationModel[_]], |
| 110 | + val weakHypothesisWeights: Array[Double], |
| 111 | + override val parent: AdaBoost, |
| 112 | + override val fittingParamMap: ParamMap) |
| 113 | + extends ClassificationModel[AdaBoostModel] |
| 114 | + with ProbabilisticClassificationModel |
| 115 | + with AdaBoostParams { |
| 116 | + |
| 117 | + require(weakHypotheses.size != 0) |
| 118 | + require(weakHypotheses.size == weakHypothesisWeights.size) |
| 119 | + |
| 120 | + // From Classifier.Model: |
| 121 | + override val numClasses: Int = weakHypotheses(0).numClasses |
| 122 | + |
| 123 | + require(weakHypotheses.forall(_.numClasses == numClasses)) |
| 124 | + |
| 125 | + private val margin: Vector => Double = (features) => { |
| 126 | + weakHypotheses.zip(weakHypothesisWeights) |
| 127 | + .foldLeft(0.0) { case (total: Double, (wh: ClassificationModel[_], weight: Double)) => |
| 128 | + val pred = if (wh.predict(features) == 1.0) 1.0 else -1.0 |
| 129 | + total + weight * pred |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + private val score: Vector => Double = (features) => { |
| 134 | + val m = margin(features) |
| 135 | + 1.0 / (1.0 + math.exp(-2.0 * m)) |
| 136 | + } |
| 137 | + |
| 138 | + override def predictProbabilities(features: Vector): Vector = { |
| 139 | + val s = score(features) |
| 140 | + Vectors.dense(Array(1.0 - s, s)) |
| 141 | + } |
| 142 | + |
| 143 | + override def predictRaw(features: Vector): Vector = { |
| 144 | + val m = margin(features) |
| 145 | + Vectors.dense(Array(-m, m)) |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | + |
| 150 | +private[ml] class AdaBoostSolver( |
| 151 | + val origData: RDD[LabeledPoint], |
| 152 | + val parent: AdaBoost, |
| 153 | + val paramMap: ParamMap) extends IterativeSolver[AdaBoostModel] { |
| 154 | + |
| 155 | + private val weakHypotheses = new ArrayBuffer[ClassificationModel[_]] |
| 156 | + private val weakHypothesisWeights = new ArrayBuffer[Double] |
| 157 | + |
| 158 | + private val wl: Classifier[_, _] = paramMap(parent.weakLearner) |
| 159 | + private val wlParamMap = paramMap(parent.weakLearnerParamMap) |
| 160 | + override val maxIterations: Int = paramMap(parent.maxIter) |
| 161 | + |
| 162 | + // TODO: Decide if this alg should cache data, or if that should be left to the user. |
| 163 | + |
| 164 | + // TODO: check for weights = 0 |
| 165 | + // TODO: EDITING HERE NOW: switch to log weights |
| 166 | + private var logInstanceWeights: RDD[Double] = origData.map(lp => math.log(lp.weight)) |
| 167 | + |
| 168 | + override def stepImpl(): Boolean = ??? /*{ |
| 169 | + // Check if the weak learner takes instance weights. |
| 170 | + val wlDataset = wl match { |
| 171 | + case wlWeighted: HasWeightCol => |
| 172 | + origData.zip(logInstanceWeights).map { case (lp: LabeledPoint, logWeight: Double) => |
| 173 | + LabeledPoint(lp.label, lp.features, weight) |
| 174 | + } |
| 175 | + case _ => |
| 176 | + // Subsample data to simulate the current instance weight distribution. |
| 177 | + // TODO: This needs to be done before AdaBoost is committed. |
| 178 | + throw new NotImplementedError( |
| 179 | + "AdaBoost currently requires that the weak learning algorithm accept instance weights.") |
| 180 | + } |
| 181 | + // Train the weak learning algorithm. |
| 182 | + val weakHypothesis: ClassificationModel[_] = wl match { |
| 183 | + case wlTagged: WeakLearner[_] => |
| 184 | + // This lets the weak learner know that the features are in its native format. |
| 185 | + wlTagged.trainNative(wlDataset, wlParamMap).asInstanceOf[ClassificationModel[_]] |
| 186 | + case _ => |
| 187 | + wl.train(wlDataset, wlParamMap).asInstanceOf[ClassificationModel[_]] |
| 188 | + } |
| 189 | + // Add the weighted weak hypothesis to the ensemble. |
| 190 | + // TODO: Handle instance weights. |
| 191 | + val predictionsAndLabels = wlDataset.map(lp => weakHypothesis.predict(lp.features)) |
| 192 | + .zip(wlDataset.map(_.label)) |
| 193 | + val eps = ClassificationEvaluator.computeMetric(predictionsAndLabels, "accuracy") |
| 194 | + val alpha = 0.5 * (math.log(1.0 - eps) - math.log(eps)) // TODO: handle eps near 0 |
| 195 | + weakHypotheses += weakHypothesis |
| 196 | + weakHypothesisWeights += alpha |
| 197 | + // Update weights. |
| 198 | + val newInstanceWeights = instanceWeights.zip(predictionsAndLabels).map { |
| 199 | + case (weight: Double, (pred: Double, label: Double)) => |
| 200 | + ??? |
| 201 | + } |
| 202 | +
|
| 203 | + }*/ |
| 204 | + |
| 205 | + override def currentModel: AdaBoostModel = { |
| 206 | + new AdaBoostModel(weakHypotheses.toArray, weakHypothesisWeights.toArray, parent, paramMap) |
| 207 | + } |
| 208 | +} |
0 commit comments