1/* 2 Copyright (c) 2014 by Contributors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17package ml.dmlc.xgboost4j.scala.spark 18 19import ml.dmlc.xgboost4j.java.XGBoostError 20import org.apache.spark.Partitioner 21import org.apache.spark.ml.feature.VectorAssembler 22import org.apache.spark.sql.SparkSession 23import org.scalatest.FunSuite 24import org.apache.spark.sql.functions._ 25 26import scala.util.Random 27 28class FeatureSizeValidatingSuite extends FunSuite with PerTest { 29 30 test("transform throwing exception if feature size of dataset is greater than model's") { 31 val modelPath = getClass.getResource("/model/0.82/model").getPath 32 val model = XGBoostClassificationModel.read.load(modelPath) 33 val r = new Random(0) 34 // 0.82/model was trained with 251 features. and transform will throw exception 35 // if feature size of data is not equal to 251 36 var df = ss.createDataFrame(Seq.fill(100)(r.nextInt(2)).map(i => (i, i))). 37 toDF("feature", "label") 38 for (x <- 1 to 252) { 39 df = df.withColumn(s"feature_${x}", lit(1)) 40 } 41 val assembler = new VectorAssembler() 42 .setInputCols(df.columns.filter(!_.contains("label"))) 43 .setOutputCol("features") 44 val thrown = intercept[Exception] { 45 model.transform(assembler.transform(df)).show() 46 } 47 assert(thrown.getMessage.contains( 48 "Number of columns does not match number of features in booster")) 49 } 50 51 test("train throwing exception if feature size of dataset is different on distributed train") { 52 val paramMap = Map("eta" -> "1", "max_depth" -> "6", "silent" -> "1", 53 "objective" -> "binary:logistic", 54 "num_round" -> 5, "num_workers" -> 2, "use_external_memory" -> true, "missing" -> 0) 55 import DataUtils._ 56 val sparkSession = SparkSession.builder().getOrCreate() 57 import sparkSession.implicits._ 58 val repartitioned = sc.parallelize(Synthetic.trainWithDiffFeatureSize, 2) 59 .map(lp => (lp.label, lp)).partitionBy( 60 new Partitioner { 61 override def numPartitions: Int = 2 62 63 override def getPartition(key: Any): Int = key.asInstanceOf[Float].toInt 64 } 65 ).map(_._2).zipWithIndex().map { 66 case (lp, id) => 67 (id, lp.label, lp.features) 68 }.toDF("id", "label", "features") 69 val xgb = new XGBoostClassifier(paramMap) 70 intercept[Exception] { 71 xgb.fit(repartitioned) 72 } 73 } 74} 75