使用spark ml时如何以另一种方式索引分类特征
how to index categorical features in another way when using spark ml
spark中的VectorIndexer根据变量出现的频率对分类特征进行索引。但我想以不同的方式索引分类特征。
例如,对于如下数据集,如果我在 spark 中使用 VectorIndexer,"a"、"b"、"c" 将被索引为 0,1,2。但我想根据标签对它们进行索引。
索引为1的数据有4行,其中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|
+-----+-----+
spark中的VectorIndexer根据变量出现的频率对分类特征进行索引。但我想以不同的方式索引分类特征。
例如,对于如下数据集,如果我在 spark 中使用 VectorIndexer,"a"、"b"、"c" 将被索引为 0,1,2。但我想根据标签对它们进行索引。 索引为1的数据有4行,其中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|
+-----+-----+