Skip to content

ENH: Weighted quantile - #9211

Closed
chunweiyuan wants to merge 4 commits into
numpy:mainfrom
chunweiyuan:weighted_quantile
Closed

chunweiyuan wants to merge 4 commits into
numpy:mainfrom
chunweiyuan:weighted_quantile

Conversation

@chunweiyuan

@chunweiyuan chunweiyuan commented Jun 2, 2017 •

Copy link
Copy Markdown

Creates quantile() function that allows weights input.

Fixes #6326, #8935


The following are plotted the same way as the graphs at the bottom of the np.percentile docs, but with an added weights argument:

weights=[1, 2, 3, 4]:
weights_1_2_3_4

weights = [2, 1, 1, 2]:
weights_2_1_1_2

@eric-wieser

This comment has been minimized.

Comment thread numpy/lib/function_base.py Resolved
Comment thread numpy/lib/function_base.py Resolved
Comment thread numpy/lib/function_base.py Resolved
Comment thread numpy/lib/function_base.py Outdated

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.

Why not ap.shape[:-1]?

Comment thread numpy/lib/function_base.py Outdated

@eric-wieser eric-wieser Jun 3, 2017 •

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.

Isn't this a superset of arraysort above? Just use this for both?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

That might work, but I think having separate names (and signature) provides more clarity on what these two routines are trying to accomplish. I think It certainly helps understanding/debugging the code. Unless there's a real performance impact I prefer to keep it the way it is, though I'd defer to your judgment.

Comment thread numpy/lib/function_base.py Outdated

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 think this should be relaxed to "Either 1D, or such that weights.ndim == a.ndim and that weights and a are broadcastable"

Comment thread numpy/lib/function_base.py Resolved
@chunweiyuan

This comment has been minimized.

Comment thread numpy/lib/function_base.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

without weights it should not be slower than the old percentile, so partition should be used and the vectorization of the index sort avoided.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Just fixed it in the latest push.

@juliantaylor

Copy link
Copy Markdown
Contributor

this does seem almost out of scope for numpy and more something for a statistics package, has this been previously discussed?

@bashtage

bashtage commented Jun 3, 2017

Copy link
Copy Markdown
Contributor

The explanation of weights can be substantially simplified if you make the connection between the normalized weights and repeating the data in the sample in the integer case.

For example, if you have [1,2,3] with weight [1,2,3] this will be have identically to the case where there are no weighs and the data are [1,2,2,3,3,3]. In Stata, for example, this type if weighting is known as fweighting (for frequency). There are other interpretations of weights that may result in a different estimator.

@chunweiyuan

Copy link
Copy Markdown
Author

I think this PR belongs in numpy:
1.) it's nothing more than an extension of percentile, and
2.) I've gone through great pain to make sure the underlying interpolation scheme, when weights is not None, is consistent with the old percentile. In the new tests there are cases where all weights are identical, and quantile renders the same result as the old percentile. There's another case where weights=[0, 1, 2], and quantile gives the same result as using the percentile on a simple repetition of the original data.

I've tried to address the comments above in the latest push. The explanation of how I compute the weighted quantile is still a bit cryptic, but I can't find a better way at the moment.

@chunweiyuan chunweiyuan changed the title Weighted quantile ENH: Weighted quantile Jun 11, 2017
@chunweiyuan

Copy link
Copy Markdown
Author

Anything I could do to help expedite this? It seems that the merge conflict in #9213 is rather small, and I could help bridge it with this PR as well.

@eric-wieser

Copy link
Copy Markdown
Member

@chunweiyuan: Thanks for pointing out the merge conflict, I can go fix that.

There was a lack of decision in the comments of #9213 whether quantile should be in the API, if we already have percentile. Perhaps asking the mailing list for opinions would resolve that.

@chunweiyuan

Copy link
Copy Markdown
Author

Doesn't seem like there's much response to my email related to the API, so I think the way forward is to keep both quantile and percentile. There was, however, one suggestion related to using an O(n) partition algorithm instead of O(n log n) (argsort) in the code. I'm not sure how that would be addressed since I need ind_sorted in my code to sort the weights array.

Comment thread numpy/lib/function_base.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This should be quantile, not percentile

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks. Fixed. This baby is now just waiting for #9213........

@madphysicist madphysicist left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This probably needs an entry somewhere in the release notes.

Comment thread numpy/lib/tests/test_function_base.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks like a q instaead of a g. If I am wrong, ignore.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You're right.

Comment thread numpy/lib/tests/test_function_base.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

How about integer weights?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I think line 3233 there tests integer weights.

Comment thread numpy/lib/function_base.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove the parens.

Comment thread numpy/lib/function_base.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This should be removed or modified. There does not need to be any implementation information in the docs. Instead, you could say something like "Calling percentile is identical to calling quantile with weights set to None and the percentiles divided by 100."

Comment thread numpy/lib/function_base.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You could save on a call to asarray by doing q=true_divide(q, 100)

@madphysicist

Copy link
Copy Markdown
Contributor

@chunweiyuan For future reference, it is probably better to rebase your branch onto master rather than merging master into your branch. The history will look much cleaner and you won't have to deal with a stray merge commit later down the line.

@chunweiyuan

Copy link
Copy Markdown
Author

Sounds good. Old habits die hard. Now this branch is just waiting on #9213, I believe.

@eric-wieser

Copy link
Copy Markdown
Member

Looks like you did something screwy with a merge/rebase there. I've seen that behaviour before, but don't remember the cause.

@eric-wieser
eric-wieser changed the base branch from master to maintenance/1.13.x August 11, 2017 18:53
@eric-wieser
eric-wieser changed the base branch from maintenance/1.13.x to master August 11, 2017 18:54
@eric-wieser

Copy link
Copy Markdown
Member

Ok, looks like actually github was being screwy - changing the base twice has removed the commits from #9475 from this PR, which was what was weird in the first place.

@lpsinger

Copy link
Copy Markdown
Contributor

I think @eric-wieser did most of the original review here.

Well this PR has been around for ~5 years, so we likely need a fresh review from all stakeholders. To name a few: @eric-wieser @juliantaylor @madphysicist @lpsinger @seberg @charris @pv @bashtage @bzah @Erotemic @shoyer @tylerjereddy please chime in if you still find this PR relevant. Thanks.

I most certainly do find this PR still relevant! I have been vendoring @chunweiyuan's code in my own project for years now. I would love to see this in Numpy at long last!

@abel-bzz abel-bzz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I finally had time to have a look at this and add my two cents.
Overall I'm happy with these changes, the only thing which bother me is how weights are defined.
As far as I understand this implementation, it only handles frequency weights. I think it's fine but, IMHO this should be explicit in the documentation.

Especially knowing that other libraries in the scientific python ecosystem implement other kind of frequency (e.g. probability frequency in xarray).

Comment thread numpy/lib/function_base.py Outdated
if np.issubdtype(arr.dtype, np.inexact):
# After the sort, slices having NaNs will have for last element a NaN
virtual_indexes_nans = np.isnan(virtual_indexes)
virtual_indexes_nans = np.isnan(virtual_indexes) # indexes have nans?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

# indexes have nans?
No, indexes cannot have NaNs. These lines are some code I forgot to remove after refactoring the initial implementation of interpolation methods.
I was putting NaN in the index array as flags for cases where the virtual index could not be computed. (e.g [NaN, 12, NaN]).
But it was a specialized nanpercentile implementation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

So you can delete from
if np.issubdtype(arr.dtype,np.inexact):
up to
next_indexes[virtual_indexes_nans] = -1.
(I can't wrap my head around how to suggest an edit to remove multiple lines directly with gh...)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks for letting me know.

# weights are a proxy to values count
wgts1d_cumsum = wgts1d.cumsum()
n = wgts1d_cumsum[-1] # sum along axis replaces n in Hyndman.
weight_space_indexes = method["get_virtual_index"](n, quantiles)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I suppose that's why those fix_gamma functions are just defined as fix_gamma=lambda gamma, _: gamma placeholders, because they're not expected to be used.

Indeed that was my reasoning for putting identity function in fix_gamma. I guess the logic should change if weights turns the virtual_indexes into floats.

"""
gamma = np.asanyarray(virtual_indexes - previous_indexes)
gamma = method["fix_gamma"](gamma, virtual_indexes)
# % 1 because index diff can be > 1 in weight space calculation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In the doc_string above: Compute gamma (a.k.a 'm' or 'weight') for the linear interpolation.
The "weight" alias mentioned here should probably be removed to avoid confusion if the weights added with this PR.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks. I removed it.

@chunweiyuan

Copy link
Copy Markdown
Author

A conceptual note: in weighted quantile, I’m not sure it makes any sense to have a weight < 1. To me,

  • a weight of 1 implies a point along an axis.
  • a weight >1 is a line along the axis.
  • a weight of 0 is the absence of the point.

In my opinion, it's not clear what a fraction of a point is. Therefore I think all weights should be >=1 (or 0), and if any should be <1, I rescale all weights such that the minimum is 1.

With that out of the way, I want to address the concern of @bzah (and perhaps many others) about the current implementation only supporting one type of weights while excluding others. That concern was a bit confusing to me, so I dug up three definitions of weights that have been thrown around, thanks to the references within the not-yet-released xarray doc of weighted quantile.

The three types of weights listed are:

  1. Analytic weights, or precision weights. These are equivalent to the precision matrix in weighted least squares. In this context, the weights can be less than 1. I do not know how this type of weights pertains to weighted quantiles, but at least in the weighted least squares equation it does not matter if you rescale the entire precision matrix by a constant.
  2. Frequency weights. This requires no explanation.
  3. Probability weights. I think these are really inverse probability weights, the same inverse probability when people talk about IP-weighting in causal inference. That means, if your sampling probabilities are [0.2, 0.8], then the actual weights are 1/[0.2, 0.8] = [5, 1.25]. Since all these weights should be >= 1, I see no issue with my current implementation.

In summary, I still think this current implementation of weighted quantile is general enough to cover the bases, and the onus should be on the user to understand the nuances of their own use case. If you're doing IP-weighting, then please take the inverse of your probabilities (and set those 1/0's to 0) first, set those to your weights, before you call the quantile function. I hope this clarifies some of the misunderstandings in this thread.

As an aside, my original intent was to submit this PR to xarray, since that's the library I use most commonly at work, but was persuaded to submit it to numpy instead. It's a little ironic that xarray has its own implementation now. But since it's not yet officially released, I have not really checked the two implementations against each other.

@chunweiyuan

Copy link
Copy Markdown
Author

@mattip @tylerjereddy @eric-wieser @seberg @charris

Any suggestions on what the next steps are? It would be nice to lay out a roadmap for this PR.

If the opinion is for an eventual merge that requires a some glaring holes to be addressed, then please feel free to itemize them here.

If the opinion is to reject, then it's fine too. Overall it's probably not in everyone's best interest to keep this PR in limbo like this.

@lpsinger

lpsinger commented Jul 11, 2022 •

Copy link
Copy Markdown
Contributor

@mattip @tylerjereddy @eric-wieser @seberg @charris

Any suggestions on what the next steps are? It would be nice to lay out a roadmap for this PR.

If the opinion is for an eventual merge that requires a some glaring holes to be addressed, then please feel free to itemize them here.

If the opinion is to reject, then it's fine too. Overall it's probably not in everyone's best interest to keep this PR in limbo like this.

I would really like to see this PR merged. In my application I have been vendoring @chunweiyuan's code for years now.


* 0, as long as they do not sum to 0
* less than 1. In this case, all weights are re-normalized by
the lowest non-zero weight prior to computation.

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 still think this is wrong and this is a serious problem for me to push it over the finish line. @lpsinger if you wish to help, maybe you can help clear this up. If this is wrong, then there needs to be a test that it is fixed as well.

Otherwise, we should look into removing vectorize, but I am happy with helping out there and looking into it.

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.

@tupui do not feel compelled, but it would be indeed be cool to push this through and getting a bit of scipy stats eyes on it to polish things up will help me push the button :).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks I will have a look!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't understand why we should have something special for weights bellow 1. The formula would work with any positive number (as far as I could see in the literature, weights are only defined as non zero positive numbers and in the end the normalization is done with the sum of weights). It would also not be consistent with np.average.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@tupui I think some form of "weights" is mentioned in every single chapter of a stats textbook, but they're not all commutable. If I start from a non-weighted (all weights = 1) case, and picture how quantiles are defined, I actually have a hard time imagining what it means to have a weight that is (0, 1). In the Hyndman paper, a weight of 1 is a point along an axis. Then what does a weight of say, 0.1 mean? Happy to learn. Thanks.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I have not been following all of the subtleties here, but it would be nice to have the same constraints on weights as numpy.average:

The only constraint on weights is that sum(weights) must not be 0.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Please disregard my comment above; I see that the existing constraints on the weights are indeed compatible with numpy.average.

@lorentzenchr lorentzenchr Oct 29, 2022 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I have the same reservations as @seberg about different handling of weights depending on their size. I think, a clear definition of a quantile is missing in this discussion based in which tests can be implemented (which are currently missing).

As we have similar discussions for expectiles in scipy, see scipy/scipy#17039 (comment), I'd like to propose one (copied from there), inspired by https://doi.org/10.48550/arXiv.0912.0902:

Statistically speaking, a quantile (at level alpha) is a property $Q$ of a distribution function $F$, e.g. $Q(F)$ (given some level alpha). Note that a quantile $Q(F)$ can be set valued. The empirical version arises by plugging in the empirical distribution $\hat{F}$ of a given sample $x$.
In my point of view, sample weights/case weights are defined on this distribution in a relative sense; for integer valued weights, it can be interpreted as repeated observation.
The weighted empirical CDF is $\hat{F}(t) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{x_i &lt;= t}$.

Implied assumptions and properties:

  1. Weights $w_i$ are non-negative real numbers.
  2. A weight of 2 is equivalent to duplicating this observation.
  3. $\hat{F}$ as well as $Q(\hat{F})$ are invariant under scalar rescaling: $w \rightarrow c*w$ for $c &gt; 0$
  4. The expected value (population level) reads as weighted average on a sample level in the defining equations:
  • Minimisation with strict consistent scoring function $S$ for $Q$: $Q(F) = \operatorname{argmin}_z E_F(S(z, X))$ for all $X\sim F$
    Sample level: $Q(\hat{F}) = \operatorname{argmin}_z \frac{1}{\sum_i w_i} \sum_i w_i S(z, x_i)$
  • First order condition / strict identification function $V$ for $Q$: $Q(F)$ is solution of $E_F(V(z, X)) = 0$ for all $X\sim F$
    Sample level: $Q(\hat{F})$ is solution of $\frac{1}{\sum_i w_i} \sum_i w_i V(z, x_i) = 0$

Notes:

  • For quantiles, the solutions are not unique. That's the reason for having all those options for method in numpy.quantile.
  • For quantiles, the most used scoring function is the pinball loss $S(z, x) = (1_{z\geq x} - \alpha) (z - x)$
  • For quantiles, the canonical identification function is $V(z, x) = 1_{z\geq x} - \alpha$.

I would expect some tests that $E[S]$ is minimized or that $E[V] = 0$, with $E$ replaced by the sample average.

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.

@lorentzenchr can you summarize that into what you think is actionable from NumPy?

The definition in the PR uses a definition where weights are frequency weights not "aweights" or whatever you call it: The quantile has a constant value around that data point if weight > 1. I am not convinced that this is a generally accepted good default. This definition does also indeed feel weird a bit weird weights < 1.

To be honest, unless this clears up, I am tempted to close the PR. If the weights in the PR are not the right way to go, I would also suggest opening a new PR with adjusted code (and closing this one right away). The reason is that this PR is getting much too unwieldy anyway with hundreds of comments.

Basically, unless someone we can easily clarify what the correct implementation is, it may be that this is just too advanced statistics to include it in NumPy.
(I don't mind adding weights, but we neither get the best speed here, nor even clearly formulated what the right thing is!)

@chunweiyuan

Copy link
Copy Markdown
Author

Hi @seberg and @tupui,

Thanks for the reviews. Much appreciated. From what I can tell, these are the two issues to be addressed:

1.) The renormalization when when weights < 1. It seems that this is a rather contentious point, and I'm fine with requiring all weights to be >= 1, and raising a flag otherwise, as @seberg suggested on March 10.. If there's no objection, that change can come in my next push.

2.) The use of vectorize(). This I'd gladly defer to those who are more familiar with the inner workings of numpy.

Thank you all for your inputs.

@chunweiyuan

Copy link
Copy Markdown
Author

Hi @seberg and @tupui,

I've taken care of (1) from above. Please let me know on follow-up steps.

Also if anyone has suggestions on additional test cases to implement, please let me know as well.

Comment thread numpy/lib/function_base.py Outdated
def percentile(a,
q,
axis=None,
weights=None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This needs to go after * to not break backward compatibility.

Comment thread numpy/lib/function_base.py Outdated
def quantile(a,
q,
axis=None,
weights=None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same as above.

Comment thread numpy/lib/nanfunctions.py Outdated
a,
q,
axis=None,
weights=None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same.

@chunweiyuan

Copy link
Copy Markdown
Author

Hi @seberg, @tupui, and @InessaPawson,

Last time we discussed on this thread, we mentioned replacing the usage of np.vectorize() as one last major roadblock for this PR. Any update on where that stands?

@seberg

seberg commented Oct 26, 2022

Copy link
Copy Markdown
Member

Fully removing the vectorize seems pretty much impossible after looking into it. I would much prefer simplifying things a bit, though. I think get_virtual_index should be split into two functions:

  • The current get_virtual_index
  • A second discretize_index only for the discrete methods (which has the floor/ceil/round and astype(intp) logic.

That is needed, because the current code is missing the discretization, because for weights you need:

  1. get_virtual_index
  2. Transform virtual index from weighted to unweighted data space
  3. Discretize virtual index (if necessary).

Right now, we don't get "discrete" logic I believe (i.e. the tests are missing assert res_weighted.dtype == res_unweighted.dtype?

If split up and the non-1d case would be solved by recursing, the weighted and unweighted code-path could probably share more code.

About vectorize: Getting rid of it may be possible (gh-16862 does it somewhat?) but should indeed not be an important goal.


Was there ever a clear decision or "prior art" reference on the choice of frequency weights? I understand now clearer where the weights >= 1 constraint comes from (not sure how strictly necessary it is, but >=1 is special for frequency weights).

But... that confuses me, probably because I had looked at gh-16862 more, and thought that aweights was the way to go.


There are more smaller things, style cleanups, etc. but we need to decide on which weights (aweights?). Then simplify the logic a bit (IMO) and then do the further cleanups.

@lorentzenchr

lorentzenchr commented Nov 24, 2022 •

Copy link
Copy Markdown
Contributor

From thread #9211 (comment).

I agree with @seberg that closing this PR and opening dedicated well specified issues, each addressing a smaller subproblem, might be the best way forward. Having said this, I want to highly appreciate the effort of @chunweiyuan in the pursuit of getting weighted quantiles into numpy! As numpy already offers quantiles and weighted mean (average), I would love to see it in numpy one day.

I would break down this effort roughly into the following issues:

  1. Add common functional tests for quantiles (like adding a constant to all values should equal quantile plus same constant, and so on). Those tests would easily extend when weights are added.
  2. Clearify precise mathematical/statistical meaning/definition of weights in empirical quantiles. One possibility is given in ENH: Weighted quantile #9211 (comment). In this issue, the wider community might be addressed to help out.
  3. Add weights for quantiles of 1d arrays, maybe only a subset of methods. Keep it private for the time being.
  4. Add broadcasting etc and release.

@chunweiyuan

chunweiyuan commented Jan 29, 2023 •

Copy link
Copy Markdown
Author

Pardon me for the late reply. It seems that there are many concerns about this PR, both on the theoretical side and on the implementation side. Please allow me to address the theory first.

I imagine computing weighted quantile on numpy to abide by the following first principles:

A.) It is an extension of the the current methods defined in Hyndman & Fan. In their paper, a value (with weight=1) is treated as a point along an axis, and the index distance between neighboring values is 1. Naturally, in the limit of all weights=1, the weighted quantile method should reproduce the unweighted quantile method already defined in numpy.

B.) weight=0 means the removal of the corresponding value. That means x = [1, 2, 3, 4, 5], w = [1, 0, 1, 1, 1], q = 0.1 is identical to x = [1, 3, 4, 5], q = 0.1.

C.) Integer weights behave identical to integer repetition of corresponding values (frequency expansion). In other words, weights=[2, 2, 2] is not the same as weights=[1, 1, 1].

With the above axioms in mind, my approach to weighted quantile is

  1. Take the existing indexing methods, and replace n with the sum of weights. This is in accordance with A, B, and C.

  2. Require the minimum weight to be 1. This is required by A. Therefore I renormalize all weights to require minimum weight to be 1. (Or at least I used to, until I encountered some serious objections here. Now I just require all non-zero weights to be >= 1).

This PR then boils down to implementing code to map indexes to and fro between normal (unweighted) space and weight space, while leveraging as much of the existing algorithms as possible.

Incidentally, there’s another approach to weighted quantile proposed by Akinshin here (others have mentioned it). Example 12 within the post obeys A, but in fact violates B and C. However, if you change his n to be the sum of w’s, then his approach becomes the same as mine. They would both satisfy ABC, while imposing the same constraint on minimum weight. His (modified) approach would yield the same results as this PR. It’s just that Akinshin takes a small detour to normalize the cumulative weights to identify the bounds between values in a cumulative probability function (perhaps more palatable to some), whereas I map directly to weight space. I encourage those interested in this topic to take a look.

Of course, there might be other approaches out there to compute weighted quantile. I merely define one that conforms to the ABC constraints defined here.

@chunweiyuan

chunweiyuan commented Jan 29, 2023 •

Copy link
Copy Markdown
Author

Now, I’d like to resolve some concerns regarding the common definitions of weights, and whether any of them conflicts with requiring all weights >= 1.

From this link, I can identify three definitions of weights:

  1. Frequency weights. This is either 0 or >=1. No problem here.
  2. Survey weights. Also called probability weights, or more correctly, inverse probability weights. This is always >= 1.
  3. Analytical weights. From what I can tell, this is only used to compute, say, weighted covariance (as in np.cov()). An example expression is here. In this case, it matters not if you multiply all weights by a constant, because that constant would show up in both the numerator and denominator. Hence the renormalization of weights to all be >=1 does NOT conflict with how analytical weights are used, from what I can tell. It’s the relative magnitude of the weights that matters here. You can try running np.cov with different multiples of the same aweights. I get the same answers. Also np.cov frankly just multiplies fweights and aweights into one w object before inserting it into the formula, so this intentional distinction is a bit unnecessary.

@chunweiyuan

chunweiyuan commented Jan 29, 2023 •

Copy link
Copy Markdown
Author

In summary, I think

  1. The theory of this PR is sound in accordance with the ABC constraints. An added validation is that Akinshin (with n = sum(weights)) arrives at the same thing.
  2. The different definitions of weights out there is a non-issue.

As for implementation details, stylistic changes, refactoring/testing and so forth, I think we can dive into those if we reach a consensus on the theoretical side.

@lorentzenchr

Copy link
Copy Markdown
Contributor

I agree with most points except:

Require the minimum weight to be 1. This is required by A. Therefore I renormalize all weights to require minimum weight to be 1.

I think all the different weight definitions apply to estimation of variances. But for (empirical) quantiles, I guess, there is no real difference, as for the (empirical) mean.

Example: Consider the median for 2 points, 1 and 3.

-x---x--> 
 1   3

The solution is any point in the half-open interval [1, 3). The different methods then say which single value exactly. It does not matter how many times we repeat these 2 observations, the answer stays the same. Therefore, as long as both observations, 1 and 3, have the same positive weight, the weight value does not matter and the result is always the interval [1, 3).

As mentioned in the issue #8935, I would also propose to start with non-controversial methods, to which @seberg seems to agree.

@chunweiyuan

Copy link
Copy Markdown
Author

I can’t say I agree with you. To me, x=[1, 3], w=[1, 1], q=0.1 is not the same as x=[1, 3], w=[2, 2], q=0.1. The former is np.quantile([1, 3], q=0.1) = 1.2, while the latter is equivalent to np.quantile([1, 1, 3, 3], q=0.1) = 1. Scaling your weights by a constant may not change the median, but it sure will change elsewhere. This is described by C outlined previously.

Some might ask why there’s a weight >= 1.0 requirement. The short answer is that the methods outlined in Hyndman & Fan are fundamentally indexing schemes, and the index pointing to the answer is tied to n, the total number of values. Because n = sum of weights for weighted quantiles (in my approach), the minimum weight needs to be 1, otherwise we get negative indexes. This is the basis behind A.

To me, any approach to computing weighted quantile on numpy must abide by the ABC constraints. A ensures backward compatibility, while B and C are definitional. I merely propose an approach to here that satisfies the ABC constraints, for all 13 existing methods. I’ve also written test cases to cover all of them, and would gladly take suggestions on additional tests.

Lastly, I think I’ve already lost track of what is meant by controversial methods again? Could someone please clarify this again?

@lorentzenchr

Copy link
Copy Markdown
Contributor

@chunweiyuan See #8935 (comment).

@chunweiyuan

Copy link
Copy Markdown
Author

Many build tests failed. I suspect it's due to something like this:

/home/runner/work/numpy/numpy/numpy/core/src/npysort/simd_qsort.dispatch.cpp:13:14: fatal error: x86-simd-sort/src/avx512-64bit-argsort.hpp: No such file or directory
   13 |     #include "x86-simd-sort/src/avx512-64bit-argsort.hpp"
      |              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.

which does coincide with the following git diff on my main branch:

diff --git a/numpy/core/src/npysort/x86-simd-sort b/numpy/core/src/npysort/x86-simd-sort
index 85fbe7d1a..c6ddd9c8b 160000
--- a/numpy/core/src/npysort/x86-simd-sort
+++ b/numpy/core/src/npysort/x86-simd-sort
@@ -1 +1 @@
-Subproject commit 85fbe7d1abca3b9a224ba1c62d52afe9a180f8ef
+Subproject commit c6ddd9c8b332713764c65e7ceb97e2ca38f15a3b
diff --git a/numpy/core/src/umath/svml b/numpy/core/src/umath/svml
index 1b21e453f..1c5260a61 160000
--- a/numpy/core/src/umath/svml
+++ b/numpy/core/src/umath/svml
@@ -1 +1 @@
-Subproject commit 1b21e453f6b1ba6a6aca392b1d810d9d41576123
+Subproject commit 1c5260a61e7dce6be48073dfa96291edb0a11d79

What is the best course of action here? commit and push? Does numpy have a standard way to resolve this?

@mattip

mattip commented Aug 6, 2023

Copy link
Copy Markdown
Member

Did you do git submodule update --init ?

@chunweiyuan

chunweiyuan commented Aug 6, 2023 •

Copy link
Copy Markdown
Author

Did you do git submodule update --init ?

Thanks. I made a mistake of deleting my remote branch. Just restored it. I updated the submodules with the command you suggested, but the build still fails. They seem to all be related to this line
https://github.com/numpy/numpy/blob/main/numpy/core/src/npysort/simd_qsort.dispatch.cpp#L13
leading to

core/src/npysort/simd_qsort.dispatch.cpp:13:14: fatal error: x86-simd-sort/src/avx512-64bit-argsort.hpp: No such file or directory

My local has that .hpp file. The problem being that, when I push to my branch with git push origin weighted_quantile, even after running the command you suggested, it somehow still does not update the x86-simd-sort submodule, so my remote is still missing the avx512-64bit-argsort.hpp file:
https://github.com/chunweiyuan/numpy/tree/weighted_quantile/numpy/core/src/npysort

I'm running out of git gymnastic moves. Any help is greatly appreciated.

@chunweiyuan

chunweiyuan commented Aug 6, 2023 •

Copy link
Copy Markdown
Author

I decided to prune this branch a bit to

1.) remove all the npysort mishaps
2.) move out commit d00661c into a separate PR (#24352)

Now both PRs look cleaner, the only failures coming from the Travis mystery.

…base

     and nanquantile/nanpercentile in lib.nanfunctions (numpy#9211)
…n lib.function_base and nanquantile/nanpercentile in lib.nanfunctions (numpy#9211).

    Move weights normalization to function_base._validate_and_ureduce_weights(), and speed improvement to conditional statement therein (numpy#9211).

    Additional docs to how weights are applied for weighted quantile calculation in lib.function_base (numpy#9211).

    Consolidate all np.vectorize() algo into one in lib.function_base._quantile() (numpy#9211).

    Better mapping from weight space previous/next indexes to real space in lib.function_base._quantile(), with additional comments. (numpy#9211)
…s in lib.function_base (numpy#9211).

    Add tests to ensure consistency 1.) between get_virtual_index/fix_gamma and discrite_shortcut in lib.function_base._QuantileMethods, and 2.) in decimal weights. (numpy#9211)

    Remove nan-index check in function_base._get_indexes. (numpy#9211)
Various other changes pertaining to api signatures.
@seberg

seberg commented Nov 8, 2023

Copy link
Copy Markdown
Member

Sorry, but closing this as I think I hinted before; it is too unwieldy and also a few open questions that need clearer answers IMO. If you have input, please reply to this thread: https://mail.python.org/archives/list/[email protected]/thread/JHKKUXFT6Z2KTZQZHX6EKQSLSJCFNPYM/

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

Labels

01 - Enhancement 64 - Good Idea Inactive PR with a good start or idea. Consider studying it if you are working on a related issue. component: numpy.lib

Projects

Development

Successfully merging this pull request may close these issues.

weighted percentile