Repository navigation
ENH: Weighted quantile - #9211
chunweiyuan wants to merge 4 commits into
Conversation
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Isn't this a superset of arraysort above? Just use this for both?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I think this should be relaxed to "Either 1D, or such that weights.ndim == a.ndim and that weights and a are broadcastable"
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
without weights it should not be slower than the old percentile, so partition should be used and the vectorization of the index sort avoided.
There was a problem hiding this comment.
Just fixed it in the latest push.
|
this does seem almost out of scope for numpy and more something for a statistics package, has this been previously discussed? |
|
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. |
|
I think this PR belongs in numpy: 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. |
|
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. |
|
@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 |
|
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 |
There was a problem hiding this comment.
This should be quantile, not percentile
There was a problem hiding this comment.
Thanks. Fixed. This baby is now just waiting for #9213........
madphysicist
left a comment
There was a problem hiding this comment.
This probably needs an entry somewhere in the release notes.
There was a problem hiding this comment.
This looks like a q instaead of a g. If I am wrong, ignore.
There was a problem hiding this comment.
How about integer weights?
There was a problem hiding this comment.
I think line 3233 there tests integer weights.
There was a problem hiding this comment.
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."
There was a problem hiding this comment.
You could save on a call to asarray by doing q=true_divide(q, 100)
|
@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. |
|
Sounds good. Old habits die hard. Now this branch is just waiting on #9213, I believe. |
|
Looks like you did something screwy with a merge/rebase there. I've seen that behaviour before, but don't remember the cause. |
|
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. |
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
left a comment
There was a problem hiding this comment.
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).
| 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? |
There was a problem hiding this comment.
# 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.
There was a problem hiding this comment.
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...)
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
|
A conceptual note: in weighted quantile, I’m not sure it makes any sense to have a weight < 1. To me,
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:
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. |
|
@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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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 :).
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Please disregard my comment above; I see that the existing constraints on the weights are indeed compatible with numpy.average.
There was a problem hiding this comment.
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
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
Implied assumptions and properties:
- Weights
$w_i$ are non-negative real numbers. - A weight of 2 is equivalent to duplicating this observation.
-
$\hat{F}$ as well as$Q(\hat{F})$ are invariant under scalar rescaling:$w \rightarrow c*w$ for$c > 0$ - 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
methodinnumpy.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
There was a problem hiding this comment.
@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!)
|
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 Thank you all for your inputs. |
| def percentile(a, | ||
| q, | ||
| axis=None, | ||
| weights=None, |
There was a problem hiding this comment.
This needs to go after * to not break backward compatibility.
| def quantile(a, | ||
| q, | ||
| axis=None, | ||
| weights=None, |
| a, | ||
| q, | ||
| axis=None, | ||
| weights=None, |
|
Hi @seberg, @tupui, and @InessaPawson, Last time we discussed on this thread, we mentioned replacing the usage of |
|
Fully removing the vectorize seems pretty much impossible after looking into it. I would much prefer simplifying things a bit, though. I think
That is needed, because the current code is missing the discretization, because for weights you need:
Right now, we don't get "discrete" logic I believe (i.e. the tests are missing 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 Was there ever a clear decision or "prior art" reference on the choice of frequency weights? I understand now clearer where the But... that confuses me, probably because I had looked at gh-16862 more, and thought that 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. |
|
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:
|
|
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 A.) It is an extension of the the current methods defined in B.) C.) Integer weights behave identical to integer repetition of corresponding values (frequency expansion). In other words, With the above axioms in mind, my approach to weighted quantile is
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). 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. |
|
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:
|
|
In summary, I think
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. |
|
I agree with most points except:
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. The solution is any point in the half-open interval [1, 3). The different As mentioned in the issue #8935, I would also propose to start with non-controversial |
|
I can’t say I agree with you. To me, 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 To me, any approach to computing weighted quantile on Lastly, I think I’ve already lost track of what is meant by |
|
Many build tests failed. I suspect it's due to something like this: which does coincide with the following What is the best course of action here? commit and push? Does numpy have a standard way to resolve this? |
|
Did you do |
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 My local has that .hpp file. The problem being that, when I push to my branch with I'm running out of git gymnastic moves. Any help is greatly appreciated. |
|
I decided to prune this branch a bit to 1.) remove all the 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.
|
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/ |
Creates
quantile()function that allowsweightsinput.Fixes #6326, #8935
The following are plotted the same way as the graphs at the bottom of the
np.percentiledocs, but with an added weights argument:weights=[1, 2, 3, 4]:weights = [2, 1, 1, 2]: