Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * Licensed to the Apache Software Foundation (ASF) under one or more
0003  * contributor license agreements.  See the NOTICE file distributed with
0004  * this work for additional information regarding copyright ownership.
0005  * The ASF licenses this file to You under the Apache License, Version 2.0
0006  * (the "License"); you may not use this file except in compliance with
0007  * the License.  You may obtain a copy of the License at
0008  *
0009  *    http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  */
0017 
0018 package org.apache.spark.ml.feature;
0019 
0020 import java.util.Arrays;
0021 import java.util.List;
0022 
0023 import org.junit.Assert;
0024 import org.junit.Test;
0025 
0026 import org.apache.spark.SharedSparkSession;
0027 import org.apache.spark.ml.attribute.Attribute;
0028 import org.apache.spark.ml.attribute.AttributeGroup;
0029 import org.apache.spark.ml.attribute.NumericAttribute;
0030 import org.apache.spark.ml.linalg.Vector;
0031 import org.apache.spark.ml.linalg.Vectors;
0032 import org.apache.spark.sql.Dataset;
0033 import org.apache.spark.sql.Row;
0034 import org.apache.spark.sql.RowFactory;
0035 import org.apache.spark.sql.types.StructType;
0036 
0037 
0038 public class JavaVectorSlicerSuite extends SharedSparkSession {
0039 
0040   @Test
0041   public void vectorSlice() {
0042     Attribute[] attrs = new Attribute[]{
0043       NumericAttribute.defaultAttr().withName("f1"),
0044       NumericAttribute.defaultAttr().withName("f2"),
0045       NumericAttribute.defaultAttr().withName("f3")
0046     };
0047     AttributeGroup group = new AttributeGroup("userFeatures", attrs);
0048 
0049     List<Row> data = Arrays.asList(
0050       RowFactory.create(Vectors.sparse(3, new int[]{0, 1}, new double[]{-2.0, 2.3})),
0051       RowFactory.create(Vectors.dense(-2.0, 2.3, 0.0))
0052     );
0053 
0054     Dataset<Row> dataset =
0055       spark.createDataFrame(data, (new StructType()).add(group.toStructField()));
0056 
0057     VectorSlicer vectorSlicer = new VectorSlicer()
0058       .setInputCol("userFeatures").setOutputCol("features");
0059 
0060     vectorSlicer.setIndices(new int[]{1}).setNames(new String[]{"f3"});
0061 
0062     Dataset<Row> output = vectorSlicer.transform(dataset);
0063 
0064     for (Row r : output.select("userFeatures", "features").takeAsList(2)) {
0065       Vector features = r.getAs(1);
0066       Assert.assertEquals(2, features.size());
0067     }
0068   }
0069 }