sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def predict(self, X):
"""Predict label for data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = (n_samples,)
"""
logprob, responsibilities = self.score_samples(X)
return responsibi... | Predict label for data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = (n_samples,) | entailment |
def sample(self, n_samples=1, random_state=None):
"""Generate random samples from the model.
Parameters
----------
n_samples : int, optional
Number of samples to generate. Defaults to 1.
Returns
-------
X : array_like, shape (n_samples, n_features)
... | Generate random samples from the model.
Parameters
----------
n_samples : int, optional
Number of samples to generate. Defaults to 1.
Returns
-------
X : array_like, shape (n_samples, n_features)
List of samples | entailment |
def fit(self, X, y=None):
"""Estimate model parameters with the expectation-maximization
algorithm.
A initialization step is performed before entering the em
algorithm. If you want to avoid this step, set the keyword
argument init_params to the empty string '' when creating the
... | Estimate model parameters with the expectation-maximization
algorithm.
A initialization step is performed before entering the em
algorithm. If you want to avoid this step, set the keyword
argument init_params to the empty string '' when creating the
GMM object. Likewise, if you ... | entailment |
def _do_mstep(self, X, responsibilities, params, min_covar=0):
""" Perform the Mstep of the EM algorithm and return the class weihgts.
"""
weights = responsibilities.sum(axis=0)
weighted_X_sum = np.dot(responsibilities.T, X)
inverse_weights = 1.0 / (weights[:, np.newaxis] + 10 * ... | Perform the Mstep of the EM algorithm and return the class weihgts. | entailment |
def _n_parameters(self):
"""Return the number of free parameters in the model."""
ndim = self.means_.shape[1]
if self.covariance_type == 'full':
cov_params = self.n_components * ndim * (ndim + 1) / 2.
elif self.covariance_type == 'diag':
cov_params = self.n_compon... | Return the number of free parameters in the model. | entailment |
def bic(self, X):
"""Bayesian information criterion for the current model fit
and the proposed data
Parameters
----------
X : array of shape(n_samples, n_dimensions)
Returns
-------
bic: float (the lower the better)
"""
return (-2 * self.... | Bayesian information criterion for the current model fit
and the proposed data
Parameters
----------
X : array of shape(n_samples, n_dimensions)
Returns
-------
bic: float (the lower the better) | entailment |
def _get_param_names(cls):
"""Get parameter names for the estimator"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
# No explicit ... | Get parameter names for the estimator | entailment |
def set_params(self, **params):
"""Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of ... | Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of a nested object.
Returns
-... | entailment |
def init_model_gaussian1d(observations, nstates, reversible=True):
"""Generate an initial model with 1D-Gaussian output densities
Parameters
----------
observations : list of ndarray((T_i), dtype=float)
list of arrays of length T_i with observation data
nstates : int
The number of s... | Generate an initial model with 1D-Gaussian output densities
Parameters
----------
observations : list of ndarray((T_i), dtype=float)
list of arrays of length T_i with observation data
nstates : int
The number of states.
Examples
--------
Generate initial model for a gaussi... | entailment |
def _p_o(self, o):
"""
Returns the output probability for symbol o from all hidden states
Parameters
----------
o : float
A single observation.
Return
------
p_o : ndarray (N)
p_o[i] is the probability density of the observation o... | Returns the output probability for symbol o from all hidden states
Parameters
----------
o : float
A single observation.
Return
------
p_o : ndarray (N)
p_o[i] is the probability density of the observation o from state i emission distribution
... | entailment |
def p_obs(self, obs, out=None):
"""
Returns the output probabilities for an entire trajectory and all hidden states
Parameters
----------
oobs : ndarray((T), dtype=int)
a discrete trajectory of length T
Return
------
p_o : ndarray (T,N)
... | Returns the output probabilities for an entire trajectory and all hidden states
Parameters
----------
oobs : ndarray((T), dtype=int)
a discrete trajectory of length T
Return
------
p_o : ndarray (T,N)
the probability of generating the symbol at t... | entailment |
def estimate(self, observations, weights):
"""
Fits the output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k,) ] with K elements
A list of K observation trajectories, each having length T_k and d dimensions
weight... | Fits the output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k,) ] with K elements
A list of K observation trajectories, each having length T_k and d dimensions
weights : [ ndarray(T_k,nstates) ] with K elements
A list... | entailment |
def sample(self, observations, prior=None):
"""
Sample a new set of distribution parameters given a sample of observations from the given state.
Both the internal parameters and the attached HMM model are updated.
Parameters
----------
observations : [ numpy.array with... | Sample a new set of distribution parameters given a sample of observations from the given state.
Both the internal parameters and the attached HMM model are updated.
Parameters
----------
observations : [ numpy.array with shape (N_k,) ] with `nstates` elements
observations... | entailment |
def generate_observation_from_state(self, state_index):
"""
Generate a single synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
Returns
-------
... | Generate a single synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
Returns
-------
observation : float
A single observation from the given state... | entailment |
def generate_observations_from_state(self, state_index, nobs):
"""
Generate synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
nobs : int
The numbe... | Generate synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
nobs : int
The number of observations to generate.
Returns
-------
observation... | entailment |
def generate_observation_trajectory(self, s_t):
"""
Generate synthetic observation data from a given state sequence.
Parameters
----------
s_t : numpy.array with shape (T,) of int type
s_t[t] is the hidden state sampled at time t
Returns
-------
... | Generate synthetic observation data from a given state sequence.
Parameters
----------
s_t : numpy.array with shape (T,) of int type
s_t[t] is the hidden state sampled at time t
Returns
-------
o_t : numpy.array with shape (T,) of type dtype
o_t[... | entailment |
def initial_distribution_samples(self):
r""" Samples of the initial distribution """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].stationary_distribution
return res | r""" Samples of the initial distribution | entailment |
def transition_matrix_samples(self):
r""" Samples of the transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].transition_matrix
return res | r""" Samples of the transition matrix | entailment |
def eigenvalues_samples(self):
r""" Samples of the eigenvalues """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].eigenvalues
return res | r""" Samples of the eigenvalues | entailment |
def eigenvectors_left_samples(self):
r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].eigenvectors_left
... | r""" Samples of the left eigenvectors of the hidden transition matrix | entailment |
def eigenvectors_right_samples(self):
r""" Samples of the right eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :, :] = self._sampled_hmms[i].eigenvectors_right
... | r""" Samples of the right eigenvectors of the hidden transition matrix | entailment |
def timescales_samples(self):
r""" Samples of the timescales """
res = np.empty((self.nsamples, self.nstates-1), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].timescales
return res | r""" Samples of the timescales | entailment |
def lifetimes_samples(self):
r""" Samples of the timescales """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].lifetimes
return res | r""" Samples of the timescales | entailment |
def set_implementation(self, impl):
"""
Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"]
"""
if impl.lower() == 'python':
self.__impl__ = self.__IMPL_PYTHON__
elif impl.lower() == 'c':... | Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"] | entailment |
def log_p_obs(self, obs, out=None, dtype=np.float32):
"""
Returns the element-wise logarithm of the output probabilities for an entire trajectory and all hidden states
This is a default implementation that will take the log of p_obs(obs) and should only be used if p_obs(obs)
is numerica... | Returns the element-wise logarithm of the output probabilities for an entire trajectory and all hidden states
This is a default implementation that will take the log of p_obs(obs) and should only be used if p_obs(obs)
is numerically stable. If there is any danger of running into numerical problems *dur... | entailment |
def _handle_outliers(self, p_o):
""" Sets observation probabilities of outliers to uniform if ignore_outliers is set.
Parameters
----------
p_o : ndarray((T, N))
output probabilities
"""
if self.ignore_outliers:
outliers = np.where(p_o.sum(axis=1)=... | Sets observation probabilities of outliers to uniform if ignore_outliers is set.
Parameters
----------
p_o : ndarray((T, N))
output probabilities | entailment |
def forward(A, pobs, pi, T=None, alpha_out=None, dtype=np.float32):
"""Compute P( obs | A, B, pi ) and all forward coefficients.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the obser... | Compute P( obs | A, B, pi ) and all forward coefficients.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observation at time t given hidden state i
pi : ... | entailment |
def backward(A, pobs, T=None, beta_out=None, dtype=np.float32):
"""Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probab... | Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observation at time t given hidden state i
beta_out : nda... | entailment |
def transition_counts(alpha, beta, A, pobs, T=None, out=None, dtype=np.float32):
""" Sum for all t the probability to transition from state i to state j.
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
... | Sum for all t the probability to transition from state i to state j.
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
beta : ndarray((T,N), dtype = float), optional, default = None
beta[t,i] is the... | entailment |
def viterbi(A, pobs, pi, dtype=np.float32):
""" Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observa... | Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observation at time t given hid... | entailment |
def sample_path(alpha, A, pobs, T=None, dtype=np.float32):
"""
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
beta : ndarray((T,N), dtype = float), optional, default = None
beta[t,i] is the ith forward coefficient of time ... | alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
beta : ndarray((T,N), dtype = float), optional, default = None
beta[t,i] is the ith forward coefficient of time t.
A : ndarray((N,N), dtype = float)
transition matrix of t... | entailment |
def coarse_grain_transition_matrix(P, M):
""" Coarse grain transition matrix P using memberships M
Computes
.. math:
Pc = (M' M)^-1 M' P M
Parameters
----------
P : ndarray(n, n)
microstate transition matrix
M : ndarray(n, m)
membership matrix. Membership to macros... | Coarse grain transition matrix P using memberships M
Computes
.. math:
Pc = (M' M)^-1 M' P M
Parameters
----------
P : ndarray(n, n)
microstate transition matrix
M : ndarray(n, m)
membership matrix. Membership to macrostate m for each microstate.
Returns
-----... | entailment |
def regularize_hidden(p0, P, reversible=True, stationary=False, C=None, eps=None):
""" Regularizes the hidden initial distribution and transition matrix.
Makes sure that the hidden initial distribution and transition matrix have
nonzero probabilities by setting them to eps and then renormalizing.
Avoid... | Regularizes the hidden initial distribution and transition matrix.
Makes sure that the hidden initial distribution and transition matrix have
nonzero probabilities by setting them to eps and then renormalizing.
Avoids zeros that would cause estimation algorithms to crash or get stuck
in suboptimal stat... | entailment |
def regularize_pobs(B, nonempty=None, separate=None, eps=None):
""" Regularizes the output probabilities.
Makes sure that the output probability distributions has
nonzero probabilities by setting them to eps and then renormalizing.
Avoids zeros that would cause estimation algorithms to crash or get stu... | Regularizes the output probabilities.
Makes sure that the output probability distributions has
nonzero probabilities by setting them to eps and then renormalizing.
Avoids zeros that would cause estimation algorithms to crash or get stuck
in suboptimal states.
Parameters
----------
B : ndar... | entailment |
def init_discrete_hmm_spectral(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None,
eps_A=None, eps_B=None, separate=None):
"""Initializes discrete HMM using spectral clustering of observation counts
Initializes HMM as described in [1]_. First estimates a M... | Initializes discrete HMM using spectral clustering of observation counts
Initializes HMM as described in [1]_. First estimates a Markov state model
on the given observations, then uses PCCA+ to coarse-grain the transition
matrix [2]_ which initializes the HMM transition matrix. The HMM output
probabili... | entailment |
def init_discrete_hmm_ml(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None,
eps_A=None, eps_B=None, separate=None):
"""Initializes discrete HMM using maximum likelihood of observation counts"""
raise NotImplementedError('ML-initialization not yet implemented') | Initializes discrete HMM using maximum likelihood of observation counts | entailment |
def update(self, Pi, Tij):
r""" Updates the transition matrix and recomputes all derived quantities """
from msmtools import analysis as msmana
# update transition matrix by copy
self._Tij = np.array(Tij)
assert msmana.is_transition_matrix(self._Tij), 'Given transition matrix is... | r""" Updates the transition matrix and recomputes all derived quantities | entailment |
def is_stationary(self):
r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution
of the hidden transition matrix. """
# for disconnected matrices, the stationary distribution depends on the estimator, so we can't compute
# it directly. Th... | r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution
of the hidden transition matrix. | entailment |
def stationary_distribution(self):
r""" Compute stationary distribution of hidden states if possible.
Raises
------
ValueError if the HMM is not stationary
"""
assert _tmatrix_disconnected.is_connected(self._Tij, strong=False), \
'No unique stationary distri... | r""" Compute stationary distribution of hidden states if possible.
Raises
------
ValueError if the HMM is not stationary | entailment |
def timescales(self):
r""" Relaxation timescales of the hidden transition matrix
Returns
-------
ts : ndarray(m)
relaxation timescales in units of the input trajectory time step,
defined by :math:`-tau / ln | \lambda_i |, i = 2,...,nstates`, where
:ma... | r""" Relaxation timescales of the hidden transition matrix
Returns
-------
ts : ndarray(m)
relaxation timescales in units of the input trajectory time step,
defined by :math:`-tau / ln | \lambda_i |, i = 2,...,nstates`, where
:math:`\lambda_i` are the hidden ... | entailment |
def lifetimes(self):
r""" Lifetimes of states of the hidden transition matrix
Returns
-------
l : ndarray(nstates)
state lifetimes in units of the input trajectory time step,
defined by :math:`-tau / ln | p_{ii} |, i = 1,...,nstates`, where
:math:`p_{... | r""" Lifetimes of states of the hidden transition matrix
Returns
-------
l : ndarray(nstates)
state lifetimes in units of the input trajectory time step,
defined by :math:`-tau / ln | p_{ii} |, i = 1,...,nstates`, where
:math:`p_{ii}` are the diagonal entries... | entailment |
def sub_hmm(self, states):
r""" Returns HMM on a subset of states
Returns the HMM restricted to the selected subset of states.
Will raise exception if the hidden transition matrix cannot be normalized on this subset
"""
# restrict initial distribution
pi_sub = self._Pi[... | r""" Returns HMM on a subset of states
Returns the HMM restricted to the selected subset of states.
Will raise exception if the hidden transition matrix cannot be normalized on this subset | entailment |
def count_matrix(self):
# TODO: does this belong here or to the BHMM sampler, or in a subclass containing HMM with data?
"""Compute the transition count matrix from hidden state trajectory.
Returns
-------
C : numpy.array with shape (nstates,nstates)
C[i,j] is the nu... | Compute the transition count matrix from hidden state trajectory.
Returns
-------
C : numpy.array with shape (nstates,nstates)
C[i,j] is the number of transitions observed from state i to state j
Raises
------
RuntimeError
A RuntimeError is raise... | entailment |
def count_init(self):
"""Compute the counts at the first time step
Returns
-------
n : ndarray(nstates)
n[i] is the number of trajectories starting in state i
"""
if self.hidden_state_trajectories is None:
raise RuntimeError('HMM model does not h... | Compute the counts at the first time step
Returns
-------
n : ndarray(nstates)
n[i] is the number of trajectories starting in state i | entailment |
def collect_observations_in_state(self, observations, state_index):
# TODO: this would work well in a subclass with data
"""Collect a vector of all observations belonging to a specified hidden state.
Parameters
----------
observations : list of numpy.array
List of ob... | Collect a vector of all observations belonging to a specified hidden state.
Parameters
----------
observations : list of numpy.array
List of observed trajectories.
state_index : int
The index of the hidden state for which corresponding observations are to be retr... | entailment |
def generate_synthetic_state_trajectory(self, nsteps, initial_Pi=None, start=None, stop=None, dtype=np.int32):
"""Generate a synthetic state trajectory.
Parameters
----------
nsteps : int
Number of steps in the synthetic state trajectory to be generated.
initial_Pi :... | Generate a synthetic state trajectory.
Parameters
----------
nsteps : int
Number of steps in the synthetic state trajectory to be generated.
initial_Pi : np.array of shape (nstates,), optional, default=None
The initial probability distribution, if samples are not... | entailment |
def generate_synthetic_observation_trajectory(self, length, initial_Pi=None):
"""Generate a synthetic realization of observables.
Parameters
----------
length : int
Length of synthetic state trajectory to be generated.
initial_Pi : np.array of shape (nstates,), optio... | Generate a synthetic realization of observables.
Parameters
----------
length : int
Length of synthetic state trajectory to be generated.
initial_Pi : np.array of shape (nstates,), optional, default=None
The initial probability distribution, if samples are not to... | entailment |
def generate_synthetic_observation_trajectories(self, ntrajectories, length, initial_Pi=None):
"""Generate a number of synthetic realization of observables from this model.
Parameters
----------
ntrajectories : int
The number of trajectories to be generated.
length :... | Generate a number of synthetic realization of observables from this model.
Parameters
----------
ntrajectories : int
The number of trajectories to be generated.
length : int
Length of synthetic state trajectory to be generated.
initial_Pi : np.array of sh... | entailment |
def nb_to_python(nb_path):
"""convert notebook to python script"""
exporter = python.PythonExporter()
output, resources = exporter.from_filename(nb_path)
return output | convert notebook to python script | entailment |
def nb_to_html(nb_path):
"""convert notebook to html"""
exporter = html.HTMLExporter(template_file='full')
output, resources = exporter.from_filename(nb_path)
header = output.split('<head>', 1)[1].split('</head>',1)[0]
body = output.split('<body>', 1)[1].split('</body>',1)[0]
# http://imgur.com... | convert notebook to html | entailment |
def p_obs(self, obs, out=None):
"""
Returns the output probabilities for an entire trajectory and all hidden states
Parameters
----------
obs : ndarray((T), dtype=int)
a discrete trajectory of length T
Return
------
p_o : ndarray (T,N)
... | Returns the output probabilities for an entire trajectory and all hidden states
Parameters
----------
obs : ndarray((T), dtype=int)
a discrete trajectory of length T
Return
------
p_o : ndarray (T,N)
the probability of generating the symbol at ti... | entailment |
def estimate(self, observations, weights):
"""
Maximum likelihood estimation of output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k) ] with K elements
A list of K observation trajectories, each having length T_k
... | Maximum likelihood estimation of output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k) ] with K elements
A list of K observation trajectories, each having length T_k
weights : [ ndarray(T_k, N) ] with K elements
A li... | entailment |
def sample(self, observations_by_state):
"""
Sample a new set of distribution parameters given a sample of observations from the given state.
The internal parameters are updated.
Parameters
----------
observations : [ numpy.array with shape (N_k,) ] with nstates elemen... | Sample a new set of distribution parameters given a sample of observations from the given state.
The internal parameters are updated.
Parameters
----------
observations : [ numpy.array with shape (N_k,) ] with nstates elements
observations[k] are all observations associate... | entailment |
def generate_observation_from_state(self, state_index):
"""
Generate a single synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
Returns
-------
... | Generate a single synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
Returns
-------
observation : float
A single observation from the given state... | entailment |
def generate_observations_from_state(self, state_index, nobs):
"""
Generate synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
nobs : int
The numbe... | Generate synthetic observation data from a given state.
Parameters
----------
state_index : int
Index of the state from which observations are to be generated.
nobs : int
The number of observations to generate.
Returns
-------
observation... | entailment |
def generate_observation_trajectory(self, s_t, dtype=None):
"""
Generate synthetic observation data from a given state sequence.
Parameters
----------
s_t : numpy.array with shape (T,) of int type
s_t[t] is the hidden state sampled at time t
Returns
... | Generate synthetic observation data from a given state sequence.
Parameters
----------
s_t : numpy.array with shape (T,) of int type
s_t[t] is the hidden state sampled at time t
Returns
-------
o_t : numpy.array with shape (T,) of type dtype
o_t[... | entailment |
def set_implementation(impl):
"""
Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"]
"""
global __impl__
if impl.lower() == 'python':
__impl__ = __IMPL_PYTHON__
elif impl.lower() == 'c':
__impl__ = __IMPL_C__
e... | Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"] | entailment |
def forward(A, pobs, pi, T=None, alpha_out=None):
"""Compute P( obs | A, B, pi ) and all forward coefficients.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability... | Compute P( obs | A, B, pi ) and all forward coefficients.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observation at time t given hidden state i
pi : ... | entailment |
def backward(A, pobs, T=None, beta_out=None):
"""Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observat... | Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observation at time t given hidden state i
T : int, optio... | entailment |
def state_probabilities(alpha, beta, T=None, gamma_out=None):
""" Calculate the (T,N)-probabilty matrix for being in state i at time t.
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
beta : ndarray((... | Calculate the (T,N)-probabilty matrix for being in state i at time t.
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
beta : ndarray((T,N), dtype = float), optional, default = None
beta[t,i] is th... | entailment |
def state_counts(gamma, T, out=None):
""" Sum the probabilities of being in state i to time t
Parameters
----------
gamma : ndarray((T,N), dtype = float), optional, default = None
gamma[t,i] is the probabilty at time t to be in state i !
T : int
number of time steps
Returns
... | Sum the probabilities of being in state i to time t
Parameters
----------
gamma : ndarray((T,N), dtype = float), optional, default = None
gamma[t,i] is the probabilty at time t to be in state i !
T : int
number of time steps
Returns
-------
count : numpy.array shape (N)
... | entailment |
def transition_counts(alpha, beta, A, pobs, T=None, out=None):
""" Sum for all t the probability to transition from state i to state j.
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
beta : ndarray((... | Sum for all t the probability to transition from state i to state j.
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
beta : ndarray((T,N), dtype = float), optional, default = None
beta[t,i] is the... | entailment |
def viterbi(A, pobs, pi):
""" Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability f... | Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm.
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observation at time t given hid... | entailment |
def sample_path(alpha, A, pobs, T=None):
""" Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations )
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
A : ndarra... | Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations )
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
A : ndarray((N,N), dtype = float)
transition matrix... | entailment |
def logger(name='BHMM', pattern='%(asctime)s %(levelname)s %(name)s: %(message)s',
date_format='%H:%M:%S', handler=logging.StreamHandler(sys.stdout)):
"""
Retrieves the logger instance associated to the given name.
:param name: The name of the logger instance.
:type name: str
:param patt... | Retrieves the logger instance associated to the given name.
:param name: The name of the logger instance.
:type name: str
:param pattern: The associated pattern.
:type pattern: str
:param date_format: The date format to be used in the pattern.
:type date_format: str
:param handler: The logg... | entailment |
def sample(self, nsamples, nburn=0, nthin=1, save_hidden_state_trajectory=False,
call_back=None):
"""Sample from the BHMM posterior.
Parameters
----------
nsamples : int
The number of samples to generate.
nburn : int, optional, default=0
Th... | Sample from the BHMM posterior.
Parameters
----------
nsamples : int
The number of samples to generate.
nburn : int, optional, default=0
The number of samples to discard to burn-in, following which `nsamples` will be generated.
nthin : int, optional, defa... | entailment |
def _update(self):
"""Update the current model using one round of Gibbs sampling.
"""
initial_time = time.time()
self._updateHiddenStateTrajectories()
self._updateEmissionProbabilities()
self._updateTransitionMatrix()
final_time = time.time()
elapsed_ti... | Update the current model using one round of Gibbs sampling. | entailment |
def _updateHiddenStateTrajectories(self):
"""Sample a new set of state trajectories from the conditional distribution P(S | T, E, O)
"""
self.model.hidden_state_trajectories = list()
for trajectory_index in range(self.nobs):
hidden_state_trajectory = self._sampleHiddenStateT... | Sample a new set of state trajectories from the conditional distribution P(S | T, E, O) | entailment |
def _sampleHiddenStateTrajectory(self, obs, dtype=np.int32):
"""Sample a hidden state trajectory from the conditional distribution P(s | T, E, o)
Parameters
----------
o_t : numpy.array with dimensions (T,)
observation[n] is the nth observation
dtype : numpy.dtype, o... | Sample a hidden state trajectory from the conditional distribution P(s | T, E, o)
Parameters
----------
o_t : numpy.array with dimensions (T,)
observation[n] is the nth observation
dtype : numpy.dtype, optional, default=numpy.int32
The dtype to to use for returne... | entailment |
def _updateEmissionProbabilities(self):
"""Sample a new set of emission probabilites from the conditional distribution P(E | S, O)
"""
observations_by_state = [self.model.collect_observations_in_state(self.observations, state)
for state in range(self.model.nstat... | Sample a new set of emission probabilites from the conditional distribution P(E | S, O) | entailment |
def _updateTransitionMatrix(self):
"""
Updates the hidden-state transition matrix and the initial distribution
"""
# TRANSITION MATRIX
C = self.model.count_matrix() + self.prior_C # posterior count matrix
# check if we work with these options
if self.reversible... | Updates the hidden-state transition matrix and the initial distribution | entailment |
def _generateInitialModel(self, output_model_type):
"""Initialize using an MLHMM.
"""
logger().info("Generating initial model for BHMM using MLHMM...")
from bhmm.estimators.maximum_likelihood import MaximumLikelihoodEstimator
mlhmm = MaximumLikelihoodEstimator(self.observations,... | Initialize using an MLHMM. | entailment |
def ensure_dtraj(dtraj):
r"""Makes sure that dtraj is a discrete trajectory (array of int)
"""
if is_int_vector(dtraj):
return dtraj
elif is_list_of_int(dtraj):
return np.array(dtraj, dtype=int)
else:
raise TypeError('Argument dtraj is not a discrete trajectory - only list o... | r"""Makes sure that dtraj is a discrete trajectory (array of int) | entailment |
def ensure_dtraj_list(dtrajs):
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
"""
if isinstance(dtrajs, list):
# elements are ints? then wrap into a list
if is_list_of_int(dtrajs):
return [np.array(dtrajs, dtype=int)]
else:
for i... | r"""Makes sure that dtrajs is a list of discrete trajectories (array of int) | entailment |
def connected_sets(C, mincount_connectivity=0, strong=True):
""" Computes the connected sets of C.
C : count matrix
mincount_connectivity : float
Minimum count which counts as a connection.
strong : boolean
True: Seek strongly connected sets. False: Seek weakly connected sets.
"""
... | Computes the connected sets of C.
C : count matrix
mincount_connectivity : float
Minimum count which counts as a connection.
strong : boolean
True: Seek strongly connected sets. False: Seek weakly connected sets. | entailment |
def closed_sets(C, mincount_connectivity=0):
""" Computes the strongly connected closed sets of C """
n = np.shape(C)[0]
S = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=True)
closed = []
for s in S:
mask = np.zeros(n, dtype=bool)
mask[s] = True
if C[... | Computes the strongly connected closed sets of C | entailment |
def nonempty_set(C, mincount_connectivity=0):
""" Returns the set of states that have at least one incoming or outgoing count """
# truncate to states with at least one observed incoming or outgoing count.
if mincount_connectivity > 0:
C = C.copy()
C[np.where(C < mincount_connectivity)] = 0
... | Returns the set of states that have at least one incoming or outgoing count | entailment |
def estimate_P(C, reversible=True, fixed_statdist=None, maxiter=1000000, maxerr=1e-8, mincount_connectivity=0):
""" Estimates full transition matrix for general connectivity structure
Parameters
----------
C : ndarray
count matrix
reversible : bool
estimate reversible?
fixed_sta... | Estimates full transition matrix for general connectivity structure
Parameters
----------
C : ndarray
count matrix
reversible : bool
estimate reversible?
fixed_statdist : ndarray or None
estimate with given stationary distribution
maxiter : int
Maximum number of ... | entailment |
def transition_matrix_partial_rev(C, P, S, maxiter=1000000, maxerr=1e-8):
"""Maximum likelihood estimation of transition matrix which is reversible on parts
Partially-reversible estimation of transition matrix. Maximizes the likelihood:
.. math:
P_S &=& arg max prod_{S, :} (p_ij)^c_ij \\
\... | Maximum likelihood estimation of transition matrix which is reversible on parts
Partially-reversible estimation of transition matrix. Maximizes the likelihood:
.. math:
P_S &=& arg max prod_{S, :} (p_ij)^c_ij \\
\Pi_S P_{S,S} &=& \Pi_S P_{S,S}
where the product runs over all elements of t... | entailment |
def enforce_reversible_on_closed(P):
""" Enforces transition matrix P to be reversible on its closed sets. """
import msmtools.analysis as msmana
n = np.shape(P)[0]
Prev = P.copy()
# treat each weakly connected set separately
sets = closed_sets(P)
for s in sets:
I = np.ix_(s, s)
... | Enforces transition matrix P to be reversible on its closed sets. | entailment |
def is_reversible(P):
""" Returns if P is reversible on its weakly connected sets """
import msmtools.analysis as msmana
# treat each weakly connected set separately
sets = connected_sets(P, strong=False)
for s in sets:
Ps = P[s, :][:, s]
if not msmana.is_transition_matrix(Ps):
... | Returns if P is reversible on its weakly connected sets | entailment |
def stationary_distribution(P, C=None, mincount_connectivity=0):
""" Simple estimator for stationary distribution for multiple strongly connected sets """
# can be replaced by msmtools.analysis.stationary_distribution in next msmtools release
from msmtools.analysis.dense.stationary_vector import stationary_... | Simple estimator for stationary distribution for multiple strongly connected sets | entailment |
def means_samples(self):
r""" Samples of the Gaussian distribution means """
res = np.empty((self.nsamples, self.nstates, self.dimension), dtype=config.dtype)
for i in range(self.nsamples):
for j in range(self.nstates):
res[i, j, :] = self._sampled_hmms[i].means[j]
... | r""" Samples of the Gaussian distribution means | entailment |
def sigmas_samples(self):
r""" Samples of the Gaussian distribution standard deviations """
res = np.empty((self.nsamples, self.nstates, self.dimension), dtype=config.dtype)
for i in range(self.nsamples):
for j in range(self.nstates):
res[i, j, :] = self._sampled_hmms... | r""" Samples of the Gaussian distribution standard deviations | entailment |
def _guess_output_type(observations):
""" Suggests a HMM model type based on the observation data
Uses simple rules in order to decide which HMM model type makes sense based on observation data.
If observations consist of arrays/lists of integer numbers (irrespective of whether the python type is
int o... | Suggests a HMM model type based on the observation data
Uses simple rules in order to decide which HMM model type makes sense based on observation data.
If observations consist of arrays/lists of integer numbers (irrespective of whether the python type is
int or float), our guess is 'discrete'.
If obse... | entailment |
def lag_observations(observations, lag, stride=1):
r""" Create new trajectories that are subsampled at lag but shifted
Given a trajectory (s0, s1, s2, s3, s4, ...) and lag 3, this function will generate 3 trajectories
(s0, s3, s6, ...), (s1, s4, s7, ...) and (s2, s5, s8, ...). Use this function in order to... | r""" Create new trajectories that are subsampled at lag but shifted
Given a trajectory (s0, s1, s2, s3, s4, ...) and lag 3, this function will generate 3 trajectories
(s0, s3, s6, ...), (s1, s4, s7, ...) and (s2, s5, s8, ...). Use this function in order to parametrize a MLE
at lag times larger than 1 witho... | entailment |
def gaussian_hmm(pi, P, means, sigmas):
""" Initializes a 1D-Gaussian HMM
Parameters
----------
pi : ndarray(nstates, )
Initial distribution.
P : ndarray(nstates,nstates)
Hidden transition matrix
means : ndarray(nstates, )
Means of Gaussian output distributions
sigma... | Initializes a 1D-Gaussian HMM
Parameters
----------
pi : ndarray(nstates, )
Initial distribution.
P : ndarray(nstates,nstates)
Hidden transition matrix
means : ndarray(nstates, )
Means of Gaussian output distributions
sigmas : ndarray(nstates, )
Standard deviatio... | entailment |
def discrete_hmm(pi, P, pout):
""" Initializes a discrete HMM
Parameters
----------
pi : ndarray(nstates, )
Initial distribution.
P : ndarray(nstates,nstates)
Hidden transition matrix
pout : ndarray(nstates,nsymbols)
Output matrix from hidden states to observable symbols... | Initializes a discrete HMM
Parameters
----------
pi : ndarray(nstates, )
Initial distribution.
P : ndarray(nstates,nstates)
Hidden transition matrix
pout : ndarray(nstates,nsymbols)
Output matrix from hidden states to observable symbols
pi : ndarray(nstates, )
Fi... | entailment |
def init_hmm(observations, nstates, lag=1, output=None, reversible=True):
"""Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
ou... | Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
output : str, optional, default=None
Output model type from [None, 'gaussia... | entailment |
def init_gaussian_hmm(observations, nstates, lag=1, reversible=True):
""" Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
Exam... | Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
Examples
--------
Generate initial model for a gaussian output model.
... | entailment |
def init_discrete_hmm(observations, nstates, lag=1, reversible=True, stationary=True, regularize=True,
method='connect-spectral', separate=None):
"""Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arr... | Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
lag : int
Lag time at which the observations should be counted.
reversi... | entailment |
def estimate_hmm(observations, nstates, lag=1, initial_model=None, output=None,
reversible=True, stationary=False, p=None, accuracy=1e-3, maxit=1000, maxit_P=100000,
mincount_connectivity=1e-2):
r""" Estimate maximum-likelihood HMM
Generic maximum-likelihood estimation of HMMs... | r""" Estimate maximum-likelihood HMM
Generic maximum-likelihood estimation of HMMs
Parameters
----------
observations : list of numpy arrays representing temporal data
`observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i`
nstates : int
The number ... | entailment |
def bayesian_hmm(observations, estimated_hmm, nsample=100, reversible=True, stationary=False,
p0_prior='mixed', transition_matrix_prior='mixed', store_hidden=False, call_back=None):
r""" Bayesian HMM based on sampling the posterior
Generic maximum-likelihood estimation of HMMs
Parameters
... | r""" Bayesian HMM based on sampling the posterior
Generic maximum-likelihood estimation of HMMs
Parameters
----------
observations : list of numpy arrays representing temporal data
`observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i`
estimated_hmm : HMM
... | entailment |
def logsumexp(arr, axis=0):
"""Computes the sum of arr assuming arr is in the log domain.
Returns log(sum(exp(arr))) while minimizing the possibility of
over/underflow.
Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import logsumexp
>>> a = np.arange(10)
>... | Computes the sum of arr assuming arr is in the log domain.
Returns log(sum(exp(arr))) while minimizing the possibility of
over/underflow.
Examples
--------
>>> import numpy as np
>>> from sklearn.utils.extmath import logsumexp
>>> a = np.arange(10)
>>> np.log(np.sum(np.exp(a)))
9.... | entailment |
def _ensure_sparse_format(spmatrix, accept_sparse, dtype, order, copy,
force_all_finite):
"""Convert a sparse matrix to a given format.
Checks the sparse format of spmatrix and converts if necessary.
Parameters
----------
spmatrix : scipy sparse matrix
Input to va... | Convert a sparse matrix to a given format.
Checks the sparse format of spmatrix and converts if necessary.
Parameters
----------
spmatrix : scipy sparse matrix
Input to validate and convert.
accept_sparse : string, list of string or None (default=None)
String[s] representing allow... | entailment |
def check_array(array, accept_sparse=None, dtype="numeric", order=None,
copy=False, force_all_finite=True, ensure_2d=True,
allow_nd=False, ensure_min_samples=1, ensure_min_features=1):
"""Input validation on an array, list, sparse matrix or similar.
By default, the input is conv... | Input validation on an array, list, sparse matrix or similar.
By default, the input is converted to an at least 2nd numpy array.
If the dtype of the array is object, attempt converting to float,
raising on failure.
Parameters
----------
array : object
Input object to check / convert.
... | entailment |
def beta_confidence_intervals(ci_X, ntrials, ci=0.95):
"""
Compute confidence intervals of beta distributions.
Parameters
----------
ci_X : numpy.array
Computed confidence interval estimate from `ntrials` experiments
ntrials : int
The number of trials that were run.
ci : flo... | Compute confidence intervals of beta distributions.
Parameters
----------
ci_X : numpy.array
Computed confidence interval estimate from `ntrials` experiments
ntrials : int
The number of trials that were run.
ci : float, optional, default=0.95
Confidence interval to report (e... | entailment |
def empirical_confidence_interval(sample, interval=0.95):
"""
Compute specified symmetric confidence interval for empirical sample.
Parameters
----------
sample : numpy.array
The empirical samples.
interval : float, optional, default=0.95
Size of desired symmetric confidence int... | Compute specified symmetric confidence interval for empirical sample.
Parameters
----------
sample : numpy.array
The empirical samples.
interval : float, optional, default=0.95
Size of desired symmetric confidence interval (0 < interval < 1)
e.g. 0.68 for 68% confidence interval... | entailment |
def generate_latex_table(sampled_hmm, conf=0.95, dt=1, time_unit='ms', obs_name='force', obs_units='pN',
caption='', outfile=None):
"""
Generate a LaTeX column-wide table showing various computed properties and uncertainties.
Parameters
----------
conf : float
confi... | Generate a LaTeX column-wide table showing various computed properties and uncertainties.
Parameters
----------
conf : float
confidence interval. Use 0.68 for 1 sigma, 0.95 for 2 sigma etc. | entailment |
def confidence_interval(data, alpha):
"""
Computes the mean and alpha-confidence interval of the given sample set
Parameters
----------
data : ndarray
a 1D-array of samples
alpha : float in [0,1]
the confidence level, i.e. percentage of data included in the interval
... | Computes the mean and alpha-confidence interval of the given sample set
Parameters
----------
data : ndarray
a 1D-array of samples
alpha : float in [0,1]
the confidence level, i.e. percentage of data included in the interval
Returns
-------
[m,l,r] where m is the me... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.