|
| 1 | +import numpy as np |
| 2 | +from numpy.typing import ArrayLike |
| 3 | +from typing import Dict |
| 4 | +import pymc as pm |
| 5 | +import xhistogram.core |
| 6 | + |
| 7 | +try: |
| 8 | + import dask.dataframe |
| 9 | + import dask.array |
| 10 | +except ImportError: |
| 11 | + dask = None |
| 12 | + |
| 13 | + |
| 14 | +__all__ = ["quantile_histogram", "discrete_histogram", "histogram_approximation"] |
| 15 | + |
| 16 | + |
| 17 | +def quantile_histogram( |
| 18 | + data: ArrayLike, n_quantiles=1000, zero_inflation=False |
| 19 | +) -> Dict[str, ArrayLike]: |
| 20 | + if dask and isinstance(data, (dask.dataframe.Series, dask.dataframe.DataFrame)): |
| 21 | + data = data.to_dask_array(lengths=True) |
| 22 | + if zero_inflation: |
| 23 | + zeros = (data == 0).sum(0) |
| 24 | + mdata = np.ma.masked_where(data == 0, data) |
| 25 | + qdata = data[data > 0] |
| 26 | + else: |
| 27 | + mdata = data |
| 28 | + qdata = data.flatten() |
| 29 | + quantiles = np.percentile(qdata, np.linspace(0, 100, n_quantiles)) |
| 30 | + if dask: |
| 31 | + (quantiles,) = dask.compute(quantiles) |
| 32 | + count, _ = xhistogram.core.histogram(mdata, bins=[quantiles], axis=0) |
| 33 | + count = count.transpose(count.ndim - 1, *range(count.ndim - 1)) |
| 34 | + lower = quantiles[:-1] |
| 35 | + upper = quantiles[1:] |
| 36 | + |
| 37 | + if zero_inflation: |
| 38 | + count = np.concatenate([zeros[None], count]) |
| 39 | + lower = np.concatenate([[0], lower]) |
| 40 | + upper = np.concatenate([[0], upper]) |
| 41 | + lower = lower.reshape(lower.shape + (1,) * (count.ndim - 1)) |
| 42 | + upper = upper.reshape(upper.shape + (1,) * (count.ndim - 1)) |
| 43 | + |
| 44 | + result = dict( |
| 45 | + lower=lower, |
| 46 | + upper=upper, |
| 47 | + mid=(lower + upper) / 2, |
| 48 | + count=count, |
| 49 | + ) |
| 50 | + return result |
| 51 | + |
| 52 | + |
| 53 | +def discrete_histogram(data: ArrayLike, min_count=None) -> Dict[str, ArrayLike]: |
| 54 | + if dask and isinstance(data, (dask.dataframe.Series, dask.dataframe.DataFrame)): |
| 55 | + data = data.to_dask_array(lengths=True) |
| 56 | + mid, count_uniq = np.unique(data, return_counts=True) |
| 57 | + if min_count is not None: |
| 58 | + mid = mid[count_uniq >= min_count] |
| 59 | + count_uniq = count_uniq[count_uniq >= min_count] |
| 60 | + bins = np.concatenate([mid, [mid.max() + 1]]) |
| 61 | + if dask: |
| 62 | + mid, bins = dask.compute(mid, bins) |
| 63 | + count, _ = xhistogram.core.histogram(data, bins=[bins], axis=0) |
| 64 | + count = count.transpose(count.ndim - 1, *range(count.ndim - 1)) |
| 65 | + mid = mid.reshape(mid.shape + (1,) * (count.ndim - 1)) |
| 66 | + return dict(mid=mid, count=count) |
| 67 | + |
| 68 | + |
| 69 | +def histogram_approximation(name, dist, *, observed: ArrayLike, **h_kwargs): |
| 70 | + """Approximate a distribution with a histogram potential. |
| 71 | +
|
| 72 | + Parameters |
| 73 | + ---------- |
| 74 | + name : str |
| 75 | + Name for the Potential |
| 76 | + dist : aesara.tensor.var.TensorVariable |
| 77 | + The output of pm.Distribution.dist() |
| 78 | + observed : ArrayLike |
| 79 | + Observed value to construct a histogram. Histogram is computed over 0th axis. Dask is supported. |
| 80 | +
|
| 81 | + Returns |
| 82 | + ------- |
| 83 | + aesara.tensor.var.TensorVariable |
| 84 | + Potential |
| 85 | +
|
| 86 | + Examples |
| 87 | + -------- |
| 88 | + Discrete variables are reduced to unique repetitions (up to min_count) |
| 89 | + >>> import pymc as pm |
| 90 | + >>> import pymc_experimental as pmx |
| 91 | + >>> production = np.random.poisson([1, 2, 5], size=(1000, 3)) |
| 92 | + >>> with pm.Model(coords=dict(plant=range(3))): |
| 93 | + ... lam = pm.Exponential("lam", 1.0, dims="plant") |
| 94 | + ... pot = pmx.distributions.histogram_approximation( |
| 95 | + ... "histogram_potential", pm.Poisson.dist(lam), observed=production, min_count=2 |
| 96 | + ... ) |
| 97 | +
|
| 98 | + Continuous variables are discretized into n_quantiles |
| 99 | + >>> measurements = np.random.normal([1, 2, 3], [0.1, 0.4, 0.2], size=(10000, 3)) |
| 100 | + >>> with pm.Model(coords=dict(tests=range(3))): |
| 101 | + ... m = pm.Normal("m", dims="tests") |
| 102 | + ... s = pm.LogNormal("s", dims="tests") |
| 103 | + ... pot = pmx.distributions.histogram_approximation( |
| 104 | + ... "histogram_potential", pm.Normal.dist(m, s), |
| 105 | + ... observed=measurements, n_quantiles=50 |
| 106 | + ... ) |
| 107 | +
|
| 108 | + For special cases like Zero Inflation in Continuous variables there is a flag. |
| 109 | + The flag adds a separate bin for zeros |
| 110 | + >>> measurements = abs(measurements) |
| 111 | + >>> measurements[100:] = 0 |
| 112 | + >>> with pm.Model(coords=dict(tests=range(3))): |
| 113 | + ... m = pm.Normal("m", dims="tests") |
| 114 | + ... s = pm.LogNormal("s", dims="tests") |
| 115 | + ... pot = pmx.distributions.histogram_approximation( |
| 116 | + ... "histogram_potential", pm.Normal.dist(m, s), |
| 117 | + ... observed=measurements, n_quantiles=50, zero_inflation=True |
| 118 | + ... ) |
| 119 | + """ |
| 120 | + if dask and isinstance(observed, (dask.dataframe.Series, dask.dataframe.DataFrame)): |
| 121 | + observed = observed.to_dask_array(lengths=True) |
| 122 | + if np.issubdtype(observed.dtype, np.integer): |
| 123 | + histogram = discrete_histogram(observed, **h_kwargs) |
| 124 | + else: |
| 125 | + histogram = quantile_histogram(observed, **h_kwargs) |
| 126 | + if dask is not None: |
| 127 | + (histogram,) = dask.compute(histogram) |
| 128 | + return pm.Potential(name, pm.logp(dist, histogram["mid"]) * histogram["count"]) |
0 commit comments