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


Python networkx.clustering方法代碼示例

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


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

示例1: decode_graph

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def decode_graph(adj, prefix):
    adj = np.asmatrix(adj)
    G = nx.from_numpy_matrix(adj)
    # G.remove_nodes_from(nx.isolates(G))
    print('num of nodes: {}'.format(G.number_of_nodes()))
    print('num of edges: {}'.format(G.number_of_edges()))
    G_deg = nx.degree_histogram(G)
    G_deg_sum = [a * b for a, b in zip(G_deg, range(0, len(G_deg)))]
    print('average degree: {}'.format(sum(G_deg_sum) / G.number_of_nodes()))
    if nx.is_connected(G):
        print('average path length: {}'.format(nx.average_shortest_path_length(G)))
        print('average diameter: {}'.format(nx.diameter(G)))
    G_cluster = sorted(list(nx.clustering(G).values()))
    print('average clustering coefficient: {}'.format(sum(G_cluster) / len(G_cluster)))
    cycle_len = []
    cycle_all = nx.cycle_basis(G, 0)
    for item in cycle_all:
        cycle_len.append(len(item))
    print('cycles', cycle_len)
    print('cycle count', len(cycle_len))
    draw_graph(G, prefix=prefix) 
開發者ID:JiaxuanYou,項目名稱:graph-generation,代碼行數:23,代碼來源:utils.py

示例2: _directed_triangles_and_degree_iter

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def _directed_triangles_and_degree_iter(G, nodes=None):
    """ Return an iterator of
    (node, total_degree, reciprocal_degree, directed_triangles).

    Used for directed clustering.

    """
    nodes_nbrs = ((n, G._pred[n], G._succ[n]) for n in G.nbunch_iter(nodes))

    for i, preds, succs in nodes_nbrs:
        ipreds = set(preds) - {i}
        isuccs = set(succs) - {i}

        directed_triangles = 0
        for j in chain(ipreds, isuccs):
            jpreds = set(G._pred[j]) - {j}
            jsuccs = set(G._succ[j]) - {j}
            directed_triangles += sum((1 for k in
                                       chain((ipreds & jpreds),
                                             (ipreds & jsuccs),
                                             (isuccs & jpreds),
                                             (isuccs & jsuccs))))
        dtotal = len(ipreds) + len(isuccs)
        dbidirectional = len(ipreds & isuccs)
        yield (i, dtotal, dbidirectional, directed_triangles) 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:27,代碼來源:cluster.py

示例3: test_k5

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def test_k5(self):
        G = nx.complete_graph(5)
        assert_equal(nx.transitivity(G), 1.0)
        G.remove_edge(1, 2)
        assert_equal(nx.transitivity(G), 0.875)

    # def test_clustering_transitivity(self):
    #     # check that weighted average of clustering is transitivity
    #     G = nx.complete_graph(5)
    #     G.remove_edge(1,2)
    #     t1=nx.transitivity(G)
    #     (cluster_d2,weights)=nx.clustering(G,weights=True)
    #     trans=[]
    #     for v in G.nodes():
    #         trans.append(cluster_d2[v]*weights[v])
    #     t2=sum(trans)
    #     assert_almost_equal(abs(t1-t2),0) 
開發者ID:holzschu,項目名稱:Carnets,代碼行數:19,代碼來源:test_cluster.py

示例4: _set_omega

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def _set_omega(self):
        """
        Calculating the graph level clustering coefficient.
        """
        self._omega = nx.transitivity(self._graph) 
開發者ID:benedekrozemberczki,項目名稱:karateclub,代碼行數:7,代碼來源:scd.py

示例5: _create_initial_partition

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def _create_initial_partition(self):
        """
        Initial local clustering coefficient based cluster membership assignments.
        """
        self._clustering_coefficient = nx.clustering(self._graph)
        self._cc_pairs = [(node_cc**0.5, node) for node, node_cc in self._clustering_coefficient.items()]
        self._cc_pairs = sorted(self._cc_pairs, key=lambda tup: tup[0])[::-1]
        self._do_initial_assignments() 
開發者ID:benedekrozemberczki,項目名稱:karateclub,代碼行數:10,代碼來源:scd.py

示例6: fit

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def fit(self, graph):
        """
        Fitting a Label Propagation clustering model.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be clustered.
        """
        self._set_seed()
        self._check_graph(graph)
        self._graph = graph
        self._create_initial_partition()
        self._set_omega()
        self._set_nodes()
        for _ in range(self.iterations):
            self._do_refinement() 
開發者ID:benedekrozemberczki,項目名稱:karateclub,代碼行數:17,代碼來源:scd.py

示例7: _create_node_feature_matrix

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def _create_node_feature_matrix(self, graph):
        """
        Calculating the node features.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph of interest.

        Return types:
            * **X** *(NumPy array)* - The node features.
        """
        log_degree = np.array([math.log(graph.degree(node)+1) for node in range(graph.number_of_nodes())]).reshape(-1, 1)
        eccentricity = np.array([nx.eccentricity(graph, node) for node in range(graph.number_of_nodes())]).reshape(-1, 1)
        clustering_coefficient = np.array([nx.clustering(graph, node) for node in range(graph.number_of_nodes())]).reshape(-1, 1)
        X = np.concatenate([log_degree, eccentricity, clustering_coefficient], axis=1)
        return X 
開發者ID:benedekrozemberczki,項目名稱:karateclub,代碼行數:17,代碼來源:geoscattering.py

示例8: _create_node_feature_matrix

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def _create_node_feature_matrix(self, graph):
        """
        Calculating the node features.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph of interest.

        Return types:
            * **X** *(NumPy array)* - The node features.
        """
        log_degree = np.array([math.log(graph.degree(node)+1) for node in range(graph.number_of_nodes())]).reshape(-1, 1)
        clustering_coefficient = np.array([nx.clustering(graph, node) for node in range(graph.number_of_nodes())]).reshape(-1, 1)
        X = np.concatenate([log_degree, clustering_coefficient], axis=1)
        return X 
開發者ID:benedekrozemberczki,項目名稱:karateclub,代碼行數:16,代碼來源:feathergraph.py

示例9: clustering_worker

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def clustering_worker(param):
    G, bins = param
    clustering_coeffs_list = list(nx.clustering(G).values())
    hist, _ = np.histogram(
            clustering_coeffs_list, bins=bins, range=(0.0, 1.0), density=False)
    return hist 
開發者ID:JiaxuanYou,項目名稱:graph-generation,代碼行數:8,代碼來源:stats.py

示例10: __init__

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def __init__(self, G_list, max_num_nodes, features='id'):
        self.max_num_nodes = max_num_nodes
        self.adj_all = []
        self.len_all = []
        self.feature_all = []

        for G in G_list:
            adj = nx.to_numpy_matrix(G)
            # the diagonal entries are 1 since they denote node probability
            self.adj_all.append(
                    np.asarray(adj) + np.identity(G.number_of_nodes()))
            self.len_all.append(G.number_of_nodes())
            if features == 'id':
                self.feature_all.append(np.identity(max_num_nodes))
            elif features == 'deg':
                degs = np.sum(np.array(adj), 1)
                degs = np.expand_dims(np.pad(degs, [0, max_num_nodes - G.number_of_nodes()], 0),
                                      axis=1)
                self.feature_all.append(degs)
            elif features == 'struct':
                degs = np.sum(np.array(adj), 1)
                degs = np.expand_dims(np.pad(degs, [0, max_num_nodes - G.number_of_nodes()],
                                             'constant'),
                                      axis=1)
                clusterings = np.array(list(nx.clustering(G).values()))
                clusterings = np.expand_dims(np.pad(clusterings, 
                                                    [0, max_num_nodes - G.number_of_nodes()],
                                                    'constant'),
                                             axis=1)
                self.feature_all.append(np.hstack([degs, clusterings])) 
開發者ID:JiaxuanYou,項目名稱:graph-generation,代碼行數:32,代碼來源:data.py

示例11: get_clustering_hist

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def get_clustering_hist(graph):
    r"""
    Compute histogram of clustering coefficient for a graph.
    Not used in our experiments.
    
    :param graph: graph representation in networkx format: nx.from_numpy_matrix(A)
    :return: histogram of clustering coefficients
    """
    clustering_coeffs_list = list(nx.clustering(graph).values())
    hist_c, _ = np.histogram(clustering_coeffs_list, bins=100, range=(0.0, 1.0), density=False)
    return hist_c 
開發者ID:davide-belli,項目名稱:generative-graph-transformer,代碼行數:13,代碼來源:statistics.py

示例12: _weighted_triangles_and_degree_iter

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def _weighted_triangles_and_degree_iter(G, nodes=None, weight='weight'):
    """ Return an iterator of (node, degree, weighted_triangles).  
    
    Used for weighted clustering.

    """
    if G.is_multigraph():
        raise NetworkXError("Not defined for multigraphs.")

    if weight is None or G.edges()==[]:
        max_weight=1.0
    else:
        max_weight=float(max(d.get(weight,1.0) 
                             for u,v,d in G.edges(data=True)))
    if nodes is None:
        nodes_nbrs = G.adj.items()
    else:
        nodes_nbrs= ( (n,G[n]) for n in G.nbunch_iter(nodes) )

    for i,nbrs in nodes_nbrs:
        inbrs=set(nbrs)-set([i])
        weighted_triangles=0.0
        seen=set()
        for j in inbrs:
            wij=G[i][j].get(weight,1.0)/max_weight
            seen.add(j)
            jnbrs=set(G[j])-seen # this keeps from double counting
            for k in inbrs&jnbrs:
                wjk=G[j][k].get(weight,1.0)/max_weight
                wki=G[i][k].get(weight,1.0)/max_weight
                weighted_triangles+=(wij*wjk*wki)**(1.0/3.0)
        yield (i,len(inbrs),weighted_triangles*2) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:34,代碼來源:cluster.py

示例13: test_clustering

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def test_clustering(self):
        G = nx.Graph()
        assert_equal(list(nx.clustering(G,weight='weight').values()),[])
        assert_equal(nx.clustering(G),{}) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:6,代碼來源:test_cluster.py

示例14: test_path

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def test_path(self):
        G = nx.path_graph(10)
        assert_equal(list(nx.clustering(G,weight='weight').values()),
                     [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
        assert_equal(nx.clustering(G,weight='weight'),
                     {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 
                      5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0}) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:9,代碼來源:test_cluster.py

示例15: test_cubical

# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import clustering [as 別名]
def test_cubical(self):
        G = nx.cubical_graph()
        assert_equal(list(nx.clustering(G,weight='weight').values()),
                     [0, 0, 0, 0, 0, 0, 0, 0])
        assert_equal(nx.clustering(G,1),0)
        assert_equal(list(nx.clustering(G,[1,2],weight='weight').values()),[0, 0])
        assert_equal(nx.clustering(G,1,weight='weight'),0)
        assert_equal(nx.clustering(G,[1,2],weight='weight'),{1: 0, 2: 0}) 
開發者ID:SpaceGroupUCL,項目名稱:qgisSpaceSyntaxToolkit,代碼行數:10,代碼來源:test_cluster.py


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