Skip to content

Contributing an ECDF function? #9057

Closed
Closed

Description

@ericmjl

Hello numpy maintainers!

I'm just wondering if there's any value in contributing an ECDF function to numpy? I've scoured the web and found that people are asking for it on StackOverflow (see here and here), and there seems to be an expectation that it should be in numpy that then gets met with frustration that we have to find it in statsmodels instead.

My proposed implementation is from @justinbois, and would be as follows:

def ecdf(data):
    return np.sort(data), np.arange(1, len(data)+1) / len(data)

(Docstrings not shown, but I'm more than happy to conform to numpy documentation standards.)

Activity

  1. njsmith commented on May 5, 2017

    @njsmith
    Member

    It seems reasonable to me (especially after seeing all those people mess it up on stack overflow), but your proposed implementation has a different interface than the ones in R and statsmodels: you return two arrays, while they return a function (hence the name :-)). Would it make more sense to do something more like

    def ecdf(data):
        xp = np.sort(data)
        yp = np.arange(1, len(data)+1) / len(data)
        def ecdf_instance(x):
            return np.interp(x, xp, yp, left=0, right=1)
        return ecdf_instance
  2. njsmith commented on May 5, 2017

    @njsmith
    Member

    Hah, no, now I messed it up... It should be a step function, and interp does linear interpolation instead.

    This is closer, though still untested...

    yp = np.arange(len(xp) + 1) / len(xp)
    def ecdf_instance(x):
        return yp[np.searchsorted(xp, x, side="right")]
  3. justinbois commented on May 5, 2017

    @justinbois

    The thing I wrote is to generate dots to plot. I like to do it that way because it shows points that were measured, as opposed to the steps (which I call "conventional" below), where the data that were measured are the concave corners. The function returns two arrays that are meant for plotting, which is why it returns two arrays.

    Strictly speaking, the way ECDFs are typically defined (see Definition 7.1 on page 97 of Wasserman's All of Statistics, Springer, 2004) it should be plotted the conventional way. But, like I said, I just like to see my data points.

    The ECDF-for-plotting calculator I use in practice (the code snippet @ericmjl shared was something I pasted into Twitter) is below. Again, it is meant for plotting all of your data points. @njsmith's proposal is what a properly defined ECDF function should compute. However, plotting it is tricky.

    So, maybe this belongs somewhere like Seaborn?

    def ecdf(data, conventional=False, buff=0.1, min_x=None, max_x=None):
        """
        Generate `x` and `y` values for plotting an ECDF.
    
        Parameters
        ----------
        data : array_like
            Array of data to be plotted as an ECDF.
        convential : bool, default False
            If True, generate `x` and `y` values for conventional ECDF.
            Otherwise, generate `x` and `y` values for "dot" style ECDF.
        buff : float, default 0.1
            How long the tails at y = 0 and y = 1 should extend as a
            fraction of the total range of the data. Ignored if
            `conventional` is False.
        min_x : float, default -np.inf
            If min_x is greater than extent computed from `buff`, tail at
            y = 0 extends to min_x. Ignored if `conventional` is False.
        max_x : float, default -np.inf
            If max_x is less than extent computed from `buff`, tail at
            y = 0 extends to max_x. Ignored if `conventional` is False.
    
        Returns
        -------
        x : array
            `x` values for plotting
        y : array
            `y` values for plotting
        """
    
        if conventional:
            return _ecdf_conventional(data, buff=buff, min_x=min_x, max_x=max_x)
        else:
            return _ecdf_dots(data)
    
    
    def _ecdf_dots(data):
        """
        Compute `x` and `y` values for plotting an ECDF.
    
        Parameters
        ----------
        data : array_like
            Array of data to be plotted as an ECDF.
    
        Returns
        -------
        x : array
            `x` values for plotting
        y : array
            `y` values for plotting
        """
        return np.sort(data), np.arange(1, len(data)+1) / len(data)
    
    
    def _ecdf_conventional(data, buff=0.1, min_x=None, max_x=None):
        """
        Generate `x` and `y` values for plotting a conventional ECDF.
    
        Parameters
        ----------
        data : array_like
            Array of data to be plotted as an ECDF.
        buff : float, default 0.1
            How long the tails at y = 0 and y = 1 should extend as a fraction
            of the total range of the data.
        min_x : float, default -np.inf
            If min_x is greater than extent computed from `buff`, tail at
            y = 0 extends to min_x.
        max_x : float, default -np.inf
            If max_x is less than extent computed from `buff`, tail at
            y = 0 extends to max_x.
    
        Returns
        -------
        x : array
            `x` values for plotting
        y : array
            `y` values for plotting
        """
    
        # Set defaults for min and max tails
        if min_x is None:
            min_x = -np.inf
        if max_x is None:
            max_x = np.inf
    
        # Get x and y values for data points
        x, y = _ecdf_dots(data)
    
        # Set up output arrays
        x_conv = np.empty(2*(len(x) + 1))
        y_conv = np.empty(2*(len(x) + 1))
    
        # y-values for steps
        y_conv[:2] = 0
        y_conv[2::2] = y
        y_conv[3::2] = y
    
        # x- values for steps
        x_conv[0] = max(min_x, x[0] - (x[-1] - x[0])*buff)
        x_conv[1] = x[0]
        x_conv[2::2] = x
        x_conv[3:-1:2] = x[1:]
        x_conv[-1] = min(max_x, x[-1] + (x[-1] - x[0])*buff)
    
        return x_conv, y_conv
  4. ericmjl commented on May 5, 2017

    @ericmjl
    Author

    Or maybe it should go into scipy.stats? Seems to me ECDF for plotting most naturally fits into seaborn (statistical plots), but perhaps ECDF function might be best served in scipy or numpy?

  5. eric-wieser commented on May 5, 2017

    @eric-wieser
    Member

    Seems like you want a scipy.stats.empirical, which matches the api of the existing scipy.stats.norm and the like - namely, derived from scipy.stats.rv_discrete:

    from scipy.stats import empirical
    
    p = empical(data).cdf(x)
    p = empical.cdf(data, x)

    Of course, you're then obliged to implement pdf as well, so it's a little more work - but it's by far the best place for the api

  6. ericmjl commented on May 5, 2017

    @ericmjl
    Author

    This is a great discussion. I was almost tempted to release an ecdf package on PyPI, but that would be overkill and following in the footsteps of JavaScript 😅...

  7. justinbois commented on May 5, 2017

    @justinbois

    We're seeing the power of two Erics!

    @eric-wieser's suggestion fits the API of scipy.stats and is in line with @njsmith's proposal. There is still the problem of generating points for a plot. In the "conventional" plots, getting the vertical part of the steps, is still really tricky. Using @njsmith's suggestion as scipy.stats.empirical would work well for generating the "dot" style plots.

    The problem with using scipy.stats.empirical, though, is that it is a different animal for the pmf/pdf methods (they're not really defined). Also, generating samples out of this as is done with scipy.stats.norm, etc., is also a bit weird to think about. What is that, bootstrapping?

    So, I worry about confusing definitions for putting this thing as scipy.stats.empirical.

  8. njsmith commented on May 5, 2017

    @njsmith
    Member

    What if the returned function also exposed the piecewise constant function's break points? So for plotting you could do something like my_ecdf = ecdf(...); plt.plot(my_ecdf.breakpoints, my_ecdf(my_ecdf.breakpoints))

    The problem with using scipy.stats.empirical, though, is that it is a different animal for the pmf/pdf methods (they're not really defined).

    There are other discrete distributions in scipy.stats, e.g. scipy.stats.binom. I think this would just be another one of those.

    What is that, bootstrapping?

    Yeah, bootstrapping is based on sampling from the empirical distribution; this is actually a very useful way to think about it if you want to analyze bootstrapping algorithms :-).

  9. njsmith commented on May 5, 2017

    @njsmith
    Member

    Hmm, it almost looks like this should work...

    def empirical(xs):
        return scipy.stats.rv_discrete(-np.inf, np.inf, values=(xs, np.full(len(xs), 1 / len(xs)))

    ...but then I noticed that the docs say that currently rv_discrete assumes internally that its support is restricted to the integers, which is not going to work here. Everything about the public interface seems usable, though.

  10. justinbois commented on May 5, 2017

    @justinbois

    For the PMF, for simplicity assuming for the moment that no measured values were repeated and that there were n measured values it is just

    PMF(x) = 1/n if x was measured
    PMF(x) = 0 otherwise

    This makes sense, but for measurements of continuous variables, though, this is not technically correct, since the empirical PDF is the sum of Dirac delta functions, each weighted by 1/n. The empirical CDF, however, is well defined, and can be calculated.

    Terminology matters, and I worry about this wrinkle. One really would not have reason to explicitly use the empirical PMF/PDF, though, right?

    I agree that rv_discrete might be problematic because of the integer restriction. For sampling out of the empirical distribution, we could just do this under the hood:
    np.random.choice(data, size=len(data)).

    It seems like having an interface like the rest of the scipy.stats distributions can be done without too much trouble.

  11. njsmith commented on May 5, 2017

    @njsmith
    Member

    This makes sense, but for measurements of continuous variables, though, this is not technically correct, since the empirical PDF is the sum of Dirac delta functions, each weighted by 1/n.

    What's technically incorrect? The PMF and PDF are different things, and the PMF is perfectly well defined for a distribution with continuous support but whose mass all falls on a countable subset of values.

    I agree that such a PMF is pretty inconvenient for computational purposes though :-)

  12. justinbois commented on May 5, 2017

    @justinbois

    I guess that I'm thinking the following. An empirical distribution is parametrized by the measured points. If the measurements can take continuous values, we could write the empirical distribution function as

    screen shot 2017-05-05 at 3 27 11 pm

    In this representation, it's a continuous distribution with a PDF, and then my worries about delta functions are real. I have seen this in various places and that's how I view empirical distribution functions of continuous variables in my head.

    But then I did some digging and one can also define the empirical distribution function as a discrete distribution, as in Efron and Tibshirani's book on the bootstrap.

    Operationally, they're the same. So, I think treating it as a PMF, especially since a quick search shows the empirical distribution function used that way, is totally fine.

    So, I hereby retract me "incorrect" statement. :-)

  13. eric-wieser commented on May 5, 2017

    @eric-wieser
    Member

    I think I'm partially to blame for the confusion here, by suggesting rv_continuous instead of rv_discrete.

    I think the best way to take this is file an issue against rv_discrete not accepting non-integer values

  14. eric-wieser commented on May 5, 2017

    @eric-wieser
    Member

    The issue seems to stem from rv_discrete integrating by using the equivalent ofrange(self.a, self.b, self.inc) to enumerate, where really it should just iterate over value if it has them.

    See scipy/scipy#3758 and scipy/scipy#6255

  15. njsmith commented on May 5, 2017

    @njsmith
    Member

    @justinbois: I'd prefer to say that a distribution is a measure m on a space O such that m(O) = 1. Or, in less formal terms: a distribution is defined by the probability it assigns to different events. The PDF you wrote defines a distribution, and that distribution has a PMF, whether you want it to or not ;-). In general, PDFs and PMFs are derived quantities; there are distributions that have one, both, or neither, and the measure theory that underlies probability theory doesn't make any distinction between continuous and discrete distributions.

    Anyway, this is just to say that (a) we should be careful to distinguish between PDFs and PMFs, like rv_discrete does (it has a .pmf attribute but not a .pdf attribute), but (b) as long as we do that then there's nothing mathematically untoward in talking about the PMF of an empirical distribution over a continuous space; it's perfectly ordinary and well-defined (if not necessarily super useful).

  16. justinbois commented on May 6, 2017

    @justinbois

    @njsmith: I get the differences between PDFs and PMFs; just trying to be sure we get everything labeled right with this scipy.stats.empirical business. I think we've got it sorted, though, and we know what we need to implement.

    Maybe we move this issue over to SciPy now? I.e., are we agreed that this is something we do want implemented and scipy.stats.empirical is the way to go?

  17. eric-wieser commented on May 6, 2017

    @eric-wieser
    Member

    Recently, scipy gained scipy.stats.rv_sample, which I think is the feature you need - it just needs fixing up to work for non-integers

  18. eric-wieser commented on May 7, 2017

    @eric-wieser
    Member

    I think I'm gonna close this, since numpy has no precedent for computing pdfs and cdfs, yet scipy does. Let's hope this makes it into scipy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions