【问题标题】:Convert KMeans "centres" output to PySpark dataframe将 KMeans“中心”输出转换为 PySpark 数据帧
【发布时间】:2019-11-12 02:23:57
【问题描述】:

我正在运行一个 K-means 聚类模型,我想分析聚类质心,但是中心输出是我的 20 个质心的列表,它们的坐标(每个 8 个)作为一个数组。我需要它作为一个数据框,集群 1:20 作为行,它们的属性值(质心坐标)作为列,如下所示:

c1 | 0.85 | 0.03 | 0.01 | 0.00 | 0.12 | 0.01 | 0.00 | 0.12 
c2 | 0.25 | 0.80 | 0.10 | 0.00 | 0.12 | 0.01 | 0.00 | 0.77
c3 | 0.05 | 0.10 | 0.00 | 0.82 | 0.00 | 0.00 | 0.22 | 0.00

数据框格式很重要,因为我想做的是:

对于每个质心 确定 3 个最强属性 为 20 个质心中的每一个创建一个“名称”,该名称是该质心中 3 个最主要特征的串联

例如:

c1 | milk_eggs_cheese
c2 | meat_milk_bread
c3 | toiletries_bread_eggs

此代码在 Zeppelin、EMR 版本 5.19、Spark2.4 中运行。该模型效果很好,但这是 Spark 文档 (https://spark.apache.org/docs/latest/ml-clustering.html#k-means) 中的样板代码,它会生成我无法真正使用的数组输出列表。

centers = model.clusterCenters()
print("Cluster Centers: ")
for center in centers:
    print(center)

这是我得到的输出的摘录。

Cluster Centers: 
[0.12391775 0.04282062 0.00368751 0.27282358 0.00533401 0.03389095
 0.04220946 0.03213536 0.00895981 0.00990327 0.01007891]
[0.09018751 0.01354349 0.0130329  0.00772877 0.00371508 0.02288211
 0.032301   0.37979978 0.002487   0.00617438 0.00610262]
[7.37626746e-02 2.02469798e-03 4.00944473e-04 9.62304581e-04
 5.98964859e-03 2.95190585e-03 8.48736175e-01 1.36797882e-03
 2.57451073e-04 6.13320072e-04 5.70559278e-04]

基于How to convert a list of array to Spark dataframe我已经尝试过:

df = sc.parallelize(centers).toDF(['fresh_items', 'wine_liquor', 'baby', 'cigarettes', 'fresh_meat', 'fruit_vegetables', 'bakery', 'toiletries', 'pets', 'coffee', 'cheese'])
df.show()

但这会引发以下错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

【问题讨论】:

    标签: pyspark amazon-emr


    【解决方案1】:

    model.clusterCenters() 为您提供 numpy 数组列表,而不是您链接的答案中的列表列表。只需在创建数据框之前将 numpy 数组转换为列表:

    bla = [e.tolist() for e in centers]
    df = sc.parallelize(bla).toDF(['fresh_items', 'wine_liquor', 'baby', 'cigarettes', 'fresh_meat', 'fruit_vegetables', 'bakery', 'toiletries', 'pets', 'coffee', 'cheese'])
    #or df = spark.createDataFrame(bla, ['fresh_items', 'wine_liquor', 'baby', 'cigarettes', 'fresh_meat', 'fruit_vegetables', 'bakery', 'toiletries', 'pets', 'coffee', 'cheese']
    df.show()
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 2021-11-16
      • 2017-01-25
      • 2021-10-29
      • 1970-01-01
      • 2020-07-31
      相关资源
      最近更新 更多