text
stringlengths
81
112k
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 ...
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 ...
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...
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...
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 =...
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_co...
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 ...
>>> _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, st...
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...
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)...
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") ...
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...
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 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, en...
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 ...
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 ---...
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...
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 >>> ...
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 -------- >>...
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 ...
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 ...
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...
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...
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 no...
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...
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. ...
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=['{', '}', ',', ' ']...
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(alph...
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 ...
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 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...
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...
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...
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...
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...
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): """ Retu...
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 , ...
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) ...
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) ...
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...
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() ...
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...
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]]), ...
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],...
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...
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 ...
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(...
Returns list of variables of the network Example ------- >>> reader = PomdpXReader("pomdpx.xml") >>> reader.get_variables() {'StateVar': [ {'vnamePrev': 'rover_0', 'vnameCurr': 'rover_1', 'ValueEnum': ['s0...
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() [{...
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() ...
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', ...
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', ...
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 ...
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'): ...
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...
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 variable...
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'...
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...
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 ------...
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 t...
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 cont...
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 ...
add reward function tag to pomdpx model Return --------------- string containing the xml for reward function tag def add_reward_function(self): """ add reward function tag to pomdpx model Return --------------- string containing the xml for reward funct...
Returns the grammar of the UAI file. def get_grammar(self): """ Returns the grammar of the UAI file. """ network_name = Word(alphas).setResultsName('network_name') no_variables = Word(nums).setResultsName('no_variables') grammar = network_name + no_variables self...
Returns a list of variables. Each variable is represented by an index of list. For example if the no of variables are 4 then the list will be [var_0, var_1, var_2, var_3] Returns ------- list: list of variables Example ------- >>> reader = UAIRea...
Returns the dictionary of variables with keys as variable name and values as domain of the variables. Returns ------- dict: dictionary containing variables and their domains Example ------- >>> reader = UAIReader('TestUAI.uai') >>> reader.get_domain() ...
Returns the edges of the network. Returns ------- set: set containing the edges of the network Example ------- >>> reader = UAIReader('TestUAI.uai') >>> reader.get_edges() {('var_0', 'var_1'), ('var_0', 'var_2'), ('var_1', 'var_2')} def get_edges(self):...
Returns list of tuple of child variable and CPD in case of Bayesian and list of tuple of scope of variables and values in case of Markov. Returns ------- list : list of tuples of child variable and values in Bayesian list of tuples of scope of variables and values in case of...
Returns an instance of Bayesian Model or Markov Model. Varibles are in the pattern var_0, var_1, var_2 where var_0 is 0th index variable, var_1 is 1st index variable. Return ------ model: an instance of Bayesian or Markov Model. Examples -------- >>> rea...
Adds domain of each variable to the network. Example ------- >>> writer = UAIWriter(model) >>> writer.get_domain() def get_domain(self): """ Adds domain of each variable to the network. Example ------- >>> writer = UAIWriter(model) >>> w...
Adds functions to the network. Example ------- >>> writer = UAIWriter(model) >>> writer.get_functions() def get_functions(self): """ Adds functions to the network. Example ------- >>> writer = UAIWriter(model) >>> writer.get_functions() ...
Adds tables to the network. Example ------- >>> writer = UAIWriter(model) >>> writer.get_tables() def get_tables(self): """ Adds tables to the network. Example ------- >>> writer = UAIWriter(model) >>> writer.get_tables() """ ...
Write the xml data into the file. Parameters ---------- filename: Name of the file. Examples ------- >>> writer = UAIWriter(model) >>> writer.write_xmlbif(test_file) def write_uai(self, filename): """ Write the xml data into the file. P...
Computes a score that measures how much a \ given variable is \"influenced\" by a given list of potential parents. def local_score(self, variable, parents): "Computes a score that measures how much a \ given variable is \"influenced\" by a given list of potential parents." var_states =...
Run the command to download target. If the command fails, clean up before re-raising the error. def _clean_check(cmd, target): """ Run the command to download target. If the command fails, clean up before re-raising the error. """ try: subprocess.check_call(cmd) except subprocess.Ca...
Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot complete. def download_file_powershell(url, target): """ Download the file at url to target using Powershell (which will validate trust). Raise an exception if the command cannot co...
Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the nu...
Parse the command line for options def _parse_args(): """ Parse the command line for options """ parser = optparse.OptionParser() parser.add_option( '--user', dest='user_install', action='store_true', default=False, help='install in user site package (requires Python 2.6 or later)')...
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 Bayes...
Remove node from the model. Removing a node also removes all the associated edges, removes the CPD of the node and marginalizes the CPDs of it's children. Parameters ---------- node : node Node which is to be removed from the model. Returns ------- ...
Add CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : list, set, tuple (array-like) List of CPDs which will be associated with the model EXAMPLE ------- >>> from pgmpy.models import BayesianModel >>> fro...
Returns the cpd of the node. If node is not specified returns all the CPDs that have been added till now to the graph Parameter --------- node: any hashable python object (optional) The node whose CPD we want. If node not specified returns all the CPDs added to t...
Removes the cpds that are provided in the argument. Parameters ---------- *cpds: TabularCPD object A CPD object on any subset of the variables of the model which is to be associated with the model. Examples -------- >>> from pgmpy.models import B...
Returns the cardinality of the node. Throws an error if the CPD for the queried node hasn't been added to the network. Parameters ---------- node: Any hashable python object(optional). The node whose cardinality we want. If node is not specified returns a dic...
Check the model for various errors. This method checks for the following errors. * Checks if the sum of the probabilities for each state is equal to 1 (tol=0.01). * Checks if the CPDs associated with nodes are consistent with their parents. Returns ------- check: boolea...
Converts bayesian model to markov model. The markov model created would be the moral graph of the bayesian model. Examples -------- >>> from pgmpy.models import BayesianModel >>> G = BayesianModel([('diff', 'grade'), ('intel', 'grade'), ... ('intel', '...
Estimates the CPD for each variable based on a given data set. Parameters ---------- data: pandas DataFrame object DataFrame object with column names identical to the variable names of the network. (If some values in the data are missing the data cells should be set to `...
Predicts states of all the missing variables. Parameters ---------- data : pandas DataFrame object A DataFrame object with column names same as the variables in the model. Examples -------- >>> import numpy as np >>> import pandas as pd >>> f...
Predicts probabilities of all states of the missing variables. Parameters ---------- data : pandas DataFrame object A DataFrame object with column names same as the variables in the model. Examples -------- >>> import numpy as np >>> import pandas as...
Checks whether the bayesian model is Imap of given JointProbabilityDistribution Parameters ----------- JPD : An instance of JointProbabilityDistribution Class, for which you want to check the Imap Returns -------- boolean : True if bayesian model is Imap for...
Returns a copy of the model. Returns ------- BayesianModel: Copy of the model on which the method was called. Examples -------- >>> from pgmpy.models import BayesianModel >>> from pgmpy.factors.discrete import TabularCPD >>> model = BayesianModel([('A', ...
Returns the cpd Examples -------- >>> from pgmpy.factors.discrete import TabularCPD >>> cpd = TabularCPD('grade', 3, [[0.1, 0.1], ... [0.1, 0.1], ... [0.8, 0.8]], ... evidence='evi1', ev...
Returns a copy of the TabularCPD object. Examples -------- >>> from pgmpy.factors.discrete import TabularCPD >>> cpd = TabularCPD('grade', 2, ... [[0.7, 0.6, 0.6, 0.2],[0.3, 0.4, 0.4, 0.8]], ... ['intel', 'diff'], [2, 2]) >>> cop...
Normalizes the cpd table. Parameters ---------- inplace: boolean If inplace=True it will modify the CPD itself, else would return a new CPD Examples -------- >>> from pgmpy.factors.discrete import TabularCPD >>> cpd_table = TabularCPD('gr...
Modifies the cpd table with marginalized values. Parameters ---------- variables: list, array-like list of variable to be marginalized inplace: boolean If inplace=True it will modify the CPD itself, else would return a new CPD Examples ...
Reduces the cpd table to the context of given variable values. Parameters ---------- values: list, array-like A list of tuples of the form (variable_name, variable_state). inplace: boolean If inplace=True it will modify the factor itself, else would return ...
Returns a new cpd table according to provided order. Parameters ---------- new_order: list list of new ordering of variables inplace: boolean If inplace == True it will modify the CPD itself otherwise new value will be returned without affecting old ...
Add linear Gaussian CPD (Conditional Probability Distribution) to the Bayesian Model. Parameters ---------- cpds : instances of LinearGaussianCPD List of LinearGaussianCPDs which will be associated with the model Examples -------- >>> from pgmpy.mo...