Compute Quantile#
quantile
#
| FUNCTION | DESCRIPTION |
|---|---|
quantile |
Compute quantiles along a specified dimension, optionally weighted. |
Functions#
quantile(X: torch.Tensor, q: torch.Tensor | float, weights: torch.Tensor | None = None, dim: int | None = None, interpolation: Literal['linear', 'nearest', 'higher', 'lower', 'midpoint'] = 'linear', keepdim: bool = False) -> torch.Tensor
#
Compute quantiles along a specified dimension, optionally weighted.
Uses torch.sort for efficiency and handles multiple quantiles
simultaneously. Overcomes limitations of torch.quantile which is
restricted to 2^24 elements.
When weights are provided, computes weighted quantiles using midpoint CDF
interpolation and torch.searchsorted.
| PARAMETER | DESCRIPTION |
|---|---|
X
|
Data tensor.
TYPE:
|
q
|
Quantile(s) to compute. Must be in [0, 1]. Scalar values are supported and will squeeze the quantile dimension from the output.
TYPE:
|
weights
|
Non-negative sample weights, same shape as
TYPE:
|
dim
|
Dimension to reduce. If None, the tensor is flattened.
TYPE:
|
interpolation
|
Interpolation method, by default "linear". Only
TYPE:
|
keepdim
|
Whether to keep the reduced dimension in the output.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Quantile values. Shape depends on |
Examples:
>>> import torch
>>> X = torch.randn(100, 5)
>>> q = torch.tensor([0.25, 0.5, 0.75])
>>> quantile(X, q, dim=0).shape
torch.Size([3, 5])
Weighted quantiles:
References
.. [1] https://discuss.pytorch.org/t/efficient-quantile-k-largest-value/ .. [2] https://github.com/pytorch/pytorch/issues/157431 .. [3] https://github.com/pytorch/pytorch/issues/64947
Source code in spectre/compute/quantile.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | |