|
| 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.feature |
| 19 | + |
| 20 | +import org.apache.spark.SparkException |
| 21 | +import org.apache.spark.annotation.AlphaComponent |
| 22 | +import org.apache.spark.ml.UnaryTransformer |
| 23 | +import org.apache.spark.ml.attribute.{Attribute, BinaryAttribute, NominalAttribute} |
| 24 | +import org.apache.spark.mllib.linalg.{Vector, Vectors, VectorUDT} |
| 25 | +import org.apache.spark.ml.param._ |
| 26 | +import org.apache.spark.ml.param.shared.{HasInputCol, HasOutputCol} |
| 27 | +import org.apache.spark.ml.util.SchemaUtils |
| 28 | +import org.apache.spark.sql.types.{DataType, DoubleType, StructType} |
| 29 | + |
| 30 | +/** |
| 31 | + * A one-hot encoder that maps a column of label indices to a column of binary vectors, with |
| 32 | + * at most a single one-value. By default, the binary vector has an element for each category, so |
| 33 | + * with 5 categories, an input value of 2.0 would map to an output vector of |
| 34 | + * (0.0, 0.0, 1.0, 0.0, 0.0). If includeFirst is set to false, the first category is omitted, so the |
| 35 | + * output vector for the previous example would be (0.0, 1.0, 0.0, 0.0) and an input value |
| 36 | + * of 0.0 would map to a vector of all zeros. Including the first category makes the vector columns |
| 37 | + * linearly dependent because they sum up to one. |
| 38 | + */ |
| 39 | +@AlphaComponent |
| 40 | +class OneHotEncoder extends UnaryTransformer[Double, Vector, OneHotEncoder] |
| 41 | + with HasInputCol with HasOutputCol { |
| 42 | + |
| 43 | + /** |
| 44 | + * Whether to include a component in the encoded vectors for the first category, defaults to true. |
| 45 | + * @group param |
| 46 | + */ |
| 47 | + final val includeFirst: BooleanParam = |
| 48 | + new BooleanParam(this, "includeFirst", "include first category") |
| 49 | + setDefault(includeFirst -> true) |
| 50 | + |
| 51 | + private var categories: Array[String] = _ |
| 52 | + |
| 53 | + /** @group setParam */ |
| 54 | + def setIncludeFirst(value: Boolean): this.type = set(includeFirst, value) |
| 55 | + |
| 56 | + /** @group setParam */ |
| 57 | + override def setInputCol(value: String): this.type = set(inputCol, value) |
| 58 | + |
| 59 | + /** @group setParam */ |
| 60 | + override def setOutputCol(value: String): this.type = set(outputCol, value) |
| 61 | + |
| 62 | + override def transformSchema(schema: StructType): StructType = { |
| 63 | + SchemaUtils.checkColumnType(schema, $(inputCol), DoubleType) |
| 64 | + val inputFields = schema.fields |
| 65 | + val outputColName = $(outputCol) |
| 66 | + require(inputFields.forall(_.name != $(outputCol)), |
| 67 | + s"Output column ${$(outputCol)} already exists.") |
| 68 | + |
| 69 | + val inputColAttr = Attribute.fromStructField(schema($(inputCol))) |
| 70 | + categories = inputColAttr match { |
| 71 | + case nominal: NominalAttribute => |
| 72 | + nominal.values.getOrElse((0 until nominal.numValues.get).map(_.toString).toArray) |
| 73 | + case binary: BinaryAttribute => binary.values.getOrElse(Array("0", "1")) |
| 74 | + case _ => |
| 75 | + throw new SparkException(s"OneHotEncoder input column ${$(inputCol)} is not nominal") |
| 76 | + } |
| 77 | + |
| 78 | + val attrValues = (if ($(includeFirst)) categories else categories.drop(1)).toArray |
| 79 | + val attr = NominalAttribute.defaultAttr.withName(outputColName).withValues(attrValues) |
| 80 | + val outputFields = inputFields :+ attr.toStructField() |
| 81 | + StructType(outputFields) |
| 82 | + } |
| 83 | + |
| 84 | + protected override def createTransformFunc(): (Double) => Vector = { |
| 85 | + val first = $(includeFirst) |
| 86 | + val vecLen = if (first) categories.length else categories.length - 1 |
| 87 | + val oneValue = Array(1.0) |
| 88 | + val emptyValues = Array[Double]() |
| 89 | + val emptyIndices = Array[Int]() |
| 90 | + label: Double => { |
| 91 | + val values = if (first || label != 0.0) oneValue else emptyValues |
| 92 | + val indices = if (first) { |
| 93 | + Array(label.toInt) |
| 94 | + } else if (label != 0.0) { |
| 95 | + Array(label.toInt - 1) |
| 96 | + } else { |
| 97 | + emptyIndices |
| 98 | + } |
| 99 | + Vectors.sparse(vecLen, indices, values) |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * Returns the data type of the output column. |
| 105 | + */ |
| 106 | + protected def outputDataType: DataType = new VectorUDT |
| 107 | +} |
0 commit comments