Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
>>> reader = UAIReader('TestUAI.uai')
>>> reader.get_model()
"""
if self.network_type == "BAYES":
model = BayesianModel()
model.add_nodes_from(self.variables)
model.add_edges_from(self.edges)
tabular_cpds = []
for cpd in self.tables:
child_var = cpd[0]
states = int(self.domain[child_var])
arr = list(map(float, cpd[1]))
values = np.array(arr)
values = values.reshape(states, values.size // states)
tabular_cpds.append(TabularCPD(child_var, states, values))
model.add_cpds(*tabular_cpds)
return model
elif self.network_type == "MARKOV":
model = MarkovModel(self.edges)
factors = []
for table in self.tables:
variables = table[0]
cardinality = [int(self.domain[var]) for var in variables]
value = list(map(float, table[1]))
factor = DiscreteFactor(
variables=variables, cardinality=cardinality, values=value
)
factors.append(factor)
>>> diff_cpd = TabularCPD(('D', 0), 2, [[0.6, 0.4]])
>>> intel_cpd = TabularCPD(('I', 0), 2, [[0.7, 0.3]])
>>> i_i_cpd = TabularCPD(('I', 1), 2, [[0.5, 0.4],
... [0.5, 0.6]],
... evidence=[('I', 0)],
... evidence_card=2)
>>> dbn.add_cpds(grade_cpd, d_i_cpd, diff_cpd, intel_cpd, i_i_cpd)
>>> dbn.get_cpds()
[,
,
,
,
]
"""
for cpd in cpds:
if not isinstance(cpd, TabularCPD):
raise ValueError("cpd should be an instance of TabularCPD")
if set(cpd.variables) - set(cpd.variables).intersection(
set(super(DynamicBayesianNetwork, self).nodes())
):
raise ValueError("CPD defined on variable not in the model", cpd)
self.cpds.extend(cpds)
# +---------+---------+---------+---------+---------+
cpd_g = TabularCPD(variable='G', variable_card=3,
values=[[0.3, 0.05, 0.9, 0.5],
[0.4, 0.25, 0.08, 0.3],
[0.3, 0.7, 0.02, 0.2]],
evidence=['I', 'D'],
evidence_card=[2, 2])
cpd_l = TabularCPD(variable='L', variable_card=2,
values=[[0.1, 0.4, 0.99],
[0.9, 0.6, 0.01]],
evidence=['G'],
evidence_card=[3])
cpd_s = TabularCPD(variable='S', variable_card=2,
values=[[0.95, 0.2],
[0.05, 0.8]],
evidence=['I'],
evidence_card=[2])
# Associating the CPDs with the network
model.add_cpds(cpd_d, cpd_i, cpd_g, cpd_l, cpd_s)
# check_model checks for the network structure and CPDs and verifies that the CPDs are correctly
# defined and sum to 1.
model.check_model()
from pgmpy.inference import VariableElimination
infer = VariableElimination(model)
# p(I=1)=0.3
# water sprinkler DGM
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
# Defining the model structure. We can define the network by just passing a list of edges.
model = BayesianModel([('C', 'S'), ('C', 'R'), ('S', 'W'), ('R', 'W')])
# Defining individual CPDs.
cpd_c = TabularCPD(variable='C', variable_card=2, values=[[0.5, 0.5]])
# In pgmpy the columns are the evidences and rows are the states of the variable.
cpd_s = TabularCPD(variable='S', variable_card=2,
values=[[0.5, 0.9],
[0.5, 0.1]],
evidence=['C'],
evidence_card=[2])
cpd_r = TabularCPD(variable='R', variable_card=2,
values=[[0.8, 0.2],
[0.2, 0.8]],
evidence=['C'],
evidence_card=[2])
cpd_w = TabularCPD(variable='W', variable_card=2,
values=[[1.0, 0.1, 0.1, 0.01],
[0.0, 0.9, 0.9, 0.99]],
evidence=['S', 'R'],
evidence_card=[2, 2])
cpd_d = TabularCPD(variable='D', variable_card=2, values=[paramsD])
cpd_i = TabularCPD(variable='I', variable_card=2, values=[paramsI])
cpd_g = TabularCPD(variable='G', variable_card=3,
values=np.reshape(paramsG, (3, 2*2)),# flat 2d matrix
evidence=['I', 'D'],
evidence_card=[2, 2])
cpd_l = TabularCPD(variable='L', variable_card=2,
values=paramsL,
evidence=['G'],
evidence_card=[3])
cpd_s = TabularCPD(variable='S', variable_card=2,
values=paramsS,
evidence=['I'],
evidence_card=[2])
model.add_cpds(cpd_d, cpd_i, cpd_g, cpd_l, cpd_s)
model.check_model()
inf_engine_ve = VariableElimination(model) # compute elim order only once
def infer_pgmpy(evidence, query):
factor = inf_engine_ve.query([query], evidence=evidence) [query]
marginal = factor.values # convert from DiscreteFactor to np array
return marginal
## Check both inference engines give same posterior marginals
## Now compute results using pgmpy
# DAG is specified a list of pairs
# eg [('D', 'G'), ('I', 'G'), ('G', 'L'), ('I', 'S')]
edges = []
nodes = list(dag.keys())
for n in nodes:
for pa in dag[n]:
edge = (pa, n)
edges.append(edge)
model = BayesianModel(edges)
cpd_d = TabularCPD(variable='D', variable_card=2, values=[paramsD])
cpd_i = TabularCPD(variable='I', variable_card=2, values=[paramsI])
cpd_g = TabularCPD(variable='G', variable_card=3,
values=np.reshape(paramsG, (3, 2*2)),# flat 2d matrix
evidence=['I', 'D'],
evidence_card=[2, 2])
cpd_l = TabularCPD(variable='L', variable_card=2,
values=paramsL,
evidence=['G'],
evidence_card=[3])
cpd_s = TabularCPD(variable='S', variable_card=2,
values=paramsS,
evidence=['I'],
evidence_card=[2])
>>> intel_cpd = TabularCPD(('I',0), 2, [[0.7, 0.3]])
>>> i_i_cpd = TabularCPD(('I', 1), 2, [[0.5, 0.4],
... [0.5, 0.6]],
... evidence=[('I', 0)],
... evidence_card=2)
>>> student.add_cpds(grade_cpd, d_i_cpd, diff_cpd, intel_cpd, i_i_cpd)
>>> student.initialize_initial_state()
"""
for cpd in self.cpds:
temp_var = (cpd.variable[0], 1 - cpd.variable[1])
parents = self.get_parents(temp_var)
if not any(x.variable == temp_var for x in self.cpds):
if all(x[1] == parents[0][1] for x in parents):
if parents:
evidence_card = cpd.cardinality[:0:-1]
new_cpd = TabularCPD(
temp_var,
cpd.variable_card,
cpd.values.reshape(
cpd.variable_card, np.prod(evidence_card)
),
parents,
evidence_card,
)
else:
if cpd.get_evidence():
initial_cpd = cpd.marginalize(
cpd.get_evidence(), inplace=False
)
new_cpd = TabularCPD(
temp_var,
cpd.variable_card,
def __init__(self, model):
self.model = model
model.check_model()
if isinstance(model, JunctionTree):
self.variables = set(chain(*model.nodes()))
else:
self.variables = model.nodes()
self.cardinality = {}
self.factors = defaultdict(list)
if isinstance(model, BayesianModel):
for node in model.nodes():
cpd = model.get_cpds(node)
if isinstance(cpd, TabularCPD):
self.cardinality[node] = cpd.variable_card
cpd = cpd.to_factor()
for var in cpd.scope():
self.factors[var].append(cpd)
elif isinstance(model, (MarkovModel, FactorGraph, JunctionTree)):
self.cardinality = model.get_cardinality()
for factor in model.get_factors():
for var in factor.variables:
self.factors[var].append(factor)
elif isinstance(model, DynamicBayesianNetwork):
self.start_bayesian_model = BayesianModel(model.get_intra_edges(0))
self.start_bayesian_model.add_cpds(*model.get_cpds(time_slice=0))
cpd_inter = [model.get_cpds(node) for node in model.get_interface_nodes(1)]
"""
try:
model = BayesianModel()
model.add_nodes_from(self.variable_names)
model.add_edges_from(self.variable_edges)
model.name = self.network_name
tabular_cpds = []
for var in sorted(self.variable_cpds.keys()):
values = self.variable_cpds[var]
sn = {
p_var: self.variable_states[p_var]
for p_var in self.variable_parents[var]
}
sn[var] = self.variable_states[var]
cpd = TabularCPD(
var,
len(self.variable_states[var]),
values,
evidence=self.variable_parents[var],
evidence_card=[
len(self.variable_states[evidence_var])
for evidence_var in self.variable_parents[var]
],
state_names=sn,
)
tabular_cpds.append(cpd)
model.add_cpds(*tabular_cpds)
if self.include_properties:
for node, properties in self.variable_properties.items():
# Defining the model structure. We can define the network by just passing a list of edges.
model = BayesianModel([('C', 'S'), ('C', 'R'), ('S', 'W'), ('R', 'W')])
# Defining individual CPDs.
cpd_c = TabularCPD(variable='C', variable_card=2, values=[[0.5, 0.5]])
# In pgmpy the columns are the evidences and rows are the states of the variable.
cpd_s = TabularCPD(variable='S', variable_card=2,
values=[[0.5, 0.9],
[0.5, 0.1]],
evidence=['C'],
evidence_card=[2])
cpd_r = TabularCPD(variable='R', variable_card=2,
values=[[0.8, 0.2],
[0.2, 0.8]],
evidence=['C'],
evidence_card=[2])
cpd_w = TabularCPD(variable='W', variable_card=2,
values=[[1.0, 0.1, 0.1, 0.01],
[0.0, 0.9, 0.9, 0.99]],
evidence=['S', 'R'],
evidence_card=[2, 2])
# Associating the CPDs with the network
model.add_cpds(cpd_c, cpd_s, cpd_r, cpd_w)
# check_model checks for the network structure and CPDs and verifies that the CPDs are correctly
# defined and sum to 1.