本文整理汇总了Python中pgmpy.models.BayesianModel.nodes方法的典型用法代码示例。如果您正苦于以下问题:Python BayesianModel.nodes方法的具体用法?Python BayesianModel.nodes怎么用?Python BayesianModel.nodes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pgmpy.models.BayesianModel
的用法示例。
在下文中一共展示了BayesianModel.nodes方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_estimate_from_independencies
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [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 nodes [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: test_build_skeleton
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [as 别名]
def test_build_skeleton(self):
ind = Independencies(['B', 'C'], ['A', ['B', 'C'], 'D'])
ind = ind.closure()
skel1, sep_sets1 = ConstraintBasedEstimator.build_skeleton("ABCD", ind)
self.assertTrue(self._edge_list_equal(skel1.edges(), [('A', 'D'), ('B', 'D'), ('C', 'D')]))
sep_sets_ref1 = {frozenset({'A', 'C'}): (), frozenset({'A', 'B'}): (), frozenset({'C', 'B'}): ()}
self.assertEqual(sep_sets1, sep_sets_ref1)
model = BayesianModel([('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E')])
skel2, sep_sets2 = ConstraintBasedEstimator.build_skeleton(model.nodes(), model.get_independencies())
self.assertTrue(self._edge_list_equal(skel2, [('D', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'E')]))
sep_sets_ref2 = {frozenset({'D', 'C'}): ('B',),
frozenset({'E', 'B'}): ('C',),
frozenset({'A', 'D'}): (),
frozenset({'E', 'D'}): ('C',),
frozenset({'E', 'A'}): ('C',),
frozenset({'A', 'B'}): ()}
# witnesses/seperators might change on each run, so we cannot compare directly
self.assertEqual(sep_sets2.keys(), sep_sets_ref2.keys())
self.assertEqual([len(v) for v in sorted(sep_sets2.values())],
[len(v) for v in sorted(sep_sets_ref2.values())])
示例4: print
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [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()
示例5: TestGibbsSampling
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [as 别名]
class TestGibbsSampling(unittest.TestCase):
def setUp(self):
# A test Bayesian model
diff_cpd = TabularCPD('diff', 2, [[0.6], [0.4]])
intel_cpd = TabularCPD('intel', 2, [[0.7], [0.3]])
grade_cpd = TabularCPD('grade', 3, [[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=['diff', 'intel'], evidence_card=[2, 2])
self.bayesian_model = BayesianModel()
self.bayesian_model.add_nodes_from(['diff', 'intel', 'grade'])
self.bayesian_model.add_edges_from([('diff', 'grade'), ('intel', 'grade')])
self.bayesian_model.add_cpds(diff_cpd, intel_cpd, grade_cpd)
# A test Markov model
self.markov_model = MarkovModel([('A', 'B'), ('C', 'B'), ('B', 'D')])
factor_ab = Factor(['A', 'B'], [2, 3], [1, 2, 3, 4, 5, 6])
factor_cb = Factor(['C', 'B'], [4, 3], [3, 1, 4, 5, 7, 8, 1, 3, 10, 4, 5, 6])
factor_bd = Factor(['B', 'D'], [3, 2], [5, 7, 2, 1, 9, 3])
self.markov_model.add_factors(factor_ab, factor_cb, factor_bd)
self.gibbs = GibbsSampling(self.bayesian_model)
def tearDown(self):
del self.bayesian_model
del self.markov_model
@patch('pgmpy.inference.Sampling.GibbsSampling._get_kernel_from_bayesian_model', autospec=True)
@patch('pgmpy.models.MarkovChain.__init__', autospec=True)
def test_init_bayesian_model(self, init, get_kernel):
model = MagicMock(spec_set=BayesianModel)
gibbs = GibbsSampling(model)
init.assert_called_once_with(gibbs)
get_kernel.assert_called_once_with(gibbs, model)
@patch('pgmpy.inference.Sampling.GibbsSampling._get_kernel_from_markov_model', autospec=True)
def test_init_markov_model(self, get_kernel):
model = MagicMock(spec_set=MarkovModel)
gibbs = GibbsSampling(model)
get_kernel.assert_called_once_with(gibbs, model)
def test_get_kernel_from_bayesian_model(self):
gibbs = GibbsSampling()
gibbs._get_kernel_from_bayesian_model(self.bayesian_model)
self.assertListEqual(list(gibbs.variables), self.bayesian_model.nodes())
self.assertDictEqual(gibbs.cardinalities, {'diff': 2, 'intel': 2, 'grade': 3})
def test_get_kernel_from_markov_model(self):
gibbs = GibbsSampling()
gibbs._get_kernel_from_markov_model(self.markov_model)
self.assertListEqual(list(gibbs.variables), self.markov_model.nodes())
self.assertDictEqual(gibbs.cardinalities, {'A': 2, 'B': 3, 'C': 4, 'D': 2})
def test_sample(self):
start_state = [State('diff', 0), State('intel', 0), State('grade', 0)]
sample = self.gibbs.sample(start_state, 2)
self.assertEquals(len(sample), 2)
self.assertEquals(len(sample.columns), 3)
self.assertIn('diff', sample.columns)
self.assertIn('intel', sample.columns)
self.assertIn('grade', sample.columns)
self.assertTrue(set(sample['diff']).issubset({0, 1}))
self.assertTrue(set(sample['intel']).issubset({0, 1}))
self.assertTrue(set(sample['grade']).issubset({0, 1, 2}))
@patch("pgmpy.inference.Sampling.GibbsSampling.random_state", autospec=True)
def test_sample_less_arg(self, random_state):
self.gibbs.state = None
random_state.return_value = [State('diff', 0), State('intel', 0), State('grade', 0)]
sample = self.gibbs.sample(size=2)
random_state.assert_called_once_with(self.gibbs)
self.assertEqual(len(sample), 2)
def test_generate_sample(self):
start_state = [State('diff', 0), State('intel', 0), State('grade', 0)]
gen = self.gibbs.generate_sample(start_state, 2)
samples = [sample for sample in gen]
self.assertEqual(len(samples), 2)
self.assertEqual({samples[0][0].var, samples[0][1].var, samples[0][2].var}, {'diff', 'intel', 'grade'})
self.assertEqual({samples[1][0].var, samples[1][1].var, samples[1][2].var}, {'diff', 'intel', 'grade'})
@patch("pgmpy.inference.Sampling.GibbsSampling.random_state", autospec=True)
def test_generate_sample_less_arg(self, random_state):
self.gibbs.state = None
gen = self.gibbs.generate_sample(size=2)
samples = [sample for sample in gen]
random_state.assert_called_once_with(self.gibbs)
self.assertEqual(len(samples), 2)
示例6: bayesnet
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [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')
示例7: TestBaseModelCreation
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [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
示例8: TestBayesianModelMethods
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [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):
#.........这里部分代码省略.........
示例9: BayesianModel
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import nodes [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())