當前位置: 首頁>>代碼示例>>Python>>正文


Python networkx.to_numpy_matrix方法代碼示例

本文整理匯總了Python中networkx.to_numpy_matrix方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.to_numpy_matrix方法的具體用法?Python networkx.to_numpy_matrix怎麽用?Python networkx.to_numpy_matrix使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在networkx的用法示例。


在下文中一共展示了networkx.to_numpy_matrix方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: learn_embedding

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def learn_embedding(self):

        graph = self.g.G
        A = nx.to_numpy_matrix(graph)

        # self._beta = 0.0728

        # M_g = np.eye(graph.number_of_nodes()) - self._beta * A
        # M_l = self._beta * A

        M_g = np.eye(graph.number_of_nodes())
        M_l = np.dot(A, A)

        S = np.dot(np.linalg.inv(M_g), M_l)
        # s: \sigma_k
        u, s, vt = lg.svds(S, k=self._d // 2)
        sigma = np.diagflat(np.sqrt(s))
        X1 = np.dot(u, sigma)
        X2 = np.dot(vt.T, sigma)
        # self._X = X2
        self._X = np.concatenate((X1, X2), axis=1) 
開發者ID:thunlp,項目名稱:OpenNE,代碼行數:23,代碼來源:hope.py

示例2: test_to_networkx

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def test_to_networkx():
    x = torch.Tensor([[1, 2], [3, 4]])
    pos = torch.Tensor([[0, 0], [1, 1]])
    edge_index = torch.tensor([[0, 1, 0], [1, 0, 0]])
    edge_attr = torch.Tensor([1, 2, 3])
    data = Data(x=x, pos=pos, edge_index=edge_index, weight=edge_attr)

    for remove_self_loops in [True, False]:
        G = to_networkx(data, node_attrs=['x', 'pos'], edge_attrs=['weight'],
                        remove_self_loops=remove_self_loops)

        assert G.nodes[0]['x'] == [1, 2]
        assert G.nodes[1]['x'] == [3, 4]
        assert G.nodes[0]['pos'] == [0, 0]
        assert G.nodes[1]['pos'] == [1, 1]

        if remove_self_loops:
            assert nx.to_numpy_matrix(G).tolist() == [[0, 1], [2, 0]]
        else:
            assert nx.to_numpy_matrix(G).tolist() == [[3, 1], [2, 0]] 
開發者ID:rusty1s,項目名稱:pytorch_geometric,代碼行數:22,代碼來源:test_convert.py

示例3: test_to_networkx_undirected

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def test_to_networkx_undirected():
    x = torch.Tensor([[1, 2], [3, 4]])
    pos = torch.Tensor([[0, 0], [1, 1]])
    edge_index = torch.tensor([[0, 1, 0], [1, 0, 0]])
    edge_attr = torch.Tensor([1, 2, 3])
    data = Data(x=x, pos=pos, edge_index=edge_index, weight=edge_attr)

    for remove_self_loops in [True, False]:
        G = to_networkx(data, node_attrs=['x', 'pos'], edge_attrs=['weight'],
                        remove_self_loops=remove_self_loops,
                        to_undirected=True)

        assert G.nodes[0]['x'] == [1, 2]
        assert G.nodes[1]['x'] == [3, 4]
        assert G.nodes[0]['pos'] == [0, 0]
        assert G.nodes[1]['pos'] == [1, 1]

        if remove_self_loops:
            assert nx.to_numpy_matrix(G).tolist() == [[0, 2], [2, 0]]
        else:
            assert nx.to_numpy_matrix(G).tolist() == [[3, 2], [2, 0]] 
開發者ID:rusty1s,項目名稱:pytorch_geometric,代碼行數:23,代碼來源:test_convert.py

示例4: get_observation

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def get_observation(self,feature='deg'):
        """

        :return: ob, where ob['adj'] is E with dim b x n x n and ob['node']
        is F with dim 1 x n x m. NB: n = node_num + node_type_num
        """
        n = self.graph.number_of_nodes()
        F = np.zeros((1, self.max_node, 1))
        F[0,:n+1,0] = 1

        E = np.zeros((1, self.max_node, self.max_node))
        E[0,:n,:n] = np.asarray(nx.to_numpy_matrix(self.graph))[np.newaxis,:,:]
        E[0,:n+1,:n+1] += np.eye(n+1)

        ob = {}
        if self.is_normalize:
            E = self.normalize_adj(E)
        ob['adj'] = E
        ob['node'] = F
        return ob 
開發者ID:bowenliu16,項目名稱:rl_graph_generation,代碼行數:22,代碼來源:molecule.py

示例5: __init__

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def __init__(self, G_list, max_num_node=None, max_prev_node=None, iteration=20000):
        self.adj_all = []
        self.len_all = []
        for G in G_list:
            self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
            self.len_all.append(G.number_of_nodes())
        if max_num_node is None:
            self.n = max(self.len_all)
        else:
            self.n = max_num_node
        if max_prev_node is None:
            print('calculating max previous node, total iteration: {}'.format(iteration))
            self.max_prev_node = max(self.calc_max_prev_node(iter=iteration))
            print('max previous node: {}'.format(self.max_prev_node))
        else:
            self.max_prev_node = max_prev_node

        # self.max_prev_node = max_prev_node

        # # sort Graph in descending order
        # len_batch_order = np.argsort(np.array(self.len_all))[::-1]
        # self.len_all = [self.len_all[i] for i in len_batch_order]
        # self.adj_all = [self.adj_all[i] for i in len_batch_order] 
開發者ID:JiaxuanYou,項目名稱:graph-generation,代碼行數:25,代碼來源:data.py

示例6: networkx_to_adjacency

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def networkx_to_adjacency(graph):
    """Simple wrapper for graph to adjacency matrix.

    Parameters
    ----------
    graph : object
        The networkx graph object.

    Returns
    -------
    matrix : array
        The numpy adjacency matrix.
    """
    msg = 'Please pass an networkx graph object, not a {}'.format(type(graph))
    assert isinstance(graph, nx.Graph), msg

    atomic_numbers = list(dict(graph.nodes('atomic_number')).values())
    adjacency = np.asarray(nx.to_numpy_matrix(graph, dtype='f'))

    assert np.shape(adjacency) == (len(atomic_numbers), len(atomic_numbers))

    adjacency += np.diag(atomic_numbers)

    return adjacency 
開發者ID:SUNCAT-Center,項目名稱:CatLearn,代碼行數:26,代碼來源:networkx_graph_api.py

示例7: edge_transform

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def edge_transform(self, g):
        e = {}
        for n1, n2, d in g.edges_iter(data=True):
            e_t = []
            e_t += [float(x) for x in list(d.values())]
            e[(n1, n2)] = e_t
        return nx.to_numpy_matrix(g), e 
開發者ID:priba,項目名稱:nmp_qc,代碼行數:9,代碼來源:grec.py

示例8: edge_transform

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def edge_transform(self, g):
        e = {}
        for n1, n2, d in g.edges_iter(data=True):
            e_t = []
            e_t += [1]
            e[(n1, n2)] = e_t
        return nx.to_numpy_matrix(g), e 
開發者ID:priba,項目名稱:nmp_qc,代碼行數:9,代碼來源:letter.py

示例9: edge_transform

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def edge_transform(self, g):
        e = {}
        for n1, n2, d in g.edges_iter(data=True):
            e_t = []
            e_t.append(d['label'])
            e[(n1, n2)] = e_t
        return nx.to_numpy_matrix(g), e 
開發者ID:priba,項目名稱:nmp_qc,代碼行數:9,代碼來源:mutag.py

示例10: gen_data

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def gen_data(min_num_nodes=20,
             max_num_nodes=100,
             num_graphs=10,
             node_emb_dim=10,
             graph_emb_dim=2,
             edge_prob=0.5,
             seed=123):
  """
    Generate synthetic graph data for graph regression, i.e., given node 
    embedding and graph structure as input, predict a graph embedding 
    as output.

    N.B.: modification to other tasks like node classification is straightforward

    A single graph in your dataset should contin:
      X: Node embedding, numpy array, shape N X D where N is # nodes
      A: Graph structure, numpy array, shape N X N X E where E is # edge types
      Y: Graph embedding, numpy array, shape N X O
  """
  npr = np.random.RandomState(seed)
  N = npr.randint(min_num_nodes, high=max_num_nodes+1, size=num_graphs)

  data = []
  for ii in range(num_graphs):    
    data_dict = {}
    data_dict['X'] = npr.randn(N[ii], node_emb_dim)
    # we assume # edge type = 1, but you can easily extend it to be more than 1
    data_dict['A'] = np.expand_dims(
        nx.to_numpy_matrix(
            nx.fast_gnp_random_graph(N[ii], edge_prob, seed=npr.randint(1000))),
        axis=2)
    data_dict['Y'] = npr.randn(1, graph_emb_dim)
    data += [data_dict]

  return data 
開發者ID:lrjconan,項目名稱:LanczosNetwork,代碼行數:37,代碼來源:get_graph_data.py

示例11: adjacency_unweighted

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def adjacency_unweighted(segmentation, connectivity=CONNECTIVITY):
    """Computes the adjacency matrix of the Region Adjacency Graph.

    Given an segmentation, this method constructs the constructs the
    corresponding Region Adjacency Graphh (RAG). Each node in the RAG
    represents a set of pixels with the same label in `segmentation`. An edge
    between two nodes exist if the nodes are spatial connected.

    Args:
        segmentation: The segmentation.
        connectivity: Integer. Pixels with a squared distance less than
          `connectivity` from each other are considered adjacent (optional).

    Returns:
        An adjacent matrix with shape [num_segments, num_segments].
    """

    def _adjacency(segmentation):
        graph = RAG(segmentation, connectivity=connectivity)

        # Simply return the unweighted adjacency matrix of the computed graph.
        return nx.to_numpy_matrix(graph, dtype=np.float32)

    return tf.py_func(
        _adjacency, [segmentation], tf.float32, stateful=False,
        name='adjacency_unweighted') 
開發者ID:rusty1s,項目名稱:graph-based-image-classification,代碼行數:28,代碼來源:adjacency.py

示例12: makeStochasticABFromNetworkxGraph

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def makeStochasticABFromNetworkxGraph(self, nxgraph, alpha,
                                          beta):  # takes a nxgraph, alpha, and beta. Returns stochastic initMatrix.
        adjMatrix = nx.to_numpy_matrix(nxgraph)  # return graph adj matrix as a np matrix

        n = adjMatrix.shape[0]  # get num nodes

        init = InitMatrix(n)
        init.make()
        for i in range(n):
            for j in range(n):
                init.setValue(adjMatrix[i, j], i, j)
        init.makeStochasticAB(alpha, beta)

        return init  # there is no gaurentee of self loops since these are other graph types generated as seeds 
開發者ID:palash1992,項目名稱:GEM-Benchmark,代碼行數:16,代碼來源:kronecker_init_matrix.py

示例13: makeFromNetworkxGraph

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def makeFromNetworkxGraph(self, nxgraph):  # takes a nxgraph, Returns initMatrix.
        adjMatrix = nx.to_numpy_matrix(nxgraph)  # return graph adj matrix as a np matrix

        n = adjMatrix.shape[0]  # get num nodes

        init = InitMatrix(n)
        init.make()
        for i in range(n):
            for j in range(n):
                init.setValue(adjMatrix[i, j], i, j)

        return init  # there is no gaurentee of self loops since these are other graph types generated as seeds 
開發者ID:palash1992,項目名稱:GEM-Benchmark,代碼行數:14,代碼來源:kronecker_init_matrix.py

示例14: test_encode_decode_adj

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def test_encode_decode_adj():
######## code test ###########
    G = nx.ladder_graph(5)
    G = nx.grid_2d_graph(20,20)
    G = nx.ladder_graph(200)
    G = nx.karate_club_graph()
    G = nx.connected_caveman_graph(2,3)
    print(G.number_of_nodes())
    
    adj = np.asarray(nx.to_numpy_matrix(G))
    G = nx.from_numpy_matrix(adj)
    #
    start_idx = np.random.randint(adj.shape[0])
    x_idx = np.array(bfs_seq(G, start_idx))
    adj = adj[np.ix_(x_idx, x_idx)]
    
    print('adj\n',adj)
    adj_output = encode_adj(adj,max_prev_node=5)
    print('adj_output\n',adj_output)
    adj_recover = decode_adj(adj_output,max_prev_node=5)
    print('adj_recover\n',adj_recover)
    print('error\n',np.amin(adj_recover-adj),np.amax(adj_recover-adj))
    
    
    adj_output = encode_adj_flexible(adj)
    for i in range(len(adj_output)):
        print(len(adj_output[i]))
    adj_recover = decode_adj_flexible(adj_output)
    print(adj_recover)
    print(np.amin(adj_recover-adj),np.amax(adj_recover-adj)) 
開發者ID:JiaxuanYou,項目名稱:graph-generation,代碼行數:32,代碼來源:data.py

示例15: test_encode_decode_adj_full

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_numpy_matrix [as 別名]
def test_encode_decode_adj_full():
########### code test #############
    # G = nx.ladder_graph(10)
    G = nx.karate_club_graph()
    # get bfs adj
    adj = np.asarray(nx.to_numpy_matrix(G))
    G = nx.from_numpy_matrix(adj)
    start_idx = np.random.randint(adj.shape[0])
    x_idx = np.array(bfs_seq(G, start_idx))
    adj = adj[np.ix_(x_idx, x_idx)]
    
    adj_output, adj_len = encode_adj_full(adj)
    print('adj\n',adj)
    print('adj_output[0]\n',adj_output[:,:,0])
    print('adj_output[1]\n',adj_output[:,:,1])
    # print('adj_len\n',adj_len)
    
    adj_recover = decode_adj_full(adj_output)
    print('adj_recover\n', adj_recover)
    print('error\n',adj_recover-adj)
    print('error_sum\n',np.amax(adj_recover-adj), np.amin(adj_recover-adj))






########## use pytorch dataloader 
開發者ID:JiaxuanYou,項目名稱:graph-generation,代碼行數:30,代碼來源:data.py


注:本文中的networkx.to_numpy_matrix方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。