Skip to content

adding weighted empirical CDF - #8192

Merged
josef-pkt merged 1 commit into
statsmodels:mainfrom
dwr-psandhu:ewcdf
Nov 30, 2022
Merged

josef-pkt merged 1 commit into
statsmodels:mainfrom
dwr-psandhu:ewcdf

Conversation

@dwr-psandhu

Copy link
Copy Markdown
Contributor
Details Adding a new feature for weighted ECDF. It collapses to ECDF if weights are the same.

@pep8speaks

pep8speaks commented Mar 24, 2022 •

Copy link
Copy Markdown

Hello @dwr-psandhu! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

Line 154:96: W291 trailing whitespace
Line 155:80: W291 trailing whitespace
Line 156:91: W291 trailing whitespace

Comment last updated at 2022-04-15 21:39:46 UTC

# which would have raised a NameError if hit, so would need to be
# fixed. See GH#5701.

class EWCDF(StepFunction):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you call it WeightedECDF? This seems easier to discover

@bashtage bashtage left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some small changes.

>>> ewcdf([3, 55, 0.5, 1.5])
array([0.42857143, 1., 0. , 0.28571429])
"""
def __init__(self, x, w, side='right'):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use weights instead of w as keyword

(I guess those are frequency or case weights)

# which would have raised a NameError if hit, so would need to be
# fixed. See GH#5701.

class WeightedECDF(StepFunction):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

qualifier as postfix is better, keeps better alphabetical order
ECDFWeighted

@josef-pkt josef-pkt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.

@josef-pkt

Copy link
Copy Markdown
Member

Also, keep the weighted version as a separate class.

Most likely ECDF will be expanded with methods that only apply for continuous distribution.
ECDFWeighted can go in the direction of supporting discrete distributions.

@josef-pkt

Copy link
Copy Markdown
Member

@dwr-psandhu

Is your application for this mainly discrete distributions?

@dwr-psandhu

Copy link
Copy Markdown
Contributor Author

@dwr-psandhu

Is your application for this mainly discrete distributions?

@josef-pkt Both ECDF and ECDFWeighted are for discrete distributions.

@josef-pkt

josef-pkt commented Mar 24, 2022 •

Copy link
Copy Markdown
Member

ECDF is not for discrete distribution, at least the plan is to expand it
e.g. no ties, i.e. no duplicate values in ECDF
confidence intervals would assume no ties and continuous underlying distribution

For discrete ECDF we could get pointwise confidence interval directly from confint_proportion, AFAIU

I guess the _conf_set function in the module, and KS test based simultaneous confint would only be appropriate for continuous distributions.

For discrete distributions we could add an option to compute the weights from a full data series,
e.g. my discrete regression diagnostics uses np.bincount to compute the empirical frequencies
e.g. plots in this notebook https://gist.github.com/josef-pkt/c932904296270d75366a24ee92a4eb2f

edit _conf_set is a simultaneous confidence band
https://en.wikipedia.org/wiki/Dvoretzky%E2%80%93Kiefer%E2%80%93Wolfowitz_inequality

it's not explicitly mentioned in wikipedia and related
but it looks like Dvoretzky-Kiefer-Wolfowitz inequality also applies to discrete distributions
top of page 4 in https://proceedings.neurips.cc/paper/2015/file/2b3bf3eee2475e03885a110e9acaab61-Paper.pdf

@dwr-psandhu

dwr-psandhu commented Mar 24, 2022 •

Copy link
Copy Markdown
Contributor Author

Ok. So is weighted ecdf only for discrete distributions? I would guess so as each observation is being weighted. In that case, is this solution acceptable?

@dwr-psandhu
dwr-psandhu requested a review from bashtage March 24, 2022 19:39
@josef-pkt

josef-pkt commented Mar 24, 2022 •

Copy link
Copy Markdown
Member

Ok. So is weighted ecdf only for discrete distributions? I would guess so as each observation is being weighted. In that case, is this solution acceptable?

Yes, we will merge what you have (with maybe more changes)

The main thoughts I have is about future development.
For example, if we allow users to optionally provide the full data, then if weights is None, we automatically compute discrete frequencies, and compute the weights internally.

If we go that route, then I would prefer a name like ECDFDiscrete which can be optimized for having much smaller unique values than observations. (It would actually also apply to discrete ordinal data, not just integer or values with a numeric distance)

Also if we follow that interpretation, then we need nobs for confidence intervals.
e.g. in your version, weights need to be case or frequency weights with nobs = weights.sum()
The scale of weights is irrelevant for the distribution, ecdf, itself. but needed if we want to add empirical properties of the sample like confint.

Comment thread statsmodels/distributions/__init__.py Outdated
@@ -1,11 +1,11 @@
from statsmodels.tools._testing import PytestTester
from .empirical_distribution import ECDF, monotone_fn_inverter, StepFunction
from .empirical_distribution import ECDF, ECDFWeighted, monotone_fn_inverter, StepFunction

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pep-8 failure line too long
use parenthesis is move to next line

@josef-pkt

Copy link
Copy Markdown
Member

ok, what I suggest:

rename
weights -> freq_weights to be more explicit, add in docstring that sum(freq_weights) is interpreted as nobs for confint
ECDFDiscrete new classname

option for discrete (or ordered categorical, maybe not needed users can just use numeric codes):
make freq_weights=None, a keyword argument
if freq_weights is None, compute unique values and frequencies, weights, either using numpy or pandas (groupby counts ?)

then independently of this PR we can add plot and confint #8193 methods

@dwr-psandhu

Copy link
Copy Markdown
Contributor Author

ok, what I suggest:

rename weights -> freq_weights to be more explicit, add in docstring that sum(freq_weights) is interpreted as nobs for confint ECDFDiscrete new classname

option for discrete (or ordered categorical, maybe not needed users can just use numeric codes): make freq_weights=None, a keyword argument if freq_weights is None, compute unique values and frequencies, weights, either using numpy or pandas (groupby counts ?)

then independently of this PR we can add plot and confint #8193 methods

@josef-pkt I only half understood so take a deeper look at the frequency counts that I did if weights are None. The answer is now subtly different between the current ECDF and ECDFDiscrete. See my log below

In [2]: from statsmodels.distributions.empirical_distribution import ECDFDiscrete

In [4]: ewcdf = ECDFDiscrete([3, 3, 1, 4])

In [5]: ewcdf([3, 55, 0.5, 1.5])
Out[5]: array([0.75, 1.  , 0.  , 0.25])

In [6]: from statsmodels.distributions.empirical_distribution import ECDF

In [7]: ecdf =  ECDF([3,3,1,4])

In [8]: ecdf([3,55,0.5,1.5])
Out[8]: array([0.75, 1.  , 0.  , 0.25])

In [9]: ecdf.x
Out[9]: array([-inf,   1.,   3.,   3.,   4.])

In [10]: ecdf.y
Out[10]: array([0.  , 0.25, 0.5 , 0.75, 1.  ])

In [11]: ewcdf.x
Out[11]: array([-inf,   1.,   3.,   4.])

In [12]: ewcdf.y
Out[12]: array([0.  , 0.25, 0.75, 1.  ])

@josef-pkt

Copy link
Copy Markdown
Member

I check the code tomorrow

the new result in your last comment looks correct, that's the difference between handling ties or not

ecdf treats the two 3 as different values, while the discrete version recognizes them as being the same.

In [9]: ecdf.x
Out[9]: array([-inf,   1.,   3.,   3.,   4.])

In [10]: ecdf.y
Out[10]: array([0.  , 0.25, 0.5 , 0.75, 1.  ])

array([0.42857143, 1., 0. , 0.28571429])
"""
def __init__(self, x, freq_weights=None, side='right'):
x = np.array(x)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

always use np.asarray instead of np.array
avoids copy if item is already an array

if freq_weights is None:
x, freq_weights = np.unique(x, return_counts=True)
assert len(freq_weights) == len(x)
w = np.array(freq_weights)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asarray conversion is only needed in an else of if freq_weights is None

ax = x.argsort()
x = x[ax]
y = np.cumsum(w[ax])
y=y/sw

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pep-8 spaces around operators y = y / sw

@josef-pkt

Copy link
Copy Markdown
Member

you can use your previous example for a unit test in "statsmodels\distributions\tests\test_ecdf.py"

also we should use an unequal spaced, noninteger testcase, something like

ewcdf = ECDFDiscrete([3.5, 3.5, 1.5, 1, 4])
which should be the same as
ewcdf = ECDFDiscrete([3.5, 1.5, 1, 4], freq_weights=[2, 1, 1, 1])

I guess that is supported without having to make changes to the code.

Do you know how to use git rebase to squash commits?
we should squash commits before merge.

@dwr-psandhu

Copy link
Copy Markdown
Contributor Author

you can use your previous example for a unit test in "statsmodels\distributions\tests\test_ecdf.py"

also we should use an unequal spaced, noninteger testcase, something like

ewcdf = ECDFDiscrete([3.5, 3.5, 1.5, 1, 4]) which should be the same as ewcdf = ECDFDiscrete([3.5, 1.5, 1, 4], freq_weights=[2, 1, 1, 1])

I guess that is supported without having to make changes to the code.

Do you know how to use git rebase to squash commits? we should squash commits before merge.

I am adding a test.
I will squash all commits into one before final merge
currently i have a test that is failing
i.e. ECDFDiscrete([3, 3, 1, 4)) is not giving the same results as ECDFDiscrete([3, 3, 1, 4], [1, 1, 1, 1]).
I will commit so you can take a look

@josef-pkt

Copy link
Copy Markdown
Member

i.e. ECDFDiscrete([3, 3, 1, 4)) is not giving the same results as ECDFDiscrete([3, 3, 1, 4], [1, 1, 1, 1]).

currently that's by design, I don't know if we should change it or if changing it is necessary

The current assumption is that, if the user provides freq_weights, then the user already provides the counts for unique values of x.
So we only combine x values, if weights is None.

@josef-pkt

Copy link
Copy Markdown
Member

Would it be useful for you handle ties even if freq_weights is specified?

for example
should we make this
ECDFDiscrete([3, 3, 1, 4], [1, 2, 1, 3])
produce the same ecdf as this
ECDFDiscrete([3, 1, 4], [3, 1, 3])

@josef-pkt josef-pkt left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I might have forgotten to submit some review comments

No I didn't
I'm often getting confused about single review comment versus starting a review that collects comments

@dwr-psandhu

Copy link
Copy Markdown
Contributor Author

Would it be useful for you handle ties even if freq_weights is specified?

for example should we make this ECDFDiscrete([3, 3, 1, 4], [1, 2, 1, 3]) produce the same ecdf as this ECDFDiscrete([3, 1, 4], [3, 1, 3])

Yes. that makes sense. I'll drop that assertion and put this one instead.
However, we should add that in the docs section to avoid surprises

@dwr-psandhu

Copy link
Copy Markdown
Contributor Author

I might have forgotten to submit some review comments

No I didn't I'm often getting confused about single review comment versus starting a review that collects comments

@josef-pkt I did a commit with a passing test based on your comment. If it all looks good, I can rebase, squashing all commits into one. Feel free to give me a good log message.

@josef-pkt josef-pkt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pep-8 and docstring changes

code itself looks good

Comment thread statsmodels/distributions/__init__.py Outdated
@@ -1,11 +1,12 @@
from statsmodels.tools._testing import PytestTester
from .empirical_distribution import ECDF, monotone_fn_inverter, StepFunction
from .empirical_distribution import (ECDF, ECDFDiscrete,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pep-8 flake failure, start list in next line,

from .empirical_distribution import (
    ECDF, ECDFDiscrete, monotone_fn_inverter, StepFunction
    )

Comment thread statsmodels/distributions/__init__.py Outdated
)

__all__ = ['test', 'ECDF', 'monotone_fn_inverter', 'StepFunction',
__all__ = ['test', 'ECDF', 'ECDFDiscrete', 'monotone_fn_inverter', 'StepFunction',

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

line too long

We will convert this to having one item per line, sorted alphabetically.
You can either do this here, or just change the line break and it will be changed as part of a future PR

x : array_like
Observations
freq_weights : array_like
Weights of the observations. sum(freq_weights) is interpreted as nobs for confint

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add:
If freq_weights is None, then the frequency counts for unique values will be computed from the data x.

Parameters
----------
x : array_like
Observations

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change to:

Data values. If freq_weights is None, then x is treated as observations and the ecdf is computed from the frequency counts of unique values using nunpy.unique. If freq_weights is not None, then x will be taken as the support of the mass point distribution with freq_weights as counts for x values.
The x values can be arbitrary sortable values and need not be integers.

e1 = ECDFDiscrete([3.5, 3.5, 1.5, 1, 4])
e2 = ECDFDiscrete([3.5, 1.5, 1, 4], freq_weights=[2, 1, 1, 1])
npt.assert_array_equal(e1.x, e2.x)
npt.assert_array_equal(e1.y, e2.y) No newline at end of file

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

modules need newline at end of file

npt.assert_array_equal(e.x, [-np.inf, 1, 3, 4])
npt.assert_array_equal(e.y, [0, 0.25, 0.75, 1])
e1 = ECDFDiscrete([3.5, 3.5, 1.5, 1, 4])
e2 = ECDFDiscrete([3.5, 1.5, 1, 4], freq_weights=[2, 1, 1, 1])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe add this example to docstring, mentioning that these are the two equivalent ways of defining the ecdf

>>> import numpy as np
>>> from statsmodels.distributions.empirical_distribution import ECDFDiscrete
>>>
>>> ewcdf = ECDFDiscrete([3, 3, 1, 4], [1, 1, 1, 1]) # For equal weights ewcdf result is same as ecdf (see above)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use example that illustrate proper use, not cases that leave duplicate x values e.g.
ewcdf = ECDFDiscrete([3, 3, 1, 4])

and example below
ewcdf = ECDFDiscrete([3, 1, 4], [1.25, 2.5, 5])

@dwr-psandhu

Copy link
Copy Markdown
Contributor Author

@josef-pkt Fixed for all your requested changes.

@dwr-psandhu

Copy link
Copy Markdown
Contributor Author

@josef-pkt @bashtage If ok, I can resubmit with commits squashed.

@josef-pkt

Copy link
Copy Markdown
Member

looks good to me

squash and I will merge it

sorry for the delay, I got lost in a poisson PR that kept growing and getting messy

@josef-pkt

Copy link
Copy Markdown
Member

this has been squashed to one commit.
Sorry, I didn't see that before.

merging
Thanks for the PR and discussion

@josef-pkt
josef-pkt merged commit 2d41628 into statsmodels:main Nov 30, 2022
@josef-pkt josef-pkt mentioned this pull request Nov 30, 2022
16 of 20 tasks
@josef-pkt josef-pkt added this to the 0.14 milestone Nov 30, 2022
@josef-pkt

Copy link
Copy Markdown
Member

trailing whitespace in statsmodels/distributions/empirical_distribution.py
I will fix it in another PR

@dwr-psandhu
dwr-psandhu deleted the ewcdf branch November 30, 2022 20:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ENH: Weighted ECDF

4 participants