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


Python networkx.to_scipy_sparse_matrix方法代碼示例

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


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

示例1: learn_embedding

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self):
        graph = self.g.G
        graph = graph.to_undirected()
        t1 = time()
        A = nx.to_scipy_sparse_matrix(graph)
        # print(np.sum(A.todense(), axis=0))
        normalize(A, norm='l1', axis=1, copy=False)
        I_n = sp.eye(graph.number_of_nodes())
        I_min_A = I_n - A
        print(I_min_A)
        u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
        t2 = time()
        self._X = vt.T
        self._X = self._X[:, 1:]
        return self._X, (t2 - t1)
        # I_n = sp.eye(graph.number_of_nodes()) 
開發者ID:thunlp,項目名稱:OpenNE,代碼行數:18,代碼來源:lle.py

示例2: learn_embedding

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self, graph=None, edge_f=None,
                        is_weighted=False, no_python=False):
        if not graph and not edge_f:
            raise Exception('graph/edge_f needed')
        if not graph:
            graph = graph_util.loadGraphFromEdgeListTxt(edge_f)
        graph = graph.to_undirected()
        t1 = time()
        A = nx.to_scipy_sparse_matrix(graph)
        normalize(A, norm='l1', axis=1, copy=False)
        I_n = sp.eye(graph.number_of_nodes())
        I_min_A = I_n - A
        try:
            u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
        except:
            u = np.random.randn(A.shape[0], self._d + 1)
            s = np.random.randn(self._d + 1, self._d + 1)
            vt = np.random.randn(self._d + 1, A.shape[0])
        t2 = time()
        self._X = vt.T
        self._X = self._X[:, 1:]
        return self._X, (t2 - t1) 
開發者ID:palash1992,項目名稱:GEM-Benchmark,代碼行數:24,代碼來源:lle.py

示例3: forceatlas2_networkx_layout

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def forceatlas2_networkx_layout(self, G, pos=None, iterations=100, weight_attr=None):
        import networkx
        try:
            import cynetworkx
        except ImportError:
            cynetworkx = None

        assert (
            isinstance(G, networkx.classes.graph.Graph)
            or (cynetworkx and isinstance(G, cynetworkx.classes.graph.Graph))
        ), "Not a networkx graph"
        assert isinstance(pos, dict) or (pos is None), "pos must be specified as a dictionary, as in networkx"
        M = networkx.to_scipy_sparse_matrix(G, dtype='f', format='lil', weight=weight_attr)
        if pos is None:
            l = self.forceatlas2(M, pos=None, iterations=iterations)
        else:
            poslist = numpy.asarray([pos[i] for i in G.nodes()])
            l = self.forceatlas2(M, pos=poslist, iterations=iterations)
        return dict(zip(G.nodes(), l))

    # A layout for igraph.
    #
    # This function returns an igraph layout 
開發者ID:bhargavchippada,項目名稱:forceatlas2,代碼行數:25,代碼來源:forceatlas2.py

示例4: parse_cora_sparse

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def parse_cora_sparse():
    path = "%s/../data/cora/" % (current_dir,)

    features, labels, id2index = _parse_cora_features_labels()

    n_papers = len(id2index)
    graph = nx.Graph()

    with open(path + 'cora.cites', 'r') as f:
        for line in f.xreadlines():
            items = line.strip().split('\t')

            tail = id2index[items[0]]
            head = id2index[items[1]]

            graph.add_edge(head, tail)

    adj = nx.to_scipy_sparse_matrix(graph, format='csr')

    return adj.astype('float32'), features.astype('float32'), labels.astype('int32') 
開發者ID:jcatw,項目名稱:dcnn,代碼行數:22,代碼來源:data.py

示例5: learn_embedding

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self, graph=None, edge_f=None,
                        is_weighted=False, no_python=False):
        if not graph and not edge_f:
            raise Exception('graph/edge_f needed')
        if not graph:
            graph = graph_util.loadGraphFromEdgeListTxt(edge_f)
        graph = graph.to_undirected()
        t1 = time()
        A = nx.to_scipy_sparse_matrix(graph)
        normalize(A, norm='l1', axis=1, copy=False)
        I_n = sp.eye(len(graph.nodes))
        I_min_A = I_n - A
        u, s, vt = lg.svds(I_min_A, k=self._d + 1, which='SM')
        t2 = time()
        self._X = vt.T
        self._X = self._X[:, 1:]
        return self._X.real, (t2 - t1) 
開發者ID:palash1992,項目名稱:GEM,代碼行數:19,代碼來源:lle.py

示例6: convert_from_geodataframe

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def convert_from_geodataframe(gdf):
    """
    Convert a GeoDataFrame to other types representing the contiguity relation
    of the GeoDataFrame's areas.

    Parameters
    ----------
    gdf : GeoDataFrame

    Returns
    -------
    other_formats : tuple
        The 1st entry is a sparse adjacency matrix of type
        :class:`scipy.sparse.csr_matrix`.
        The 2nd entry is a networkx graph.
        The 3rd entry is a dict. Each key is an area and each value is an
        iterable of the key area's neighbors.
        The 4th entry is a PySAL W object.
    """
    w = weights.Rook.from_dataframe(gdf)
    graph = w.to_networkx()
    adj = nx.to_scipy_sparse_matrix(graph)
    neighbor_dict = w.neighbors
    return adj, graph, neighbor_dict, w 
開發者ID:pysal,項目名稱:region,代碼行數:26,代碼來源:util.py

示例7: prepare_params

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def prepare_params(g, data):
    params = {}
    params['infeats'] = data.features.astype('float32') # Only support float32 as feature for now

    # Generate adjacency matrix
    adjacency = nx.to_scipy_sparse_matrix(g)
    params['g_data'] = adjacency.data.astype('float32')
    params['indices'] = adjacency.indices.astype('int32')
    params['indptr'] = adjacency.indptr.astype('int32')

    # Normalization w.r.t. node degrees
    degs = [g.in_degree[i] for i in range(g.number_of_nodes())]
    params['norm'] = np.power(degs, -0.5).astype('float32')
    params['norm'] = params['norm'].reshape((params['norm'].shape[0], 1))

    return params 
開發者ID:apache,項目名稱:incubator-tvm,代碼行數:18,代碼來源:build_gcn.py

示例8: __init__

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def __init__(self, transform=None):
        super(KarateClub, self).__init__('.', transform, None, None)

        G = nx.karate_club_graph()

        adj = nx.to_scipy_sparse_matrix(G).tocoo()
        row = torch.from_numpy(adj.row.astype(np.int64)).to(torch.long)
        col = torch.from_numpy(adj.col.astype(np.int64)).to(torch.long)
        edge_index = torch.stack([row, col], dim=0)
        data = Data(edge_index=edge_index)
        data.num_nodes = edge_index.max().item() + 1
        data.x = torch.eye(data.num_nodes, dtype=torch.float)
        y = [0 if G.nodes[i]['club'] == 'Mr. Hi' else 1 for i in G.nodes]
        data.y = torch.tensor(y)
        self.data, self.slices = self.collate([data]) 
開發者ID:rusty1s,項目名稱:pytorch_geometric,代碼行數:17,代碼來源:karate.py

示例9: learn_embedding

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def learn_embedding(self, graph=None, edge_f=None,
                        is_weighted=False, no_python=False):
        if not graph and not edge_f:
            raise Exception('graph/edge_f needed')
        if not graph:
            graph = graph_util.loadGraphFromEdgeListTxt(edge_f)

        t1 = time()
        # A = nx.to_scipy_sparse_matrix(graph)
        # I = sp.eye(graph.number_of_nodes())
        # M_g = I - self._beta*A
        # M_l = self._beta*A
        A = nx.to_numpy_matrix(graph)
        M_g = np.eye(len(graph.nodes)) - self._beta * A
        M_l = self._beta * A
        S = np.dot(np.linalg.inv(M_g), M_l)

        u, s, vt = lg.svds(S, k=self._d // 2)
        X1 = np.dot(u, np.diag(np.sqrt(s)))
        X2 = np.dot(vt.T, np.diag(np.sqrt(s)))
        t2 = time()
        self._X = np.concatenate((X1, X2), axis=1)

        p_d_p_t = np.dot(u, np.dot(np.diag(s), vt))
        eig_err = np.linalg.norm(p_d_p_t - S)
        print('SVD error (low rank): %f' % eig_err)
        return self._X, (t2 - t1) 
開發者ID:palash1992,項目名稱:GEM,代碼行數:29,代碼來源:hope.py

示例10: test_identity_graph_matrix

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_graph_matrix(self):
        "Conversion from graph to sparse matrix to graph."
        A = nx.to_scipy_sparse_matrix(self.G1)
        self.identity_conversion(self.G1, A, nx.Graph()) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:6,代碼來源:test_convert_scipy.py

示例11: test_identity_digraph_matrix

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_digraph_matrix(self):
        "Conversion from digraph to sparse matrix to digraph."
        A = nx.to_scipy_sparse_matrix(self.G2)
        self.identity_conversion(self.G2, A, nx.DiGraph()) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:6,代碼來源:test_convert_scipy.py

示例12: test_identity_weighted_graph_matrix

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_weighted_graph_matrix(self):
        """Conversion from weighted graph to sparse matrix to weighted graph."""
        A = nx.to_scipy_sparse_matrix(self.G3)
        self.identity_conversion(self.G3, A, nx.Graph()) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:6,代碼來源:test_convert_scipy.py

示例13: test_identity_weighted_digraph_matrix

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_identity_weighted_digraph_matrix(self):
        """Conversion from weighted digraph to sparse matrix to weighted digraph."""
        A = nx.to_scipy_sparse_matrix(self.G4)
        self.identity_conversion(self.G4, A, nx.DiGraph()) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:6,代碼來源:test_convert_scipy.py

示例14: test_nodelist

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_nodelist(self):
        """Conversion from graph to sparse matrix to graph with nodelist."""
        P4 = path_graph(4)
        P3 = path_graph(3)
        nodelist = P3.nodes()
        A = nx.to_scipy_sparse_matrix(P4, nodelist=nodelist)
        GA = nx.Graph(A)
        self.assert_equal(GA, P3)

        # Make nodelist ambiguous by containing duplicates.
        nodelist += [nodelist[0]]
        assert_raises(nx.NetworkXError, nx.to_numpy_matrix, P3, 
                      nodelist=nodelist) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:15,代碼來源:test_convert_scipy.py

示例15: test_format_keyword

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import to_scipy_sparse_matrix [as 別名]
def test_format_keyword(self):
        WP4 = nx.Graph()
        WP4.add_edges_from( (n,n+1,dict(weight=0.5,other=0.3))
                            for n in range(3) )
        P4 = path_graph(4)
        A = nx.to_scipy_sparse_matrix(P4, format='csr')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4,weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='csc')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4,weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='coo')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4,weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='bsr')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4,weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='lil')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4,weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='dia')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4,weight=None).todense())

        A = nx.to_scipy_sparse_matrix(P4, format='dok')
        np_assert_equal(A.todense(),
                        nx.to_scipy_sparse_matrix(WP4,weight=None).todense()) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:34,代碼來源:test_convert_scipy.py


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