gpt4 book ai didi

apache-spark - 使用spark ml时如何以另一种方式索引分类特征

转载 作者:行者123 更新时间:2023-12-04 04:13:16 24 4
gpt4 key购买 nike

spark中的VectorIndexer根据变量出现的频率对分类特征进行索引。但我想以不同的方式索引分类特征。

例如,对于如下数据集,如果我在 spark 中使用 VectorIndexer,则“a”、“b”、“c”将被索引为 0,1,2。但我想根据标签对它们进行索引。有 4 行索引为 1 的数据,其中 3 行具有特征'a',1 行特征'c'。所以在这里我将索引 'a' 为 0,'c' 索引为 1,'b' 索引为 2。

有什么方便的方法可以实现吗?

 label|feature
-----------------
1 | a
1 | c
0 | a
0 | b
1 | a
0 | b
0 | b
0 | c
1 | a

最佳答案

如果我正确理解你的问题,你正在寻找复制 StringIndexer() 的行为关于分组数据。为此(在 pySpark 中),我们首先定义一个 udf,它将对包含每组所有值的 List 列进行操作。请注意,具有相同计数的元素将被任意排序。

from collections import Counter
from pyspark.sql.types import ArrayType, IntegerType

def encoder(col):

# Generate count per letter
x = Counter(col)

# Create a dictionary, mapping each letter to its rank
ranking = {pair[0]: rank
for rank, pair in enumerate(x.most_common())}

# Use dictionary to replace letters by rank
new_list = [ranking[i] for i in col]

return(new_list)

encoder_udf = udf(encoder, ArrayType(IntegerType()))

现在我们可以使用 collect_list()feature 列聚合到按 label 列分组的列表中,并应用我们的 udf 按行:

from pyspark.sql.functions import collect_list, explode

df1 = (df.groupBy("label")
.agg(collect_list("feature")
.alias("features"))
.withColumn("index",
encoder_udf("features")))

因此,您可以展开 index 列以获取编码值而不是字母:

df1.select("label", explode(df1.index).alias("index")).show()
+-----+-----+
|label|index|
+-----+-----+
| 0| 1|
| 0| 0|
| 0| 0|
| 0| 0|
| 0| 2|
| 1| 0|
| 1| 1|
| 1| 0|
| 1| 0|
+-----+-----+

关于apache-spark - 使用spark ml时如何以另一种方式索引分类特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40262719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com