PySpark:OneHotEncoder 的输出看起来很奇怪
PySpark: Output of OneHotEncoder looks odd
Spark 文档包含 a PySpark example 的 OneHotEncoder
:
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])
这是什么意思?我应该如何阅读此输出,这种有点奇怪的格式背后的原因是什么?
没什么奇怪的。这些只是 SparseVectors
其中:
- 第一个元素是向量的大小
- 第一个数组
[...]
是一个索引列表。
- 第二个数组是值列表。
未明确列出的指数为 0.0。
Spark 文档包含 a PySpark example 的 OneHotEncoder
:
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])
这是什么意思?我应该如何阅读此输出,这种有点奇怪的格式背后的原因是什么?
没什么奇怪的。这些只是 SparseVectors
其中:
- 第一个元素是向量的大小
- 第一个数组
[...]
是一个索引列表。 - 第二个数组是值列表。
未明确列出的指数为 0.0。