本文整理汇总了Python中pgmpy.models.MarkovModel.nodes方法的典型用法代码示例。如果您正苦于以下问题:Python MarkovModel.nodes方法的具体用法?Python MarkovModel.nodes怎么用?Python MarkovModel.nodes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pgmpy.models.MarkovModel
的用法示例。
在下文中一共展示了MarkovModel.nodes方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate
# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import nodes [as 别名]
class generate(object):
def __init__(self, adj_mat=None, struct=None):
DEBUG = False
self.G = MarkovModel()
self.n_nodes = adj_mat.shape[0]
if DEBUG: print 'struct', struct
if struct == 'complete':
self._complete_graph(adj_mat)
if struct == 'nodes':
self._nodes_only(adj_mat)
if struct is None:
self._import_adj(adj_mat)
self._ising_factors(Wf=5, Wi=5, f_type='mixed')
if DEBUG: print 'generate_init', self.G, self.G.nodes()
def get_model(self):
return self.G
def _complete_graph(self, adj_mat):
"""
generate the complete graph over len(adj_mat)
"""
self._nodes_only(adj_mat)
for i in range(self.n_nodes):
self.G.add_edges_from([(i, j)
for j in range(self.n_nodes)])
def _import_adj(self, adj_mat):
"""
add nodes and edges to graph
adj_mat - square matrix, numpy array like
"""
DEBUG = False
assert (adj_mat is not None), "can't import empty adj mat"
# add nodes
self._nodes_only(adj_mat)
# add edges
for i in range(self.n_nodes):
edges_list = ([(i, j)
for j in range(self.n_nodes)
if adj_mat[i][j]])
if DEBUG: print edges_list
self.G.add_edges_from(edges_list)
if DEBUG: print len(self.G)
def _nodes_only(self, adj_mat):
"""
add nodes to graph
adj_mat - aquare matrix, numpy array like
"""
global DEBUG
assert (adj_mat is not None), "can't import empty adj mat"
assert (self.n_nodes == adj_mat.shape[1]), "adj_mat is not sqaure"
self.G.add_nodes_from([i for i in range(self.n_nodes)])
if DEBUG: print '_nodes_only', [i for i in range(self.n_nodes)]
if DEBUG: print '_nodes_only print G', self.G.nodes()
assert (self.n_nodes == len(self.G)), "graph size is incosistent with adj_mat"
def _ising_factors(self, Wf=1, Wi=1, f_type='mixed'):
"""
Add ising-like factors to model graph
cardinality is the number of possible values
in our case we have boolean nodes, thus cardinality = 2
Wf = \theta_i = ~U[-Wf, Wf]
type = 'mixed' = ~U[-Wi,Wi]
'attractive' = ~U[0,Wi]
"""
self._field_factors(Wf)
self._interact_factors(Wi, f_type)
def _field_factors(self, w, states=2):
"""
this function assigns factor for single node
currently states=2 for ising model generation
"""
for i in self.G.nodes():
phi_i = Factor([i], [states], self._wf(w, states))
self.G.add_factors(phi_i)
def _interact_factors(self, w, f_type, states=2):
"""
this function assigns factor for two interacting nodes
currently states=2 for ising model generation
"""
for e in self.G.edges():
# if DEBUG: print 'interact_factors edges,states, values',e,[e[0],
# e[1]],len(e)*[states], self._wi(w, f_type, states)
phi_ij = Factor([e[0], e[1]], [states] * len(e), self._wi(w, f_type, states))
self.G.add_factors(phi_ij)
def _wf(self, w, k):
"""
generate field factor
"""
# if DEBUG: print 'w',type(w),w
return np.random.uniform(low=-1 * w, high=w, size=k)
#.........这里部分代码省略.........
示例2: TestMarkovModelCreation
# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import nodes [as 别名]
class TestMarkovModelCreation(unittest.TestCase):
def setUp(self):
self.graph = MarkovModel()
def test_class_init_without_data(self):
self.assertIsInstance(self.graph, MarkovModel)
def test_class_init_with_data_string(self):
self.g = MarkovModel([('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):
self.g = MarkovModel([(1, 2), (2, 3)])
def test_add_node_string(self):
self.graph.add_node('a')
self.assertListEqual(self.graph.nodes(), ['a'])
def test_add_node_nonstring(self):
self.graph.add_node(1)
def test_add_nodes_from_string(self):
self.graph.add_nodes_from(['a', 'b', 'c', 'd'])
self.assertListEqual(sorted(self.graph.nodes()), ['a', 'b', 'c', 'd'])
def test_add_nodes_from_non_string(self):
self.graph.add_nodes_from([1, 2, 3, 4])
def test_add_edge_string(self):
self.graph.add_edge('d', 'e')
self.assertListEqual(sorted(self.graph.nodes()), ['d', 'e'])
self.assertListEqual(hf.recursive_sorted(self.graph.edges()),
[['d', 'e']])
self.graph.add_nodes_from(['a', 'b', 'c'])
self.graph.add_edge('a', 'b')
self.assertListEqual(hf.recursive_sorted(self.graph.edges()),
[['a', 'b'], ['d', 'e']])
def test_add_edge_nonstring(self):
self.graph.add_edge(1, 2)
def test_add_edge_selfloop(self):
self.assertRaises(ValueError, self.graph.add_edge, 'a', 'a')
def test_add_edges_from_string(self):
self.graph.add_edges_from([('a', 'b'), ('b', 'c')])
self.assertListEqual(sorted(self.graph.nodes()), ['a', 'b', 'c'])
self.assertListEqual(hf.recursive_sorted(self.graph.edges()),
[['a', 'b'], ['b', 'c']])
self.graph.add_nodes_from(['d', 'e', 'f'])
self.graph.add_edges_from([('d', 'e'), ('e', 'f')])
self.assertListEqual(sorted(self.graph.nodes()),
['a', 'b', 'c', 'd', 'e', 'f'])
self.assertListEqual(hf.recursive_sorted(self.graph.edges()),
hf.recursive_sorted([('a', 'b'), ('b', 'c'),
('d', 'e'), ('e', 'f')]))
def test_add_edges_from_nonstring(self):
self.graph.add_edges_from([(1, 2), (2, 3)])
def test_add_edges_from_self_loop(self):
self.assertRaises(ValueError, self.graph.add_edges_from,
[('a', 'a')])
def test_number_of_neighbors(self):
self.graph.add_edges_from([('a', 'b'), ('b', 'c')])
self.assertEqual(len(self.graph.neighbors('b')), 2)
def tearDown(self):
del self.graph
示例3: MarkovModel
# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import nodes [as 别名]
import numpy as np
import pandas as pd
from pgmpy.models import MarkovModel
from pgmpy.estimators import MaximumLikelihoodEstimator
# Generating random data
raw_data = np.random.randint(low=0, high=2, size=(1000, 2))
data = pd.DataFrame(raw_data, columns=['X', 'Y'])
model = MarkovModel()
model.fit(data, estimator=MaximumLikelihoodEstimator)
model.get_factors()
model.nodes()
model.edges()
示例4: TestGibbsSampling
# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel 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)