如何用Sp求中值和分位数

2024-05-11 19:12:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用分布式方法IPython和Spark找到整数的RDD中值?RDD大约是700000个元素,因此太大,无法收集和找到中位数。

这个问题和这个问题类似。但是,问题的答案是使用Scala,我不知道。

How can I calculate exact median with Apache Spark?

使用Scala答案的思想,我试图用Python编写一个类似的答案。

我知道我首先想对RDD排序。我不知道怎么做。我看到了sortBy(按给定的keyfunc对这个RDD进行排序)和sortByKey(对这个RDD进行排序,假设它由(键、值)对组成)方法。我认为use key value和myRDD都只有整数元素。

  1. 首先,我想做myrdd.sortBy(lambda x: x)
  2. 接下来我将找到rdd的长度(rdd.count())。
  3. 最后,我想在rdd的中心找到元素或2个元素。我也需要这个方法的帮助。

编辑:

我有个主意。也许我可以索引我的RDD,然后key=index和value=element。然后我可以试着按价值排序?我不知道这是否可能,因为只有一个sortByKey方法。


Tags: 方法key答案元素排序valueipython分布式
3条回答

火花2.0+:

您可以使用实现Greenwald-Khanna algorithmapproxQuantile方法:

Python

df.approxQuantile("x", [0.5], 0.25)

斯卡拉

df.stat.approxQuantile("x", Array(0.5), 0.25)

其中最后一个参数是相对误差。数值越小,结果越精确,计算量越大。

由于Spark 2.2(SPARK-14352),它支持对多个列的估计:

df.approxQuantile(["x", "y", "z"], [0.5], 0.25)

以及

df.approxQuantile(Array("x", "y", "z"), Array(0.5), 0.25)

火花<;2.0

Python

正如我在评论中提到的,这很可能不值得大惊小怪。如果数据相对较小(如您的情况),则只需在本地收集和计算中值:

import numpy as np

np.random.seed(323)
rdd = sc.parallelize(np.random.randint(1000000, size=700000))

%time np.median(rdd.collect())
np.array(rdd.collect()).nbytes

在我那台几年前的电脑上大约需要0.01秒,内存大约为5.5MB。

如果数据要大得多,排序将是一个限制因素,因此与其获得确切的值,不如在本地进行采样、收集和计算。但如果你真的想用星火,像这样的东西应该能起到作用(如果我没有搞砸任何事情的话):

from numpy import floor
import time

def quantile(rdd, p, sample=None, seed=None):
    """Compute a quantile of order p ∈ [0, 1]
    :rdd a numeric rdd
    :p quantile(between 0 and 1)
    :sample fraction of and rdd to use. If not provided we use a whole dataset
    :seed random number generator seed to be used with sample
    """
    assert 0 <= p <= 1
    assert sample is None or 0 < sample <= 1

    seed = seed if seed is not None else time.time()
    rdd = rdd if sample is None else rdd.sample(False, sample, seed)

    rddSortedWithIndex = (rdd.
        sortBy(lambda x: x).
        zipWithIndex().
        map(lambda (x, i): (i, x)).
        cache())

    n = rddSortedWithIndex.count()
    h = (n - 1) * p

    rddX, rddXPlusOne = (
        rddSortedWithIndex.lookup(x)[0]
        for x in int(floor(h)) + np.array([0L, 1L]))

    return rddX + (h - floor(h)) * (rddXPlusOne - rddX)

还有一些测试:

np.median(rdd.collect()), quantile(rdd, 0.5)
## (500184.5, 500184.5)
np.percentile(rdd.collect(), 25), quantile(rdd, 0.25)
## (250506.75, 250506.75)
np.percentile(rdd.collect(), 75), quantile(rdd, 0.75)
(750069.25, 750069.25)

最后让我们定义中值:

from functools import partial
median = partial(quantile, p=0.5)

到目前为止还不错,但在没有任何网络通信的情况下,本地模式需要4.66秒。也许有办法改善这一点,但为什么还要费心呢?

与语言无关Hive UDAF):

如果使用HiveContext,也可以使用配置单元UDAFs。积分值:

rdd.map(lambda x: (float(x), )).toDF(["x"]).registerTempTable("df")

sqlContext.sql("SELECT percentile_approx(x, 0.5) FROM df")

连续值:

sqlContext.sql("SELECT percentile(x, 0.5) FROM df")

percentile_approx中,可以传递一个额外的参数,该参数确定要使用的记录数。

下面是我使用窗口函数(pyspark 2.2.0)的方法。

from pyspark.sql import DataFrame

class median():
    """ Create median class with over method to pass partition """
    def __init__(self, df, col, name):
        assert col
        self.column=col
        self.df = df
        self.name = name

    def over(self, window):
        from pyspark.sql.functions import percent_rank, pow, first

        first_window = window.orderBy(self.column)                                  # first, order by column we want to compute the median for
        df = self.df.withColumn("percent_rank", percent_rank().over(first_window))  # add percent_rank column, percent_rank = 0.5 coressponds to median
        second_window = window.orderBy(pow(df.percent_rank-0.5, 2))                 # order by (percent_rank - 0.5)^2 ascending
        return df.withColumn(self.name, first(self.column).over(second_window))     # the first row of the window corresponds to median

def addMedian(self, col, median_name):
    """ Method to be added to spark native DataFrame class """
    return median(self, col, median_name)

# Add method to DataFrame class
DataFrame.addMedian = addMedian

然后调用addMedian方法计算col2的中值:

from pyspark.sql import Window

median_window = Window.partitionBy("col1")
df = df.addMedian("col2", "median").over(median_window)

最后你可以根据需要分组。

df.groupby("col1", "median")

如果您只想要一个RDD方法,而不想移动到DF,则添加一个解决方案。 此代码段可以为RDD为double获取百分位数。

如果您输入的百分位数为50,您应该获得您所需的中位数。 如果有什么角落的案子没交代,请告诉我。

/**
  * Gets the nth percentile entry for an RDD of doubles
  *
  * @param inputScore : Input scores consisting of a RDD of doubles
  * @param percentile : The percentile cutoff required (between 0 to 100), e.g 90%ile of [1,4,5,9,19,23,44] = ~23.
  *                     It prefers the higher value when the desired quantile lies between two data points
  * @return : The number best representing the percentile in the Rdd of double
  */    
  def getRddPercentile(inputScore: RDD[Double], percentile: Double): Double = {
    val numEntries = inputScore.count().toDouble
    val retrievedEntry = (percentile * numEntries / 100.0 ).min(numEntries).max(0).toInt


    inputScore
      .sortBy { case (score) => score }
      .zipWithIndex()
      .filter { case (score, index) => index == retrievedEntry }
      .map { case (score, index) => score }
      .collect()(0)
  }

相关问题 更多 >