VectorAssembler需要输入什么数据类型?

2024-09-24 06:29:58 发布

您现在位置:Python中文网/ 问答频道 /正文

核心问题就在这里

from pyspark.ml.feature import VectorAssembler
df = spark.createDataFrame([([1, 2, 3], 0, 3)], ["a", "b", "c"])
vecAssembler = VectorAssembler(outputCol="features", inputCols=["a", "b", "c"])
vecAssembler.transform(df).show()

有错误IllegalArgumentException: Data type array<bigint> of column a is not supported.

我知道这有点像玩具问题,但我正试图通过步骤将其集成到一个较长的管道中

  • 字符串索引器
  • OneHotEncoding
  • 自定义一元转换器,将所有1乘以10
    • 这里应该返回什么数据类型
  • 然后使用VectorAssembler将向量组合成单个向量进行建模

如果我能为VectorAssembler确定正确的输入数据类型,我应该能够正确地将所有内容串在一起。我认为输入类型是向量,但我不知道如何构建向量


Tags: fromimportdf核心向量mlfeaturespark
1条回答
网友
1楼 · 发布于 2024-09-24 06:29:58

根据docs报告

VectorAssembler accepts the following input column types: all numeric types, boolean type, and vector type.

因此,首先需要将数组列转换为向量列(方法来自this question

from pyspark.ml.linalg import Vectors, VectorUDT
from pyspark.sql.functions import udf
list_to_vector_udf = udf(lambda l: Vectors.dense(l), VectorUDT())
df_with_vectors = df.withColumn('a', list_to_vector_udf('a'))

然后可以使用向量汇编程序:

vecAssembler = VectorAssembler(outputCol="features", inputCols=["a", "b", "c"])

vecAssembler.transform(df_with_vectors).show(truncate=False)
+      -+ -+ -+          -+
|a            |b  |c  |features             |
+      -+ -+ -+          -+
|[1.0,2.0,3.0]|0  |3  |[1.0,2.0,3.0,0.0,3.0]|
+      -+ -+ -+          -+

相关问题 更多 >