使用 VectorAssembler 处理动态列

Geo*_*ler 1 pipeline apache-spark apache-spark-ml

使用 sparks 矢量汇编器需要预先定义要组装的列。

但是,如果在前面的步骤将修改数据帧列的管道中使用向量汇编程序,我如何指定列而不手动硬编码所有值?

由于df.columns包含正确的值时,调用构造函数矢量汇编的目前我没有看到另一种方式来处理或拆分管道-这是坏的,以及因为CrossValidator将不再正常工作。

val vectorAssembler = new VectorAssembler()
    .setInputCols(df.columns
      .filter(!_.contains("target"))
      .filter(!_.contains("idNumber")))
    .setOutputCol("features")
Run Code Online (Sandbox Code Playgroud)

编辑

的初始 df

---+------+---+-
|foo|   id|baz|
+---+------+---+
|  0| 1    |  A|
|  1|2     |  A|
|  0| 3    |  null|
|  1| 4    |  C|
+---+------+---+
Run Code Online (Sandbox Code Playgroud)

将转换如下。您可以看到 nan 值将被归入最频繁的原始列和一些派生的特征,例如,如此处所述isA,如果 baz 是 A,则为 1,否则为 0,如果最初为空 N

+---+------+---+-------+
|foo|id    |baz| isA    |
+---+------+---+-------+
|  0| 1    |  A| 1      |
|  1|2     |  A|1       |
|  0| 3    |   A|    n  |
|  1| 4    |  C|    0   |
+---+------+---+-------+
Run Code Online (Sandbox Code Playgroud)

稍后在管道中,使用 stringIndexer 使数据适合 ML/vectorAssembler。

isA 不存在于原始 df 中,但不是“唯一”输出列,该帧中除 foo 和 id 列之外的所有列都应由向量汇编程序转换。

我希望现在更清楚了。

eli*_*sah 5

如果我正确理解您的问题,那么答案将非常简单直接,您只需要使用 .getOutputCol上一个转换器中的 。

示例(来自官方文档):

// Prepare training documents from a list of (id, text, label) tuples.
val training = spark.createDataFrame(Seq(
  (0L, "a b c d e spark", 1.0),
  (1L, "b d", 0.0),
  (2L, "spark f g h", 1.0),
  (3L, "hadoop mapreduce", 0.0)
)).toDF("id", "text", "label")

// Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
val tokenizer = new Tokenizer()
  .setInputCol("text")
  .setOutputCol("words")
val hashingTF = new HashingTF()
  .setNumFeatures(1000)
  .setInputCol(tokenizer.getOutputCol) // <==== Using the tokenizer output column
  .setOutputCol("features")
val lr = new LogisticRegression()
  .setMaxIter(10)
  .setRegParam(0.001)
val pipeline = new Pipeline()
  .setStages(Array(tokenizer, hashingTF, lr))
Run Code Online (Sandbox Code Playgroud)

现在让我们考虑另一个假设列将其应用于 VectorAssembler alpha

val assembler = new VectorAssembler()
  .setInputCols(Array("alpha", tokenizer.getOutputCol)
  .setOutputCol("features")
Run Code Online (Sandbox Code Playgroud)