INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a generator type object whose each iteration yields a sample
def generate_sample(self, initial_pos, num_adapt, num_samples, stepsize=None): """ Returns a generator type object whose each iteration yields a sample Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the sta...
Discretizes the continuous distribution into discrete probability masses using various methods.
def discretize(self, method, *args, **kwargs): """ Discretizes the continuous distribution into discrete probability masses using various methods. Parameters ---------- method : A Discretizer Class from pgmpy.discretize *args, **kwargs: The parameter...
Reduces the factor to the context of the given variable values.
def reduce(self, values, inplace=True): """ Reduces the factor to the context of the given variable values. Parameters ---------- values: list, array-like A list of tuples of the form (variable_name, variable_value). inplace: boolean If inplace=T...
Marginalize the factor with respect to the given variables.
def marginalize(self, variables, inplace=True): """ Marginalize the factor with respect to the given variables. Parameters ---------- variables: list, array-like List of variables with respect to which factor is to be maximized. inplace: boolean ...
Normalizes the pdf of the continuous factor so that it integrates to 1 over all the variables.
def normalize(self, inplace=True): """ Normalizes the pdf of the continuous factor so that it integrates to 1 over all the variables. Parameters ---------- inplace: boolean If inplace=True it will modify the factor itself, else would return a new ...
Gives the ContinuousFactor operation ( product or divide ) with the other factor.
def _operate(self, other, operation, inplace=True): """ Gives the ContinuousFactor operation (product or divide) with the other factor. Parameters ---------- other: ContinuousFactor The ContinuousFactor to be multiplied. operation: String ...
Gives the ContinuousFactor divide with the other factor.
def divide(self, other, inplace=True): """ Gives the ContinuousFactor divide with the other factor. Parameters ---------- other: ContinuousFactor The ContinuousFactor to be divided. Returns ------- ContinuousFactor or None: ...
Returns factor product over args.
def factor_product(*args): """ Returns factor product over `args`. Parameters ---------- args: `BaseFactor` instances. factors to be multiplied Returns ------- BaseFactor: `BaseFactor` representing factor product over all the `BaseFactor` instances in args. Examples --...
Returns DiscreteFactor representing phi1/ phi2.
def factor_divide(phi1, phi2): """ Returns `DiscreteFactor` representing `phi1 / phi2`. Parameters ---------- phi1: Factor The Dividend. phi2: Factor The Divisor. Returns ------- DiscreteFactor: `DiscreteFactor` representing factor division `phi1 / phi2`. Exam...
Method to estimate the model parameters ( CPDs ).
def get_parameters(self, prior_type='BDeu', equivalent_sample_size=5, pseudo_counts=None): """ Method to estimate the model parameters (CPDs). Parameters ---------- prior_type: 'dirichlet', 'BDeu', or 'K2' string indicting which type of prior to use for the model par...
Method to estimate the CPD for a given variable.
def estimate_cpd(self, node, prior_type='BDeu', pseudo_counts=[], equivalent_sample_size=5): """ Method to estimate the CPD for a given variable. Parameters ---------- node: int, string (any hashable python object) The name of the variable for which the CPD is to be ...
Generates sample ( s ) from joint distribution of the bayesian network.
def forward_sample(self, size=1, return_type='dataframe'): """ Generates sample(s) from joint distribution of the bayesian network. Parameters ---------- size: int size of sample to be generated return_type: string (dataframe | recarray) Return t...
Generates sample ( s ) from joint distribution of the bayesian network given the evidence.
def rejection_sample(self, evidence=None, size=1, return_type="dataframe"): """ Generates sample(s) from joint distribution of the bayesian network, given the evidence. Parameters ---------- evidence: list of `pgmpy.factor.State` namedtuples None if no eviden...
Generates weighted sample ( s ) from joint distribution of the bayesian network that comply with the given evidence. Probabilistic Graphical Model Principles and Techniques Koller and Friedman Algorithm 12. 2 pp 493.
def likelihood_weighted_sample(self, evidence=None, size=1, return_type="dataframe"): """ Generates weighted sample(s) from joint distribution of the bayesian network, that comply with the given evidence. 'Probabilistic Graphical Model Principles and Techniques', Koller and Fried...
Computes the Gibbs transition models from a Bayesian Network. Probabilistic Graphical Model Principles and Techniques Koller and Friedman Section 12. 3. 3 pp 512 - 513.
def _get_kernel_from_bayesian_model(self, model): """ Computes the Gibbs transition models from a Bayesian Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: BayesianM...
Computes the Gibbs transition models from a Markov Network. Probabilistic Graphical Model Principles and Techniques Koller and Friedman Section 12. 3. 3 pp 512 - 513.
def _get_kernel_from_markov_model(self, model): """ Computes the Gibbs transition models from a Markov Network. 'Probabilistic Graphical Model Principles and Techniques', Koller and Friedman, Section 12.3.3 pp 512-513. Parameters: ----------- model: MarkovModel ...
Sample from the Markov Chain.
def sample(self, start_state=None, size=1, return_type="dataframe"): """ Sample from the Markov Chain. Parameters: ----------- start_state: dict or array-like iterable Representing the starting states of the variables. If None is passed, a random start_state is chose...
Generator version of self. sample
def generate_sample(self, start_state=None, size=1): """ Generator version of self.sample Return Type: ------------ List of State namedtuples, representing the assignment to all variables of the model. Examples: --------- >>> from pgmpy.factors.discrete ...
Return a list of states that the variable takes in the data
def _collect_state_names(self, variable): "Return a list of states that the variable takes in the data" states = sorted(list(self.data.ix[:, variable].dropna().unique())) return states
Return counts how often each state of variable occured in the data. If a list of parents is provided counting is done conditionally for each state configuration of the parents.
def state_counts(self, variable, parents=[], complete_samples_only=None): """ Return counts how often each state of 'variable' occured in the data. If a list of parents is provided, counting is done conditionally for each state configuration of the parents. Parameters --...
Return counts how often each state of variable occured in the data. If the variable has parents counting is done conditionally for each state configuration of the parents.
def state_counts(self, variable, **kwargs): """ Return counts how often each state of 'variable' occured in the data. If the variable has parents, counting is done conditionally for each state configuration of the parents. Parameters ---------- variable: string ...
Add a single node to the cluster graph.
def add_node(self, node, **kwargs): """ Add a single node to the cluster graph. Parameters ---------- node: node A node should be a collection of nodes forming a clique. It can be a list, set or tuple of nodes Examples -------- >>...
Add multiple nodes to the cluster graph.
def add_nodes_from(self, nodes, **kwargs): """ Add multiple nodes to the cluster graph. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, etc.). Examples -------- >>> from pgmpy.models import ClusterGraph ...
Add an edge between two clique nodes.
def add_edge(self, u, v, **kwargs): """ Add an edge between two clique nodes. Parameters ---------- u, v: nodes Nodes can be any list or set or tuple of nodes forming a clique. Examples -------- >>> from pgmpy.models import ClusterGraph ...
Associate a factor to the graph. See factors class for the order of potential values
def add_factors(self, *factors): """ Associate a factor to the graph. See factors class for the order of potential values Parameters ---------- *factor: pgmpy.factors.factors object A factor object on any subset of the variables of the model which ...
Return the factors that have been added till now to the graph.
def get_factors(self, node=None): """ Return the factors that have been added till now to the graph. If node is not None, it would return the factor corresponding to the given node. Examples -------- >>> from pgmpy.models import ClusterGraph >>> from pgm...
Returns the cardinality of the node
def get_cardinality(self, node=None): """ Returns the cardinality of the node Parameters ---------- node: any hashable python object (optional) The node whose cardinality we want. If node is not specified returns a dictionary with the given variable as ke...
r Returns the partition function for a given undirected graph.
def get_partition_function(self): r""" Returns the partition function for a given undirected graph. A partition function is defined as .. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i) where m is the number of factors present in the graph and X are all the random variables pr...
Check the model for various errors. This method checks for the following errors.
def check_model(self): """ Check the model for various errors. This method checks for the following errors. * Checks if factors are defined for all the cliques or not. * Check for running intersection property is not done explicitly over here as it done in the add_edge...
Returns a copy of ClusterGraph.
def copy(self): """ Returns a copy of ClusterGraph. Returns ------- ClusterGraph: copy of ClusterGraph Examples ------- >>> from pgmpy.factors.discrete import DiscreteFactor >>> G = ClusterGraph() >>> G.add_nodes_from([('a', 'b'), ('b', '...
This is the message - update method.
def _update_message(self, sending_cluster): """ This is the message-update method. Parameters ---------- sending_cluster: The resulting messages are lambda_{c-->s} from the given cluster 'c' to all of its intersection_sets 's'. Here 's' are the elements ...
Finds the index of the maximum values for all the single node dual objectives.
def _local_decode(self): """ Finds the index of the maximum values for all the single node dual objectives. Reference: code presented by Sontag in 2012 here: http://cs.nyu.edu/~dsontag/code/README_v2.html """ # The current assignment of the single node factors is stored ...
This method checks the integrality gap to ensure either: * we have found a near to exact solution or * stuck on a local minima.
def _is_converged(self, dual_threshold=None, integrality_gap_threshold=None): """ This method checks the integrality gap to ensure either: * we have found a near to exact solution or * stuck on a local minima. Parameters ---------- dual_threshold: double ...
Finds all the triangles present in the given model
def find_triangles(self): """ Finds all the triangles present in the given model Examples -------- >>> from pgmpy.models import MarkovModel >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.inference import Mplp >>> mm = MarkovModel() ...
From a set of variables forming a triangle in the model we form the corresponding Clusters. These clusters are then appended to the code.
def _update_triangles(self, triangles_list): """ From a set of variables forming a triangle in the model, we form the corresponding Clusters. These clusters are then appended to the code. Parameters ---------- triangle_list : list The list of vari...
Returns the score of each of the triplets found in the current model
def _get_triplet_scores(self, triangles_list): """ Returns the score of each of the triplets found in the current model Parameters --------- triangles_list: list The list of variables forming the triangles to be updated. It is of the form of ...
Updates messages until either Mplp converges or if doesn t converges ; halts after no_iterations.
def _run_mplp(self, no_iterations): """ Updates messages until either Mplp converges or if doesn't converges; halts after no_iterations. Parameters -------- no_iterations: integer Number of maximum iterations that we want MPLP to run. """ ...
This method finds all the triplets that are eligible and adds them iteratively in the bunch of max_triplets
def _tighten_triplet(self, max_iterations, later_iter, max_triplets, prolong): """ This method finds all the triplets that are eligible and adds them iteratively in the bunch of max_triplets Parameters ---------- max_iterations: integer Maximum number of ...
MAP query method using Max Product LP method. This returns the best assignment of the nodes in the form of a dictionary.
def map_query(self, init_iter=1000, later_iter=20, dual_threshold=0.0002, integrality_gap_threshold=0.0002, tighten_triplet=True, max_triplets=5, max_iterations=100, prolong=False): """ MAP query method using Max Product LP method. This returns the best assignment of the nodes ...
Add an edge between u and v.
def add_edge(self, u, v, **kwargs): """ Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph Parameters ---------- u,v : nodes Nodes can be any hashable Python object. Examples ...
Associate a factor to the graph. See factors class for the order of potential values
def add_factors(self, *factors): """ Associate a factor to the graph. See factors class for the order of potential values Parameters ---------- *factor: pgmpy.factors.factors object A factor object on any subset of the variables of the model which ...
Returns all the factors containing the node. If node is not specified returns all the factors that have been added till now to the graph.
def get_factors(self, node=None): """ Returns all the factors containing the node. If node is not specified returns all the factors that have been added till now to the graph. Parameter --------- node: any hashable python object (optional) The node whose fact...
Check the model for various errors. This method checks for the following errors -
def check_model(self): """ Check the model for various errors. This method checks for the following errors - * Checks if the cardinalities of all the variables are consistent across all the factors. * Factors are defined for all the random variables. Returns ---...
Converts the markov model into factor graph.
def to_factor_graph(self): """ Converts the markov model into factor graph. A factor graph contains two types of nodes. One type corresponds to random variables whereas the second type corresponds to factors over these variables. The graph only contains edges between variables a...
Triangulate the graph.
def triangulate(self, heuristic='H6', order=None, inplace=False): """ Triangulate the graph. If order of deletion is given heuristic algorithm will not be used. Parameters ---------- heuristic: H1 | H2 | H3 | H4 | H5 | H6 The heuristic algorithm to use to de...
Creates a junction tree ( or clique tree ) for a given markov model.
def to_junction_tree(self): """ Creates a junction tree (or clique tree) for a given markov model. For a given markov model (H) a junction tree (G) is a graph 1. where each node in G corresponds to a maximal clique in H 2. each sepset in G separates the variables strictly on one...
Returns all the local independencies present in the markov model.
def get_local_independencies(self, latex=False): """ Returns all the local independencies present in the markov model. Local independencies are the independence assertion in the form of .. math:: {X \perp W - {X} - MB(X) | MB(X)} where MB is the markov blanket of all the random ...
Creates a Bayesian Model which is a minimum I - Map for this markov model.
def to_bayesian_model(self): """ Creates a Bayesian Model which is a minimum I-Map for this markov model. The ordering of parents may not remain constant. It would depend on the ordering of variable in the junction tree (which is not constant) all the time. Examples ...
Returns the partition function for a given undirected graph.
def get_partition_function(self): """ Returns the partition function for a given undirected graph. A partition function is defined as .. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i) where m is the number of factors present in the graph and X are all the random variables pre...
Returns a copy of this Markov Model.
def copy(self): """ Returns a copy of this Markov Model. Returns ------- MarkovModel: Copy of this Markov model. Examples ------- >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.models import MarkovModel >>> G = Marko...
Returns the probability density function ( pdf ).
def pdf(self): """ Returns the probability density function(pdf). Returns ------- function: The probability density function of the distribution. Examples -------- >>> from pgmpy.factors.distributions import GaussianDistribution >>> dist = GD(var...
Returns the precision matrix of the distribution.
def precision_matrix(self): """ Returns the precision matrix of the distribution. Precision is defined as the inverse of the variance. This method returns the inverse matrix of the covariance. Examples -------- >>> import numpy as np >>> from pgmpy.facto...
Modifies the distribution with marginalized values.
def marginalize(self, variables, inplace=True): """ Modifies the distribution with marginalized values. Parameters ---------- variables: iterator over any hashable object. List of variables over which marginalization is to be done. inplace: boolean ...
Reduces the distribution to the context of the given variable values.
def reduce(self, values, inplace=True): """ Reduces the distribution to the context of the given variable values. The formula for the obtained conditional distribution is given by - For, .. math:: N(X_j | X_i = x_i) ~ N(mu_{j.i} ; sig_{j.i}) where, .. math:: mu...
Normalizes the distribution. In case of a Gaussian Distribution the distribution is always normalized therefore this method doesn t do anything and has been implemented only for a consistent API across distributions.
def normalize(self, inplace=True): """ Normalizes the distribution. In case of a Gaussian Distribution the distribution is always normalized, therefore this method doesn't do anything and has been implemented only for a consistent API across distributions. """ phi...
Return a copy of the distribution.
def copy(self): """ Return a copy of the distribution. Returns ------- GaussianDistribution: copy of the distribution Examples -------- >>> import numpy as np >>> from pgmpy.factors.distributions import GaussianDistribution as GD >>> gaus...
u Returns an equivalent CanonicalDistribution object.
def to_canonical_factor(self): u""" Returns an equivalent CanonicalDistribution object. The formulas for calculating the cannonical factor parameters for N(μ; Σ) = C(K; h; g) are as follows - K = sigma^(-1) h = sigma^(-1) * mu g = -(0.5) * mu.T * sigma^(-1) * mu...
Gives the CanonicalDistribution operation ( product or divide ) with the other factor.
def _operate(self, other, operation, inplace=True): """ Gives the CanonicalDistribution operation (product or divide) with the other factor. Parameters ---------- other: CanonicalDistribution The CanonicalDistribution to be multiplied. operation: Str...
TODO: Make it work when using * instead of product.
def product(self, other, inplace=True): """ TODO: Make it work when using `*` instead of product. Returns the product of two gaussian distributions. Parameters ---------- other: GaussianDistribution The GaussianDistribution to be multiplied. inplace...
Returns the division of two gaussian distributions.
def divide(self, other, inplace=True): """ Returns the division of two gaussian distributions. Parameters ---------- other: GaussianDistribution The GaussianDistribution to be divided. inplace: boolean If True, modifies the distribution itself, o...
Discretizes the continuous distribution into discrete probability masses using specified method.
def discretize(self, method, *args, **kwargs): """ Discretizes the continuous distribution into discrete probability masses using specified method. Parameters ---------- method: string, BaseDiscretizer instance A Discretizer Class from pgmpy.factors.discretiz...
Reduces the factor to the context of the given variable values.
def reduce(self, values, inplace=True): """ Reduces the factor to the context of the given variable values. Parameters ---------- values: list, array-like A list of tuples of the form (variable_name, variable_value). inplace: boolean If inplace=T...
Marginalize the distribution with respect to the given variables.
def marginalize(self, variables, inplace=True): """ Marginalize the distribution with respect to the given variables. Parameters ---------- variables: list, array-like List of variables to be removed from the marginalized distribution. inplace: boolean ...
Normalizes the pdf of the distribution so that it integrates to 1 over all the variables.
def normalize(self, inplace=True): """ Normalizes the pdf of the distribution so that it integrates to 1 over all the variables. Parameters ---------- inplace: boolean If inplace=True it will modify the distribution itself, else would return a new...
Gives the CustomDistribution operation ( product or divide ) with the other distribution.
def _operate(self, other, operation, inplace=True): """ Gives the CustomDistribution operation (product or divide) with the other distribution. Parameters ---------- other: CustomDistribution The CustomDistribution to be multiplied. operation: str ...
Implementation of a generalized variable elimination.
def _variable_elimination(self, variables, operation, evidence=None, elimination_order=None, joint=True): """ Implementation of a generalized variable elimination. Parameters ---------- variables: list, array-like variables that are not to be eliminated. oper...
Parameters ---------- variables: list list of variables for which you want to compute the probability
def query(self, variables, evidence=None, elimination_order=None, joint=True): """ Parameters ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict key, value pair as {var: state_of_var_observed} ...
Computes the max - marginal over the variables given the evidence.
def max_marginal(self, variables=None, evidence=None, elimination_order=None): """ Computes the max-marginal over the variables given the evidence. Parameters ---------- variables: list list of variables over which we want to compute the max-marginal. evidenc...
Computes the MAP Query over the variables given the evidence.
def map_query(self, variables=None, evidence=None, elimination_order=None): """ Computes the MAP Query over the variables given the evidence. Note: When multiple variables are passed, it returns the map_query for each of them individually. Parameters ---------- ...
Returns the induced graph formed by running Variable Elimination on the network.
def induced_graph(self, elimination_order): """ Returns the induced graph formed by running Variable Elimination on the network. Parameters ---------- elimination_order: list, array like List of variables in the order in which they are to be eliminated. Exam...
Returns the width ( integer ) of the induced graph formed by running Variable Elimination on the network. The width is the defined as the number of nodes in the largest clique in the graph minus 1.
def induced_width(self, elimination_order): """ Returns the width (integer) of the induced graph formed by running Variable Elimination on the network. The width is the defined as the number of nodes in the largest clique in the graph minus 1. Parameters ---------- elimi...
This is belief - update method.
def _update_beliefs(self, sending_clique, recieving_clique, operation): """ This is belief-update method. Parameters ---------- sending_clique: node (as the operation is on junction tree, node should be a tuple) Node sending the message recieving_clique: node...
Checks whether the calibration has converged or not. At convergence the sepset belief would be precisely the sepset marginal.
def _is_converged(self, operation): """ Checks whether the calibration has converged or not. At convergence the sepset belief would be precisely the sepset marginal. Parameters ---------- operation: str ('marginalize' | 'maximize') The operation to do for pas...
Generalized calibration of junction tree or clique using belief propagation. This method can be used for both calibrating as well as max - calibrating. Uses Lauritzen - Spiegelhalter algorithm or belief - update message passing.
def _calibrate_junction_tree(self, operation): """ Generalized calibration of junction tree or clique using belief propagation. This method can be used for both calibrating as well as max-calibrating. Uses Lauritzen-Spiegelhalter algorithm or belief-update message passing. Param...
This is a generalized query method that can be used for both query and map query.
def _query(self, variables, operation, evidence=None, joint=True): """ This is a generalized query method that can be used for both query and map query. Parameters ---------- variables: list list of variables for which you want to compute the probability oper...
Query method using belief propagation.
def query(self, variables, evidence=None, joint=True): """ Query method using belief propagation. Parameters ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict key, value pair as {var:...
MAP Query method using belief propagation.
def map_query(self, variables=None, evidence=None): """ MAP Query method using belief propagation. Note: When multiple variables are passed, it returns the map_query for each of them individually. Parameters ---------- variables: list list of variabl...
Fit using MLE method.
def maximum_likelihood_estimator(self, data, states): """ Fit using MLE method. Parameters ---------- data: pandas.DataFrame or 2D array Dataframe of values containing samples from the conditional distribution, (Y|X) and corresponding X values. ...
Determine βs from data
def fit( self, data, states, estimator=None, complete_samples_only=True, **kwargs): """ Determine βs from data Parameters ---------- data: pandas.DataFrame Dataframe containing samples from the c...
Returns a copy of the distribution.
def copy(self): """ Returns a copy of the distribution. Returns ------- LinearGaussianCPD: copy of the distribution Examples -------- >>> from pgmpy.factors.continuous import LinearGaussianCPD >>> cpd = LinearGaussianCPD('Y', [0.2, -2, 3, 7], 9....
Return a segment of a horizontal line with optional colons which indicate column s alignment ( as in pipe output format ).
def _pipe_segment_with_colons(align, colwidth): """Return a segment of a horizontal line with optional colons which indicate column's alignment (as in `pipe` output format).""" w = colwidth if align in ["right", "decimal"]: return ('-' * (w - 1)) + ":" elif align == "center": return ...
Return a horizontal line with optional colons to indicate column s alignment ( as in pipe output format ).
def _pipe_line_with_colons(colwidths, colaligns): """Return a horizontal line with optional colons to indicate column's alignment (as in `pipe` output format).""" segments = [_pipe_segment_with_colons(a, w) for a, w in zip(colaligns, colwidths)] return "|" + "|".join(segments) + "|"
Construct a simple TableFormat with columns separated by a separator.
def simple_separated_format(separator): """Construct a simple TableFormat with columns separated by a separator. >>> tsv = simple_separated_format("\\t") ; \ tabulate([["foo", 1], ["spam", 23]], tablefmt=tsv) == 'foo \\t 1\\nspam\\t23' True """ return TableFormat(None, None, None, None, ...
>>> _isint ( 123 ) True >>> _isint ( 123. 45 ) False
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, _text_type)) and \ _isconvertible(int, string)
Symbols after a decimal point - 1 if the string lacks the decimal point.
def _afterpoint(string): """Symbols after a decimal point, -1 if the string lacks the decimal point. >>> _afterpoint("123.45") 2 >>> _afterpoint("1001") -1 >>> _afterpoint("eggs") -1 >>> _afterpoint("123e45") 2 """ if _isnumber(string): if _isint(string): ...
Flush right.
def _padleft(width, s, has_invisible=True): """Flush right. >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' True """ iwidth = width + len(s) - len(_strip_invisible(s)) if has_invisible else width fmt = "{0:>%ds}" % iwidth return fmt.format(s)
Remove invisible ANSI color codes.
def _strip_invisible(s): "Remove invisible ANSI color codes." if isinstance(s, _text_type): return re.sub(_invisible_codes, "", s) else: # a bytestring return re.sub(_invisible_codes_bytes, "", s)
Visible width of a printed string. ANSI color codes are removed.
def _visible_width(s): """Visible width of a printed string. ANSI color codes are removed. >>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world") (5, 5) """ if isinstance(s, _text_type) or isinstance(s, _binary_type): return len(_strip_invisible(s)) else: return le...
The least generic type all column values are convertible to.
def _column_type(strings, has_invisible=True): """The least generic type all column values are convertible to. >>> _column_type(["1", "2"]) is _int_type True >>> _column_type(["1", "2.3"]) is _float_type True >>> _column_type(["1", "2.3", "four"]) is _text_type True >>> _column_type(["f...
Format row according to DataRow format without padding.
def _build_simple_row(padded_cells, rowfmt): "Format row according to DataRow format without padding." begin, sep, end = rowfmt return (begin + sep.join(padded_cells) + end).rstrip()
Return a string which represents a row of data cells.
def _build_row(padded_cells, colwidths, colaligns, rowfmt): "Return a string which represents a row of data cells." if not rowfmt: return None if hasattr(rowfmt, "__call__"): return rowfmt(padded_cells, colwidths, colaligns) else: return _build_simple_row(padded_cells, rowfmt)
Return a string which represents a horizontal line.
def _build_line(colwidths, colaligns, linefmt): "Return a string which represents a horizontal line." if not linefmt: return None if hasattr(linefmt, "__call__"): return linefmt(colwidths, colaligns) else: begin, fill, sep, end = linefmt cells = [fill*w for w in colwidth...
Produce a plain - text representation of the table.
def _format_table(fmt, headers, rows, colwidths, colaligns): """Produce a plain-text representation of the table.""" lines = [] hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else [] pad = fmt.padding headerrow = fmt.headerrow padded_widths = [(w + 2*pad) for w in colwidths...
Returns a list of strings representing the values about which the discretization method calculates the probabilty masses.
def get_labels(self): """ Returns a list of strings representing the values about which the discretization method calculates the probabilty masses. Default value is the points - [low, low+step, low+2*step, ......... , high-step] unless the method is overridden by...
This method calculates the kth order limiting moment of the distribution. It is given by -
def _lim_moment(self, u, order=1): """ This method calculates the kth order limiting moment of the distribution. It is given by - E(u) = Integral (-inf to u) [ (x^k)*pdf(x) dx ] + (u^k)(1-cdf(u)) where, pdf is the probability density function and cdf is the cumulative d...
Method to estimate the model parameters ( CPDs ) using Maximum Likelihood Estimation.
def get_parameters(self): """ Method to estimate the model parameters (CPDs) using Maximum Likelihood Estimation. Returns ------- parameters: list List of TabularCPDs, one for each variable of the model Examples -------- >>> import numpy as n...
Method to estimate the CPD for a given variable.
def estimate_cpd(self, node): """ Method to estimate the CPD for a given variable. Parameters ---------- node: int, string (any hashable python object) The name of the variable for which the CPD is to be estimated. Returns ------- CPD: Tabula...
Estimates a DAG for the data set using the PC constraint - based structure learning algorithm. Independencies are identified from the data set using a chi - squared statistic with the acceptance threshold of significance_level. PC identifies a partially directed acyclic graph ( PDAG ) given that the tested independenci...
def estimate(self, significance_level=0.01): """ Estimates a DAG for the data set, using the PC constraint-based structure learning algorithm. Independencies are identified from the data set using a chi-squared statistic with the acceptance threshold of `significance_level`. PC i...
Estimates a graph skeleton ( UndirectedGraph ) for the data set. Uses the build_skeleton method ( PC algorithm ) ; independencies are determined using a chisquare statistic with the acceptance threshold of significance_level. Returns a tuple ( skeleton separating_sets ).
def estimate_skeleton(self, significance_level=0.01): """Estimates a graph skeleton (UndirectedGraph) for the data set. Uses the build_skeleton method (PC algorithm); independencies are determined using a chisquare statistic with the acceptance threshold of `significance_level`. Returns ...
Estimates a DAG from an Independencies () - object or a decision function for conditional independencies. This requires that the set of independencies admits a faithful representation ( e. g. is a set of d - seperation for some BN or is closed under the semi - graphoid axioms ). See build_skeleton skeleton_to_pdag pdag...
def estimate_from_independencies(nodes, independencies): """Estimates a DAG from an Independencies()-object or a decision function for conditional independencies. This requires that the set of independencies admits a faithful representation (e.g. is a set of d-seperation for some BN or i...