当前位置: 首页>>代码示例>>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;未经允许,请勿转载。