当前位置: 首页>>代码示例>>Python>>正文


Python MarkovModel.add_nodes_from方法代码示例

本文整理汇总了Python中pgmpy.models.MarkovModel.add_nodes_from方法的典型用法代码示例。如果您正苦于以下问题:Python MarkovModel.add_nodes_from方法的具体用法?Python MarkovModel.add_nodes_from怎么用?Python MarkovModel.add_nodes_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pgmpy.models.MarkovModel的用法示例。


在下文中一共展示了MarkovModel.add_nodes_from方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: to_markov_model

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [as 别名]
    def to_markov_model(self):
        """
        Converts the factor graph into markov model.

        A markov model contains nodes as random variables and edge between
        two nodes imply interaction between them.

        Examples
        --------
        >>> from pgmpy.models import FactorGraph
        >>> from pgmpy.factors import Factor
        >>> G = FactorGraph()
        >>> G.add_nodes_from(['a', 'b', 'c'])
        >>> phi1 = Factor(['a', 'b'], [2, 2], np.random.rand(4))
        >>> phi2 = Factor(['b', 'c'], [2, 2], np.random.rand(4))
        >>> G.add_factors(phi1, phi2)
        >>> G.add_nodes_from([phi1, phi2])
        >>> G.add_edges_from([('a', phi1), ('b', phi1),
        ...                   ('b', phi2), ('c', phi2)])
        >>> mm = G.to_markov_model()
        """
        from pgmpy.models import MarkovModel
        mm = MarkovModel()

        variable_nodes = self.get_variable_nodes()

        if len(set(self.nodes()) - set(variable_nodes)) != len(self.factors):
            raise ValueError('Factors not associated with all the factor nodes.')

        mm.add_nodes_from(variable_nodes)
        for factor in self.factors:
            scope = factor.scope()
            mm.add_edges_from(itertools.combinations(scope, 2))
            mm.add_factors(factor)

        return mm
开发者ID:ankurankan,项目名称:pgmpy,代码行数:38,代码来源:FactorGraph.py

示例2: generate

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [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)

#.........这里部分代码省略.........
开发者ID:elkbrsathuji,项目名称:pyMRF,代码行数:103,代码来源:generate.py

示例3: MarkovModel

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [as 别名]
from pgmpy.models import MarkovModel
from pgmpy.factors import Factor
model = MarkovModel()
# Fig 2.7(a) represents the Markov model
model.add_nodes_from(['A', 'B', 'C', 'D'])
model.add_edges_from([('A', 'B'), ('B', 'C'),
                      ('C', 'D'), ('D', 'A')])
# Adding some factors.
phi_A_B = Factor(['A', 'B'], [2, 2], [1, 100,
phi_B_C = Factor(['B', 'C'], [2, 2], [100, 1,
phi_C_D = Factor(['C', 'D'], [2, 2], [1, 100,
phi_D_A = Factor(['D', 'A'], [2, 2], [100, 1,
model.add_factors(phi_A_B, phi_B_C, phi_C_D,
bayesian_model = model.to_bayesian_model()
bayesian_model.edges()
开发者ID:xenron,项目名称:sandbox-da-python,代码行数:17,代码来源:B04016_02_14.py

示例4: TestUndirectedGraphFactorOperations

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [as 别名]
class TestUndirectedGraphFactorOperations(unittest.TestCase):
    def setUp(self):
        self.graph = MarkovModel()

    def test_add_factor_raises_error(self):
        self.graph.add_edges_from([('Alice', 'Bob'), ('Bob', 'Charles'),
                                   ('Charles', 'Debbie'), ('Debbie', 'Alice')])
        factor = Factor(['Alice', 'Bob', 'John'], [2, 2, 2], np.random.rand(8))
        self.assertRaises(ValueError, self.graph.add_factors, factor)

    def test_add_single_factor(self):
        self.graph.add_nodes_from(['a', 'b', 'c'])
        phi = Factor(['a', 'b'], [2, 2], range(4))
        self.graph.add_factors(phi)
        six.assertCountEqual(self, self.graph.factors, [phi])

    def test_add_multiple_factors(self):
        self.graph.add_nodes_from(['a', 'b', 'c'])
        phi1 = Factor(['a', 'b'], [2, 2], range(4))
        phi2 = Factor(['b', 'c'], [2, 2], range(4))
        self.graph.add_factors(phi1, phi2)
        six.assertCountEqual(self, self.graph.factors, [phi1, phi2])

    def test_get_factors(self):
        self.graph.add_nodes_from(['a', 'b', 'c'])
        phi1 = Factor(['a', 'b'], [2, 2], range(4))
        phi2 = Factor(['b', 'c'], [2, 2], range(4))
        six.assertCountEqual(self, self.graph.get_factors(), [])
        self.graph.add_factors(phi1, phi2)
        six.assertCountEqual(self, self.graph.get_factors(), [phi1, phi2])

    def test_remove_single_factor(self):
        self.graph.add_nodes_from(['a', 'b', 'c'])
        phi1 = Factor(['a', 'b'], [2, 2], range(4))
        phi2 = Factor(['b', 'c'], [2, 2], range(4))
        self.graph.add_factors(phi1, phi2)
        self.graph.remove_factors(phi1)
        six.assertCountEqual(self, self.graph.factors, [phi2])

    def test_remove_multiple_factors(self):
        self.graph.add_nodes_from(['a', 'b', 'c'])
        phi1 = Factor(['a', 'b'], [2, 2], range(4))
        phi2 = Factor(['b', 'c'], [2, 2], range(4))
        self.graph.add_factors(phi1, phi2)
        self.graph.remove_factors(phi1, phi2)
        six.assertCountEqual(self, self.graph.factors, [])

    def test_partition_function(self):
        self.graph.add_nodes_from(['a', 'b', 'c'])
        phi1 = Factor(['a', 'b'], [2, 2], range(4))
        phi2 = Factor(['b', 'c'], [2, 2], range(4))
        self.graph.add_factors(phi1, phi2)
        self.graph.add_edges_from([('a', 'b'), ('b', 'c')])
        self.assertEqual(self.graph.get_partition_function(), 22.0)

    def test_partition_function_raises_error(self):
        self.graph.add_nodes_from(['a', 'b', 'c', 'd'])
        phi1 = Factor(['a', 'b'], [2, 2], range(4))
        phi2 = Factor(['b', 'c'], [2, 2], range(4))
        self.graph.add_factors(phi1, phi2)
        self.assertRaises(ValueError,
                          self.graph.get_partition_function)

    def tearDown(self):
        del self.graph
开发者ID:ankurankan,项目名称:pgmpy,代码行数:67,代码来源:test_MarkovModel.py

示例5: TestMarkovModelCreation

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [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
开发者ID:ankurankan,项目名称:pgmpy,代码行数:74,代码来源:test_MarkovModel.py

示例6: TestUndirectedGraphTriangulation

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [as 别名]

#.........这里部分代码省略.........
        H = self.graph.triangulate(heuristic='H4', inplace=True)
        self.assertListEqual(hf.recursive_sorted(H.edges()),
                             [['a', 'b'], ['a', 'd'], ['b', 'c'],
                              ['b', 'd'], ['c', 'd']])

    def test_triangulation_h5_create_new(self):
        self.graph.add_edges_from([('a', 'b'), ('b', 'c'), ('c', 'd'),
                                   ('d', 'a')])
        phi1 = DiscreteFactor(['a', 'b'], [2, 3], np.random.rand(6))
        phi2 = DiscreteFactor(['b', 'c'], [3, 4], np.random.rand(12))
        phi3 = DiscreteFactor(['c', 'd'], [4, 5], np.random.rand(20))
        phi4 = DiscreteFactor(['d', 'a'], [5, 2], np.random.random(10))
        self.graph.add_factors(phi1, phi2, phi3, phi4)
        H = self.graph.triangulate(heuristic='H5', inplace=True)
        self.assertListEqual(hf.recursive_sorted(H.edges()),
                             [['a', 'b'], ['a', 'd'], ['b', 'c'],
                              ['b', 'd'], ['c', 'd']])

    def test_triangulation_h6_create_new(self):
        self.graph.add_edges_from([('a', 'b'), ('b', 'c'), ('c', 'd'),
                                   ('d', 'a')])
        phi1 = DiscreteFactor(['a', 'b'], [2, 3], np.random.rand(6))
        phi2 = DiscreteFactor(['b', 'c'], [3, 4], np.random.rand(12))
        phi3 = DiscreteFactor(['c', 'd'], [4, 5], np.random.rand(20))
        phi4 = DiscreteFactor(['d', 'a'], [5, 2], np.random.random(10))
        self.graph.add_factors(phi1, phi2, phi3, phi4)
        H = self.graph.triangulate(heuristic='H6', inplace=True)
        self.assertListEqual(hf.recursive_sorted(H.edges()),
                             [['a', 'b'], ['a', 'd'], ['b', 'c'],
                              ['b', 'd'], ['c', 'd']])

    def test_copy(self):
        # Setup the original graph
        self.graph.add_nodes_from(['a', 'b'])
        self.graph.add_edges_from([('a', 'b')])

        # Generate the copy
        copy = self.graph.copy()

        # Ensure the copied model is correct
        self.assertTrue(copy.check_model())

        # Basic sanity checks to ensure the graph was copied correctly
        self.assertEqual(len(copy.nodes()), 2)
        self.assertListEqual(copy.neighbors('a'), ['b'])
        self.assertListEqual(copy.neighbors('b'), ['a'])

        # Modify the original graph ...
        self.graph.add_nodes_from(['c'])
        self.graph.add_edges_from([('c', 'b')])

        # ... and ensure none of those changes get propagated
        self.assertEqual(len(copy.nodes()), 2)
        self.assertListEqual(copy.neighbors('a'), ['b'])
        self.assertListEqual(copy.neighbors('b'), ['a'])
        with self.assertRaises(nx.NetworkXError):
            copy.neighbors('c')

        # Ensure the copy has no factors at this point
        self.assertEqual(len(copy.get_factors()), 0)

        # Add factors to the original graph
        phi1 = DiscreteFactor(['a', 'b'], [2, 2], [[0.3, 0.7], [0.9, 0.1]])
        self.graph.add_factors(phi1)

        # The factors should not get copied over
开发者ID:MariosRichards,项目名称:BES_analysis_code,代码行数:70,代码来源:test_MarkovModel.py

示例7: MarkovModel

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [as 别名]
from pgmpy.models import MarkovModel
mm = MarkovModel()
mm.add_nodes_from(['x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7'])
mm.add_edges_from([('x1', 'x3'), ('x1', 'x4'), ('x2', 'x4'),
                   ('x2', 'x5'), ('x3', 'x6'), ('x4', 'x6'),
                   ('x4', 'x7'), ('x5', 'x7')])
mm.get_local_independencies()
开发者ID:xenron,项目名称:sandbox-da-python,代码行数:9,代码来源:B04016_02_12.py

示例8: MarkovModel

# 需要导入模块: from pgmpy.models import MarkovModel [as 别名]
# 或者: from pgmpy.models.MarkovModel import add_nodes_from [as 别名]
from pgmpy.models import MarkovModel
mm = MarkovModel()
mm.add_nodes_from(['A', 'B', 'C'])
mm.add_edges_from([('A', 'B'), ('B', 'C'), ('C', 'A')])
mm.add_factors(phi1, phi2, phi3)
factor_graph_from_mm = mm.to_factor_graph()
# While converting a markov model into factor graph, factor nodes
# would be automatically added the factor nodes would be in the
# form of phi_node1_node2_...
factor_graph_from_mm.nodes()
factor_graph.edges()
# FactorGraph to MarkovModel
phi = Factor(['A', 'B', 'C'], [2, 2, 2],
np.random.rand(8))
factor_graph = FactorGraph()
factor_graph.add_nodes_from(['A', 'B', 'C', 'phi'])
factor_graph.add_edges_from([('A', 'phi'), ('B', 'phi'), ('C', 'phi')])
开发者ID:xenron,项目名称:sandbox-da-python,代码行数:19,代码来源:B04016_02_11.py


注:本文中的pgmpy.models.MarkovModel.add_nodes_from方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。