本文整理汇总了Python中pgmpy.models.BayesianModel.edges方法的典型用法代码示例。如果您正苦于以下问题:Python BayesianModel.edges方法的具体用法?Python BayesianModel.edges怎么用?Python BayesianModel.edges使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pgmpy.models.BayesianModel
的用法示例。
在下文中一共展示了BayesianModel.edges方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_estimate_from_independencies
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import edges [as 别名]
def test_estimate_from_independencies(self):
ind = Independencies(['B', 'C'], ['A', ['B', 'C'], 'D'])
ind = ind.closure()
model = ConstraintBasedEstimator.estimate_from_independencies("ABCD", ind)
self.assertSetEqual(set(model.edges()),
set([('B', 'D'), ('A', 'D'), ('C', 'D')]))
model1 = BayesianModel([('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E')])
model2 = ConstraintBasedEstimator.estimate_from_independencies(
model1.nodes(),
model1.get_independencies())
self.assertTrue(set(model2.edges()) == set(model1.edges()) or
set(model2.edges()) == set([('B', 'C'), ('A', 'C'), ('C', 'E'), ('D', 'B')]))
示例2: get_model
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import edges [as 别名]
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('type') == "BayesianNetwork":
model = BayesianModel(self.probnet['edges'].keys())
tabular_cpds = []
cpds = self.probnet['Potentials']
for cpd in cpds:
var = list(cpd['Variables'].keys())[0]
states = self.probnet['Variables'][var]['States']
evidence = cpd['Variables'][var]
evidence_card = [len(self.probnet['Variables'][evidence_var]['States'])
for evidence_var in evidence]
arr = list(map(float, cpd['Values'].split()))
values = np.array(arr)
values = values.reshape((len(states), values.size//len(states)))
tabular_cpds.append(TabularCPD(var, len(states), values, evidence, evidence_card))
model.add_cpds(*tabular_cpds)
variables = model.nodes()
for var in variables:
for prop_name, prop_value in self.probnet['Variables'][var].items():
model.node[var][prop_name] = prop_value
edges = model.edges()
for edge in edges:
for prop_name, prop_value in self.probnet['edges'][edge].items():
model.edge[edge[0]][edge[1]][prop_name] = prop_value
return model
else:
raise ValueError("Please specify only Bayesian Network.")
示例3: print
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import edges [as 别名]
import numpy as np
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import BayesianEstimator
# Generating random data for two coin tossing examples
raw_data = np.random.randint(low=0, high=2, size=(1000, 2))
data = pd.DataFrame(raw_data, columns=['X', 'Y'])
print(data)
coin_model = BayesianModel()
coin_model.fit(data, estimator=BayesianEstimator)
coin_model.get_cpds()
coin_model.nodes()
coin_model.edges()
示例4: bayesnet
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import edges [as 别名]
#.........这里部分代码省略.........
import six # NOQA
def try_query(evidence):
print('--------')
query_vars = ut.setdiff_ordered(varnames, list(evidence.keys()))
evidence_str = ', '.join(pretty_evidence(evidence))
probs = name_belief.query(query_vars, evidence)
factor_list = probs.values()
joint_factor = pgmpy.factors.factor_product(*factor_list)
print('P(' + ', '.join(query_vars) + ' | ' + evidence_str + ')')
# print(six.text_type(joint_factor))
factor = joint_factor # NOQA
# print_factor(factor)
# import utool as ut
print(ut.hz_str([(f._str(phi_or_p='phi')) for f in factor_list]))
for evidence in evidence_dict:
try_query(evidence)
evidence = {'Aij': 1, 'Ajk': 1, 'Aki': 1, 'Ni': 0}
try_query(evidence)
evidence = {'Aij': 0, 'Ajk': 0, 'Aki': 0, 'Ni': 0}
try_query(evidence)
globals()['score_nice'] = score_nice
globals()['name_nice'] = name_nice
globals()['score_basis'] = score_basis
globals()['nid_basis'] = nid_basis
print('Independencies')
print(name_model.get_independencies())
print(name_model.local_independencies([Ni.variable]))
# name_belief = BeliefPropagation(name_model)
# # name_belief = VariableElimination(name_model)
# for case in special_cases:
# test_data = case.drop('Lk', axis=1)
# test_data = test_data.reset_index(drop=True)
# print('----')
# for i in range(test_data.shape[0]):
# evidence = test_data.loc[i].to_dict()
# probs = name_belief.query(['Lk'], evidence)
# factor = probs['Lk']
# probs = factor.values
# evidence_ = evidence.copy()
# evidence_['Li'] = name_nice[evidence['Li']]
# evidence_['Lj'] = name_nice[evidence['Lj']]
# evidence_['Sij'] = score_nice[evidence['Sij']]
# evidence_['Sjk'] = score_nice[evidence['Sjk']]
# nice2_prob = ut.odict(zip(name_nice, probs.tolist()))
# ut.print_python_code('P(Lk | {evidence}) = {cpt}'.format(
# evidence=(ut.repr2(evidence_, explicit=True, nobraces=True, strvals=True)),
# cpt=ut.repr3(nice2_prob, precision=3, align=True, key_order_metric='-val')
# ))
# for case in special_cases:
# test_data = case.drop('Lk', axis=1)
# test_data = test_data.drop('Lj', axis=1)
# test_data = test_data.reset_index(drop=True)
# print('----')
# for i in range(test_data.shape[0]):
# evidence = test_data.loc[i].to_dict()
# query_vars = ['Lk', 'Lj']
# probs = name_belief.query(query_vars, evidence)
# for queryvar in query_vars:
# factor = probs[queryvar]
# print(factor._str('phi'))
# probs = factor.values
# evidence_ = evidence.copy()
# evidence_['Li'] = name_nice[evidence['Li']]
# evidence_['Sij'] = score_nice[evidence['Sij']]
# evidence_['Sjk'] = score_nice[evidence['Sjk']]
# nice2_prob = ut.odict(zip([queryvar + '=' + x for x in name_nice], probs.tolist()))
# ut.print_python_code('P({queryvar} | {evidence}) = {cpt}'.format(
# query_var=query_var,
# evidence=(ut.repr2(evidence_, explicit=True, nobraces=True, strvals=True)),
# cpt=ut.repr3(nice2_prob, precision=3, align=True, key_order_metric='-val')
# ))
# _ draw model
import plottool as pt
import networkx as netx
fig = pt.figure() # NOQA
fig.clf()
ax = pt.gca()
netx_nodes = [(node, {}) for node in name_model.nodes()]
netx_edges = [(etup[0], etup[1], {}) for etup in name_model.edges()]
netx_graph = netx.DiGraph()
netx_graph.add_nodes_from(netx_nodes)
netx_graph.add_edges_from(netx_edges)
# pos = netx.graphviz_layout(netx_graph)
pos = netx.pydot_layout(netx_graph, prog='dot')
netx.draw(netx_graph, pos=pos, ax=ax, with_labels=True)
pt.plt.savefig('foo.png')
ut.startfile('foo.png')
示例5: TestBaseModelCreation
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import edges [as 别名]
class TestBaseModelCreation(unittest.TestCase):
def setUp(self):
self.G = BayesianModel()
def test_class_init_without_data(self):
self.assertIsInstance(self.G, nx.DiGraph)
def test_class_init_with_data_string(self):
self.g = BayesianModel([('a', 'b'), ('b', 'c')])
self.assertListEqual(sorted(self.g.nodes()), ['a', 'b', 'c'])
self.assertListEqual(hf.recursive_sorted(self.g.edges()),
[['a', 'b'], ['b', 'c']])
def test_class_init_with_data_nonstring(self):
BayesianModel([(1, 2), (2, 3)])
def test_add_node_string(self):
self.G.add_node('a')
self.assertListEqual(self.G.nodes(), ['a'])
def test_add_node_nonstring(self):
self.G.add_node(1)
def test_add_nodes_from_string(self):
self.G.add_nodes_from(['a', 'b', 'c', 'd'])
self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c', 'd'])
def test_add_nodes_from_non_string(self):
self.G.add_nodes_from([1, 2, 3, 4])
def test_add_edge_string(self):
self.G.add_edge('d', 'e')
self.assertListEqual(sorted(self.G.nodes()), ['d', 'e'])
self.assertListEqual(self.G.edges(), [('d', 'e')])
self.G.add_nodes_from(['a', 'b', 'c'])
self.G.add_edge('a', 'b')
self.assertListEqual(hf.recursive_sorted(self.G.edges()),
[['a', 'b'], ['d', 'e']])
def test_add_edge_nonstring(self):
self.G.add_edge(1, 2)
def test_add_edge_selfloop(self):
self.assertRaises(ValueError, self.G.add_edge, 'a', 'a')
def test_add_edge_result_cycle(self):
self.G.add_edges_from([('a', 'b'), ('a', 'c')])
self.assertRaises(ValueError, self.G.add_edge, 'c', 'a')
def test_add_edges_from_string(self):
self.G.add_edges_from([('a', 'b'), ('b', 'c')])
self.assertListEqual(sorted(self.G.nodes()), ['a', 'b', 'c'])
self.assertListEqual(hf.recursive_sorted(self.G.edges()),
[['a', 'b'], ['b', 'c']])
self.G.add_nodes_from(['d', 'e', 'f'])
self.G.add_edges_from([('d', 'e'), ('e', 'f')])
self.assertListEqual(sorted(self.G.nodes()),
['a', 'b', 'c', 'd', 'e', 'f'])
self.assertListEqual(hf.recursive_sorted(self.G.edges()),
hf.recursive_sorted([('a', 'b'), ('b', 'c'),
('d', 'e'), ('e', 'f')]))
def test_add_edges_from_nonstring(self):
self.G.add_edges_from([(1, 2), (2, 3)])
def test_add_edges_from_self_loop(self):
self.assertRaises(ValueError, self.G.add_edges_from,
[('a', 'a')])
def test_add_edges_from_result_cycle(self):
self.assertRaises(ValueError, self.G.add_edges_from,
[('a', 'b'), ('b', 'c'), ('c', 'a')])
def test_update_node_parents_bm_constructor(self):
self.g = BayesianModel([('a', 'b'), ('b', 'c')])
self.assertListEqual(self.g.predecessors('a'), [])
self.assertListEqual(self.g.predecessors('b'), ['a'])
self.assertListEqual(self.g.predecessors('c'), ['b'])
def test_update_node_parents(self):
self.G.add_nodes_from(['a', 'b', 'c'])
self.G.add_edges_from([('a', 'b'), ('b', 'c')])
self.assertListEqual(self.G.predecessors('a'), [])
self.assertListEqual(self.G.predecessors('b'), ['a'])
self.assertListEqual(self.G.predecessors('c'), ['b'])
def tearDown(self):
del self.G
示例6: TestBayesianModelMethods
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import edges [as 别名]
class TestBayesianModelMethods(unittest.TestCase):
def setUp(self):
self.G = BayesianModel([('a', 'd'), ('b', 'd'),
('d', 'e'), ('b', 'c')])
self.G1 = BayesianModel([('diff', 'grade'), ('intel', 'grade')])
diff_cpd = TabularCPD('diff', 2, values=[[0.2], [0.8]])
intel_cpd = TabularCPD('intel', 3, values=[[0.5], [0.3], [0.2]])
grade_cpd = TabularCPD('grade', 3, values=[[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8, 0.8, 0.8]],
evidence=['diff', 'intel'], evidence_card=[2, 3])
self.G1.add_cpds(diff_cpd, intel_cpd, grade_cpd)
self.G2 = BayesianModel([('d', 'g'), ('g', 'l'), ('i', 'g'), ('i', 'l')])
def test_moral_graph(self):
moral_graph = self.G.moralize()
self.assertListEqual(sorted(moral_graph.nodes()), ['a', 'b', 'c', 'd', 'e'])
for edge in moral_graph.edges():
self.assertTrue(edge in [('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'b'), ('e', 'd')] or
(edge[1], edge[0]) in [('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'b'), ('e', 'd')])
def test_moral_graph_with_edge_present_over_parents(self):
G = BayesianModel([('a', 'd'), ('d', 'e'), ('b', 'd'), ('b', 'c'), ('a', 'b')])
moral_graph = G.moralize()
self.assertListEqual(sorted(moral_graph.nodes()), ['a', 'b', 'c', 'd', 'e'])
for edge in moral_graph.edges():
self.assertTrue(edge in [('a', 'b'), ('c', 'b'), ('d', 'a'), ('d', 'b'), ('d', 'e')] or
(edge[1], edge[0]) in [('a', 'b'), ('c', 'b'), ('d', 'a'), ('d', 'b'), ('d', 'e')])
def test_get_ancestors_of_success(self):
ancenstors1 = self.G2._get_ancestors_of('g')
ancenstors2 = self.G2._get_ancestors_of('d')
ancenstors3 = self.G2._get_ancestors_of(['i', 'l'])
self.assertEqual(ancenstors1, {'d', 'i', 'g'})
self.assertEqual(ancenstors2, {'d'})
self.assertEqual(ancenstors3, {'g', 'i', 'l', 'd'})
def test_get_ancestors_of_failure(self):
self.assertRaises(ValueError, self.G2._get_ancestors_of, 'h')
def test_local_independencies(self):
self.assertEqual(self.G.local_independencies('a'), Independencies(['a', ['b', 'c']]))
self.assertEqual(self.G.local_independencies('c'), Independencies(['c', ['a', 'd', 'e'], 'b']))
self.assertEqual(self.G.local_independencies('d'), Independencies(['d', 'c', ['b', 'a']]))
self.assertEqual(self.G.local_independencies('e'), Independencies(['e', ['c', 'b', 'a'], 'd']))
self.assertEqual(self.G.local_independencies('b'), Independencies(['b', 'a']))
self.assertEqual(self.G1.local_independencies('grade'), Independencies())
def test_get_independencies(self):
chain = BayesianModel([('X', 'Y'), ('Y', 'Z')])
self.assertEqual(chain.get_independencies(), Independencies(('X', 'Z', 'Y'), ('Z', 'X', 'Y')))
fork = BayesianModel([('Y', 'X'), ('Y', 'Z')])
self.assertEqual(fork.get_independencies(), Independencies(('X', 'Z', 'Y'), ('Z', 'X', 'Y')))
collider = BayesianModel([('X', 'Y'), ('Z', 'Y')])
self.assertEqual(collider.get_independencies(), Independencies(('X', 'Z'), ('Z', 'X')))
def test_is_imap(self):
val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032,
0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128]
JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val)
fac = DiscreteFactor(['diff', 'intel', 'grade'], [2, 3, 3], val)
self.assertTrue(self.G1.is_imap(JPD))
self.assertRaises(TypeError, self.G1.is_imap, fac)
def test_get_immoralities(self):
G = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y')])
self.assertEqual(G.get_immoralities(), {('w', 'x'), ('w', 'z')})
G1 = BayesianModel([('x', 'y'), ('z', 'y'), ('z', 'x'), ('w', 'y')])
self.assertEqual(G1.get_immoralities(), {('w', 'x'), ('w', 'z')})
G2 = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y'), ('w', 'x')])
self.assertEqual(G2.get_immoralities(), {('w', 'z')})
def test_is_iequivalent(self):
G = BayesianModel([('x', 'y'), ('z', 'y'), ('x', 'z'), ('w', 'y')])
self.assertRaises(TypeError, G.is_iequivalent, MarkovModel())
G1 = BayesianModel([('V', 'W'), ('W', 'X'), ('X', 'Y'), ('Z', 'Y')])
G2 = BayesianModel([('W', 'V'), ('X', 'W'), ('X', 'Y'), ('Z', 'Y')])
self.assertTrue(G1.is_iequivalent(G2))
G3 = BayesianModel([('W', 'V'), ('W', 'X'), ('Y', 'X'), ('Z', 'Y')])
self.assertFalse(G3.is_iequivalent(G2))
def test_copy(self):
model_copy = self.G1.copy()
self.assertEqual(sorted(self.G1.nodes()), sorted(model_copy.nodes()))
self.assertEqual(sorted(self.G1.edges()), sorted(model_copy.edges()))
self.assertNotEqual(id(self.G1.get_cpds('diff')),
id(model_copy.get_cpds('diff')))
self.G1.remove_cpds('diff')
diff_cpd = TabularCPD('diff', 2, values=[[0.3], [0.7]])
self.G1.add_cpds(diff_cpd)
self.assertNotEqual(self.G1.get_cpds('diff'),
model_copy.get_cpds('diff'))
self.G1.remove_node('intel')
self.assertNotEqual(sorted(self.G1.nodes()), sorted(model_copy.nodes()))
self.assertNotEqual(sorted(self.G1.edges()), sorted(model_copy.edges()))
def test_remove_node(self):
#.........这里部分代码省略.........
示例7: BayesianModel
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import edges [as 别名]
# Bayesian network for students
from pgmpy.models import BayesianModel
model = BayesianModel()
# Add nodes
model.add_nodes_from(['difficulty', 'intelligence', 'grade', 'sat', 'letter'])
print(model.nodes())
# Add edges
model.add_edges_from([('difficulty', 'grade'), ('intelligence', 'grade'), ('intelligence', 'sat'), ('grade', 'letter')])
print(model.edges())