INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
MAP query method using Max Product LP method. This returns the best assignment of the nodes in the form of a dictionary. Parameters ---------- init_iter: integer Number of maximum iterations that we want MPLP to run for the first time. later_iter: integer ...
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. 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 -------- >>> from pgmpy.models import MarkovM...
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 Parameters ---------- *factor: pgmpy.factors.factors object A factor object on any subset of the variables of the model which is to be associated with the model. Returns...
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 ...
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 ------- check: boolean Tru...
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 ---...
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 factor we want. If node is not specified Examples...
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...
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 and factor nodes. Each factor node is as...
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...
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 side of the edge to other. Exa...
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. 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 variables in X Parameters ---------- latex: ...
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. 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 -------- >>> from pgmpy.models impor...
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. 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 present. Examples -------- >>> f...
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 the probability density function(pdf). Returns ------- function: The probability density function of the distribution. Examples -------- >>> from pgmpy.factors.distributions import GaussianDistribution >>> dist = GD(variables=['x1', 'x2', 'x3'], ...
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. 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.factors.distributions import GaussianDistribution as ...
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. Parameters ---------- variables: iterator over any hashable object. List of variables over which marginalization is to be done. inplace: boolean If inplace=True it will modify the distribution itself, ...
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. 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_{j.i} = mu_j + sig_{j, i} * {sig_{i, i}^{-1}} * (x_i - mu_i...
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. Returns ------- GaussianDistribution: copy of the distribution Examples -------- >>> import numpy as np >>> from pgmpy.factors.distributions import GaussianDistribution as GD >>> gauss_dis = GD(variables=['x1', 'x2', 'x...
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. 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 - log((2*pi)^(n/2) * det(s...
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...
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: boolean If True, modifies the distribution its...
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...
Gives the CanonicalDistribution operation (product or divide) with the other factor. Parameters ---------- other: CanonicalDistribution The CanonicalDistribution to be multiplied. operation: String 'product' for multiplication operation and '...
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...
Returns the division of two gaussian distributions. Parameters ---------- other: GaussianDistribution The GaussianDistribution to be divided. inplace: boolean If True, modifies the distribution itself, otherwise returns a new GaussianDistribution obj...
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. Parameters ---------- method: string, BaseDiscretizer instance A Discretizer Class from pgmpy.factors.discretize *args, **kwargs: values The parameters to be...
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. Parameters ---------- values: list, array-like A list of tuples of the form (variable_name, variable_value). inplace: boolean If inplace=True it will modify the factor itself, else would return ...
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. Parameters ---------- variables: list, array-like List of variables to be removed from the marginalized distribution. inplace: boolean If inplace=True it will modify the factor itself, else would ...
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. Parameters ---------- inplace: boolean If inplace=True it will modify the distribution itself, else would return a new distribution. Returns ------- ...
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. Parameters ---------- other: CustomDistribution The CustomDistribution to be multiplied. operation: str 'product' for multiplication operation and 'divide' for ...
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. Parameters ---------- variables: list, array-like variables that are not to be eliminated. operation: str ('marginalize' | 'maximize') The operation to do for eliminating the variable. evidence: dict ...
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 evidence: dict a dict key, value pair as {var: state_of_var_observed} None if no evidence elimination_order: list order of variable elim...
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. Parameters ---------- variables: list list of variables over which we want to compute the max-marginal. evidence: dict a dict key, value pair as {var: state_of_var_observed} None if no e...
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. Note: When multiple variables are passed, it returns the map_query for each of them individually. Parameters ---------- variables: list list of variables over which we want to compute the max-marginal. ...
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. Parameters ---------- elimination_order: list, array like List of variables in the order in which they are to be eliminated. Examples -------- >>> import numpy as np >>>...
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. Parameters ---------- elimination_order: list, array like List of variables in ...
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. Parameters ---------- sending_clique: node (as the operation is on junction tree, node should be a tuple) Node sending the message recieving_clique: node (as the operation is on junction tree, node should be a tuple) Node recieving t...
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. Parameters ---------- operation: str ('marginalize' | 'maximize') The operation to do for passing messages between nodes. if operation ==...
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...
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 operation: str ('marginalize' | 'maximize') The operation to do for passing mes...
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...
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. Parameters ---------- operation: str ('marginalize' | 'm...
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...
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: state_of_var_observed} None if no evidence joint: boo...
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. Note: When multiple variables are passed, it returns the map_query for each of them individually. Parameters ---------- variables: list list of variables for which you want to compute the probability evidence: dict ...
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. Parameters ---------- data: pandas.DataFrame or 2D array Dataframe of values containing samples from the conditional distribution, (Y|X) and corresponding X values. states: All the input states that are jointly gaussian. Returns ...
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 Parameters ---------- data: pandas.DataFrame Dataframe containing samples from the conditional distribution, p(Y|X) estimator: 'MLE' or 'MAP' completely_samples_only: boolean (True or False) Are they downsampled or complete? De...
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. Returns ------- LinearGaussianCPD: copy of the distribution Examples -------- >>> from pgmpy.factors.continuous import LinearGaussianCPD >>> cpd = LinearGaussianCPD('Y', [0.2, -2, 3, 7], 9.6, ['X1', 'X2', 'X3']) >>> c...
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. >>> tsv = simple_separated_format("\\t") ; \ tabulate([["foo", 1], ["spam", 23]], tablefmt=tsv) == 'foo \\t 1\\nspam\\t23' True
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. >>> _afterpoint("123.45") 2 >>> _afterpoint("1001") -1 >>> _afterpoint("eggs") -1 >>> _afterpoint("123e45") 2
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. >>> _padleft(6, '\u044f\u0439\u0446\u0430') == ' \u044f\u0439\u0446\u0430' True
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. >>> _visible_width('\x1b[31mhello\x1b[0m'), _visible_width("world") (5, 5)
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. >>> _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(["four", '\u043f\u044f\u0442\u044c']) is _text_type T...
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. Default value is the points - [low, low+step, low+2*step, ......... , high-step] unless the method is overridden by a subclass. Examples ---...
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 - 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 density function of the distribution. Reference...
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. Returns ------- parameters: list List of TabularCPDs, one for each variable of the model Examples -------- >>> import numpy as np >>> import pandas as pd >>> ...
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. Parameters ---------- node: int, string (any hashable python object) The name of the variable for which the CPD is to be estimated. Returns ------- CPD: TabularCPD Examples -------- >>...
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 ...
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). Parameters ...
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_skeleto...
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...
Completes a PDAG to a DAG, without adding v-structures, if such a completion exists. If no faithful extension is possible, some fully oriented DAG that corresponds to the PDAG is returned and a warning is generated. This is a static method. Parameters ---------- pdag: DA...
def pdag_to_dag(pdag): """Completes a PDAG to a DAG, without adding v-structures, if such a completion exists. If no faithful extension is possible, some fully oriented DAG that corresponds to the PDAG is returned and a warning is generated. This is a static method. Parameters ...
Construct the DAG pattern (representing the I-equivalence class) for a given DAG. This is the "inverse" to pdag_to_dag.
def model_to_pdag(model): """Construct the DAG pattern (representing the I-equivalence class) for a given DAG. This is the "inverse" to pdag_to_dag. """ if not isinstance(model, DAG): raise TypeError("model: Expected DAG instance, " + "got type {m...
Orients the edges of a graph skeleton based on information from `separating_sets` to form a DAG pattern (DAG). Parameters ---------- skel: UndirectedGraph An undirected graph skeleton as e.g. produced by the estimate_skeleton method. separating_sets: dic...
def skeleton_to_pdag(skel, separating_sets): """Orients the edges of a graph skeleton based on information from `separating_sets` to form a DAG pattern (DAG). Parameters ---------- skel: UndirectedGraph An undirected graph skeleton as e.g. produced by the ...
Estimates a graph skeleton (UndirectedGraph) from a set of independencies using (the first part of) the PC algorithm. The independencies can either be provided as an instance of the `Independencies`-class or by passing a decision function that decides any conditional independency assertion. ...
def build_skeleton(nodes, independencies): """Estimates a graph skeleton (UndirectedGraph) from a set of independencies using (the first part of) the PC algorithm. The independencies can either be provided as an instance of the `Independencies`-class or by passing a decision function tha...
A method that returns variable grammar
def get_variable_grammar(self): """ A method that returns variable grammar """ # Defining a expression for valid word word_expr = Word(alphanums + '_' + '-') word_expr2 = Word(initChars=printables, excludeChars=['{', '}', ',', ' ']) name_expr = Suppress('variable...
Retruns the name of the network Example --------------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIF.BifReader("bif_test.bif") >>> reader.network_name() 'Dog-Problem'
def get_network_name(self): """ Retruns the name of the network Example --------------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIF.BifReader("bif_test.bif") >>> reader.network_name() 'Dog-Problem' """ start = self.network.f...
A method that returns probability grammar
def get_probability_grammar(self): """ A method that returns probability grammar """ # Creating valid word expression for probability, it is of the format # wor1 | var2 , var3 or var1 var2 var3 or simply var word_expr = Word(alphanums + '-' + '_') + Suppress(Optional("|")...
Returns list of variables of the network Example ------------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_variables() ['light-on','bowel_problem','dog-out','hear-bark','family-out']
def get_variables(self): """ Returns list of variables of the network Example ------------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_variables() ['light-on','bowel_problem','dog-out','hear-bark','fami...
Returns the states of variables present in the network Example ----------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_states() {'bowel-problem': ['true','false'], 'dog-out': ['true','false'], 'family-ou...
def get_states(self): """ Returns the states of variables present in the network Example ----------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_states() {'bowel-problem': ['true','false'], 'dog-...
Returns the property of the variable Example ------------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_property() {'bowel-problem': ['position = (335, 99)'], 'dog-out': ['position = (300, 195)'], 'family...
def get_property(self): """ Returns the property of the variable Example ------------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_property() {'bowel-problem': ['position = (335, 99)'], 'dog-out'...
Returns the parents of the variables present in the network Example -------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_parents() {'bowel-problem': [], 'dog-out': ['family-out', 'bowel-problem'], 'famil...
def get_parents(self): """ Returns the parents of the variables present in the network Example -------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_parents() {'bowel-problem': [], 'dog-out': ['fa...
Returns the CPD of the variables present in the network Example -------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_values() {'bowel-problem': np.array([[0.01], [0.99]]), 'do...
def get_values(self): """ Returns the CPD of the variables present in the network Example -------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_values() {'bowel-problem': np.array([[0.01], ...
Returns the edges of the network Example -------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_edges() [['family-out', 'light-on'], ['family-out', 'dog-out'], ['bowel-problem', 'dog-out'], ['do...
def get_edges(self): """ Returns the edges of the network Example -------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_edges() [['family-out', 'light-on'], ['family-out', 'dog-out'], ['...
Returns the fitted bayesian model Example ---------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_model() <pgmpy.models.BayesianModel.BayesianModel object at 0x7f20af154320>
def get_model(self): """ Returns the fitted bayesian model Example ---------- >>> from pgmpy.readwrite import BIFReader >>> reader = BIFReader("bif_test.bif") >>> reader.get_model() <pgmpy.models.BayesianModel.BayesianModel object at 0x7f20af154320> ...
Add states to variable of BIF Returns ------- dict: dict of type {variable: a list of states} Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >>> writer = BIFWriter(model) ...
def get_states(self): """ Add states to variable of BIF Returns ------- dict: dict of type {variable: a list of states} Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() ...
Create template for writing in BIF format
def BIF_templates(self): """ Create template for writing in BIF format """ network_template = Template('network $name {\n}\n') # property tag may or may not be present in model,and since no of properties # can be more than one , will replace them accoriding to format othe...
Add property to variables in BIF Returns ------- dict: dict of type {variable: list of properties } Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >>> writer = BIFWriter(model) ...
def get_properties(self): """ Add property to variables in BIF Returns ------- dict: dict of type {variable: list of properties } Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_mo...
Add the parents to BIF Returns ------- dict: dict of type {variable: a list of parents} Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >>> writer = BIFWriter(model) >>> wr...
def get_parents(self): """ Add the parents to BIF Returns ------- dict: dict of type {variable: a list of parents} Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >...
Adds tables to BIF Returns ------- dict: dict of type {variable: array} Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >>> writer = BIFWriter(model) >>> writer.get_cpds() ...
def get_cpds(self): """ Adds tables to BIF Returns ------- dict: dict of type {variable: array} Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >>> writer = BIFWrit...
Writes the BIF data into a file Parameters ---------- filename : Name of the file Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() >>> writer = BIFWriter(model) >>> writer.w...
def write_bif(self, filename): """ Writes the BIF data into a file Parameters ---------- filename : Name of the file Example ------- >>> from pgmpy.readwrite import BIFReader, BIFWriter >>> model = BIFReader('dog-problem.bif').get_model() ...
Makes a copy of the factor. Returns ------- CanonicalDistribution object: Copy of the factor Examples -------- >>> from pgmpy.factors.continuous import CanonicalDistribution >>> phi = CanonicalDistribution(['X', 'Y'], np.array([[1, -1], [-1, 1]]), ...
def copy(self): """ Makes a copy of the factor. Returns ------- CanonicalDistribution object: Copy of the factor Examples -------- >>> from pgmpy.factors.continuous import CanonicalDistribution >>> phi = CanonicalDistribution(['X', 'Y'], np.array...
Return an equivalent Joint Gaussian Distribution. Examples -------- >>> import numpy as np >>> from pgmpy.factors.continuous import CanonicalDistribution >>> phi = CanonicalDistribution(['x1', 'x2'], np.array([[3, -2], [-2, 4]]), np.array([[5],...
def to_joint_gaussian(self): """ Return an equivalent Joint Gaussian Distribution. Examples -------- >>> import numpy as np >>> from pgmpy.factors.continuous import CanonicalDistribution >>> phi = CanonicalDistribution(['x1', 'x2'], np.array([[3, -2], [-2, 4]]),...
Reduces the distribution to the context of the given variable values. Let C(X,Y ; K, h, g) be some canonical form over X,Y where, k = [[K_XX, K_XY], ; h = [[h_X], [K_YX, K_YY]] [h_Y]] The formula for the obtained conditional distribution for setti...
def reduce(self, values, inplace=True): """ Reduces the distribution to the context of the given variable values. Let C(X,Y ; K, h, g) be some canonical form over X,Y where, k = [[K_XX, K_XY], ; h = [[h_X], [K_YX, K_YY]] [h_Y]] The...
u""" Modifies the factor with marginalized values. Let C(X,Y ; K, h, g) be some canonical form over X,Y where, k = [[K_XX, K_XY], ; h = [[h_X], [K_YX, K_YY]] [h_Y]] In this case, the result of the integration operation is a canonical ...
def marginalize(self, variables, inplace=True): u""" Modifies the factor with marginalized values. Let C(X,Y ; K, h, g) be some canonical form over X,Y where, k = [[K_XX, K_XY], ; h = [[h_X], [K_YX, K_YY]] [h_Y]] In this case, the ...
Gives the CanonicalDistribution operation (product or divide) with the other factor. The product of two canonical factors over the same scope X is simply: C(K1, h1, g1) * C(K2, h2, g2) = C(K1+K2, h1+h2, g1+g2) The division of canonical forms is defined analogously: C(...
def _operate(self, other, operation, inplace=True): """ Gives the CanonicalDistribution operation (product or divide) with the other factor. The product of two canonical factors over the same scope X is simply: C(K1, h1, g1) * C(K2, h2, g2) = C(K1+K2, h1+h2, g1+g2) ...
Returns list of variables of the network Example ------- >>> reader = PomdpXReader("pomdpx.xml") >>> reader.get_variables() {'StateVar': [ {'vnamePrev': 'rover_0', 'vnameCurr': 'rover_1', 'ValueEnum': ['s0...
def get_variables(self): """ Returns list of variables of the network Example ------- >>> reader = PomdpXReader("pomdpx.xml") >>> reader.get_variables() {'StateVar': [ {'vnamePrev': 'rover_0', 'vnameCurr': 'rover_1...
Returns the state, action and observation variables as a dictionary in the case of table type parameter and a nested structure in case of decision diagram parameter Examples -------- >>> reader = PomdpXReader('Test_PomdpX.xml') >>> reader.get_initial_beliefs() [{...
def get_initial_beliefs(self): """ Returns the state, action and observation variables as a dictionary in the case of table type parameter and a nested structure in case of decision diagram parameter Examples -------- >>> reader = PomdpXReader('Test_PomdpX.xml') ...
Returns the transition of the state variables as nested dict in the case of table type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml') >>> reader.get_state_transition_function() ...
def get_state_transition_function(self): """ Returns the transition of the state variables as nested dict in the case of table type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml'...
Returns the observation function as nested dict in the case of table- type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml') >>> reader.get_obs_function() [{'Var': 'obs_sensor', ...
def get_obs_function(self): """ Returns the observation function as nested dict in the case of table- type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml') >>> reader.get_...
Returns the reward function as nested dict in the case of table- type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml') >>> reader.get_reward_function() [{'Var': 'reward_rover', ...
def get_reward_function(self): """ Returns the reward function as nested dict in the case of table- type parameter and a nested structure in case of decision diagram parameter Example -------- >>> reader = PomdpXReader('Test_PomdpX.xml') >>> reader.get_re...
This method supports the functional tags by providing the actual values in the function as list of dict in case of table type parameter or as nested dict in case of decision diagram
def get_parameter(self, var): """ This method supports the functional tags by providing the actual values in the function as list of dict in case of table type parameter or as nested dict in case of decision diagram """ parameter = [] for parameter_tag in var.fin...
This method returns parameters as list of dict in case of table type parameter
def get_parameter_tbl(self, parameter): """ This method returns parameters as list of dict in case of table type parameter """ par = [] for entry in parameter.findall('Entry'): instance = defaultdict(list) instance['Instance'] = entry.find('Instanc...
This method returns parameters as nested dicts in case of decision diagram parameter.
def get_parameter_dd(self, parameter): """ This method returns parameters as nested dicts in case of decision diagram parameter. """ dag = defaultdict(list) dag_elem = parameter.find('DAG') node = dag_elem.find('Node') root = node.get('var') def g...
supports adding variables to the xml Parameters --------------- var: The SubElement variable tag: The SubElement tag to which enum value is to be added Return --------------- None
def _add_value_enum(self, var, tag): """ supports adding variables to the xml Parameters --------------- var: The SubElement variable tag: The SubElement tag to which enum value is to be added Return --------------- None """ if va...
Add variables to PomdpX Return --------------- xml containing variables tag
def get_variables(self): """ Add variables to PomdpX Return --------------- xml containing variables tag """ state_variables = self.model['variables']['StateVar'] for var in state_variables: state_var_tag = etree.SubElement(self.variable, 'Sta...
helper function for adding parameters in condition Parameters --------------- dag_tag: etree SubElement the DAG tag is contained in this subelement node_dict: dictionary the decision diagram dictionary Return --------------- N...
def add_parameter_dd(self, dag_tag, node_dict): """ helper function for adding parameters in condition Parameters --------------- dag_tag: etree SubElement the DAG tag is contained in this subelement node_dict: dictionary the decision ...
helper function for adding probability conditions for model\ Parameters --------------- condition: dictionary contains and element of conditions list condprob: etree SubElement the tag to which condition is added Return ------...
def add_conditions(self, condition, condprob): """ helper function for adding probability conditions for model\ Parameters --------------- condition: dictionary contains and element of conditions list condprob: etree SubElement ...
add state transition function tag to pomdpx model Return --------------- string containing the xml for state transition tag
def add_state_transition_function(self): """ add state transition function tag to pomdpx model Return --------------- string containing the xml for state transition tag """ state_transition_function = self.model['state_transition_function'] for condition ...
add initial belief tag to pomdpx model Return --------------- string containing the xml for initial belief tag
def add_initial_belief(self): """ add initial belief tag to pomdpx model Return --------------- string containing the xml for initial belief tag """ initial_belief = self.model['initial_state_belief'] for condition in initial_belief: condprob ...
add observation function tag to pomdpx model Return --------------- string containing the xml for observation function tag
def add_obs_function(self): """ add observation function tag to pomdpx model Return --------------- string containing the xml for observation function tag """ obs_function = self.model['obs_function'] for condition in obs_function: condprob = ...