Python networkx.karate_club_graph() Examples
The following are 30
code examples of networkx.karate_club_graph().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 7 votes |
def hub_dominance(graph, communities, **kwargs): """Hub dominance. The hub dominance of a community is defined as the ratio of the degree of its most connected node w.r.t. the theoretically maximal degree within the community. :param graph: a networkx/igraph object :param communities: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> scd = evaluation.hub_dominance(g,communities) """ return __quality_indexes(graph, communities, lambda graph, coms: max([x[1] for x in list(nx.degree(nx.subgraph(graph, coms)))]) / (len(coms) - 1), **kwargs)
Example #2
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 7 votes |
def avg_distance(graph, communities, **kwargs): """Average distance. The average distance of a community is defined average path length across all possible pair of nodes composing it. :param graph: a networkx/igraph object :param communities: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> scd = evaluation.avg_distance(g,communities) """ return __quality_indexes(graph, communities, lambda graph, coms: nx.average_shortest_path_length(nx.subgraph(graph, coms)), **kwargs)
Example #3
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def z_modularity(self): """ Z-modularity is another variant of the standard modularity proposed to avoid the resolution limit. The concept of this version is based on an observation that the difference between the fraction of edges inside communities and the expected number of such edges in a null model should not be considered as the only contribution to the final quality of algorithms structure. :return: the z-modularity score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.z_modularity() :References: Miyauchi, Atsushi, and Yasushi Kawase. **Z-score-based modularity for algorithms detection in networks.** PloS one 11.1 (2016): e0147805. """ if self.__check_graph(): return evaluation.z_modularity(self.graph, self) else: raise ValueError("Graph instance not specified")
Example #4
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def link_modularity(graph, communities, **kwargs): """ Quality function designed for directed graphs with overlapping communities. :param graph: a networkx/igraph object :param communities: NodeClustering object :return: FitnessResult object Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = evaluation.link_modularity(g,communities) :References: 1. Nicosia, V., Mangioni, G., Carchiolo, V., Malgeri, M.: Extending the definition of modularity to directed graphs with overlapping communities. Journal of Statistical Mechanics: Theory and Experiment 2009(03), 03024 (2009) """ graph = convert_graph_formats(graph, nx.Graph) return FitnessResult(score=cal_modularity(graph, communities.communities))
Example #5
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def normalized_mutual_information(self, clustering): """ Normalized Mutual Information between two clusterings. Normalized Mutual Information (NMI) is an normalization of the Mutual Information (MI) score to scale the results between 0 (no mutual information) and 1 (perfect correlation). In this function, mutual information is normalized by ``sqrt(H(labels_true) * H(labels_pred))`` :param clustering: NodeClustering object :return: normalized mutual information score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> mod = communities.normalized_mutual_information(leiden_communities) """ return evaluation.normalized_mutual_information(self, clustering)
Example #6
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def significance(self): """ Significance estimates how likely a partition of dense communities appear in a random graph. :return: the significance score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.significance() :References: Traag, V. A., Aldecoa, R., & Delvenne, J. C. (2015). **Detecting communities using asymptotical surprise.** Physical Review E, 92(2), 022816. """ if self.__check_graph(): return evaluation.significance(self.graph, self) else: raise ValueError("Graph instance not specified")
Example #7
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def surprise(self): """ Surprise is statistical approach proposes a quality metric assuming that edges between vertices emerge randomly according to a hyper-geometric distribution. According to the Surprise metric, the higher the score of a partition, the less likely it is resulted from a random realization, the better the quality of the algorithms structure. :return: the surprise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.surprise() :References: Traag, V. A., Aldecoa, R., & Delvenne, J. C. (2015). **Detecting communities using asymptotical surprise.** Physical Review E, 92(2), 022816. """ if self.__check_graph(): return evaluation.surprise(self.graph, self) else: raise ValueError("Graph instance not specified")
Example #8
Source File: test_compartment.py From ndlib with BSD 2-Clause "Simplified" License | 6 votes |
def test_edge_attribute(self): g = nx.karate_club_graph() attr = {(u, v): {"even": int((u+v) % 2)} for (u, v) in g.edges()} nx.set_edge_attributes(g, attr) model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c = cpm.EdgeCategoricalAttribute("even", "0", probability=0.6) model.add_rule("Susceptible", "Infected", c) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.1) model.set_initial_status(config) iterations = model.iteration_bunch(10) self.assertEqual(len(iterations), 10)
Example #9
Source File: test_compartment.py From ndlib with BSD 2-Clause "Simplified" License | 6 votes |
def test_node_attribute(self): g = nx.karate_club_graph() attr = {n: {"even": int(n % 2)} for n in g.nodes()} nx.set_node_attributes(g, attr) model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c = cpm.NodeCategoricalAttribute("even", "0", probability=0.6) model.add_rule("Susceptible", "Infected", c) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.1) model.set_initial_status(config) iterations = model.iteration_bunch(10) self.assertEqual(len(iterations), 10)
Example #10
Source File: test_embedding_utils.py From dwave-system with Apache License 2.0 | 6 votes |
def test_identity_embedding(self): """a 1-to-1 embedding should not change the adjacency""" target_adj = nx.karate_club_graph() embedding = {v: {v} for v in target_adj} source_adj = dwave.embedding.target_to_source(target_adj, embedding) # test the adjacencies are equal (source_adj is a dict and target_adj is a networkx graph) for v in target_adj: self.assertIn(v, source_adj) for u in target_adj[v]: self.assertIn(u, source_adj[v]) for v in source_adj: self.assertIn(v, target_adj) for u in source_adj[v]: self.assertIn(u, target_adj[v])
Example #11
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def f1(self, clustering): """ Compute the average F1 score of the optimal algorithms matches among the partitions in input. Works on overlapping/non-overlapping complete/partial coverage partitions. :param clustering: NodeClustering object :return: F1 score (harmonic mean of precision and recall) :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> mod = communities.f1(leiden_communities) :Reference: 1. Rossetti, G., Pappalardo, L., & Rinzivillo, S. (2016). **A novel approach to evaluate algorithms detection internal on ground truth.** In Complex Networks VII (pp. 133-144). Springer, Cham. """ return evaluation.f1(self, clustering)
Example #12
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def nf1(self, clustering): """ Compute the Normalized F1 score of the optimal algorithms matches among the partitions in input. Works on overlapping/non-overlapping complete/partial coverage partitions. :param clustering: NodeClustering object :return: MatchingResult instance :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> leiden_communities = algorithms.leiden(g) >>> mod = communities.nf1(leiden_communities) :Reference: 1. Rossetti, G., Pappalardo, L., & Rinzivillo, S. (2016). **A novel approach to evaluate algorithms detection internal on ground truth.** 2. Rossetti, G. (2017). : **RDyn: graph benchmark handling algorithms dynamics. Journal of Complex Networks.** 5(6), 893-912. """ return evaluation.nf1(self, clustering)
Example #13
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def edges_inside(graph, community, **kwargs): """Number of edges internal to the community. :param graph: a networkx/igraph object :param community: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = evaluation.edges_inside(g,communities) :References: 1. Radicchi, F., Castellano, C., Cecconi, F., Loreto, V., & Parisi, D. (2004). Defining and identifying communities in networks. Proceedings of the National Academy of Sciences, 101(9), 2658-2663. """ return __quality_indexes(graph, community, pq.PartitionQuality.edges_inside, **kwargs)
Example #14
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def avg_transitivity(graph, communities, **kwargs): """Average transitivity. The average transitivity of a community is defined the as the average clustering coefficient of its nodes w.r.t. their connection within the community itself. :param graph: a networkx/igraph object :param communities: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> scd = evaluation.avg_transitivity(g,communities) """ return __quality_indexes(graph, communities, lambda graph, coms: nx.average_clustering(nx.subgraph(graph, coms)), **kwargs)
Example #15
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def link_modularity(self): """ Quality function designed for directed graphs with overlapping communities. :return: the link modularity score :Example: >>> from cdlib import evaluation >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.link_modularity() """ if self.__check_graph(): return evaluation.link_modularity(self.graph, self) else: raise ValueError("Graph instance not specified")
Example #16
Source File: test_compartment.py From ndlib with BSD 2-Clause "Simplified" License | 6 votes |
def test_countwodn(self): g = nx.karate_club_graph() model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c = cpm.CountDown(name="time", iterations=4) model.add_rule("Susceptible", "Infected", c) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.1) model.set_initial_status(config) iterations = model.iteration_bunch(100) self.assertEqual(len(iterations), 100)
Example #17
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def triangle_participation_ratio(self, **kwargs): """ Fraction of algorithms nodes that belong to a triad. .. math:: f(S) = \\frac{ | \{ u: u \in S,\{(v,w):v, w \in S,(u,v) \in E,(u,w) \in E,(v,w) \in E \} \\not = \\emptyset \} |}{n_S} where :math:`n_S` is the set of algorithms nodes. :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.triangle_participation_ratio() """ if self.__check_graph(): return evaluation.triangle_participation_ratio(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #18
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def flake_odf(self, **kwargs): """ Fraction of nodes in S that have fewer edges pointing inside than to the outside of the algorithms. .. math:: f(S) = \\frac{| \{ u:u \in S,| \{(u,v) \in E: v \in S \}| < d(u)/2 \}|}{n_S} where :math:`E` is the graph edge set, :math:`v` is a node in :math:`S`, :math:`d(u)` is the degree of :math:`u` and :math:`n_S` is the set of algorithms nodes. :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.flake_odf() """ if self.__check_graph(): return evaluation.flake_odf(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #19
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def max_odf(self, **kwargs): """ Maximum fraction of edges of a node of a algorithms that point outside the algorithms itself. .. math:: max_{u \\in S} \\frac{|\{(u,v)\\in E: v \\not\\in S\}|}{d(u)} where :math:`E` is the graph edge set, :math:`v` is a node in :math:`S` and :math:`d(u)` is the degree of :math:`u` :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.max_odf() """ if self.__check_graph(): return evaluation.max_odf(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #20
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def conductance(self, **kwargs): """ Fraction of total edge volume that points outside the algorithms. .. math:: f(S) = \\frac{c_S}{2 m_S+c_S} where :math:`c_S` is the number of algorithms nodes and, :math:`m_S` is the number of algorithms edges :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.conductance() """ if self.__check_graph(): return evaluation.conductance(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #21
Source File: test_distance.py From netrd with MIT License | 6 votes |
def test_quantum_jsd(): """Run the above tests again using the collision entropy instead of the Von Neumann entropy to ensure that all the logic of the JSD implementation is tested. """ with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="JSD is only a metric for 0 ≤ q < 2.") JSD = distance.QuantumJSD() G = nx.karate_club_graph() dist = JSD.dist(G, G, beta=0.1, q=2) assert np.isclose(dist, 0.0) G1 = nx.fast_gnp_random_graph(100, 0.3) G2 = nx.barabasi_albert_graph(100, 5) dist = JSD.dist(G1, G2, beta=0.1, q=2) assert dist > 0.0 G1 = nx.barabasi_albert_graph(100, 4) G2 = nx.fast_gnp_random_graph(100, 0.3) dist1 = JSD.dist(G1, G2, beta=0.1, q=2) dist2 = JSD.dist(G2, G1, beta=0.1, q=2) assert np.isclose(dist1, dist2)
Example #22
Source File: test_distance.py From netrd with MIT License | 6 votes |
def test_weighted_input(): G1 = nx.karate_club_graph() G2 = nx.karate_club_graph() rand = np.random.RandomState(seed=42) edge_weights = {e: rand.randint(0, 1000) for e in G2.edges} nx.set_edge_attributes(G2, edge_weights, "weight") assert nx.is_isomorphic(G1, G2) for label, obj in distance.__dict__.items(): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") if isinstance(obj, type) and BaseDistance in obj.__bases__: dist = obj().dist(G1, G2) warning_triggered = False for warning in w: if "weighted" in str(warning.message): warning_triggered = True if not warning_triggered: assert not np.isclose(dist, 0.0) else: assert np.isclose(dist, 0.0)
Example #23
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def edges_inside(self, **kwargs): """ Number of edges internal to the algorithms. :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.edges_inside() """ if self.__check_graph(): return evaluation.edges_inside(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #24
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def cut_ratio(self, **kwargs): """ Fraction of existing edges (out of all possible edges) leaving the algorithms. ..math:: f(S) = \\frac{c_S}{n_S (n − n_S)} where :math:`c_S` is the number of algorithms nodes and, :math:`n_S` is the number of edges on the algorithms boundary :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.cut_ratio() """ if self.__check_graph(): return evaluation.cut_ratio(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #25
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def expansion(self, **kwargs): """ Number of edges per algorithms node that point outside the cluster. .. math:: f(S) = \\frac{c_S}{n_S} where :math:`n_S` is the number of edges on the algorithms boundary, :math:`c_S` is the number of algorithms nodes. :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.expansion() """ if self.__check_graph(): return evaluation.expansion(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #26
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def average_internal_degree(self, **kwargs): """ The average internal degree of the algorithms set. .. math:: f(S) = \\frac{2m_S}{n_S} where :math:`m_S` is the number of algorithms internal edges and :math:`n_S` is the number of algorithms nodes. :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.average_internal_degree() """ if self.__check_graph(): return evaluation.average_internal_degree(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #27
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def internal_edge_density(self, **kwargs): """ The internal density of the algorithms set. .. math:: f(S) = \\frac{m_S}{n_S(n_S−1)/2} where :math:`m_S` is the number of algorithms internal edges and :math:`n_S` is the number of algorithms nodes. :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.internal_edge_density() """ if self.__check_graph(): return evaluation.internal_edge_density(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #28
Source File: node_clustering.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def normalized_cut(self, **kwargs): """ Normalized variant of the Cut-Ratio .. math:: : f(S) = \\frac{c_S}{2m_S+c_S} + \\frac{c_S}{2(m−m_S )+c_S} where :math:`m` is the number of graph edges, :math:`m_S` is the number of algorithms internal edges and :math:`c_S` is the number of algorithms nodes. :param summary: (optional, default True) if **True**, an overall summary is returned for the partition (min, max, avg, std); if **False** a list of community-wise score :return: a FitnessResult object/a list of community-wise score :Example: >>> from cdlib.algorithms import louvain >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = communities.normalized_cut() """ if self.__check_graph(): return evaluation.normalized_cut(self.graph, self, **kwargs) else: raise ValueError("Graph instance not specified")
Example #29
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def size(graph, communities, **kwargs): """Size is the number of nodes in the community :param graph: a networkx/igraph object :param communities: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> sz = evaluation.size(g,communities) """ return __quality_indexes(graph, communities, lambda g, com: len(com), **kwargs)
Example #30
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def scaled_density(graph, communities, **kwargs): """Scaled density. The scaled density of a community is defined as the ratio of the community density w.r.t. the complete graph density. :param graph: a networkx/igraph object :param communities: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> scd = evaluation.scaled_density(g,communities) """ return __quality_indexes(graph, communities, lambda graph, coms: nx.density(nx.subgraph(graph, coms)) / nx.density(graph), **kwargs)