INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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([... | def add_edge(self, u, v, **kwargs):
"""
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
... |
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... | def check_model(self):
"""
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 runn... |
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()
... | def copy(self):
"""
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 JunctionTr... |
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... | def generate_probmodelxml(model, encoding='utf-8', prettyprint=True):
"""
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 ... |
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)
... | def write_probmodelxml(model, path, encoding='utf-8', prettyprint=True):
"""
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.
Filenam... |
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... | def get_probmodel_data(model):
"""
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
--------
>>> ... |
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():
etree.SubElement(add_prop, 'Property', attrib={'n... |
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(self.variables, 'Variable', attri... |
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={'var1': edge[0], 'var2': edge[1],
... |
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, 'Constraint', attrib={'name': constraint... |
Adds Decision Criteria to the ProbModelXML.
Parameters
----------
criteria_dict: dict
Dictionary containing Deecision Criteria data.
For example: {'effectiveness': {}, 'cost': {}}
Examples
-------
>>> writer = ProbModelXMLWriter(model)
>>... | def _add_decision_criteria(self, criteria_dict):
"""
Adds Decision Criteria to the ProbModelXML.
Parameters
----------
criteria_dict: dict
Dictionary containing Deecision Criteria data.
For example: {'effectiveness': {}, 'cost': {}}
Examples
... |
Adds Potentials to the ProbModelXML.
Parameters
----------
potential: dict
Dictionary containing Potential data.
For example: {'role': 'Utility',
'Variables': ['D0', 'D1', 'C0', 'C1'],
'type': 'Tree/ADD',
... | def _add_potential(self, potential, parent_tag):
"""
Adds Potentials to the ProbModelXML.
Parameters
----------
potential: dict
Dictionary containing Potential data.
For example: {'role': 'Utility',
'Variables': ['D0', 'D1', 'C0'... |
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/... | def _add_element(potential, var, potential_tag):
"""
Helper function to add variable tag to the potential_tag
Parameters
----------
potential: dict
Dictionary containing Potential data.
For example: {'role': 'Utility',
'Variables... |
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"?>' % self.encoding
stream.write(header.encode... |
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.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = ProbModelXMLWriter(model)
>>> writer.write_file(test_file)
"""
writer = self.__s... |
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.
"""
self.probnet = {}
# Add general properties
probnet_elem = self.xml.find('ProbNet')
self.probnet['type'... |
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... | def add_probnet_additionalconstraints(self, constraint):
"""
Adds Additional Constraints to the probnet dict.
Parameters
----------
criterion: <Element Constraint at AdditionalConstraints Node in XML>
etree Element consisting Constraint tag.
Examples
... |
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... | def add_criterion(self, criterion):
"""
Adds Decision Criteria to the probnet dict.
Parameters
----------
criterion: <Element Criterion at Decision Criteria Node in XML>
etree Element consisting DecisionCritera tag.
Examples
-------
>>> reade... |
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, variable):
"""
Adds Variables to the probnet dict.
Parameters
----------
variable: <Element Variable at Variables Node in XML>
etree Element consisting Variable tag.
Examples
-------
>>> reader = ProbModelXMLReader()
... |
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 Edges to the probnet dict.
Parameters
----------
edge: <Element Link at Links Node in XML>
etree Element consisting Variable tag.
Examples
-------
>>> reader = ProbModelXMLReader()
>>> reader.add_edg... |
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... | def add_potential(self, potential, potential_dict):
"""
Adds Potential to the potential dict.
Parameters
----------
potential: <Element Potential at Potentials node in XML>
etree Element consisting Potential tag.
potential_dict: dict{}
Dictionary ... |
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 ProbModel.
Return
---------------
model: an instance of BayesianModel.
Examples
-------
>>> reader = ProbModelXMLReader()
>>> reader.get_model()
"""
if self.probnet.get('t... |
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)... | def all_dags(self, nodes=None):
"""
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
----------
... |
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
-... | def all_scores(self):
"""
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... |
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... | def estimate(self):
"""
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
-------
... |
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, ... | def del_variables(self, variables):
"""
Deletes variables from the NoisyOrModel.
Parameters
----------
variables: list, tuple, dict (array like)
list of variables to be deleted.
Examples
--------
>>> from pgmpy.models import NoisyOrModel
... |
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
... | def add_variables(self, variables, cardinality, inhibitor_probability):
"""
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, t... |
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:
warn("Pandas installation not found. Returning n... |
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 = 0.5 * np.dot(sub_vec, grad)
return grad, lo... |
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 step in time for updating position position
... |
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... | def get_cardinality(self, variables):
"""
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}
... |
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.
... | def assignment(self, index):
"""
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 assignme... |
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
-----... | def identity_factor(self):
"""
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 th... |
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... | def marginalize(self, variables, inplace=True):
"""
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 f... |
Normalizes the values of factor so that they sum to 1.
Parameters
----------
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor
Returns
-------
DiscreteFactor or None: if inplace=True (default) retur... | def normalize(self, inplace=True):
"""
Normalizes the values of factor so that they sum to 1.
Parameters
----------
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor
Returns
-------
... |
Reduces the factor 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 factor 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 ... |
DiscreteFactor sum with `phi1`.
Parameters
----------
phi1: `DiscreteFactor` instance.
DiscreteFactor to be added.
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor.
Returns
-------
... | def sum(self, phi1, inplace=True):
"""
DiscreteFactor sum with `phi1`.
Parameters
----------
phi1: `DiscreteFactor` instance.
DiscreteFactor to be added.
inplace: boolean
If inplace=True it will modify the factor itself, else would return
... |
DiscreteFactor division by `phi1`.
Parameters
----------
phi1 : `DiscreteFactor` instance
The denominator for division.
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor.
Returns
------... | def divide(self, phi1, inplace=True):
"""
DiscreteFactor division by `phi1`.
Parameters
----------
phi1 : `DiscreteFactor` instance
The denominator for division.
inplace: boolean
If inplace=True it will modify the factor itself, else would return... |
Returns a copy of the factor.
Returns
-------
DiscreteFactor: copy of the factor
Examples
--------
>>> import numpy as np
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> phi = DiscreteFactor(['x1', 'x2', 'x3'], [2, 3, 3], np.arange(18))
... | def copy(self):
"""
Returns a copy of the factor.
Returns
-------
DiscreteFactor: copy of the factor
Examples
--------
>>> import numpy as np
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> phi = DiscreteFactor(['x1', 'x2', 'x3'... |
Checks whether given parameter is a 1d array like object, and returns a numpy array object | def _check_1d_array_object(parameter, name_param):
"""
Checks whether given parameter is a 1d array like object, and returns a numpy array object
"""
if isinstance(parameter, (np.ndarray, list, tuple, np.matrix)):
parameter = np.array(parameter)
if parameter.ndim != 1:
raise ... |
Generate the string from `__str__` method.
Parameters
----------
phi_or_p: 'phi' | 'p'
'phi': When used for Factors.
'p': When used for CPDs.
print_state_names: boolean
If True, the user defined state names are displayed. | def _str(self, phi_or_p="phi", tablefmt="grid", print_state_names=True):
"""
Generate the string from `__str__` method.
Parameters
----------
phi_or_p: 'phi' | 'p'
'phi': When used for Factors.
'p': When used for CPDs.
print_state_names:... |
Raises an error when the length of given two arguments is not equal | def _check_length_equal(param_1, param_2, name_param_1, name_param_2):
"""
Raises an error when the length of given two arguments is not equal
"""
if len(param_1) != len(param_2):
raise ValueError("Length of {} must be same as Length of {}".format(name_param_1, name_param_2)) |
Returns list of variables of the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_variables()
['light-on', 'bowel-problem', 'dog-out', 'hear-bark', 'family-out'] | def get_variables(self):
"""
Returns list of variables of the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_variables()
['light-on', 'bowel-problem', 'dog-out', 'hear-bark', 'family-out']
"""
variable... |
Returns the edges of the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_edges()
[['family-out', 'light-on'],
['family-out', 'dog-out'],
['bowel-problem', 'dog-out'],
['dog-out', 'hear-bark']] | def get_edges(self):
"""
Returns the edges of the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_edges()
[['family-out', 'light-on'],
['family-out', 'dog-out'],
['bowel-problem', 'dog-out'],
... |
Returns the states of variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_states()
{'bowel-problem': ['true', 'false'],
'dog-out': ['true', 'false'],
'family-out': ['true', 'false'],
'he... | def get_states(self):
"""
Returns the states of variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_states()
{'bowel-problem': ['true', 'false'],
'dog-out': ['true', 'false'],
'fa... |
Returns the parents of the variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_parents()
{'bowel-problem': [],
'dog-out': ['family-out', 'bowel-problem'],
'family-out': [],
'hear-bark': ... | def get_parents(self):
"""
Returns the parents of the variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_parents()
{'bowel-problem': [],
'dog-out': ['family-out', 'bowel-problem'],
... |
Returns the CPD of the variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_values()
{'bowel-problem': array([[ 0.01],
[ 0.99]]),
'dog-out': array([[ 0.99, 0.01, 0.97, 0... | def get_values(self):
"""
Returns the CPD of the variables present in the network
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_values()
{'bowel-problem': array([[ 0.01],
[ 0.99]]),
... |
Returns the property of the variable
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_property()
{'bowel-problem': ['position = (190, 69)'],
'dog-out': ['position = (155, 165)'],
'family-out': ['position = (112, 69)'],
... | def get_property(self):
"""
Returns the property of the variable
Examples
--------
>>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml")
>>> reader.get_property()
{'bowel-problem': ['position = (190, 69)'],
'dog-out': ['position = (155, 165)'],
'f... |
Add variables to XMLBIF
Return
------
dict: dict of type {variable: variable tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_variables()
{'bowel-problem': <Element VARIABLE at 0x7fe28607dd88>,
'family-out': <Element VARIA... | def get_variables(self):
"""
Add variables to XMLBIF
Return
------
dict: dict of type {variable: variable tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_variables()
{'bowel-problem': <Element VARIABLE at 0x7fe2860... |
Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Element OUTCOME at 0x7ffbabfcdec8>, <Element OUTCOME at 0x7ffbabfcdf08>]... | def get_states(self):
"""
Add outcome to variables of XMLBIF
Return
------
dict: dict of type {variable: outcome tags}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_states()
{'dog-out': [<Element OUTCOME at 0x7ffbabfcd... |
Transform the input state_name into a valid state in XMLBIF.
XMLBIF states must start with a letter an only contain letters,
numbers and underscores. | def _make_valid_state_name(self, state_name):
"""Transform the input state_name into a valid state in XMLBIF.
XMLBIF states must start with a letter an only contain letters,
numbers and underscores.
"""
s = str(state_name)
s_fixed = pp.CharsNotIn(pp.alphanums + "_").setPa... |
Add property to variables in XMLBIF
Return
------
dict: dict of type {variable: property tag}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_property()
{'light-on': <Element PROPERTY at 0x7f7a2ffac1c8>,
'family-out': <Element ... | def get_properties(self):
"""
Add property to variables in XMLBIF
Return
------
dict: dict of type {variable: property tag}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_property()
{'light-on': <Element PROPERTY at 0x7... |
Add Definition to XMLBIF
Return
------
dict: dict of type {variable: definition tag}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_definition()
{'hear-bark': <Element DEFINITION at 0x7f1d48977408>,
'family-out': <Element DEFI... | def get_definition(self):
"""
Add Definition to XMLBIF
Return
------
dict: dict of type {variable: definition tag}
Examples
--------
>>> writer = XMLBIFWriter(model)
>>> writer.get_definition()
{'hear-bark': <Element DEFINITION at 0x7f1d4... |
Add Table to XMLBIF.
Return
---------------
dict: dict of type {variable: table tag}
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.get_values()
{'dog-out': <Element TABLE at 0x7f240726f3c8>,
'light-on': <Element TABLE at 0x7f24072... | def get_values(self):
"""
Add Table to XMLBIF.
Return
---------------
dict: dict of type {variable: table tag}
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.get_values()
{'dog-out': <Element TABLE at 0x7f240726f3c8>,
... |
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file) | def write_xmlbif(self, filename):
"""
Write the xml data into the file.
Parameters
----------
filename: Name of the file.
Examples
-------
>>> writer = XMLBIFWriter(model)
>>> writer.write_xmlbif(test_file)
"""
with open(filename,... |
Returns the marginal distribution over variables.
Parameters
----------
variables: string, list, tuple, set, dict
Variable or list of variables over which marginal distribution needs
to be calculated
inplace: Boolean (default True)
If Fals... | def marginal_distribution(self, variables, inplace=True):
"""
Returns the marginal distribution over variables.
Parameters
----------
variables: string, list, tuple, set, dict
Variable or list of variables over which marginal distribution needs
to... |
Check if the Joint Probability Distribution satisfies the given independence condition.
Parameters
----------
event1: list
random variable whose independence is to be checked.
event2: list
random variable from which event1 is independent.
values: 2D array... | def check_independence(self, event1, event2, event3=None, condition_random_variable=False):
"""
Check if the Joint Probability Distribution satisfies the given independence condition.
Parameters
----------
event1: list
random variable whose independence is to be chec... |
Returns the independent variables in the joint probability distribution.
Returns marginally independent variables if condition=None.
Returns conditionally independent variables if condition!=None
Parameter
---------
condition: array_like
Random Variable on which ... | def get_independencies(self, condition=None):
"""
Returns the independent variables in the joint probability distribution.
Returns marginally independent variables if condition=None.
Returns conditionally independent variables if condition!=None
Parameter
---------
... |
Returns a Bayesian Model which is minimal IMap of the Joint Probability Distribution
considering the order of the variables.
Parameters
----------
order: array-like
The order of the random variables.
Examples
--------
>>> import numpy as np
>... | def minimal_imap(self, order):
"""
Returns a Bayesian Model which is minimal IMap of the Joint Probability Distribution
considering the order of the variables.
Parameters
----------
order: array-like
The order of the random variables.
Examples
... |
Returns Conditional Probability Distribution after setting values to 1.
Parameters
----------
values: list or array_like
A list of tuples of the form (variable_name, variable_state).
The values on which to condition the Joint Probability Distribution.
inplace: Bo... | def conditional_distribution(self, values, inplace=True):
"""
Returns Conditional Probability Distribution after setting values to 1.
Parameters
----------
values: list or array_like
A list of tuples of the form (variable_name, variable_state).
The values... |
Checks whether the given BayesianModel is Imap of JointProbabilityDistribution
Parameters
-----------
model : An instance of BayesianModel Class, for which you want to
check the Imap
Returns
--------
boolean : True if given bayesian model is Imap for Joint P... | def is_imap(self, model):
"""
Checks whether the given BayesianModel is Imap of JointProbabilityDistribution
Parameters
-----------
model : An instance of BayesianModel Class, for which you want to
check the Imap
Returns
--------
boolean : Tr... |
Returns the acceptance probability for given new position(position) and momentum | def _acceptance_prob(self, position, position_bar, momentum, momentum_bar):
"""
Returns the acceptance probability for given new position(position) and momentum
"""
# Parameters to help in evaluating Joint distribution P(position, momentum)
_, logp = self.grad_log_pdf(position, ... |
Temporary method to fix issue in numpy 0.12 #852 | def _get_condition(self, acceptance_prob, a):
"""
Temporary method to fix issue in numpy 0.12 #852
"""
if a == 1:
return (acceptance_prob ** a) > (1/(2**a))
else:
return (1/(acceptance_prob ** a)) > (2**(-a)) |
Method for choosing initial value of stepsize
References
-----------
Matthew D. Hoffman, Andrew Gelman, The No-U-Turn Sampler: Adaptively
Setting Path Lengths in Hamiltonian Monte Carlo. Journal of
Machine Learning Research 15 (2014) 1351-1381
Algorithm 4 : Heuristic for... | def _find_reasonable_stepsize(self, position, stepsize_app=1):
"""
Method for choosing initial value of stepsize
References
-----------
Matthew D. Hoffman, Andrew Gelman, The No-U-Turn Sampler: Adaptively
Setting Path Lengths in Hamiltonian Monte Carlo. Journal of
... |
Runs a single sampling iteration to return a sample | def _sample(self, position, trajectory_length, stepsize, lsteps=None):
"""
Runs a single sampling iteration to return a sample
"""
# Resampling momentum
momentum = np.reshape(np.random.normal(0, 1, len(position)), position.shape)
# position_m here will be the previous sa... |
Method to return samples using Hamiltonian Monte Carlo
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_samples: int
Number of samples to be generated
... | def sample(self, initial_pos, num_samples, trajectory_length, stepsize=None, return_type='dataframe'):
"""
Method to return samples using Hamiltonian Monte Carlo
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter positio... |
Method returns a generator type object whose each iteration yields a sample
using Hamiltonian Monte Carlo
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_... | def generate_sample(self, initial_pos, num_samples, trajectory_length, stepsize=None):
"""
Method returns a generator type object whose each iteration yields a sample
using Hamiltonian Monte Carlo
Parameters
----------
initial_pos: A 1d array like object
Vect... |
Run tha adaptation for stepsize for better proposals of position | def _adapt_params(self, stepsize, stepsize_bar, h_bar, mu, index_i, alpha, n_alpha=1):
"""
Run tha adaptation for stepsize for better proposals of position
"""
gamma = 0.05 # free parameter that controls the amount of shrinkage towards mu
t0 = 10.0 # free parameter that stabili... |
Method returns a generator type object whose each iteration yields a sample
using Hamiltonian Monte Carlo
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_... | def generate_sample(self, initial_pos, num_adapt, num_samples, trajectory_length, stepsize=None):
"""
Method returns a generator type object whose each iteration yields a sample
using Hamiltonian Monte Carlo
Parameters
----------
initial_pos: A 1d array like object
... |
A list of states example -
[('x1', 'easy'), ('x2', 'hard')]
Returns
-------
True, if arg is a list of states else False. | def is_list_of_states(self, arg):
"""
A list of states example -
[('x1', 'easy'), ('x2', 'hard')]
Returns
-------
True, if arg is a list of states else False.
"""
return isinstance(arg, list) and all(isinstance(i, tuple) for i in arg) |
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... |
Check if the given nodes form a clique.
Parameters
----------
nodes: list, array-like
List of nodes to check if they are a part of any clique.
Examples
--------
>>> from pgmpy.base import UndirectedGraph
>>> G = UndirectedGraph(ebunch=[('A', 'B'), ('... | def is_clique(self, nodes):
"""
Check if the given nodes form a clique.
Parameters
----------
nodes: list, array-like
List of nodes to check if they are a part of any clique.
Examples
--------
>>> from pgmpy.base import UndirectedGraph
... |
Set the start state of the Markov Chain. If the start_state is given as a array-like iterable, its contents
are reordered in the internal representation.
Parameters:
-----------
start_state: dict or array-like iterable object
Dict (or list) of tuples representing the startin... | def set_start_state(self, start_state):
"""
Set the start state of the Markov Chain. If the start_state is given as a array-like iterable, its contents
are reordered in the internal representation.
Parameters:
-----------
start_state: dict or array-like iterable object
... |
Checks if a list representing the state of the variables is valid. | def _check_state(self, state):
"""
Checks if a list representing the state of the variables is valid.
"""
if not hasattr(state, '__iter__') or isinstance(state, six.string_types):
raise ValueError('Start state must be a non-string iterable object.')
state_vars = {s.va... |
Add a variable to the model.
Parameters:
-----------
variable: any hashable python object
card: int
Representing the cardinality of the variable to be added.
Examples:
---------
>>> from pgmpy.models import MarkovChain as MC
>>> model = MC()... | def add_variable(self, variable, card=0):
"""
Add a variable to the model.
Parameters:
-----------
variable: any hashable python object
card: int
Representing the cardinality of the variable to be added.
Examples:
---------
>>> from ... |
Add several variables to the model at once.
Parameters:
-----------
variables: array-like iterable object
List of variables to be added.
cards: array-like iterable object
List of cardinalities of the variables to be added.
Examples:
---------
... | def add_variables_from(self, variables, cards):
"""
Add several variables to the model at once.
Parameters:
-----------
variables: array-like iterable object
List of variables to be added.
cards: array-like iterable object
List of cardinalities o... |
Adds a transition model for a particular variable.
Parameters:
-----------
variable: any hashable python object
must be an existing variable of the model.
transition_model: dict or 2d array
dict representing valid transition probabilities defined for every possib... | def add_transition_model(self, variable, transition_model):
"""
Adds a transition model for a particular variable.
Parameters:
-----------
variable: any hashable python object
must be an existing variable of the model.
transition_model: dict or 2d array
... |
Given an instantiation (partial or complete) of the variables of the model,
compute the probability of observing it over multiple windows in a given sample.
If 'sample' is not passed as an argument, generate the statistic by sampling from the
Markov Chain, starting with a random initial state.
... | def prob_from_sample(self, state, sample=None, window_size=None):
"""
Given an instantiation (partial or complete) of the variables of the model,
compute the probability of observing it over multiple windows in a given sample.
If 'sample' is not passed as an argument, generate the stati... |
Sample from the Markov Chain.
Parameters:
-----------
start_state: dict or array-like iterable
Representing the starting states of the variables. If None is passed, a random start_state is chosen.
size: int
Number of samples to be generated.
Return Type:... | def sample(self, start_state=None, size=1):
"""
Sample from the Markov Chain.
Parameters:
-----------
start_state: dict or array-like iterable
Representing the starting states of the variables. If None is passed, a random start_state is chosen.
size: int
... |
Generator version of self.sample
Return Type:
------------
List of State namedtuples, representing the assignment to all variables of the model.
Examples:
---------
>>> from pgmpy.models.MarkovChain import MarkovChain
>>> from pgmpy.factors.discrete import State... | def generate_sample(self, start_state=None, size=1):
"""
Generator version of self.sample
Return Type:
------------
List of State namedtuples, representing the assignment to all variables of the model.
Examples:
---------
>>> from pgmpy.models.MarkovChai... |
Checks if the given markov chain is stationary and checks the steady state
probablity values for the state are consistent.
Parameters:
-----------
tolerance: float
represents the diff between actual steady state value and the computed value
sample: [State(i,j)]
... | def is_stationarity(self, tolerance=0.2, sample=None):
"""
Checks if the given markov chain is stationary and checks the steady state
probablity values for the state are consistent.
Parameters:
-----------
tolerance: float
represents the diff between actual s... |
Generates a random state of the Markov Chain.
Return Type:
------------
List of namedtuples, representing a random assignment to all variables of the model.
Examples:
---------
>>> from pgmpy.models import MarkovChain as MC
>>> model = MC(['intel', 'diff'], [2, ... | def random_state(self):
"""
Generates a random state of the Markov Chain.
Return Type:
------------
List of namedtuples, representing a random assignment to all variables of the model.
Examples:
---------
>>> from pgmpy.models import MarkovChain as MC
... |
Returns a copy of Markov Chain Model.
Return Type:
------------
MarkovChain : Copy of MarkovChain.
Examples:
---------
>>> from pgmpy.models import MarkovChain
>>> from pgmpy.factors.discrete import State
>>> model = MarkovChain()
>>> model.add_v... | def copy(self):
"""
Returns a copy of Markov Chain Model.
Return Type:
------------
MarkovChain : Copy of MarkovChain.
Examples:
---------
>>> from pgmpy.models import MarkovChain
>>> from pgmpy.factors.discrete import State
>>> model = M... |
Returns `True` if `assertion` is contained in this `Independencies`-object,
otherwise `False`.
Parameters
----------
assertion: IndependenceAssertion()-object
Examples
--------
>>> from pgmpy.independencies import Independencies, IndependenceAssertion
>>... | def contains(self, assertion):
"""
Returns `True` if `assertion` is contained in this `Independencies`-object,
otherwise `False`.
Parameters
----------
assertion: IndependenceAssertion()-object
Examples
--------
>>> from pgmpy.independencies impo... |
Adds assertions to independencies.
Parameters
----------
assertions: Lists or Tuples
Each assertion is a list or tuple of variable, independent_of and given.
Examples
--------
>>> from pgmpy.independencies import Independencies
>>> independencies... | def add_assertions(self, *assertions):
"""
Adds assertions to independencies.
Parameters
----------
assertions: Lists or Tuples
Each assertion is a list or tuple of variable, independent_of and given.
Examples
--------
>>> from pgmpy.inde... |
Returns a new `Independencies()`-object that additionally contains those `IndependenceAssertions`
that are implied by the the current independencies (using with the `semi-graphoid axioms
<https://en.wikipedia.org/w/index.php?title=Conditional_independence&oldid=708760689#Rules_of_conditional_independenc... | def closure(self):
"""
Returns a new `Independencies()`-object that additionally contains those `IndependenceAssertions`
that are implied by the the current independencies (using with the `semi-graphoid axioms
<https://en.wikipedia.org/w/index.php?title=Conditional_independence&oldid=708... |
Returns `True` if the `entailed_independencies` are implied by this `Independencies`-object, otherwise `False`.
Entailment is checked using the semi-graphoid axioms.
Might be very slow if more than six variables are involved.
Parameters
----------
entailed_independencies: Indep... | def entails(self, entailed_independencies):
"""
Returns `True` if the `entailed_independencies` are implied by this `Independencies`-object, otherwise `False`.
Entailment is checked using the semi-graphoid axioms.
Might be very slow if more than six variables are involved.
Para... |
Returns a list of all ancestors of all the observed nodes.
Parameters
----------
obs_nodes_list: string, list-type
name of all the observed nodes | def _get_ancestors_of(self, obs_nodes_list):
"""
Returns a list of all ancestors of all the observed nodes.
Parameters
----------
obs_nodes_list: string, list-type
name of all the observed nodes
"""
if not obs_nodes_list:
return set()
... |
Returns all the nodes reachable from start via an active trail.
Parameters
----------
start: Graph node
observed : List of nodes (optional)
If given the active trail would be computed assuming these nodes to be observed.
Examples
--------
>>> from p... | def active_trail_nodes(self, start, observed=None):
"""
Returns all the nodes reachable from start via an active trail.
Parameters
----------
start: Graph node
observed : List of nodes (optional)
If given the active trail would be computed assuming these nod... |
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 found.
Examples
--------
>>> from pgmpy.models import ... | 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 found.
... |
Computes the CPD for each node from a given data in the form of a pandas dataframe.
If a variable from the data is not present in the model, it adds that node into the model.
Parameters
----------
data : pandas DataFrame object
A DataFrame object with column names same as th... | def fit(self, data, parent_node=None, estimator=None):
"""
Computes the CPD for each node from a given data in the form of a pandas dataframe.
If a variable from the data is not present in the model, it adds that node into the model.
Parameters
----------
data : pandas D... |
Computes a score to measure how well the given `BayesianModel` fits to the data set.
(This method relies on the `local_score`-method that is implemented in each subclass.)
Parameters
----------
model: `BayesianModel` instance
The Bayesian network that is to be scored. Nodes ... | def score(self, model):
"""
Computes a score to measure how well the given `BayesianModel` fits to the data set.
(This method relies on the `local_score`-method that is implemented in each subclass.)
Parameters
----------
model: `BayesianModel` instance
The B... |
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... |
Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
2-D array of shape (M, len(arrays)) cont... | def cartesian(arrays, out=None):
"""Generate a cartesian product of input arrays.
Parameters
----------
arrays : list of array-like
1-D arrays to form the cartesian product of.
out : ndarray
Array to place the cartesian product in.
Returns
-------
out : ndarray
... |
Generate a sample of given size, given a probability mass function.
Parameters
----------
values: numpy.array: Array of all possible values that the random variable
can take.
weights: numpy.array or list of numpy.array: Array(s) representing the PMF of the random variable.
size: int: Si... | def sample_discrete(values, weights, size=1):
"""
Generate a sample of given size, given a probability mass function.
Parameters
----------
values: numpy.array: Array of all possible values that the random variable
can take.
weights: numpy.array or list of numpy.array: Array(s) repr... |
Generates all subsets of list `l` (as tuples).
Example
-------
>>> from pgmpy.utils.mathext import powerset
>>> list(powerset([1,2,3]))
[(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)] | def powerset(l):
"""
Generates all subsets of list `l` (as tuples).
Example
-------
>>> from pgmpy.utils.mathext import powerset
>>> list(powerset([1,2,3]))
[(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]
"""
return chain.from_iterable(combinations(l, r) for r in range(len(l)+1... |
Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter | def clean_draft_pages_from_space(confluence, space_key, count, date_now):
"""
Remove draft pages from space using datetime.now
:param confluence:
:param space_key:
:param count:
:param date_now:
:return: int counter
"""
pages = confluence.get_all_draft_pages_from_space(space=space_ke... |
Provide content by type (page, blog, comment)
:param page_id: A string containing the id of the type content container.
:param type:
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: how many items should be returned after the... | def get_page_child_by_type(self, page_id, type='page', start=None, limit=None):
"""
Provide content by type (page, blog, comment)
:param page_id: A string containing the id of the type content container.
:param type:
:param start: OPTIONAL: The start point of the collection to re... |
Returns the list of labels on a piece of Content.
:param space: Space key
:param title: Title of the page
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of labels to return, this may be restricted by... | def get_page_by_title(self, space, title, start=None, limit=None):
"""
Returns the list of labels on a piece of Content.
:param space: Space key
:param title: Title of the page
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param ... |
Remove all draft pages for all spaces older than DRAFT_DAYS
:param days: int
:param confluence:
:return: | def clean_all_draft_pages_from_all_spaces(confluence, days=30):
"""
Remove all draft pages for all spaces older than DRAFT_DAYS
:param days: int
:param confluence:
:return:
"""
date_now = datetime.datetime.now()
count = 0
limit = 50
flag = True
i = 0
while flag:
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.