text
stringlengths
81
112k
The linear Gaussian Bayesian Networks are an alternative representation for the class of multivariate Gaussian distributions. This method returns an equivalent joint Gaussian distribution. Returns ------- GaussianDistribution: An equivalent joint Gaussian ...
Checks the model for various errors. This method checks for the following error - * Checks if the CPDs associated with nodes are consistent with their parents. Returns ------- check: boolean True if all the checks pass. def check_model(self): """ Ch...
r""" Base method used for product of factor sets. Suppose :math:`\vec\phi_1` and :math:`\vec\phi_2` are two factor sets then their product is a another factors set :math:`\vec\phi_3 = \vec\phi_1 \cup \vec\phi_2`. Parameters ---------- factorsets_list: FactorSet1, FactorSet2, ..., FactorSetn ...
r""" Base method for dividing two factor sets. Division of two factor sets :math:`\frac{\vec\phi_1}{\vec\phi_2}` basically translates to union of all the factors present in :math:`\vec\phi_2` and :math:`\frac{1}{\phi_i}` of all the factors present in :math:`\vec\phi_2`. Parameters ---------- f...
r""" Return the factor sets product with the given factor sets Suppose :math:`\vec\phi_1` and :math:`\vec\phi_2` are two factor sets then their product is a another factors set :math:`\vec\phi_3 = \vec\phi_1 \cup \vec\phi_2`. Parameters ---------- factorsets: FactorSet1...
r""" Returns a new factor set instance after division by the factor set Division of two factor sets :math:`\frac{\vec\phi_1}{\vec\phi_2}` basically translates to union of all the factors present in :math:`\vec\phi_2` and :math:`\frac{1}{\phi_i}` of all the factors present in :math:`\vec...
Marginalizes the factors present in the factor sets with respect to the given variables. Parameters ---------- variables: list, array-like List of the variables to be marginalized. inplace: boolean (Default value True) If inplace=True it will modify the factor s...
Adds a single node to the Network Parameters ---------- node: node A node can be any hashable Python object. Examples -------- >>> from pgmpy.models import DynamicBayesianNetwork as DBN >>> dbn = DBN() >>> dbn.add_node('A') ['A'] def...
Returns the list of nodes present in the network Examples -------- >>> from pgmpy.models import DynamicBayesianNetwork as DBN >>> dbn = DBN() >>> dbn.add_nodes_from(['A', 'B', 'C']) >>> sorted(dbn._nodes()) ['B', 'A', 'C'] def _nodes(self): """ R...
Add an edge between two nodes. The nodes will be automatically added if they are not present in the network. Parameters ---------- start: tuple Both the start and end nodes should specify the time slice as (node_name, time_slice). Here, node_name can be an...
Add all the edges in ebunch. If nodes referred in the ebunch are not already present, they will be automatically added. Node names can be any hashable python object. Parameters ---------- ebunch : list, array-like List of edges to add. Each edge must be of the f...
Returns the intra slice edges present in the 2-TBN. Parameter --------- time_slice: int (whole number) The time slice for which to get intra edges. The timeslice should be a positive value or zero. Examples -------- >>> from pgmpy.models ...
Returns the nodes in the first timeslice whose children are present in the first timeslice. Parameters ---------- time_slice:int The timeslice should be a positive value greater than or equal to zero Examples -------- >>> from pgmpy.models import Dynamic...
Returns the nodes present in a particular timeslice Parameters ---------- time_slice:int The timeslice should be a positive value greater than or equal to zero Examples -------- >>> from pgmpy.models import DynamicBayesianNetwork as DBN >>> dbn =...
This method adds the cpds to the dynamic bayesian network. Note that while adding variables and the evidence in cpd, they have to be of the following form (node_name, time_slice) Here, node_name is the node that is inserted while the time_slice is an integer value, which denotes ...
Returns the CPDs that have been associated with the network. Parameters ---------- node: tuple (node_name, time_slice) The node should be in the following form (node_name, time_slice). Here, node_name is the node that is inserted while the time_slice is an in...
Removes the cpds that are provided in the argument. Parameters ---------- *cpds : list, set, tuple (array-like) List of CPDs which are to be associated with the model. Each CPD should be an instance of `TabularCPD`. Examples -------- >>> from pgm...
Check the model for various errors. This method checks for the following errors. * Checks if the sum of the probabilities in each associated CPD for each state is equal to 1 (tol=0.01). * Checks if the CPDs associated with nodes are consistent with their parents. Returns ...
This method will automatically re-adjust the cpds and the edges added to the bayesian network. If an edge that is added as an intra time slice edge in the 0th timeslice, this method will automatically add it in the 1st timeslice. It will also add the cpds. However, to call this method, one needs...
Removes all the immoralities in the Network and creates a moral graph (UndirectedGraph). A v-structure X->Z<-Y is an immorality if there is no directed edge between X and Y. Examples -------- >>> from pgmpy.models import DynamicBayesianNetwork as DBN >>> dbn = D...
Returns a copy of the dynamic bayesian network. Returns ------- DynamicBayesianNetwork: copy of the dynamic bayesian network Examples -------- >>> from pgmpy.models import DynamicBayesianNetwork as DBN >>> from pgmpy.factors.discrete import TabularCPD >>...
Generates a list of legal (= not in tabu_list) graph modifications for a given model, together with their score changes. Possible graph modifications: (1) add, (2) remove, or (3) flip a single edge. For details on scoring see Koller & Fridman, Probabilistic Graphical Models, Section 18.4.3.3 (pa...
Performs local hill climb search to estimates the `DAG` structure that has optimal score, according to the scoring method supplied in the constructor. Starts at model `start` and proceeds by step-by-step network modifications until a local maximum is reached. Only estimates network structure, no...
Returns the optimal elimination order based on the cost function. The node having the least cost is removed first. Parameters ---------- nodes: list, tuple, set (array-like) The variables which are to be eliminated. Examples -------- >>> import numpy...
Cost function for WeightedMinFill. The cost of eliminating a node is the sum of weights of the edges that need to be added to the graph due to its elimination, where a weight of an edge is the product of the weights, domain cardinality, of its constituent vertices. def cost(self, node): ...
The cost of a eliminating a node is the product of weights, domain cardinality, of its neighbors. def cost(self, node): """ The cost of a eliminating a node is the product of weights, domain cardinality, of its neighbors. """ return np.prod([self.bayesian_model.get_cardi...
Returns a dictionary of STATICPROPERTIES Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_static_properties() {'FORMAT': 'MSR DTAS XML', 'VERSION': '0.2', 'CREATOR': 'Microsoft Research DTAS'} def get_static_properties(self): """ Returns a...
Returns a list of variables. Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_variables() {'a': {'TYPE': 'discrete', 'XPOS': '13495', 'YPOS': '10465', 'DESCRIPTION': '(a) Metastatic Cancer', 'STATES': ['Present', 'Absent']} ...
Returns a list of tuples. Each tuple contains two elements (parent, child) for each edge. Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_edges() [('a', 'b'), ('a', 'c'), ('b', 'd'), ('c', 'd'), ('c', 'e')] def get_edges(self): """ Return...
Returns a dictionary of name and its distribution. Distribution is a ndarray. The ndarray is stored in the standard way such that the rightmost variable changes most often. Consider a CPD of variable 'd' which has parents 'b' and 'c' (distribution['CONDSET'] = ['b', 'c']) | d_0 ...
Returns an instance of Bayesian Model. def get_model(self): """ Returns an instance of Bayesian Model. """ model = BayesianModel() model.add_nodes_from(self.variables) model.add_edges_from(self.edges) model.name = self.model_name tabular_cpds = [] ...
Set attributes for ANALYSISNOTEBOOK tag Parameters ---------- **data: dict {name: value} for the attributes to be set. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> writer = XBNWriter() >>> writer.set_analys...
Set STATICPROPERTIES tag for the network Parameters ---------- **data: dict {name: value} for name and value of the property. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> writer = XBNWriter() >>> writer.set...
Set variables for the network. Parameters ---------- data: dict dict for variable in the form of example as shown. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> writer = XBNWriter() >>> writer.set_variables(...
Set edges/arc in the network. Parameters ---------- edge_list: array_like list, tuple, dict or set whose each elements has two values (parent, child). Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> writer = XBNWriter...
Set distributions in the network. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> writer =XBNWriter() >>> writer.set_distributions() def set_distributions(self): """ Set distributions in the network. Examples ---...
Add an edge between variable_node and factor_node. Parameters ---------- u, v: nodes Nodes can be any hashable Python object. Examples -------- >>> from pgmpy.models import FactorGraph >>> G = FactorGraph() >>> G.add_nodes_from(['a', 'b', 'c'...
Check the model for various errors. This method checks for the following errors. In the same time it also updates the cardinalities of all the random variables. * Check whether bipartite property of factor graph is still maintained or not. * Check whether factors are associate...
Returns variable nodes present in the graph. Before calling this method make sure that all the factors are added properly. Examples -------- >>> from pgmpy.models import FactorGraph >>> from pgmpy.factors.discrete import DiscreteFactor >>> G = FactorGraph() ...
Returns factors nodes present in the graph. Before calling this method make sure that all the factors are added properly. Examples -------- >>> from pgmpy.models import FactorGraph >>> from pgmpy.factors.discrete import DiscreteFactor >>> G = FactorGraph() ...
Converts the factor graph into markov model. A markov model contains nodes as random variables and edge between two nodes imply interaction between them. Examples -------- >>> from pgmpy.models import FactorGraph >>> from pgmpy.factors.discrete import DiscreteFactor ...
Returns 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 FactorGraph >>> from pgmpy.factors.discrete import DiscreteFactor >>> ...
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 =...
Extracting the cliques from the junction tree which are a subset of the given nodes. Parameters: ---------- junction_tree: Junction tree from which the nodes are to be extracted. nodes: iterable container A container of nodes (list, dict, set, etc.). de...
Getting the evidence belonging to a particular timeslice. Parameters: ---------- evidence: dict a dict key, value pair as {var: state_of_var_observed} None if no evidence time: int the evidence corresponding to the time slice shift: int ...
Marginalizing the factor selectively for a set of variables. Parameters: ---------- nodes: list, array-like A container of nodes (list, dict, set, etc.). factor: factor factor which is to be marginalized. def _marginalize_factor(self, nodes, factor): ""...
Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor which needs to be updated corresponding to the input clique. out_clique_potential: factor ...
Extracts the required factor from the junction tree. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. evidence: dict a dict key, value pair as {var: state_of_var_observed} def _get_factor(self, belief_prop, ev...
Shifting the factor to a certain required time slice. Parameters: ---------- factor: DiscreteFactor The factor which needs to be shifted. shift: int The new timeslice to which the factor should belong to. def _shift_factor(self, factor, shift): """ ...
Forward inference 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 ...
Backward inference 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 ...
Query method for Dynamic Bayesian Network using Interface Algorithm. 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 ...
Adds a single node to the Graph. Parameters ---------- node: str, int, or any hashable python object. The node to add to the graph. weight: int, float The weight of the node. Examples -------- >>> from pgmpy.base import DAG >>> G...
Add multiple nodes to the Graph. **The behviour of adding weights is different than in networkx. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, or any hashable python object). weights: list, tuple (default=None) ...
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. weight: int, float (default=None) The weight of the edge...
Add all the edges in ebunch. If nodes referred in the ebunch are not already present, they will be automatically added. Node names can be any hashable python object. **The behavior of adding weights is different than networkx. Parameters ---------- ebunch : con...
Removes all the immoralities in the DAG and creates a moral graph (UndirectedGraph). A v-structure X->Z<-Y is an immorality if there is no directed edge between X and Y. Examples -------- >>> from pgmpy.base import DAG >>> G = DAG(ebunch=[('diff', 'grade'), ('in...
Returns a list of roots of the graph. Examples -------- >>> from pgmpy.base import DAG >>> graph = DAG([('A', 'B'), ('B', 'C'), ('B', 'D'), ('E', 'B')]) >>> graph.get_roots() ['A', 'E'] def get_roots(self): """ Returns a list of roots of the graph. ...
Computes independencies in the DAG, by checking d-seperation. Parameters ---------- latex: boolean If latex=True then latex string of the independence assertion would be created. Examples -------- >>> from pgmpy.base import DAG >>> chain ...
Returns an instance of Independencies containing the local independencies of each of the variables. Parameters ---------- variables: str or array like variables whose local independencies are to be found. Examples -------- >>> from pgmpy.models impor...
Checks whether the given model is I-equivalent Two graphs G1 and G2 are said to be I-equivalent if they have same skeleton and have same set of immoralities. Note: For same skeleton different names of nodes can work but for immoralities names of nodes must be same Parameters ...
Finds all the immoralities in the model A v-structure X -> Z <- Y is an immorality if there is no direct edge between X and Y . Returns ------- set: A set of all the immoralities in the model Examples --------- >>> from pgmpy.base import DAG >>> student ...
Returns True if there is any active trail between start and end node Parameters ---------- start : Graph Node end : Graph Node observed : List of nodes (optional) If given the active trail would be computed assuming these nodes to be observed. additional_obser...
Returns a markov blanket for a random variable. In the case of Bayesian Networks, the markov blanket is the set of node's parents, its children and its children's other parents. Returns ------- list(blanket_nodes): List of nodes contained in Markov Blanket Parameters ...
Returns a dictionary with the given variables as keys and all the nodes reachable from that respective variable as values. Parameters ---------- variables: str or array like variables whose active trails are to be found. observed : List of nodes (optional) ...
Returns a dictionary of all ancestors of all the observed nodes including the node itself. Parameters ---------- obs_nodes_list: string, list-type name of all the observed nodes Examples -------- >>> from pgmpy.base import DAG >>> model = DAG([...
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 JunctionTree >>> G = JunctionTree() >>> G.add_nodes_from([...
Check the model for various errors. This method checks for the following errors. In the same time also updates the cardinalities of all the random variables. * Checks if clique potentials are defined for all the cliques or not. * Check for running intersection property is not done expli...
Returns a copy of JunctionTree. Returns ------- JunctionTree : copy of JunctionTree Examples -------- >>> import numpy as np >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.models import JunctionTree >>> G = JunctionTree() ...
Generate ProbModelXML lines for model. Parameters ---------- model : Graph The Bayesian or Markov Model encoding : string (optional) Encoding for text data prettyprint: bool (optional) If True uses line breaks and indenting in output XML. Examples -------- >>> G...
Write model in ProbModelXML format to path. Parameters ---------- model : A NetworkX graph Bayesian network or Markov network path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed. encoding : string (optional) ...
Returns the model_data based on the given model. Parameters ---------- model: BayesianModel instance Model to write Return ------ model_data: dict dictionary containing model data of the given model. Examples -------- >>> model_data = pgmpy.readwrite.get_model_data...
Sets AdditionalProperties of the ProbModelXML. def _add_additional_properties(position, properties_dict): """ Sets AdditionalProperties of the ProbModelXML. """ add_prop = etree.SubElement(position, 'AdditionalProperties') for key, value in properties_dict.items(): e...
Adds a node to the ProbModelXML. def _add_variable(self, variable): """ Adds a node to the ProbModelXML. """ # TODO: Add feature for accepting additional properties of states. variable_data = self.data['probnet']['Variables'][variable] variable_element = etree.SubElement...
Adds an edge to the ProbModelXML. def _add_link(self, edge): """ Adds an edge to the ProbModelXML. """ edge_data = self.data['probnet']['edges'][edge] if isinstance(edge, six.string_types): edge = eval(edge) link = etree.SubElement(self.links, 'Link', attrib=...
Adds constraint to the ProbModelXML. def _add_constraint(self, constraint): """ Adds constraint to the ProbModelXML. """ constraint_data = self.data['probnet']['AdditionalConstraints'][constraint] constraint_element = etree.SubElement( self.additional_constraints, 'C...
Adds Decision Criteria to the ProbModelXML. Parameters ---------- criteria_dict: dict Dictionary containing Deecision Criteria data. For example: {'effectiveness': {}, 'cost': {}} Examples ------- >>> writer = ProbModelXMLWriter(model) >>...
Adds Potentials to the ProbModelXML. Parameters ---------- potential: dict Dictionary containing Potential data. For example: {'role': 'Utility', 'Variables': ['D0', 'D1', 'C0', 'C1'], 'type': 'Tree/ADD', ...
Helper function to add variable tag to the potential_tag Parameters ---------- potential: dict Dictionary containing Potential data. For example: {'role': 'Utility', 'Variables': ['D0', 'D1', 'C0', 'C1'], 'type': 'Tree/...
Dumps the data to stream after appending header. def dump(self, stream): """ Dumps the data to stream after appending header. """ if self.prettyprint: self.indent(self.xml) document = etree.ElementTree(self.xml) header = '<?xml version="1.0" encoding="%s"?>' ...
Write the xml data into the file. Parameters ---------- filename: Name of the file. Examples ------- >>> writer = ProbModelXMLWriter(model) >>> writer.write_file(test_file) def write_file(self, filename): """ Write the xml data into the file. ...
Returns a BayesianModel or MarkovModel object depending on the type of ProbModelXML passed to ProbModelXMLReader class. def create_probnet(self): """ Returns a BayesianModel or MarkovModel object depending on the type of ProbModelXML passed to ProbModelXMLReader class. """ ...
Adds Additional Constraints to the probnet dict. Parameters ---------- criterion: <Element Constraint at AdditionalConstraints Node in XML> etree Element consisting Constraint tag. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.add_add...
Adds Decision Criteria to the probnet dict. Parameters ---------- criterion: <Element Criterion at Decision Criteria Node in XML> etree Element consisting DecisionCritera tag. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.add_criterio...
Adds Variables to the probnet dict. Parameters ---------- variable: <Element Variable at Variables Node in XML> etree Element consisting Variable tag. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.add_node(variable) def add_node(self...
Adds Edges to the probnet dict. Parameters ---------- edge: <Element Link at Links Node in XML> etree Element consisting Variable tag. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.add_edge(edge) def add_edge(self, edge): """...
Adds Potential to the potential dict. Parameters ---------- potential: <Element Potential at Potentials node in XML> etree Element consisting Potential tag. potential_dict: dict{} Dictionary to parse Potential tag. Examples ------- >>> re...
Returns the model instance of the ProbModel. Return --------------- model: an instance of BayesianModel. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.get_model() def get_model(self): """ Returns the model instance of the ProbMod...
Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- nodes: list of nodes for the DAGs (optional)...
Computes a list of DAGs and their structure scores, ordered by score. Returns ------- list: a list of (score, dag) pairs A list of (score, dag)-tuples, where score is a float and model a acyclic nx.DiGraph. The list is ordered by score values. Examples -...
Estimates the `DAG` structure that fits best to the given data set, according to the scoring method supplied in the constructor. Exhaustively searches through all models. Only estimates network structure, no parametrization. Returns ------- model: `DAG` instance A `D...
Adds variables to the NoisyOrModel. Parameters ---------- variables: list, tuple, dict (array like) array containing names of the variables that are to be added. cardinality: list, tuple, dict (array like) array containing integers representing the cardinality ...
Deletes variables from the NoisyOrModel. Parameters ---------- variables: list, tuple, dict (array like) list of variables to be deleted. Examples -------- >>> from pgmpy.models import NoisyOrModel >>> model = NoisyOrModel(['x1', 'x2', 'x3'], [2, 3, ...
A utility function to return samples according to type def _return_samples(return_type, samples): """ A utility function to return samples according to type """ if return_type.lower() == "dataframe": if HAS_PANDAS: return pandas.DataFrame.from_records(samples) else: ...
Method that finds gradient and its log at position def _get_gradient_log_pdf(self): """ Method that finds gradient and its log at position """ sub_vec = self.variable_assignments - self.model.mean.flatten() grad = - np.dot(self.model.precision_matrix, sub_vec) log_pdf = ...
Method to perform time splitting using leapfrog def _get_proposed_values(self): """ Method to perform time splitting using leapfrog """ # Take half step in time for updating momentum momentum_bar = self.momentum + 0.5 * self.stepsize * self.grad_log_position # Take full...
Returns cardinality of a given variable Parameters ---------- variables: list, array-like A list of variable names. Returns ------- dict: Dictionary of the form {variable: variable_cardinality} Examples -------- >>> from pgmpy.fa...
Returns a list of assignments for the corresponding index. Parameters ---------- index: list, array-like List of indices whose assignment is to be computed Returns ------- list: Returns a list of full assignments of all the variables of the factor. ...
Returns the identity factor. Def: The identity factor of a factor has the same scope and cardinality as the original factor, but the values for all the assignments is 1. When the identity factor is multiplied with the factor it returns the factor itself. Returns -----...
Modifies the factor with marginalized values. Parameters ---------- variables: list, array-like List of variables over which to marginalize. inplace: boolean If inplace=True it will modify the factor itself, else would return a new factor. R...