PySpark ML:获取KMeans群集统计信息

时间:2017-11-06 05:30:07

标签: machine-learning pyspark cluster-analysis k-means apache-spark-ml

我已经构建了一个KMeansModel。我的结果存储在一个名为的PySpark DataFrame中 transformed

(a)我如何解释transformed的内容?

(b)如何从transformed创建一个或多个Pandas DataFrame,以显示14个群集中每个群集的13个要素的摘要统计信息?

from pyspark.ml.clustering import KMeans
# Trains a k-means model.
kmeans = KMeans().setK(14).setSeed(1)
model = kmeans.fit(X_spark_scaled) # Fits a model to the input dataset with optional parameters.

transformed = model.transform(X_spark_scaled).select("features", "prediction") # X_spark_scaled is my PySpark DataFrame consisting of 13 features
transformed.show(5, truncate = False)
+------------------------------------------------------------------------------------------------------------------------------------+----------+
|features                                                                                                                            |prediction|
+------------------------------------------------------------------------------------------------------------------------------------+----------+
|(14,[4,5,7,8,9,13],[1.0,1.0,485014.0,0.25,2.0,1.0])                                                                                 |12        |
|(14,[2,7,8,9,12,13],[1.0,2401233.0,1.0,1.0,1.0,1.0])                                                                                |2         |
|(14,[2,4,5,7,8,9,13],[0.3333333333333333,0.6666666666666666,0.6666666666666666,2429111.0,0.9166666666666666,1.3333333333333333,3.0])|2         |
|(14,[4,5,7,8,9,12,13],[1.0,1.0,2054748.0,0.15384615384615385,11.0,1.0,1.0])                                                         |11        |
|(14,[2,7,8,9,13],[1.0,43921.0,1.0,1.0,1.0])                                                                                         |1         |
+------------------------------------------------------------------------------------------------------------------------------------+----------+
only showing top 5 rows

顺便说一句,我从另一篇SO帖子中发现,我可以将功能映射到他们的名字,如下所示。在一个或多个Pandas数据帧中为每个集群的每个特征提供汇总统计(平均值,中值,标准,最小值,最大值)会很不错。

attr_list = [attr for attr in chain(*transformed.schema['features'].metadata['ml_attr']['attrs'].values())]
attr_list

评论中的每个请求,这里是一个快照,包含2条数据记录(不想提供太多记录 - 这里有专有信息)

+---------------------+------------------------+-----------------------+----------------------+----------------------+------------------------------+---------------------------------+------------+-------------------+--------------------+------------------------------------+--------------------------+-------------------------------+-----------------+--------------------+--------------------+
|device_type_robot_pct|device_type_smart_tv_pct|device_type_desktop_pct|device_type_tablet_pct|device_type_mobile_pct|device_type_mobile_persist_pct|visitors_seen_with_anonymiser_pct|ip_time_span|          ip_weight|mean_ips_per_visitor|visitors_seen_with_multi_country_pct|international_visitors_pct|visitors_seen_with_multi_ua_pct|count_tuids_on_ip|            features|      scaledFeatures|
+---------------------+------------------------+-----------------------+----------------------+----------------------+------------------------------+---------------------------------+------------+-------------------+--------------------+------------------------------------+--------------------------+-------------------------------+-----------------+--------------------+--------------------+
|                  0.0|                     0.0|                    0.0|                   0.0|                   1.0|                           1.0|                              0.0|    485014.0|               0.25|                 2.0|                                 0.0|                       0.0|                            0.0|              1.0|(14,[4,5,7,8,9,13...|(14,[4,5,7,8,9,13...|
|                  0.0|                     0.0|                    1.0|                   0.0|                   0.0|                           0.0|                              0.0|   2401233.0|                1.0|                 1.0|                                 0.0|                       0.0|                            1.0|              1.0|(14,[2,7,8,9,12,1...|(14,[2,7,8,9,12,1...|

1 个答案:

答案 0 :(得分:8)

正如Anony-Mousse评论的那样,(Py)Spark ML确实很多更加局限于scikit-learn或其他类似的软件包,而且这样的功能并非无足轻重;尽管如此,这是一种获得你想要的东西的方法(集群统计):

spark.version
# u'2.2.0'

from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors

# toy data - 5-d features including sparse vectors
df = spark.createDataFrame(
 [(Vectors.sparse(5,[(0, 164.0),(1,520.0)]), 1.0),
  (Vectors.dense([519.0,2723.0,0.0,3.0,4.0]), 1.0),
  (Vectors.sparse(5,[(0, 2868.0), (1, 928.0)]), 1.0),
  (Vectors.sparse(5,[(0, 57.0), (1, 2715.0)]), 0.0),
  (Vectors.dense([1241.0,2104.0,0.0,0.0,2.0]), 1.0)],
 ["features", "target"])

df.show()
# +--------------------+------+ 
# |            features|target| 
# +--------------------+------+ 
# |(5,[0,1],[164.0,5...|   1.0|
# |[519.0,2723.0,0.0...|   1.0| 
# |(5,[0,1],[2868.0,...|   1.0|
# |(5,[0,1],[57.0,27...|   0.0| 
# |[1241.0,2104.0,0....|   1.0|
# +--------------------+------+

kmeans = KMeans(k=3, seed=1)
model = kmeans.fit(df.select('features'))

transformed = model.transform(df).select("features", "prediction")
transformed.show()
# +--------------------+----------+
# |            features|prediction|
# +--------------------+----------+
# |(5,[0,1],[164.0,5...|         1| 
# |[519.0,2723.0,0.0...|         2|
# |(5,[0,1],[2868.0,...|         0|
# |(5,[0,1],[57.0,27...|         2|
# |[1241.0,2104.0,0....|         2|
# +--------------------+----------+

到此为止,关于你的第一个问题:

  

如何解释transformed的内容?

features列只是原始数据中同一列的复制。

prediction列是相应数据记录所属的集群;在我的例子中,有5个数据记录和k=3个集群,我最终在集群#0中有1个记录,在集群#1中有1个记录,在集群#2中有3个记录。

关于你的第二个问题:

  

如何从transformed创建一个或多个Pandas DataFrame,以显示14个群集中每个群集的13个功能中每个功能的摘要统计信息?

(注意:您似乎有 14 功能,而不是13 ......)

这是一个看似简单的任务的一个很好的例子,遗憾的是,PySpark没有提供现成的功能 - 尤其是因为所有功能都分组在单个向量features中;要做到这一点,我们必须首先"反汇编" features,有效地提出了VectorAssembler反转操作。

我现在能想到的唯一方法是暂时恢复到RDD并执行map操作[编辑:这不是必需的 - 请参阅下面的更新];这是上面我的集群#2的一个例子,它包含密集和稀疏向量:

# keep only cluster #2:
cl_2 = transformed.filter(transformed.prediction==2)
cl_2.show() 
# +--------------------+----------+ 
# |            features|prediction|
# +--------------------+----------+
# |[519.0,2723.0,0.0...|         2|
# |(5,[0,1],[57.0,27...|         2|
# |[1241.0,2104.0,0....|         2| 
# +--------------------+----------+

# set the data dimensionality as a parameter:
dimensionality = 5

cluster_2 = cl_2.drop('prediction').rdd.map(lambda x: [float(x[0][i]) for i in range(dimensionality)]).toDF(schema=['x'+str(i) for i in range(dimensionality)])
cluster_2.show()
# +------+------+---+---+---+ 
# |    x0|    x1| x2| x3| x4|
# +------+------+---+---+---+
# | 519.0|2723.0|0.0|3.0|4.0|
# |  57.0|2715.0|0.0|0.0|0.0| 
# |1241.0|2104.0|0.0|0.0|2.0|
# +------+------+---+---+---+

(如果您的初始数据位于Spark数据框initial_data中,则可以将最后一部分更改为toDF(schema=initial_data.columns),以保留原始要素名称。)

从这一点开始,您可以将cluster_2数据帧转换为pandas(如果它适合您的内存),或者使用Spark数据帧的describe()函数来获取摘要统计信息:

cluster_2.describe().show()
# result:
+-------+-----------------+-----------------+---+------------------+---+ 
|summary|               x0|               x1| x2|                x3| x4|
+-------+-----------------+-----------------+---+------------------+---+ 
|  count|                3|                3|  3|                 3|  3|
|   mean|605.6666666666666|           2514.0|0.0|               1.0|2.0|
| stddev|596.7389155512932|355.0929455790413|0.0|1.7320508075688772|2.0|
|    min|             57.0|           2104.0|0.0|               0.0|0.0|
|    max|           1241.0|           2723.0|0.0|               3.0|4.0|
+-------+-----------------+-----------------+---+------------------+---+

在您的情况下使用上面的dimensionality=14代码可以完成工作......

meanstddev中的所有这些(可称无用的)有效数字感到恼火?作为奖励,这里有一个小实用函数我已经出现some time ago以获得一个非常好的总结:

def prettySummary(df):
    """ Neat summary statistics of a Spark dataframe
    Args:
        pyspark.sql.dataframe.DataFrame (df): input dataframe
    Returns:
        pandas.core.frame.DataFrame: a pandas dataframe with the summary statistics of df
    """
    import pandas as pd
    temp = df.describe().toPandas()
    temp.iloc[1:3,1:] = temp.iloc[1:3,1:].convert_objects(convert_numeric=True)
    pd.options.display.float_format = '{:,.2f}'.format
    return temp

stats_df = prettySummary(cluster_2)
stats_df
# result:
    summary     x0       x1   x2   x3   x4
 0  count        3        3    3    3    3 
 1   mean   605.67 2,514.00 0.00 1.00 2.00 
 2 stddev   596.74   355.09 0.00 1.73 2.00 
 3    min     57.0   2104.0  0.0  0.0  0.0 
 4    max   1241.0   2723.0  0.0  3.0  4.0

更新:再次考虑它,并查看您的示例数据,我提出了一个更直接的解决方案,而无需调用中间RDD(一个人们可能更愿意避免的操作) ,如果可能的话)......

关键观察是transformed的完整内容,即没有 select语句;保持与上面相同的玩具数据集,我们得到:

transformed = model.transform(df)  # no 'select' statements
transformed.show()
# +--------------------+------+----------+
# |            features|target|prediction| 
# +--------------------+------+----------+
# |(5,[0,1],[164.0,5...|   1.0|         1|
# |[519.0,2723.0,0.0...|   1.0|         2|
# |(5,[0,1],[2868.0,...|   1.0|         0|
# |(5,[0,1],[57.0,27...|   0.0|         2|
# |[1241.0,2104.0,0....|   1.0|         2|
# +--------------------+------+----------+

正如您所看到的那样,要转换的数据框df中存在的任何其他列(仅在我的情况下只有一个 - target)只是"传递"转型程序和最终结果出现在最终结果中......

希望您开始明白这一点:如果df包含您最初的14个要素,每个要素都在一个单独的列中,另外还有第15个列为features的列(大致如您的示例数据所示,但没有最后一列),然后是以下代码:

kmeans = KMeans().setK(14)
model = kmeans.fit(df.select('features'))
transformed = model.transform(df).drop('features')

将为您留下包含15列的Spark数据框transformed,即您的最初14个要素加上带有相应群集编号的prediction列。

从这一点开始,您可以按照我上面显示的filter来自transformed的特定群集进行操作,并获取您的摘要统计信息,但您已经避免了(代价高昂......)转换为中间临时RDD,从而将所有操作保存在Spark数据帧的更高效的上下文中......