|
| 1 | +""" |
| 2 | +This module provides alternatives for the few additional functions found in |
| 3 | +and once used from the bottlechest package (fork of bottleneck). |
| 4 | +
|
| 5 | +It also patches bottleneck to contain these functions. |
| 6 | +""" |
| 7 | +import numpy as np |
| 8 | +from scipy.sparse import issparse |
| 9 | +import bottleneck as bn |
| 10 | + |
| 11 | + |
| 12 | +def bincount(X, max_val=None, weights=None, minlength=None): |
| 13 | + """Return counts of values in array X. |
| 14 | +
|
| 15 | + Works kind of like np.bincount(), except that it also supports floating |
| 16 | + arrays with nans. |
| 17 | + """ |
| 18 | + X = np.asanyarray(X) |
| 19 | + if X.dtype.kind == 'f' and bn.anynan(X): |
| 20 | + nonnan = ~np.isnan(X) |
| 21 | + nans = (~nonnan).sum(axis=0) |
| 22 | + X = X[nonnan] |
| 23 | + if weights is not None: |
| 24 | + weights = weights[nonnan] |
| 25 | + else: |
| 26 | + nans = 0 if X.ndim == 1 else np.zeros(X.shape[1]) |
| 27 | + if minlength is None and max_val is not None: |
| 28 | + minlength = max_val + 1 |
| 29 | + return (np.bincount(X.astype(np.int32, copy=False), |
| 30 | + weights=weights, |
| 31 | + minlength=minlength), |
| 32 | + nans) |
| 33 | + |
| 34 | + |
| 35 | +def countnans(X, weights=None, axis=None, dtype=None, keepdims=False): |
| 36 | + """ |
| 37 | + Count the undefined elements in arr along given axis. |
| 38 | +
|
| 39 | + Parameters |
| 40 | + ---------- |
| 41 | + X : array_like |
| 42 | + weights : array_like |
| 43 | + Weights to weight the nans with, before or after counting (depending |
| 44 | + on the weights shape). |
| 45 | +
|
| 46 | + Returns |
| 47 | + ------- |
| 48 | + counts |
| 49 | + """ |
| 50 | + X = np.asanyarray(X) |
| 51 | + isnan = np.isnan(X) |
| 52 | + if weights is not None and weights.shape == X.shape: |
| 53 | + isnan = isnan * weights |
| 54 | + counts = isnan.sum(axis=axis, dtype=dtype, keepdims=keepdims) |
| 55 | + if weights is not None and weights.shape != X.shape: |
| 56 | + counts = counts * weights |
| 57 | + return counts |
| 58 | + |
| 59 | + |
| 60 | +def contingency(X, y, max_X=None, max_y=None, weights=None, mask=None): |
| 61 | + """ |
| 62 | + Compute the contingency matrices for each column of X (excluding the masked) |
| 63 | + versus the vector y. |
| 64 | +
|
| 65 | + If the array is 1-dimensional, a 2d contingency matrix is returned. If the |
| 66 | + array is 2d, the function returns a 3d array, with the first dimension |
| 67 | + corresponding to column index (variable in the input array). |
| 68 | +
|
| 69 | + The rows of contingency matrix correspond to values of variables, the |
| 70 | + columns correspond to values in vector `y`. |
| 71 | + (??? isn't it the other way around ???) |
| 72 | +
|
| 73 | + Rows in the input array can be weighted (argument `weights`). A subset of |
| 74 | + columns can be selected by additional argument `mask`. |
| 75 | +
|
| 76 | + The function also returns a count of NaN values per each value of `y`. |
| 77 | +
|
| 78 | + Parameters |
| 79 | + ---------- |
| 80 | + X : array_like |
| 81 | + With values in columns. |
| 82 | + y : 1d array |
| 83 | + Vector of true values. |
| 84 | + max_X : int |
| 85 | + The maximal value in the array |
| 86 | + max_y : int |
| 87 | + The maximal value in `y` |
| 88 | + weights : ... |
| 89 | + mask : sequence |
| 90 | + Discrete columns of X. |
| 91 | +
|
| 92 | + Returns |
| 93 | + ------- |
| 94 | + contingencies: (m × ny × nx) array |
| 95 | + m number of masked (used) columns (all if mask=None), i.e. |
| 96 | + for each column of X; |
| 97 | + ny number of uniques in y, |
| 98 | + nx number of uniques in column of X. |
| 99 | + nans : array_like |
| 100 | + Number of nans in each column of X for each unique value of y. |
| 101 | + """ |
| 102 | + if weights is not None and np.any(weights) and np.unique(weights)[0] != 1: |
| 103 | + raise ValueError('weights not yet supported') |
| 104 | + |
| 105 | + was_1d = False |
| 106 | + if X.ndim == 1: |
| 107 | + X = X[..., np.newaxis] |
| 108 | + was_1d = True |
| 109 | + |
| 110 | + contingencies, nans = [], [] |
| 111 | + ny = np.unique(y).size if max_y is None else max_y + 1 |
| 112 | + for i in range(X.shape[1]): |
| 113 | + if mask is not None and not mask[i]: |
| 114 | + contingencies.append(np.zeros((ny, max_X + 1))) |
| 115 | + nans.append(np.zeros(ny)) |
| 116 | + continue |
| 117 | + col = X[..., i] |
| 118 | + nx = np.unique(col[~np.isnan(col)]).size if max_X is None else max_X + 1 |
| 119 | + if issparse(col): |
| 120 | + col = np.ravel(col.todense()) |
| 121 | + contingencies.append( |
| 122 | + bincount(y + ny * col, |
| 123 | + minlength=ny * nx)[0].reshape(nx, ny).T) |
| 124 | + nans.append( |
| 125 | + bincount(y[np.isnan(col)], minlength=ny)[0]) |
| 126 | + if was_1d: |
| 127 | + return contingencies[0], nans[0] |
| 128 | + return np.array(contingencies), np.array(nans) |
| 129 | + |
| 130 | + |
| 131 | +def stats(X, weights=None, compute_variance=False): |
| 132 | + """ |
| 133 | + Compute min, max, #nans, mean and variance. |
| 134 | +
|
| 135 | + Result is a tuple (min, max, mean, variance, #nans, #non-nans) or an |
| 136 | + array of shape (len(X), 6). |
| 137 | +
|
| 138 | + The mean and the number of nans and non-nans are weighted. |
| 139 | +
|
| 140 | + Computation of variance requires an additional pass and is not enabled |
| 141 | + by default. Zeros are filled in instead of variance. |
| 142 | +
|
| 143 | + Parameters |
| 144 | + ---------- |
| 145 | + X : array_like, 1 or 2 dimensions |
| 146 | + Input array. |
| 147 | + weights : array_like, optional |
| 148 | + Weights, array of the same length as `x`. |
| 149 | + compute_variance : bool, optional |
| 150 | + If set to True, the function also computes variance. |
| 151 | +
|
| 152 | + Returns |
| 153 | + ------- |
| 154 | + out : a 6-element tuple or an array of shape (len(x), 6) |
| 155 | + Computed (min, max, mean, variance or 0, #nans, #non-nans) |
| 156 | +
|
| 157 | + Raises |
| 158 | + ------ |
| 159 | + ValueError |
| 160 | + If the length of the weight vector does not match the length of the |
| 161 | + array |
| 162 | + """ |
| 163 | + if weights is not None: |
| 164 | + X = X * weights |
| 165 | + is_numeric = np.issubdtype(X.dtype, np.number) |
| 166 | + nans = (np.isnan(X) if is_numeric else ~X.astype(bool)).sum(axis=0) |
| 167 | + variance = np.nanvar(X, axis=0) if compute_variance and is_numeric else np.zeros(X.shape[1]) |
| 168 | + return np.column_stack(( |
| 169 | + np.nanmin(X, axis=0) if is_numeric else np.tile(np.inf, X.shape[1]), |
| 170 | + np.nanmax(X, axis=0) if is_numeric else np.tile(-np.inf, X.shape[1]), |
| 171 | + np.nanmean(X, axis=0) if is_numeric else np.zeros(X.shape[1]), |
| 172 | + variance, |
| 173 | + nans, |
| 174 | + X.shape[0] - nans)) |
0 commit comments