You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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:
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
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?
defecdf(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 """ifconventional:
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 """returnnp.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 tailsifmin_xisNone:
min_x=-np.infifmax_xisNone:
max_x=np.inf# Get x and y values for data pointsx, y=_ecdf_dots(data)
# Set up output arraysx_conv=np.empty(2*(len(x) +1))
y_conv=np.empty(2*(len(x) +1))
# y-values for stepsy_conv[:2] =0y_conv[2::2] =yy_conv[3::2] =y# x- values for stepsx_conv[0] =max(min_x, x[0] - (x[-1] -x[0])*buff)
x_conv[1] =x[0]
x_conv[2::2] =xx_conv[3:-1:2] =x[1:]
x_conv[-1] =min(max_x, x[-1] + (x[-1] -x[0])*buff)
returnx_conv, y_conv
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?
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:
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 😅...
@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.
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 :-).
...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.
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.
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 :-)
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
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. :-)
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.
@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).
@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?
Activity
njsmith commentedon May 5, 2017
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
njsmith commentedon May 5, 2017
Hah, no, now I messed it up... It should be a step function, and
interpdoes linear interpolation instead.This is closer, though still untested...
justinbois commentedon May 5, 2017
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?
ericmjl commentedon May 5, 2017
Or maybe it should go into
scipy.stats? Seems to me ECDF for plotting most naturally fits intoseaborn(statistical plots), but perhaps ECDF function might be best served in scipy or numpy?eric-wieser commentedon May 5, 2017
Seems like you want a
scipy.stats.empirical, which matches the api of the existingscipy.stats.normand the like - namely, derived fromscipy.stats.rv_discrete:Of course, you're then obliged to implement
pdfas well, so it's a little more work - but it's by far the best place for the apiericmjl commentedon May 5, 2017
This is a great discussion. I was almost tempted to release an
ecdfpackage on PyPI, but that would be overkill and following in the footsteps of JavaScript 😅...justinbois commentedon May 5, 2017
We're seeing the power of two Erics!
@eric-wieser's suggestion fits the API of
scipy.statsand 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 asscipy.stats.empiricalwould work well for generating the "dot" style plots.The problem with using
scipy.stats.empirical, though, is that it is a different animal for thepmf/pdfmethods (they're not really defined). Also, generating samples out of this as is done withscipy.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.njsmith commentedon May 5, 2017
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))There are other discrete distributions in
scipy.stats, e.g.scipy.stats.binom. I think this would just be another one of those.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 :-).
njsmith commentedon May 5, 2017
Hmm, it almost looks like this should work...
...but then I noticed that the docs say that currently
rv_discreteassumes internally that its support is restricted to the integers, which is not going to work here. Everything about the public interface seems usable, though.justinbois commentedon May 5, 2017
For the PMF, for simplicity assuming for the moment that no measured values were repeated and that there were
nmeasured values it is justPMF(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_discretemight 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.statsdistributions can be done without too much trouble.njsmith commentedon May 5, 2017
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 :-)
justinbois commentedon May 5, 2017
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
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. :-)
eric-wieser commentedon May 5, 2017
I think I'm partially to blame for the confusion here, by suggesting
rv_continuousinstead ofrv_discrete.I think the best way to take this is file an issue against
rv_discretenot accepting non-integer valueseric-wieser commentedon May 5, 2017
The issue seems to stem from
rv_discreteintegrating 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
njsmith commentedon May 5, 2017
@justinbois: I'd prefer to say that a distribution is a measure
mon a spaceOsuch thatm(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_discretedoes (it has a.pmfattribute but not a.pdfattribute), 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).justinbois commentedon May 6, 2017
@njsmith: I get the differences between PDFs and PMFs; just trying to be sure we get everything labeled right with this
scipy.stats.empiricalbusiness. 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.empiricalis the way to go?eric-wieser commentedon May 6, 2017
Recently, scipy gained
scipy.stats.rv_sample, which I think is the feature you need - it just needs fixing up to work for non-integerseric-wieser commentedon May 7, 2017
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!