|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.ml.r |
| 19 | + |
| 20 | +import org.apache.hadoop.fs.Path |
| 21 | +import org.json4s._ |
| 22 | +import org.json4s.JsonDSL._ |
| 23 | +import org.json4s.jackson.JsonMethods._ |
| 24 | + |
| 25 | +import org.apache.spark.ml.{Pipeline, PipelineModel} |
| 26 | +import org.apache.spark.ml.attribute.{Attribute, AttributeGroup, NominalAttribute} |
| 27 | +import org.apache.spark.ml.classification.{GBTClassificationModel, GBTClassifier} |
| 28 | +import org.apache.spark.ml.feature.{IndexToString, RFormula} |
| 29 | +import org.apache.spark.ml.linalg.Vector |
| 30 | +import org.apache.spark.ml.util._ |
| 31 | +import org.apache.spark.sql.{DataFrame, Dataset} |
| 32 | + |
| 33 | +private[r] class GBTClassifierWrapper private ( |
| 34 | + val pipeline: PipelineModel, |
| 35 | + val formula: String, |
| 36 | + val features: Array[String]) extends MLWritable { |
| 37 | + |
| 38 | + import GBTClassifierWrapper._ |
| 39 | + |
| 40 | + private val gbtcModel: GBTClassificationModel = |
| 41 | + pipeline.stages(1).asInstanceOf[GBTClassificationModel] |
| 42 | + |
| 43 | + lazy val numFeatures: Int = gbtcModel.numFeatures |
| 44 | + lazy val featureImportances: Vector = gbtcModel.featureImportances |
| 45 | + lazy val numTrees: Int = gbtcModel.getNumTrees |
| 46 | + lazy val treeWeights: Array[Double] = gbtcModel.treeWeights |
| 47 | + |
| 48 | + def summary: String = gbtcModel.toDebugString |
| 49 | + |
| 50 | + def transform(dataset: Dataset[_]): DataFrame = { |
| 51 | + pipeline.transform(dataset) |
| 52 | + .drop(PREDICTED_LABEL_INDEX_COL) |
| 53 | + .drop(gbtcModel.getFeaturesCol) |
| 54 | + } |
| 55 | + |
| 56 | + override def write: MLWriter = new |
| 57 | + GBTClassifierWrapper.GBTClassifierWrapperWriter(this) |
| 58 | +} |
| 59 | + |
| 60 | +private[r] object GBTClassifierWrapper extends MLReadable[GBTClassifierWrapper] { |
| 61 | + |
| 62 | + val PREDICTED_LABEL_INDEX_COL = "pred_label_idx" |
| 63 | + val PREDICTED_LABEL_COL = "prediction" |
| 64 | + |
| 65 | + def fit( // scalastyle:ignore |
| 66 | + data: DataFrame, |
| 67 | + formula: String, |
| 68 | + maxDepth: Int, |
| 69 | + maxBins: Int, |
| 70 | + maxIter: Int, |
| 71 | + stepSize: Double, |
| 72 | + minInstancesPerNode: Int, |
| 73 | + minInfoGain: Double, |
| 74 | + checkpointInterval: Int, |
| 75 | + lossType: String, |
| 76 | + seed: String, |
| 77 | + subsamplingRate: Double, |
| 78 | + maxMemoryInMB: Int, |
| 79 | + cacheNodeIds: Boolean): GBTClassifierWrapper = { |
| 80 | + |
| 81 | + val rFormula = new RFormula() |
| 82 | + .setFormula(formula) |
| 83 | + .setForceIndexLabel(true) |
| 84 | + RWrapperUtils.checkDataColumns(rFormula, data) |
| 85 | + val rFormulaModel = rFormula.fit(data) |
| 86 | + |
| 87 | + // get feature names from output schema |
| 88 | + val schema = rFormulaModel.transform(data).schema |
| 89 | + val featureAttrs = AttributeGroup.fromStructField(schema(rFormulaModel.getFeaturesCol)) |
| 90 | + .attributes.get |
| 91 | + val features = featureAttrs.map(_.name.get) |
| 92 | + |
| 93 | + // get label names from output schema |
| 94 | + val labelAttr = Attribute.fromStructField(schema(rFormulaModel.getLabelCol)) |
| 95 | + .asInstanceOf[NominalAttribute] |
| 96 | + val labels = labelAttr.values.get |
| 97 | + |
| 98 | + // assemble and fit the pipeline |
| 99 | + val rfc = new GBTClassifier() |
| 100 | + .setMaxDepth(maxDepth) |
| 101 | + .setMaxBins(maxBins) |
| 102 | + .setMaxIter(maxIter) |
| 103 | + .setStepSize(stepSize) |
| 104 | + .setMinInstancesPerNode(minInstancesPerNode) |
| 105 | + .setMinInfoGain(minInfoGain) |
| 106 | + .setCheckpointInterval(checkpointInterval) |
| 107 | + .setLossType(lossType) |
| 108 | + .setSubsamplingRate(subsamplingRate) |
| 109 | + .setMaxMemoryInMB(maxMemoryInMB) |
| 110 | + .setCacheNodeIds(cacheNodeIds) |
| 111 | + .setFeaturesCol(rFormula.getFeaturesCol) |
| 112 | + .setPredictionCol(PREDICTED_LABEL_INDEX_COL) |
| 113 | + if (seed != null && seed.length > 0) rfc.setSeed(seed.toLong) |
| 114 | + |
| 115 | + val idxToStr = new IndexToString() |
| 116 | + .setInputCol(PREDICTED_LABEL_INDEX_COL) |
| 117 | + .setOutputCol(PREDICTED_LABEL_COL) |
| 118 | + .setLabels(labels) |
| 119 | + |
| 120 | + val pipeline = new Pipeline() |
| 121 | + .setStages(Array(rFormulaModel, rfc, idxToStr)) |
| 122 | + .fit(data) |
| 123 | + |
| 124 | + new GBTClassifierWrapper(pipeline, formula, features) |
| 125 | + } |
| 126 | + |
| 127 | + override def read: MLReader[GBTClassifierWrapper] = new GBTClassifierWrapperReader |
| 128 | + |
| 129 | + override def load(path: String): GBTClassifierWrapper = super.load(path) |
| 130 | + |
| 131 | + class GBTClassifierWrapperWriter(instance: GBTClassifierWrapper) |
| 132 | + extends MLWriter { |
| 133 | + |
| 134 | + override protected def saveImpl(path: String): Unit = { |
| 135 | + val rMetadataPath = new Path(path, "rMetadata").toString |
| 136 | + val pipelinePath = new Path(path, "pipeline").toString |
| 137 | + |
| 138 | + val rMetadata = ("class" -> instance.getClass.getName) ~ |
| 139 | + ("formula" -> instance.formula) ~ |
| 140 | + ("features" -> instance.features.toSeq) |
| 141 | + val rMetadataJson: String = compact(render(rMetadata)) |
| 142 | + |
| 143 | + sc.parallelize(Seq(rMetadataJson), 1).saveAsTextFile(rMetadataPath) |
| 144 | + instance.pipeline.save(pipelinePath) |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + class GBTClassifierWrapperReader extends MLReader[GBTClassifierWrapper] { |
| 149 | + |
| 150 | + override def load(path: String): GBTClassifierWrapper = { |
| 151 | + implicit val format = DefaultFormats |
| 152 | + val rMetadataPath = new Path(path, "rMetadata").toString |
| 153 | + val pipelinePath = new Path(path, "pipeline").toString |
| 154 | + val pipeline = PipelineModel.load(pipelinePath) |
| 155 | + |
| 156 | + val rMetadataStr = sc.textFile(rMetadataPath, 1).first() |
| 157 | + val rMetadata = parse(rMetadataStr) |
| 158 | + val formula = (rMetadata \ "formula").extract[String] |
| 159 | + val features = (rMetadata \ "features").extract[Array[String]] |
| 160 | + |
| 161 | + new GBTClassifierWrapper(pipeline, formula, features) |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments