本文整理汇总了Python中pgmpy.models.BayesianModel.add_cpds方法的典型用法代码示例。如果您正苦于以下问题:Python BayesianModel.add_cpds方法的具体用法?Python BayesianModel.add_cpds怎么用?Python BayesianModel.add_cpds使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pgmpy.models.BayesianModel
的用法示例。
在下文中一共展示了BayesianModel.add_cpds方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
def setUp(self):
self.sn2 = {'grade': ['A', 'B', 'F'], 'diff': ['high', 'low'],
'intel': ['poor', 'good', 'very good']}
self.sn1 = {'speed': ['low', 'medium', 'high'],
'switch': ['on', 'off'], 'time': ['day', 'night']}
self.phi1 = DiscreteFactor(['speed', 'switch', 'time'],
[3, 2, 2], np.ones(12))
self.phi2 = DiscreteFactor(['speed', 'switch', 'time'],
[3, 2, 2], np.ones(12), state_names=self.sn1)
self.cpd1 = TabularCPD('grade', 3, [[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.cpd2 = TabularCPD('grade', 3, [[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],
state_names=self.sn2)
student = BayesianModel([('diff', 'grade'), ('intel', 'grade')])
diff_cpd = TabularCPD('diff', 2, [[0.2, 0.8]])
intel_cpd = TabularCPD('intel', 2, [[0.3, 0.7]])
grade_cpd = TabularCPD('grade', 3, [[0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1],
[0.8, 0.8, 0.8, 0.8]],
evidence=['diff', 'intel'],
evidence_card=[2, 2])
student.add_cpds(diff_cpd, intel_cpd, grade_cpd)
self.model1 = Inference(student)
self.model2 = Inference(student, state_names=self.sn2)
示例2: get_model
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
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>
"""
try:
model = BayesianModel(self.variable_edges)
model.name = self.network_name
model.add_nodes_from(self.variable_names)
tabular_cpds = []
for var in sorted(self.variable_cpds.keys()):
values = self.variable_cpds[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]])
tabular_cpds.append(cpd)
model.add_cpds(*tabular_cpds)
for node, properties in self.variable_properties.items():
for prop in properties:
prop_name, prop_value = map(lambda t: t.strip(), prop.split('='))
model.node[node][prop_name] = prop_value
return model
except AttributeError:
raise AttributeError('First get states of variables, edges, parents and network name')
示例3: main
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
def main():
# Defining the network structure
model = BayesianModel([('C', 'H'), ('P', 'H')])
# H: host
# P: prize
# C: contestant
# Defining the CPDs:
cpd_c = TabularCPD('C', 3, [[0.33, 0.33, 0.33]])
cpd_p = TabularCPD('P', 3, [[0.33, 0.33, 0.33]])
cpd_h = TabularCPD('H', 3, [[0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 0.0, 1.0, 0.5],
[0.5, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5],
[0.5, 1.0, 0.0, 1.0, 0.5, 0.0, 0.0, 0.0, 0.0]],
evidence=['C', 'P'], evidence_card=[3, 3])
# Associating the CPDs with the network structure.
model.add_cpds(cpd_c, cpd_p, cpd_h)
# Some other methods
# model.get_cpds()
# check_model check for the model structure and the associated CPD and
# returns True if everything is correct otherwise throws an exception
# print model.check_model()
# Infering the posterior probability
infer = VariableElimination(model)
posterior_p = infer.query(['H'], evidence={'C': 0, 'P': 0})
print(posterior_p['H'])
示例4: setUp
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
def setUp(self):
nodes = {'c': {'STATES': ['Present', 'Absent'],
'DESCRIPTION': '(c) Brain Tumor',
'YPOS': '11935',
'XPOS': '15250',
'TYPE': 'discrete'},
'a': {'STATES': ['Present', 'Absent'],
'DESCRIPTION': '(a) Metastatic Cancer',
'YPOS': '10465',
'XPOS': '13495',
'TYPE': 'discrete'},
'b': {'STATES': ['Present', 'Absent'],
'DESCRIPTION': '(b) Serum Calcium Increase',
'YPOS': '11965',
'XPOS': '11290',
'TYPE': 'discrete'},
'e': {'STATES': ['Present', 'Absent'],
'DESCRIPTION': '(e) Papilledema',
'YPOS': '13240',
'XPOS': '17305',
'TYPE': 'discrete'},
'd': {'STATES': ['Present', 'Absent'],
'DESCRIPTION': '(d) Coma',
'YPOS': '12985',
'XPOS': '13960',
'TYPE': 'discrete'}}
model = BayesianModel([('b', 'd'), ('a', 'b'), ('a', 'c'), ('c', 'd'), ('c', 'e')])
cpd_distribution = {'a': {'TYPE': 'discrete', 'DPIS': np.array([[0.2, 0.8]])},
'e': {'TYPE': 'discrete', 'DPIS': np.array([[0.8, 0.2],
[0.6, 0.4]]), 'CONDSET': ['c'], 'CARDINALITY': [2]},
'b': {'TYPE': 'discrete', 'DPIS': np.array([[0.8, 0.2],
[0.2, 0.8]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},
'c': {'TYPE': 'discrete', 'DPIS': np.array([[0.2, 0.8],
[0.05, 0.95]]), 'CONDSET': ['a'], 'CARDINALITY': [2]},
'd': {'TYPE': 'discrete', 'DPIS': np.array([[0.8, 0.2],
[0.9, 0.1],
[0.7, 0.3],
[0.05, 0.95]]), 'CONDSET': ['b', 'c'], 'CARDINALITY': [2, 2]}}
tabular_cpds = []
for var, values in cpd_distribution.items():
evidence = values['CONDSET'] if 'CONDSET' in values else []
cpd = values['DPIS']
evidence_card = values['CARDINALITY'] if 'CARDINALITY' in values else []
states = nodes[var]['STATES']
cpd = TabularCPD(var, len(states), cpd,
evidence=evidence,
evidence_card=evidence_card)
tabular_cpds.append(cpd)
model.add_cpds(*tabular_cpds)
for var, properties in nodes.items():
model.node[var] = properties
self.maxDiff = None
self.writer = XMLBeliefNetwork.XBNWriter(model=model)
示例5: bayesnet_examples
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
def bayesnet_examples():
from pgmpy.factors import TabularCPD
from pgmpy.models import BayesianModel
import pandas as pd
student_model = BayesianModel([('D', 'G'),
('I', 'G'),
('G', 'L'),
('I', 'S')])
# we can generate some random data.
raw_data = np.random.randint(low=0, high=2, size=(1000, 5))
data = pd.DataFrame(raw_data, columns=['D', 'I', 'G', 'L', 'S'])
data_train = data[: int(data.shape[0] * 0.75)]
student_model.fit(data_train)
student_model.get_cpds()
data_test = data[int(0.75 * data.shape[0]): data.shape[0]]
data_test.drop('D', axis=1, inplace=True)
student_model.predict(data_test)
grade_cpd = 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])
difficulty_cpd = TabularCPD(
variable='D',
variable_card=2,
values=[[0.6, 0.4]])
intel_cpd = TabularCPD(
variable='I',
variable_card=2,
values=[[0.7, 0.3]])
letter_cpd = TabularCPD(
variable='L',
variable_card=2,
values=[[0.1, 0.4, 0.99],
[0.9, 0.6, 0.01]],
evidence=['G'],
evidence_card=[3])
sat_cpd = TabularCPD(
variable='S',
variable_card=2,
values=[[0.95, 0.2],
[0.05, 0.8]],
evidence=['I'],
evidence_card=[2])
student_model.add_cpds(grade_cpd, difficulty_cpd,
intel_cpd, letter_cpd,
sat_cpd)
示例6: get_model
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
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.
Examples
--------
>>> reader = UAIReader('TestUAI.uai')
>>> reader.get_model()
"""
if self.network_type == 'BAYES':
model = BayesianModel(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)
model.add_factors(*factors)
return model
示例7: get_model
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [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.")
示例8: get_model
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
def get_model(self):
model = BayesianModel(self.get_edges())
model.name = self.network_name
tabular_cpds = []
for var, values in self.variable_CPD.items():
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]])
tabular_cpds.append(cpd)
model.add_cpds(*tabular_cpds)
for node, properties in self.variable_property.items():
for prop in properties:
prop_name, prop_value = map(lambda t: t.strip(), prop.split('='))
model.node[node][prop_name] = prop_value
return model
示例9: get_model
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
def get_model(self):
"""
Returns an instance of Bayesian Model.
"""
model = BayesianModel(self.edges)
model.name = self.model_name
tabular_cpds = []
for var, values in self.variable_CPD.items():
evidence = values['CONDSET'] if 'CONDSET' in values else []
cpd = values['DPIS']
evidence_card = values['CARDINALITY'] if 'CARDINALITY' in values else []
states = self.variables[var]['STATES']
cpd = TabularCPD(var, len(states), cpd,
evidence=evidence,
evidence_card=evidence_card)
tabular_cpds.append(cpd)
model.add_cpds(*tabular_cpds)
for var, properties in self.variables.items():
model.node[var] = properties
return model
示例10: TestGibbsSampling
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [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)
示例11: TestBayesianModelMethods
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [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):
#.........这里部分代码省略.........
示例12: bayesnet
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
#.........这里部分代码省略.........
evidence_card=[num_same_diff]) # [::-1])
cpd.semtype = 'score'
return cpd
score_cpds = [score_cpd('i', 'j'), score_cpd('j', 'k')]
cpd_list = name_cpds + score_cpds + samediff_cpds
else:
score_measure = np.array([get_expected_scores_prob(level1, level2)
for level1, level2 in
zip(np.linspace(.1, .9, num_scores),
np.linspace(.2, .8, num_scores))])
score_values = (score_measure / score_measure.sum(axis=0)).tolist()
def score_cpd(aid1, aid2):
cpd = TabularCPD(
variable='S' + aid1 + aid2,
variable_card=num_scores,
values=score_values,
evidence=['N' + aid1, 'N' + aid2],
evidence_card=[num_names, num_names])
cpd.semtype = 'score'
return cpd
score_cpds = [score_cpd('i', 'j'), score_cpd('j', 'k')]
cpd_list = name_cpds + score_cpds
pass
input_graph = []
for cpd in cpd_list:
if cpd.evidence is not None:
for evar in cpd.evidence:
input_graph.append((evar, cpd.variable))
name_model = BayesianModel(input_graph)
name_model.add_cpds(*cpd_list)
var2_cpd.update(dict(zip([cpd.variable for cpd in cpd_list], cpd_list)))
globals()['var2_cpd'] = var2_cpd
varnames = [cpd.variable for cpd in cpd_list]
# --- PRINT CPDS ---
cpd = score_cpds[0]
def print_cpd(cpd):
print('CPT: %r' % (cpd,))
index = semtype2_nice[cpd.semtype]
if cpd.evidence is None:
columns = ['None']
else:
basis_lists = [semtype2_nice[var2_cpd[ename].semtype] for ename in cpd.evidence]
columns = [','.join(x) for x in ut.iprod(*basis_lists)]
data = cpd.get_cpd()
print(pd.DataFrame(data, index=index, columns=columns))
for cpd in name_model.get_cpds():
print('----')
print(cpd._str('phi'))
print_cpd(cpd)
# --- INFERENCE ---
Ni = name_cpds[0]
event_space_combos = {}
event_space_combos[Ni.variable] = 0 # Set ni to always be Fred
for cpd in cpd_list:
示例13: TestXMLBIFWriterMethodsString
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
class TestXMLBIFWriterMethodsString(unittest.TestCase):
def setUp(self):
edges = [
["family-out", "dog-out"],
["bowel-problem", "dog-out"],
["family-out", "light-on"],
["dog-out", "hear-bark"],
]
cpds = {
"bowel-problem": np.array([[0.01], [0.99]]),
"dog-out": np.array([[0.99, 0.01, 0.97, 0.03], [0.9, 0.1, 0.3, 0.7]]),
"family-out": np.array([[0.15], [0.85]]),
"hear-bark": np.array([[0.7, 0.3], [0.01, 0.99]]),
"light-on": np.array([[0.6, 0.4], [0.05, 0.95]]),
}
states = {
"bowel-problem": ["true", "false"],
"dog-out": ["true", "false"],
"family-out": ["true", "false"],
"hear-bark": ["true", "false"],
"light-on": ["true", "false"],
}
parents = {
"bowel-problem": [],
"dog-out": ["family-out", "bowel-problem"],
"family-out": [],
"hear-bark": ["dog-out"],
"light-on": ["family-out"],
}
properties = {
"bowel-problem": ["position = (190, 69)"],
"dog-out": ["position = (155, 165)"],
"family-out": ["position = (112, 69)"],
"hear-bark": ["position = (154, 241)"],
"light-on": ["position = (73, 165)"],
}
self.model = BayesianModel(edges)
tabular_cpds = []
for var, values in cpds.items():
cpd = TabularCPD(
var,
len(states[var]),
values,
evidence=parents[var],
evidence_card=[len(states[evidence_var]) for evidence_var in parents[var]],
)
tabular_cpds.append(cpd)
self.model.add_cpds(*tabular_cpds)
for node, properties in properties.items():
for prop in properties:
prop_name, prop_value = map(lambda t: t.strip(), prop.split("="))
self.model.node[node][prop_name] = prop_value
self.writer = XMLBIFWriter(model=self.model)
def test_file(self):
self.expected_xml = etree.XML(
"""<BIF version="0.3">
<NETWORK>
<VARIABLE TYPE="nature">
<NAME>bowel-problem</NAME>
<OUTCOME>0</OUTCOME>
<OUTCOME>1</OUTCOME>
<PROPERTY>position = (190, 69)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>dog-out</NAME>
<OUTCOME>0</OUTCOME>
<OUTCOME>1</OUTCOME>
<PROPERTY>position = (155, 165)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>family-out</NAME>
<OUTCOME>0</OUTCOME>
<OUTCOME>1</OUTCOME>
<PROPERTY>position = (112, 69)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>hear-bark</NAME>
<OUTCOME>0</OUTCOME>
<OUTCOME>1</OUTCOME>
<PROPERTY>position = (154, 241)</PROPERTY>
</VARIABLE>
<VARIABLE TYPE="nature">
<NAME>light-on</NAME>
<OUTCOME>0</OUTCOME>
<OUTCOME>1</OUTCOME>
<PROPERTY>position = (73, 165)</PROPERTY>
</VARIABLE>
<DEFINITION>
<FOR>bowel-problem</FOR>
<TABLE>0.01 0.99 </TABLE>
</DEFINITION>
<DEFINITION>
<FOR>dog-out</FOR>
<GIVEN>bowel-problem</GIVEN>
<GIVEN>family-out</GIVEN>
#.........这里部分代码省略.........
示例14: configure
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
#.........这里部分代码省略.........
for k in range(len(modelDict[j]['pickleData']['original'])):
print modelDict[j]['pickleData']['original'][k]
if modelDict[j]['pickleData']['original'][k] not in modelDict[selfName]['labels']:
modelDict[j]['pickleData']['original'][k] = 'unknown'
for j in modelList:
if modelDict[j]['pickleData']['original'] != modelDict[selfName]['actualLabels']:
failFlag = True
print 'original classifications of', j, 'are not identical to those of', selfName
if failFlag:
return False
# Update netStructureString to reflect changes in the modelList names
strSections = netStructureString.split("'")
for k in range(len(strSections)):
if len(strSections[k]) > 2 and ',' not in strSections[k]:
strSections[k] = strSections[k].split(' ')[0]
netStructureString = "'".join(strSections)
netStructure = ast.literal_eval(netStructureString)
# ---------------------------------------------------------------------------------------------------------------
# iterate through actual labels
# for each actual label, iterate through models
# for each model find classification label of this model for current actual label
# get the index of the current classification and add it to its CPD
# also calculate which item in the joint CPD needs to be incremented
for j in range(len(modelDict[selfName]['actualLabels'])):
currActualLabel = modelDict[selfName]['actualLabels'][j]
row = modelDict[selfName]['labels'].index(currActualLabel)
colVar = np.zeros([len(modelList)])
for k in range(len(modelList)):
cmod = modelList[k]
if k != 0:
pmod = modelList[k-1]
colVar *= len(modelDict[pmod]['labels'])
colVar[k] = modelDict[cmod]['labels'].index(
modelDict[cmod]['pickleData']['results'][j])
modelDict[cmod]['CPD'][0, colVar[k]] += 1
col = sum(colVar)
modelDict[selfName]['CPD'][row, col] += 1
# take all CPD's and normalise the matrices
evidenceCard = copy.deepcopy(modelList)
for j in modelDict:
if j == selfName:
# this is a joint CPD matrix
# normalise columns to have sum = 1
modelDict[j]['CPD'] = normalize(modelDict[j]['CPD'], axis=0, norm='l1')
else:
# normalise sum of matrix = 1
modelDict[j]['CPD'] /= np.sum(modelDict[j]['CPD'])
evidenceCard[evidenceCard.index(j)] = len(modelDict[j]['labels'])
print modelDict[j]['CPD']
model = BayesianModel(netStructure)
# create TabularCPD data structure to nest calculated CPD
for j in modelDict:
if j == selfName:
modelDict[j]['cpdObject'] = TabularCPD(variable=j, variable_card=len(modelDict[j]['labels']),
values=modelDict[j]['CPD'],
evidence=modelList,
evidence_card=evidenceCard)
else:
modelDict[j]['cpdObject'] = TabularCPD(variable=j,
variable_card=len(modelDict[j]['labels']),
values=modelDict[j]['CPD'])
# Associating the CPDs with the network
for j in modelDict:
model.add_cpds(modelDict[j]['cpdObject'])
# check_model checks for the network structure and CPDs and verifies that the CPDs are correctly
# defined and sum to 1.
if not model.check_model():
print 'Model check returned unsuccessful'
return False
infer = VariableElimination(model)
confMatrix = np.zeros(len(modelDict[selfName]['labels']))
# iterate over all original data and perform classifications to calculate if accuracy with PGN has increased
for j in range(len(modelDict[selfName]['actualLabels'])):
currEvidenceDict = dict()
for k in modelList:
currEvidenceDict[k] = modelDict[k]['labels'].index(modelDict[k]['pickleData']['results'][j])
q = infer.query([selfName], currEvidenceDict)
inferenceClass = modelDict[selfName]['labels'][np.argmax(q[selfName].values)]
actualClass = modelDict[selfName]['actualLabels'][j]
confMatrix[modelDict[selfName].index(actualClass), modelDict[selfName].index(inferenceClass)] += 1
print "%Accuracy with PGN"
dCalc = SAMTesting.calculateData(modelDict[selfName]['actualLabels'], confMatrix)
return True
示例15: TestBayesianModelSampling
# 需要导入模块: from pgmpy.models import BayesianModel [as 别名]
# 或者: from pgmpy.models.BayesianModel import add_cpds [as 别名]
class TestBayesianModelSampling(unittest.TestCase):
def setUp(self):
self.bayesian_model = BayesianModel([('A', 'J'), ('R', 'J'), ('J', 'Q'),
('J', 'L'), ('G', 'L')])
cpd_a = TabularCPD('A', 2, [[0.2], [0.8]])
cpd_r = TabularCPD('R', 2, [[0.4], [0.6]])
cpd_j = TabularCPD('J', 2,
[[0.9, 0.6, 0.7, 0.1],
[0.1, 0.4, 0.3, 0.9]],
['R', 'A'], [2, 2])
cpd_q = TabularCPD('Q', 2,
[[0.9, 0.2],
[0.1, 0.8]],
['J'], [2])
cpd_l = TabularCPD('L', 2,
[[0.9, 0.45, 0.8, 0.1],
[0.1, 0.55, 0.2, 0.9]],
['G', 'J'], [2, 2])
cpd_g = TabularCPD('G', 2, [[0.6], [0.4]])
self.bayesian_model.add_cpds(cpd_a, cpd_g, cpd_j, cpd_l, cpd_q, cpd_r)
self.sampling_inference = BayesianModelSampling(self.bayesian_model)
self.markov_model = MarkovModel()
def test_init(self):
with self.assertRaises(TypeError):
BayesianModelSampling(self.markov_model)
def test_forward_sample(self):
sample = self.sampling_inference.forward_sample(25)
self.assertEquals(len(sample), 25)
self.assertEquals(len(sample.columns), 6)
self.assertIn('A', sample.columns)
self.assertIn('J', sample.columns)
self.assertIn('R', sample.columns)
self.assertIn('Q', sample.columns)
self.assertIn('G', sample.columns)
self.assertIn('L', sample.columns)
self.assertTrue(set(sample.A).issubset({State('A', 0), State('A', 1)}))
self.assertTrue(set(sample.J).issubset({State('J', 0), State('J', 1)}))
self.assertTrue(set(sample.R).issubset({State('R', 0), State('R', 1)}))
self.assertTrue(set(sample.Q).issubset({State('Q', 0), State('Q', 1)}))
self.assertTrue(set(sample.G).issubset({State('G', 0), State('G', 1)}))
self.assertTrue(set(sample.L).issubset({State('L', 0), State('L', 1)}))
def test_rejection_sample_basic(self):
sample = self.sampling_inference.rejection_sample([State('A', 1), State('J', 1), State('R', 1)], 25)
self.assertEquals(len(sample), 25)
self.assertEquals(len(sample.columns), 6)
self.assertIn('A', sample.columns)
self.assertIn('J', sample.columns)
self.assertIn('R', sample.columns)
self.assertIn('Q', sample.columns)
self.assertIn('G', sample.columns)
self.assertIn('L', sample.columns)
self.assertTrue(set(sample.A).issubset({State('A', 1)}))
self.assertTrue(set(sample.J).issubset({State('J', 1)}))
self.assertTrue(set(sample.R).issubset({State('R', 1)}))
self.assertTrue(set(sample.Q).issubset({State('Q', 0), State('Q', 1)}))
self.assertTrue(set(sample.G).issubset({State('G', 0), State('G', 1)}))
self.assertTrue(set(sample.L).issubset({State('L', 0), State('L', 1)}))
def test_likelihood_weighted_sample(self):
sample = self.sampling_inference.likelihood_weighted_sample([State('A', 0), State('J', 1), State('R', 0)], 25)
self.assertEquals(len(sample), 25)
self.assertEquals(len(sample.columns), 7)
self.assertIn('A', sample.columns)
self.assertIn('J', sample.columns)
self.assertIn('R', sample.columns)
self.assertIn('Q', sample.columns)
self.assertIn('G', sample.columns)
self.assertIn('L', sample.columns)
self.assertIn('_weight', sample.columns)
self.assertTrue(set(sample.A).issubset({State('A', 0), State('A', 1)}))
self.assertTrue(set(sample.J).issubset({State('J', 0), State('J', 1)}))
self.assertTrue(set(sample.R).issubset({State('R', 0), State('R', 1)}))
self.assertTrue(set(sample.Q).issubset({State('Q', 0), State('Q', 1)}))
self.assertTrue(set(sample.G).issubset({State('G', 0), State('G', 1)}))
self.assertTrue(set(sample.L).issubset({State('L', 0), State('L', 1)}))
def tearDown(self):
del self.sampling_inference
del self.bayesian_model
del self.markov_model