组合VectorAssembler和HashingTF变换器的Spark管道

ran*_*lot 0 apache-spark apache-spark-sql apache-spark-ml

让我们定义一个Spark管道,它将几列组合在一起,然后应用特征哈希:

val df = sqlContext.createDataFrame(Seq((0.0, 1.0, 2.0), (3.0, 4.0, 5.0))).toDF("colx", "coly", "colz")
val va = new VectorAssembler().setInputCols(Array("colx", "coly", "colz")).setOutputCol("ft")
val hashIt = new HashingTF().setInputCol("ft").setOutputCol("ft2")
val pipeline = new Pipeline().setStages(Array(va, hashIt))
Run Code Online (Sandbox Code Playgroud)

使用pipeline.fit(df)throws 安装管道:

java.lang.IllegalArgumentException:要求失败:输入列必须是ArrayType,但是得到了org.apache.spark.mllib.linalg.VectorUDT@f71b0bce

是否有允许VectorAssemblerHashingTF能够一起工作的变压器?

eli*_*sah 5

就个人而言,我甚至不会为此目的使用Pipeline API,array功能就足够了

val df = sqlContext.createDataFrame(Seq((0.0, 1.0, 2.0), (3.0, 4.0, 5.0)))
               .toDF("colx", "coly", "colz")
               .withColumn("ft", array('colx, 'coly, 'colz))

val hashIt = new HashingTF().setInputCol("ft").setOutputCol("ft2")
val res = hashIt.transform(df)

res.show(false)
# +----+----+----+---------------+------------------------------+
# |colx|coly|colz|ft             |ft2                           |
# +----+----+----+---------------+------------------------------+
# |0.0 |1.0 |2.0 |[0.0, 1.0, 2.0]|(262144,[0,1,2],[1.0,1.0,1.0])|
# |3.0 |4.0 |5.0 |[3.0, 4.0, 5.0]|(262144,[3,4,5],[1.0,1.0,1.0])|
# +----+----+----+---------------+------------------------------+
Run Code Online (Sandbox Code Playgroud)

作为问题的后续,要在列数> 3的情况下概括数组函数的应用,下面的步骤将所有列连接成一列,其中包含所有需要列的数组:

val df2 = sqlContext.createDataFrame(Seq((0.0, 1.0, 2.0), (3.0, 4.0, 5.0)))
                .toDF("colx", "coly", "colz")
val cols = (for (i <- df2.columns) yield df2(i)).toList
df2.withColumn("ft",array(cols :_*)).show

# +----+----+----+---------------+
# |colx|coly|colz|             ft|
# +----+----+----+---------------+
# | 0.0| 1.0| 2.0|[0.0, 1.0, 2.0]|
# | 3.0| 4.0| 5.0|[3.0, 4.0, 5.0]|
# +----+----+----+---------------+
Run Code Online (Sandbox Code Playgroud)