|
| 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.mllib.util.MLlibTestSparkContext |
| 21 | + |
| 22 | +import org.scalatest.FunSuite |
| 23 | +import org.apache.spark.sql.SQLContext |
| 24 | +import org.apache.spark.ml.attribute.{NominalAttribute, Attribute} |
| 25 | + |
| 26 | +class OneHotEncoderSuite extends FunSuite with MLlibTestSparkContext { |
| 27 | + private var sqlContext: SQLContext = _ |
| 28 | + |
| 29 | + override def beforeAll(): Unit = { |
| 30 | + super.beforeAll() |
| 31 | + sqlContext = new SQLContext(sc) |
| 32 | + } |
| 33 | + |
| 34 | + test("OneHotEncoder") { |
| 35 | + val data = sc.parallelize(Seq((0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")), 2) |
| 36 | + val df = sqlContext.createDataFrame(data).toDF("id", "label") |
| 37 | + val indexer = new StringIndexer() |
| 38 | + .setInputCol("label") |
| 39 | + .setOutputCol("labelIndex") |
| 40 | + .fit(df) |
| 41 | + val transformed = indexer.transform(df) |
| 42 | + val attr = Attribute.fromStructField(transformed.schema("labelIndex")) |
| 43 | + .asInstanceOf[NominalAttribute] |
| 44 | + assert(attr.values.get === Array("a", "c", "b")) |
| 45 | + |
| 46 | + val encoder = new OneHotEncoder(attr.values.get) |
| 47 | + .setInputCol("labelIndex") |
| 48 | + val encoded = encoder.transform(transformed) |
| 49 | + |
| 50 | + val output = encoded.select("id", "labelIndex_a", "labelIndex_c", "labelIndex_b").map { r => |
| 51 | + (r.getInt(0), r.getDouble(1), r.getDouble(2), r.getDouble(3)) |
| 52 | + }.collect().toSet |
| 53 | + // a -> 0, b -> 2, c -> 1 |
| 54 | + val expected = Set((0, 1.0, 0.0, 0.0), (1, 0.0, 0.0, 1.0), (2, 0.0, 1.0, 0.0), |
| 55 | + (3, 1.0, 0.0, 0.0), (4, 1.0, 0.0, 0.0), (5, 0.0, 1.0, 0.0)) |
| 56 | + assert(output === expected) |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments