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