Source code for graph_tool.inference.histogram

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2026 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from .. import _get_rng, Vector_double, Vector_int64_t

from .. dl_import import dl_import
dl_import("from . import libgraph_tool_inference as libinference")

from . util import *
from . base_states import *

from collections.abc import Iterable
import numpy as np

[docs] class HistState(object): r"""Bayesian nonparametric histogram of multivariate data. Parameters ---------- x : :class:`numpy.ndarray` of shape ``(N, D)`` Data points, with one row for each of the :math:`N` points, and one column for each of the :math:`D` dimensions. weights : iterable of ``int`` (optional, default: ``None``) Integer weights (multiplicities) of the data points. If not given, every point has weight one. bins : list of ``int`` or :class:`numpy.ndarray` (optional, default: ``None``) Initial bins, with one entry for each dimension. An integer entry gives the number of bins of equal width that span the range of the data in that dimension, and an array gives the bin edges. If not given, a single bin is used for every dimension. alpha : ``float`` (optional, default: ``2``) Hyperparameter of the prior distribution of the bin edges. pcount : ``float`` (optional, default: ``1``) Pseudocount of every bin, i.e. the concentration parameter of the Dirichlet prior of the bin probabilities. bounded : list of pairs of ``bool`` (optional, default: ``None``) For each dimension, a pair ``(lower, upper)`` that specifies whether the lowest and the highest bin edges are fixed. If not given, the edges are not fixed. discrete : list of ``bool`` (optional, default: ``None``) For each dimension, whether its values are integers. If all dimensions are discrete, the values are stored as integers. conditional : ``int`` (optional, default: ``None``) If given, only the first ``conditional`` dimensions are modelled, as a distribution conditioned on the values of the remaining ones. If not given, the joint distribution of all dimensions is modelled. categorical : list of ``bool`` (optional, default: ``None``) For each dimension, whether its values are categories, in which case each distinct value has its own bin, and no bin edges are inferred. The categories must be non-negative integers. They are the distinct values in the data, unless an array of bin edges is given for that dimension, whose values, except the last one, are then the categories (which must include every value in the data). Notes ----- The data are modelled by a histogram with piecewise constant density inside each (multidimensional) bin. The probabilities of the bins have a Dirichlet prior with concentration parameter ``pcount``, and the bin edges (and hence their number) are latent variables, which are sampled with :meth:`~HistState.mcmc_sweep`, according to their posterior distribution. The value returned by :meth:`~HistState.entropy` is the negative joint log probability of the data and the bin edges, i.e. the description length of the data. Examples -------- .. testsetup:: hist np.random.seed(42) gt.seed_rng(42) .. doctest:: hist >>> x = np.random.normal(size=(1000, 1)) >>> state = gt.HistState(x, bins=[20]) >>> for i in range(100): ... ret = state.mcmc_sweep() >>> print(state.get_lpdf([0.]) > state.get_lpdf([2.])) True """ def __init__(self, x, weights=None, bins=None, alpha=2, pcount=1., bounded=None, discrete=None, conditional=None, categorical=None, **kwargs): self.force_double = kwargs.pop("force_double", None) if len(kwargs) > 0: raise TypeError("unrecognized keyword arguments: " + str(list(kwargs.keys()))) if discrete is not None and all(discrete) and not self.force_double: x = np.asarray(x, dtype="int64") else: x = np.asarray(x, dtype="double") self.D = x.shape[1] if weights is None: weights = [] weights = np.asarray(weights, dtype="uint64") self.alpha = alpha self.pcount = pcount if bounded is None: bounded = [(False, False)] * self.D if discrete is None: discrete = [False] * self.D self.bounded = self.obounded = [(bool(x), bool(y)) for x, y in bounded] self.discrete = self.odiscrete = [bool(x) for x in discrete] if conditional is None: conditional = self.D self.conditional = conditional if categorical is None: categorical = [False] * self.D self.categorical = self.ocategorical = [bool(x) for x in categorical] if bins is None: bins = [1] * self.D # rows of removed points (see remove_point()) hold invalid values if x.dtype == np.int64: valid = np.all(x != np.iinfo(np.int64).max, axis=1) else: valid = np.all(~np.isnan(x), axis=1) self.bins = [] for j in range(self.D): if self.categorical[j]: xj = x[valid, j] if np.any(xj < 0) or np.any(xj != np.floor(xj)): raise ValueError(f"the values of the categorical " f"dimension {j} must be non-negative " "integers") if self.categorical[j] and isinstance(bins[j], (int, np.integer)): # each category is the lower edge of its own bin, so that # the number of bins is the number of categories b = np.unique(xj) if len(b) == 0: b = np.zeros(1) b = np.append(b, b[-1] + 1) elif isinstance(bins[j], (int, np.integer)): if discrete[j]: # integer edges, of which there may be fewer than # requested if the range of values is small b = np.unique(np.floor(np.linspace(x[:,j].min(), x[:,j].max() + 1, bins[j] + 1))) else: b = np.linspace(x[:,j].min(), x[:,j].max(), bins[j] + 1) b[-1] += 1e-8 else: b = np.asarray(bins[j]) if len(b) < 2 or np.any(np.diff(b) <= 0): raise ValueError(f"the bin edges of dimension {j} must " "be strictly increasing, with at least " "two values") if self.categorical[j]: if not np.all(np.isin(xj, b[:-1])): raise ValueError(f"the categories of dimension {j} " "(the bin edges except the last) " "must include every value") elif (len(x) > 0 and (x[:,j].min() < b[0] or x[:,j].max() >= b[-1])): raise ValueError(f"the bin edges of dimension {j} must " "cover the values, i.e. " "b[0] <= x < b[-1]") if self._get_dtype() == "int64": b = Vector_int64_t(len(b), b) else: b = Vector_double(len(b), b) self.bins.append(b) self.obins = self.bins self.x_r = x self.w_r = weights self._state = libinference.make_hist_state(self, self.D) def __copy__(self): return self.copy()
[docs] def copy(self, **kwargs): r"""Copies the state. The parameters override the state properties, and have the same meaning as in the constructor.""" return HistState(**dict(self.__getstate__(), **kwargs))
def __getstate__(self): return dict(x=self.get_x(), weights=self.get_weights(), bins=[b.a.copy() for b in self.bins], alpha=self.alpha, pcount=self.pcount, bounded=self.bounded, discrete=self.discrete, conditional=self.conditional, categorical=self.categorical, force_double=self.force_double) def __setstate__(self, state): self.__init__(**state) def __repr__(self): return "<HistState object with data shape %s, bin shape %s, discrete %s, bounded %s at 0x%x>" % \ (self.get_x().shape, tuple(len(s) for s in self.bins), self.discrete, self.bounded, id(self)) def _get_dtype(self): if all(self.discrete) and not self.force_double: return "int64" return "double"
[docs] def get_x(self): r"""Returns the data points as an array of shape ``(N, D)``.""" return self._state.get_x()
[docs] def get_weights(self): r"""Returns the weights of the data points.""" return self._state.get_w()
[docs] def trim_points(self): r"""Compacts the stored data by discarding the points that have been removed, which changes the positions of the remaining points.""" self._state.trim_points()
[docs] def add_point(self, pos, val, w=1): r"""Adds a data point with values ``val`` and weight ``w`` at position ``pos``.""" dtype = self._get_dtype() self._state.add_point(pos, w, np.asarray(val, dtype=dtype))
[docs] def remove_point(self, pos): r"""Removes the data point at position ``pos``.""" self._state.remove_point(pos)
[docs] @copy_state_wrap def entropy(self, **kwargs): r"""Returns the description length of the data and the bin edges, i.e. the negative logarithm of their joint probability.""" S = self._state.entropy() return S
def _get_entropy_args(self, kwargs): return None
[docs] def get_lpdf(self, x, mle=True): r"""Returns the logarithm of the probability density at point ``x`` (conditioned on the remaining dimensions if ``conditional`` was given). If ``mle == True``, the posterior mode of the bin probabilities is used (which is their maximum likelihood estimate for ``pcount == 1``), otherwise their posterior mean.""" dtype = self._get_dtype() return self._state.get_lpdf(np.asarray(x, dtype=dtype), mle)
[docs] def get_cond_mean(self, x, j, mle=True): r"""Returns the mean of dimension ``j``, conditioned on the values of the other dimensions given by ``x`` (the value ``x[j]`` is ignored). The parameter ``mle`` has the same meaning as in :meth:`~HistState.get_lpdf`.""" dtype = self._get_dtype() return self._state.get_cond_mean(np.asarray(x, dtype=dtype), j, mle)
[docs] def predictive_sample(self, x=None, n=1): r"""Returns ``n`` points sampled from the posterior predictive distribution, as an array of shape ``(n, conditional)``. If ``conditional`` was given, ``x`` must contain the values of the conditioning dimensions.""" dtype = self._get_dtype() if self.conditional < self.D: x = np.asarray(x, dtype=dtype) else: x = np.zeros(1, dtype=dtype) return self._state.sample(n, x, _get_rng())
[docs] def replace_point(self, pos, x, w=1): r"""Replaces the data point at position ``pos`` with values ``x`` and weight ``w``.""" dtype = self._get_dtype() return self._state.replace_point(pos, w, np.asarray(x, dtype=dtype))
[docs] def virtual_replace_point_dS(self, pos, x): r"""Returns the change in description length if the data point at position ``pos`` were replaced with values ``x``, without performing the replacement.""" dtype = self._get_dtype() return self._state.replace_point_dS(pos, np.asarray(x, dtype=dtype))
[docs] @mcmc_sweep_wrap def mcmc_sweep(self, beta=1., niter=1, verbose=False, **kwargs): r"""Performs ``niter`` sweeps of a Metropolis-Hastings MCMC to sample the bin edges, at inverse temperature ``beta``. It returns a tuple ``(dS, nattempts, nmoves)`` with the change in description length, and the number of attempted and accepted moves.""" if len(kwargs) > 0: raise ValueError("unrecognized keyword arguments: " + str(list(kwargs.keys()))) mcmc_state = DictState(locals()) mcmc_state.state = self._state dS, nattempts, nmoves = \ libinference.hist_mcmc_sweep(mcmc_state, self._state, self.D, _get_rng()) return dS, nattempts, nmoves