| 1 |
import numpy as np |
| 2 |
from scipy import special |
| 3 |
|
| 4 |
|
| 5 |
def normalize(a, axis=None): |
| 6 |
""" |
| 7 |
Normalize the input array so that it sums to 1. |
| 8 |
|
| 9 |
Parameters |
| 10 |
---------- |
| 11 |
a : array |
| 12 |
Non-normalized input data. |
| 13 |
|
| 14 |
axis : int |
| 15 |
Dimension along which normalization is performed. |
| 16 |
|
| 17 |
Notes |
| 18 |
----- |
| 19 |
Modifies the input **inplace**. |
| 20 |
""" |
| 21 |
a_sum = a.sum(axis) |
| 22 |
if axis and a.ndim > 1: |
| 23 |
|
| 24 |
a_sum[a_sum == 0] = 1 |
| 25 |
shape = list(a.shape) |
| 26 |
shape[axis] = 1 |
| 27 |
a_sum.shape = shape |
| 28 |
|
| 29 |
a /= a_sum |
| 30 |
|
| 31 |
|
| 32 |
def log_normalize(a, axis=None): |
| 33 |
""" |
| 34 |
Normalize the input array so that ``sum(exp(a)) == 1``. |
| 35 |
|
| 36 |
Parameters |
| 37 |
---------- |
| 38 |
a : array |
| 39 |
Non-normalized input data. |
| 40 |
|
| 41 |
axis : int |
| 42 |
Dimension along which normalization is performed. |
| 43 |
|
| 44 |
Notes |
| 45 |
----- |
| 46 |
Modifies the input **inplace**. |
| 47 |
""" |
| 48 |
if axis is not None and a.shape[axis] == 1: |
| 49 |
|
| 50 |
|
| 51 |
a[:] = 0 |
| 52 |
else: |
| 53 |
with np.errstate(under="ignore"): |
| 54 |
a_lse = special.logsumexp(a, axis, keepdims=True) |
| 55 |
a -= a_lse |
| 56 |
|
| 57 |
|
| 58 |
def fill_covars(covars, covariance_type='full', n_components=1, n_features=1): |
| 59 |
if covariance_type == 'full': |
| 60 |
return covars |
| 61 |
elif covariance_type == 'diag': |
| 62 |
return np.array(list(map(np.diag, covars))) |
| 63 |
elif covariance_type == 'tied': |
| 64 |
return np.tile(covars, (n_components, 1, 1)) |
| 65 |
elif covariance_type == 'spherical': |
| 66 |
|
| 67 |
|
| 68 |
covars = np.ravel(covars) |
| 69 |
eye = np.eye(n_features)[np.newaxis, :, :] |
| 70 |
covars = covars[:, np.newaxis, np.newaxis] |
| 71 |
return eye * covars |