INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | def pdag_to_dag(pdag):
"""Completes a PDAG to a DAG, without adding v-structures, if such a
completion exists. If no faithful extension is possible, some fully
oriented DAG that corresponds to the PDAG is returned and a warning is
generated. This is a static method.
Parameters
... |
Construct the DAG pattern ( representing the I - equivalence class ) for a given DAG. This is the inverse to pdag_to_dag. | def model_to_pdag(model):
"""Construct the DAG pattern (representing the I-equivalence class) for
a given DAG. This is the "inverse" to pdag_to_dag.
"""
if not isinstance(model, DAG):
raise TypeError("model: Expected DAG instance, " +
"got type {m... |
Orients the edges of a graph skeleton based on information from separating_sets to form a DAG pattern ( DAG ). | def skeleton_to_pdag(skel, separating_sets):
"""Orients the edges of a graph skeleton based on information from
`separating_sets` to form a DAG pattern (DAG).
Parameters
----------
skel: UndirectedGraph
An undirected graph skeleton as e.g. produced by the
... |
Estimates a graph skeleton ( UndirectedGraph ) from a set of independencies using ( the first part of ) the PC algorithm. The independencies can either be provided as an instance of the Independencies - class or by passing a decision function that decides any conditional independency assertion. Returns a tuple ( skelet... | def build_skeleton(nodes, independencies):
"""Estimates a graph skeleton (UndirectedGraph) from a set of independencies
using (the first part of) the PC algorithm. The independencies can either be
provided as an instance of the `Independencies`-class or by passing a
decision function tha... |
A method that returns variable grammar | def get_variable_grammar(self):
"""
A method that returns variable grammar
"""
# Defining a expression for valid word
word_expr = Word(alphanums + '_' + '-')
word_expr2 = Word(initChars=printables, excludeChars=['{', '}', ',', ' '])
name_expr = Suppress('variable... |
A method that returns probability grammar | def get_probability_grammar(self):
"""
A method that returns probability grammar
"""
# Creating valid word expression for probability, it is of the format
# wor1 | var2 , var3 or var1 var2 var3 or simply var
word_expr = Word(alphanums + '-' + '_') + Suppress(Optional("|")... |
Retruns the name of the network | def get_network_name(self):
"""
Retruns the name of the network
Example
---------------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIF.BifReader("bif_test.bif")
>>> reader.network_name()
'Dog-Problem'
"""
start = self.network.f... |
Returns list of variables of the network | def get_variables(self):
"""
Returns list of variables of the network
Example
-------------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_variables()
['light-on','bowel_problem','dog-out','hear-bark','fami... |
Returns the states of variables present in the network | def get_states(self):
"""
Returns the states of variables present in the network
Example
-----------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_states()
{'bowel-problem': ['true','false'],
'dog-... |
Returns the property of the variable | def get_property(self):
"""
Returns the property of the variable
Example
-------------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_property()
{'bowel-problem': ['position = (335, 99)'],
'dog-out'... |
Returns the parents of the variables present in the network | def get_parents(self):
"""
Returns the parents of the variables present in the network
Example
--------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_parents()
{'bowel-problem': [],
'dog-out': ['fa... |
Returns the CPD of the variables present in the network | def get_values(self):
"""
Returns the CPD of the variables present in the network
Example
--------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_values()
{'bowel-problem': np.array([[0.01],
... |
Returns the edges of the network | def get_edges(self):
"""
Returns the edges of the network
Example
--------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_edges()
[['family-out', 'light-on'],
['family-out', 'dog-out'],
['... |
Returns the fitted bayesian model | def get_model(self):
"""
Returns the fitted bayesian model
Example
----------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIFReader("bif_test.bif")
>>> reader.get_model()
<pgmpy.models.BayesianModel.BayesianModel object at 0x7f20af154320>
... |
Create template for writing in BIF format | def BIF_templates(self):
"""
Create template for writing in BIF format
"""
network_template = Template('network $name {\n}\n')
# property tag may or may not be present in model,and since no of properties
# can be more than one , will replace them accoriding to format othe... |
Add states to variable of BIF | def get_states(self):
"""
Add states to variable of BIF
Returns
-------
dict: dict of type {variable: a list of states}
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
... |
Add property to variables in BIF | def get_properties(self):
"""
Add property to variables in BIF
Returns
-------
dict: dict of type {variable: list of properties }
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_mo... |
Add the parents to BIF | def get_parents(self):
"""
Add the parents to BIF
Returns
-------
dict: dict of type {variable: a list of parents}
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
>... |
Adds tables to BIF | def get_cpds(self):
"""
Adds tables to BIF
Returns
-------
dict: dict of type {variable: array}
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
>>> writer = BIFWrit... |
Writes the BIF data into a file | def write_bif(self, filename):
"""
Writes the BIF data into a file
Parameters
----------
filename : Name of the file
Example
-------
>>> from pgmpy.readwrite import BIFReader, BIFWriter
>>> model = BIFReader('dog-problem.bif').get_model()
... |
Makes a copy of the factor. | def copy(self):
"""
Makes a copy of the factor.
Returns
-------
CanonicalDistribution object: Copy of the factor
Examples
--------
>>> from pgmpy.factors.continuous import CanonicalDistribution
>>> phi = CanonicalDistribution(['X', 'Y'], np.array... |
Return an equivalent Joint Gaussian Distribution. | def to_joint_gaussian(self):
"""
Return an equivalent Joint Gaussian Distribution.
Examples
--------
>>> import numpy as np
>>> from pgmpy.factors.continuous import CanonicalDistribution
>>> phi = CanonicalDistribution(['x1', 'x2'], np.array([[3, -2], [-2, 4]]),... |
Reduces the distribution to the context of the given variable values. | def reduce(self, values, inplace=True):
"""
Reduces the distribution to the context of the given variable values.
Let C(X,Y ; K, h, g) be some canonical form over X,Y where,
k = [[K_XX, K_XY], ; h = [[h_X],
[K_YX, K_YY]] [h_Y]]
The... |
u Modifies the factor with marginalized values. | def marginalize(self, variables, inplace=True):
u"""
Modifies the factor with marginalized values.
Let C(X,Y ; K, h, g) be some canonical form over X,Y where,
k = [[K_XX, K_XY], ; h = [[h_X],
[K_YX, K_YY]] [h_Y]]
In this case, the ... |
Gives the CanonicalDistribution operation ( product or divide ) with the other factor. | def _operate(self, other, operation, inplace=True):
"""
Gives the CanonicalDistribution operation (product or divide) with
the other factor.
The product of two canonical factors over the same scope
X is simply:
C(K1, h1, g1) * C(K2, h2, g2) = C(K1+K2, h1+h2, g1+g2)
... |
Returns list of variables of the network | def get_variables(self):
"""
Returns list of variables of the network
Example
-------
>>> reader = PomdpXReader("pomdpx.xml")
>>> reader.get_variables()
{'StateVar': [
{'vnamePrev': 'rover_0',
'vnameCurr': 'rover_1... |
Returns the state action and observation variables as a dictionary in the case of table type parameter and a nested structure in case of decision diagram parameter | def get_initial_beliefs(self):
"""
Returns the state, action and observation variables as a dictionary
in the case of table type parameter and a nested structure in case of
decision diagram parameter
Examples
--------
>>> reader = PomdpXReader('Test_PomdpX.xml')
... |
Returns the transition of the state variables as nested dict in the case of table type parameter and a nested structure in case of decision diagram parameter | def get_state_transition_function(self):
"""
Returns the transition of the state variables as nested dict in the
case of table type parameter and a nested structure in case of
decision diagram parameter
Example
--------
>>> reader = PomdpXReader('Test_PomdpX.xml'... |
Returns the observation function as nested dict in the case of table - type parameter and a nested structure in case of decision diagram parameter | def get_obs_function(self):
"""
Returns the observation function as nested dict in the case of table-
type parameter and a nested structure in case of
decision diagram parameter
Example
--------
>>> reader = PomdpXReader('Test_PomdpX.xml')
>>> reader.get_... |
Returns the reward function as nested dict in the case of table - type parameter and a nested structure in case of decision diagram parameter | def get_reward_function(self):
"""
Returns the reward function as nested dict in the case of table-
type parameter and a nested structure in case of
decision diagram parameter
Example
--------
>>> reader = PomdpXReader('Test_PomdpX.xml')
>>> reader.get_re... |
This method supports the functional tags by providing the actual values in the function as list of dict in case of table type parameter or as nested dict in case of decision diagram | def get_parameter(self, var):
"""
This method supports the functional tags by providing the actual
values in the function as list of dict in case of table type parameter or as
nested dict in case of decision diagram
"""
parameter = []
for parameter_tag in var.fin... |
This method returns parameters as list of dict in case of table type parameter | def get_parameter_tbl(self, parameter):
"""
This method returns parameters as list of dict in case of table type
parameter
"""
par = []
for entry in parameter.findall('Entry'):
instance = defaultdict(list)
instance['Instance'] = entry.find('Instanc... |
This method returns parameters as nested dicts in case of decision diagram parameter. | def get_parameter_dd(self, parameter):
"""
This method returns parameters as nested dicts in case of decision
diagram parameter.
"""
dag = defaultdict(list)
dag_elem = parameter.find('DAG')
node = dag_elem.find('Node')
root = node.get('var')
def g... |
supports adding variables to the xml | def _add_value_enum(self, var, tag):
"""
supports adding variables to the xml
Parameters
---------------
var: The SubElement variable
tag: The SubElement tag to which enum value is to be added
Return
---------------
None
"""
if va... |
Add variables to PomdpX | def get_variables(self):
"""
Add variables to PomdpX
Return
---------------
xml containing variables tag
"""
state_variables = self.model['variables']['StateVar']
for var in state_variables:
state_var_tag = etree.SubElement(self.variable, 'Sta... |
helper function for adding parameters in condition | def add_parameter_dd(self, dag_tag, node_dict):
"""
helper function for adding parameters in condition
Parameters
---------------
dag_tag: etree SubElement
the DAG tag is contained in this subelement
node_dict: dictionary
the decision ... |
helper function for adding probability conditions for model \ | def add_conditions(self, condition, condprob):
"""
helper function for adding probability conditions for model\
Parameters
---------------
condition: dictionary
contains and element of conditions list
condprob: etree SubElement
... |
add initial belief tag to pomdpx model | def add_initial_belief(self):
"""
add initial belief tag to pomdpx model
Return
---------------
string containing the xml for initial belief tag
"""
initial_belief = self.model['initial_state_belief']
for condition in initial_belief:
condprob ... |
add state transition function tag to pomdpx model | def add_state_transition_function(self):
"""
add state transition function tag to pomdpx model
Return
---------------
string containing the xml for state transition tag
"""
state_transition_function = self.model['state_transition_function']
for condition ... |
add observation function tag to pomdpx model | def add_obs_function(self):
"""
add observation function tag to pomdpx model
Return
---------------
string containing the xml for observation function tag
"""
obs_function = self.model['obs_function']
for condition in obs_function:
condprob = ... |
add reward function tag to pomdpx model | 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 ] | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 | 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. | 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. | 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. | 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 | 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. | 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. | 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. | 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. | 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. | 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... |
Predicts states of all the missing variables. | 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. | 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
--------
... |
Checks whether the bayesian model is Imap of given JointProbabilityDistribution | 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
--------
... |
Returns a copy of the model. | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 - | 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. | 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. | 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 | 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 | 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. | 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 | 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 | 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. | 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. | 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. | 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. | 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 | 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 the index of the time_slice that the node ... | 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... |
Returns the CPDs that have been associated with the network. | 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... |
Removes the cpds that are provided in the argument. | 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`.
... |
Check the model for various errors. This method checks for the following errors. | def check_model(self):
"""
Check the model for various errors. This method checks for the following
errors.
* Checks if the 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 to add cpds as well as t... | 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 ). | 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. | 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 ( page 818 ). If a nu... | 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 parametrization. | 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. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.