INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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 function tag """ reward_function = self.model['reward_function'] for condition in reward_function: condprob ...
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.no_variables = int(grammar.parseStrin...
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...
def get_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 Exampl...
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() ...
def get_domain(self): """ 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('TestUA...
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 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'), ...
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...
def get_tables(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 o...
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...
def get_model(self): """ 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. ...
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) >>> writer.get_domain() """ if isinstance(self.model, BayesianModel): cpds = self.model.get_cpds() cpds.sort(key=l...
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() """ if isinstance(self.model, BayesianModel): cpds = self.model.get_cpds() cpds.sort(key=lambda x:...
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() """ if isinstance(self.model, BayesianModel): cpds = self.model.get_cpds() cpds.sort(key=lambda x: x.variab...
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. Parameters ---------- filename: Name of the file. Examples ------- >>> writer = UAIWriter(model) >>> writer.write_xmlbif(test_file) """ writer = self.__str__() ...
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 = self.state_names[variable] var_cardinality = len(var_states) state_counts = self.state_counts(variable, par...
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.CalledProcessError: if os.access(target, os.F_OK): os.unlink(target) raise
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 complete. """ target = os.path.abspath(target) cmd = [ 'powershell', '-Command', "(new-object System.Ne...
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...
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay=15, downloader_factory=get_best_downloader): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools versio...
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)') parser.add_option( '--d...
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...
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 ...
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 ------- ...
def remove_node(self, node): """ 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 ...
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...
def add_cpds(self, *cpds): """ 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 pg...
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...
def get_cpds(self, node=None): """ 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 sp...
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...
def remove_cpds(self, *cpds): """ 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 ...
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...
def get_cardinality(self, node=None): """ 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 ...
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...
def check_model(self): """ 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. Re...
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', '...
def to_markov_model(self): """ 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', 'grad...
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 `...
def fit(self, data, estimator=None, state_names=[], complete_samples_only=True, **kwargs): """ 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 varia...
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...
def is_imap(self, JPD): """ 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 -------- ...
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...
def predict(self, data): """ 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 ...
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...
def predict_probability(self, data): """ 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 -------- ...
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', ...
def copy(self): """ 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 ...
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...
def get_values(self): """ 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]], ...
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...
def copy(self): """ 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]], ... ['inte...
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...
def normalize(self, inplace=True): """ 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 i...
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 ...
def marginalize(self, variables, inplace=True): """ 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 its...
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 ...
def reduce(self, values, inplace=True): """ 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=Tr...
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 ...
def reorder_parents(self, new_order, inplace=True): """ 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...
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...
def add_cpds(self, *cpds): """ 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 Exam...
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 ...
def to_joint_gaussian(self): """ 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 ...
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): """ 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. ...
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 ...
def factorset_product(*factorsets_list): 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_lis...
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...
def factorset_divide(factorset1, factorset2): 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:...
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...
def product(self, factorset, inplace=True): 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`. Paramete...
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...
def divide(self, factorset, inplace=True): 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}...
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...
def marginalize(self, variables, inplace=True): """ 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...
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 add_node(self, node, **attr): """ 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 = ...
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): """ 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'] ...
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...
def add_edge(self, start, end, **kwargs): """ 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 ...
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...
def add_edges_from(self, ebunch, **kwargs): """ 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 ...
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 ...
def get_intra_edges(self, time_slice=0): """ 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. ...
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...
def get_interface_nodes(self, time_slice=0): """ 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 Examp...
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 =...
def get_slice_nodes(self, time_slice=0): """ 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....
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 ...
def add_cpds(self, *cpds): """ 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...
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...
def remove_cpds(self, *cpds): """ 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`. ...
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...
def get_cpds(self, node=None, time_slice=0): """ 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 th...
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 ...
def check_model(self): """ 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 consist...
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...
def initialize_initial_state(self): """ 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 t...
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...
def moralize(self): """ 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 DynamicBa...
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 >>...
def copy(self): """ 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.d...
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...
def _legal_operations(self, model, tabu_list=[], max_indegree=None): """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 ...
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...
def estimate(self, start=None, tabu_length=0, max_indegree=None): """ 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 modifi...
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...
def get_elimination_order(self, nodes=None): """ 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 elimin...
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): """ 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 constituen...
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_cardinality(neig_node) for neig_node in self.moralized_model.neighbors(node)])
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 dictionary of STATICPROPERTIES Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_static_properties() {'FORMAT': 'MSR DTAS XML', 'VERSION': '0.2', 'CREATOR': 'Microsoft Research DTAS'} ""...
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']} ...
def get_variables(self): """ 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', ...
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): """ 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')] ...
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 ...
def get_distributions(self): """ 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['CONDS...
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 = [] for var, values in self.variable_CPD.i...
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...
def set_analysisnotebook(self, **data): """ Set attributes for ANALYSISNOTEBOOK tag Parameters ---------- **data: dict {name: value} for the attributes to be set. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter ...
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...
def set_static_properties(self, **data): """ Set STATICPROPERTIES tag for the network Parameters ---------- **data: dict {name: value} for name and value of the property. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNW...
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...
def set_edges(self, edge_list): """ 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.XMLBeliefNet...
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(...
def set_variables(self, data): """ 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 >>> wri...
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'...
def add_edge(self, u, v, **kwargs): """ 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 = F...
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...
def check_model(self): """ 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. ...
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() ...
def get_variable_nodes(self): """ 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...
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() ...
def get_factor_nodes(self): """ 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 Di...
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 ...
def to_markov_model(self): """ 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 p...
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 >>> ...
def get_factors(self, node=None): """ 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 pgm...
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.).
def _get_clique(self, junction_tree, nodes): """ 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 contai...
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 = self.state_names[variable] var_cardinality = len(var_states) state_counts = self.state_counts(variable, par...
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 ...
def _get_evidence(self, evidence_dict, time_slice, shift): """ 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 ...
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): """ 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 margi...
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 ...
def _update_belief(self, belief_prop, clique, clique_potential, message=None): """ Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor w...
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, evidence): """ 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 {...
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): """ 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....
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 ...
def forward_inference(self, variables, evidence=None, args=None): """ Forward inference method using belief propagation. Parameters: ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict ...
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 ...
def backward_inference(self, variables, evidence=None): """ 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...
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 ...
def query(self, variables, evidence=None, args='exact'): """ 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 ...
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...
def add_node(self, node, weight=None): """ 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 --...
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) ...
def add_nodes_from(self, nodes, weights=None): """ 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 ...
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...
def add_edge(self, u, v, weight=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: i...
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...
def moralize(self): """ 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 >>>...
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. Examples -------- >>> from pgmpy.base import DAG >>> graph = DAG([('A', 'B'), ('B', 'C'), ('B', 'D'), ('E', 'B')]) >>> graph.get_roots() ['A', 'E'] """ return [node for node, i...
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 ...
def get_independencies(self, latex=False): """ 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 ---...
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...
def local_independencies(self, variables): """ 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. ...
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 ...
def is_iequivalent(self, model): """ 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 ...
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 ...
def get_immoralities(self): """ 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 --------- >>>...
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...
def is_active_trail(self, start, end, observed=None): """ 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...
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 ...
def get_markov_blanket(self, node): """ 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 ...
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) ...
def active_trail_nodes(self, variables, observed=None): """ 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 tra...
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([...
def _get_ancestors_of(self, obs_nodes_list): """ 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 --------...