【问题标题】:PySpark: Output of OneHotEncoder looks odd [duplicate]PySpark:OneHotEncoder 的输出看起来很奇怪 [重复]
【发布时间】:2018-09-12 22:37:21
【问题描述】:

Spark 文档包含 a PySpark exampleOneHotEncoder

from pyspark.ml.feature import OneHotEncoder, StringIndexer

df = spark.createDataFrame([
    (0, "a"),
    (1, "b"),
    (2, "c"),
    (3, "a"),
    (4, "a"),
    (5, "c")
], ["id", "category"])

stringIndexer = StringIndexer(inputCol="category", outputCol="categoryIndex")
model = stringIndexer.fit(df)
indexed = model.transform(df)

encoder = OneHotEncoder(inputCol="categoryIndex", outputCol="categoryVec")
encoded = encoder.transform(indexed)
encoded.show()

我希望列 categoryVec 看起来像这样:

[0.0, 0.0]
[1.0, 0.0]
[0.0, 1.0]
[0.0, 0.0]
[0.0, 0.0]
[0.0, 1.0]

categoryVec实际上是这样的:

(2, [0], [1.0])
    (2, [], [])
(2, [1], [1.0])
(2, [0], [1.0])
(2, [0], [1.0])
(2, [1], [1.0])    

这是什么意思?我应该如何阅读这个输出,这种有点奇怪的格式背后的原因是什么?

【问题讨论】:

    标签: apache-spark pyspark apache-spark-mllib one-hot-encoding


    【解决方案1】:

    这里没有什么奇怪的。这些只是SparseVectors,其中:

    • 第一个元素是向量的大小
    • 第一个数组[...] 是一个索引列表。
    • 第二个数组是值列表。

    未明确列出的指数为 0.0。

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 2021-12-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2015-09-18
      • 2021-03-25
      • 2015-03-20
      • 2011-07-19
      相关资源
      最近更新 更多