本文整理汇总了Python中networkx.betweenness_centrality方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.betweenness_centrality方法的具体用法?Python networkx.betweenness_centrality怎么用?Python networkx.betweenness_centrality使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.betweenness_centrality方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: calc_BC
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def calc_BC(protein_graph, prefix, generate_plots=True):
bc = nx.betweenness_centrality(protein_graph, normalized=False)
bc = np.asarray(list(bc.values()))
num_nodes = len(protein_graph.nodes())
nodes_axis = range(1, num_nodes + 1)
if generate_plots:
plt.plot(nodes_axis, bc)
plt.title("%s BC" % prefix, fontsize=18)
plt.xlabel('Node Indices', fontsize=16)
plt.ylabel('BC', fontsize=16)
plt.savefig("%s_BC.png" % prefix, dpi=300, bbox_inches='tight')
plt.close()
bc = bc.reshape(1, num_nodes)
np.savetxt("%s_bc.dat" % prefix, bc)
return bc
示例2: test_florentine_families_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def test_florentine_families_graph(self):
"""Betweenness centrality: Florentine families graph"""
G=nx.florentine_families_graph()
b_answer=\
{'Acciaiuoli': 0.000,
'Albizzi': 0.212,
'Barbadori': 0.093,
'Bischeri': 0.104,
'Castellani': 0.055,
'Ginori': 0.000,
'Guadagni': 0.255,
'Lamberteschi': 0.000,
'Medici': 0.522,
'Pazzi': 0.000,
'Peruzzi': 0.022,
'Ridolfi': 0.114,
'Salviati': 0.143,
'Strozzi': 0.103,
'Tornabuoni': 0.092}
b=nx.betweenness_centrality(G,
weight=None,
normalized=True)
for n in sorted(G):
assert_almost_equal(b[n],b_answer[n],places=3)
示例3: test_G2
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def test_G2(self):
"""Weighted betweenness centrality: G2"""
G=nx.DiGraph()
G.add_weighted_edges_from([('s','u',10) ,('s','x',5) ,
('u','v',1) ,('u','x',2) ,
('v','y',1) ,('x','u',3) ,
('x','v',5) ,('x','y',2) ,
('y','s',7) ,('y','v',6)])
b_answer={'y':5.0,'x':5.0,'s':4.0,'u':2.0,'v':2.0}
b=nx.betweenness_centrality(G,
weight='weight',
normalized=False)
for n in sorted(G):
assert_almost_equal(b[n],b_answer[n])
示例4: test_K5_endpoints
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def test_K5_endpoints(self):
"""Betweenness centrality: K5 endpoints"""
G = nx.complete_graph(5)
b = nx.betweenness_centrality(G,
weight=None,
normalized=False,
endpoints=True)
b_answer = {0: 4.0, 1: 4.0, 2: 4.0, 3: 4.0, 4: 4.0}
for n in sorted(G):
assert_almost_equal(b[n], b_answer[n])
# normalized = True case
b = nx.betweenness_centrality(G,
weight=None,
normalized=True,
endpoints=True)
b_answer = {0: 0.4, 1: 0.4, 2: 0.4, 3: 0.4, 4: 0.4}
for n in sorted(G):
assert_almost_equal(b[n], b_answer[n])
示例5: test_P3_endpoints
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def test_P3_endpoints(self):
"""Betweenness centrality: P3 endpoints"""
G = nx.path_graph(3)
b_answer = {0: 2.0, 1: 3.0, 2: 2.0}
b = nx.betweenness_centrality(G,
weight=None,
normalized=False,
endpoints=True)
for n in sorted(G):
assert_almost_equal(b[n], b_answer[n])
# normalized = True case
b_answer = {0: 2/3, 1: 1.0, 2: 2/3}
b = nx.betweenness_centrality(G,
weight=None,
normalized=True,
endpoints=True)
for n in sorted(G):
assert_almost_equal(b[n], b_answer[n])
示例6: test_florentine_families_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def test_florentine_families_graph(self):
"""Betweenness centrality: Florentine families graph"""
G = nx.florentine_families_graph()
b_answer =\
{'Acciaiuoli': 0.000,
'Albizzi': 0.212,
'Barbadori': 0.093,
'Bischeri': 0.104,
'Castellani': 0.055,
'Ginori': 0.000,
'Guadagni': 0.255,
'Lamberteschi': 0.000,
'Medici': 0.522,
'Pazzi': 0.000,
'Peruzzi': 0.022,
'Ridolfi': 0.114,
'Salviati': 0.143,
'Strozzi': 0.103,
'Tornabuoni': 0.092}
b = nx.betweenness_centrality(G,
weight=None,
normalized=True)
for n in sorted(G):
assert_almost_equal(b[n], b_answer[n], places=3)
示例7: test_disconnected_path_endpoints
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def test_disconnected_path_endpoints(self):
"""Betweenness centrality: disconnected path endpoints"""
G = nx.Graph()
nx.add_path(G, [0, 1, 2])
nx.add_path(G, [3, 4, 5, 6])
b_answer = {0: 2, 1: 3, 2: 2, 3: 3, 4: 5, 5: 5, 6: 3}
b = nx.betweenness_centrality(G,
weight=None,
normalized=False,
endpoints=True)
for n in sorted(G):
assert_almost_equal(b[n], b_answer[n])
# normalized = True case
b = nx.betweenness_centrality(G,
weight=None,
normalized=True,
endpoints=True)
for n in sorted(G):
assert_almost_equal(b[n], b_answer[n] / 21)
示例8: betweenness_centrality
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def betweenness_centrality(adjacency, labels=None):
def _betweeness_centrality(adjacency, labels):
graph = nx.from_numpy_matrix(adjacency)
labeling = nx.betweenness_centrality(graph, normalized=False)
labeling = list(labeling.items())
labeling = sorted(labeling, key=lambda n: n[1], reverse=True)
return np.array([labels[n[0]] for n in labeling])
labels = _labels_default(labels, adjacency)
return tf.py_func(_betweeness_centrality, [adjacency, labels], tf.int32,
stateful=False, name='betweenness_centrality')
示例9: __get_centrality_pdf
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def __get_centrality_pdf(self, skew = False, smooth = False):
"""
produces a probability distribution which is proportional to nodes betweeness centrality scores
the betweeness centrality counts on how many shortest paths a node is
connecting to thos nodes will most likely make them even more central
however it is good for the node operating those operation as this node
itself gets a position in the network which is close to central nodes
this distribution can be skewed and smoothed
"""
self.__logger.info(
"CENTRALITY_PDF: Try to generate a PDF proportional to centrality scores")
pdf = {}
cumsum = 0
for n, score in nx.betweenness_centrality(self.G).items():
pdf[n] = score
cumsum += score
#renoremalize result
pdf = {k:v/cumsum for k, v in pdf.items()}
self.__logger.info(
"CENTRALITY_PDF: Generated pdf")
if skew and smooth:
self.__logger.info(
"CENTRALITY_PDF: Won't skew and smooth distribution ignore both")
smooth = False
skew = False
return self.__manipulate_pdf(pdf, skew, smooth)
示例10: main
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def main(opts):
df = pd.read_csv(opts['biogrid'], sep='\t')
interact_df = df[['Official Symbol Interactor A',
'Official Symbol Interactor B']]
interact_genes = interact_df.dropna().values.tolist()
G = nx.Graph()
G.add_edges_from(map(tuple, interact_genes))
gene_betweeness = nx.betweenness_centrality(G)
gene_degree = G.degree()
result = [[key, gene_betweeness[key], gene_degree[key]]
for key in gene_degree]
result = [['gene', 'gene_betweeness', 'gene_degree']] + result
with open(opts['output'], 'wb') as handle:
csv.writer(handle, delimiter='\t').writerows(result)
示例11: get_center
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def get_center(graph: nx.Graph) -> Hashable:
centralities = nx.betweenness_centrality(graph)
return max(centralities, key=centralities.get)
示例12: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def __init__(self, method='degree', analyzer=NltkNormalizer().split_and_normalize):
self.analyze = analyzer
self.method = method
self.methods_on_digraph = {'hits', 'pagerank', 'katz'}
self._get_scores = {'degree': nx.degree, 'betweenness': nx.betweenness_centrality,
'pagerank': nx.pagerank_scipy, 'hits': self._hits, 'closeness': nx.closeness_centrality,
'katz': nx.katz_centrality}[method]
# Add a new value when a new vocabulary item is seen
self.vocabulary = defaultdict()
self.vocabulary.default_factory = self.vocabulary.__len__
示例13: node_selection_with_1d_wl
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def node_selection_with_1d_wl(G, features, num_channel, num_sample, num_neighbor, stride):
"""construct features for cnn"""
X = np.zeros((num_channel, num_sample, num_neighbor), dtype=np.float32)
node2id = dict([(node, vid) for vid, node in enumerate(G.nodes())])
id2node = dict(zip(node2id.values(), node2id.keys()))
betweenness = nx.betweenness_centrality(G)
sorted_nodes = sorted(betweenness.items(), key=lambda d: d[1], reverse=False)
# obtain normalized neighbors' features for each vertex
i = 0
j = 0
root_list = []
distance_list = []
graph_list = []
while j < num_sample:
if i < len(sorted_nodes):
neighbors_dict = assemble_neighbor(G, sorted_nodes[i][0], num_neighbor, sorted_nodes)
# construct subgraph and sort neighbors with a labeling measurement like degree centrality
sub_g = G.subgraph(neighbors_dict.keys())
root_list.append(sorted_nodes[i][0])
distance_list.append(neighbors_dict)
graph_list.append(sub_g)
else:
# zero receptive field
X[:, j, :] = np.zeros((num_channel, num_neighbor), dtype=np.float32)
i += stride
j += 1
init_labels = dict([(v, features[id].argmax(axis=0)) for v, id in node2id.items()])
graph_labels_list = one_dim_wl(graph_list, init_labels)
# finally relabel based on 1d-wl and distance to root node
for i in range(len(root_list)):
# set root node the first position
graph_labels_list[i][root_list[i]] = 0
sorted_measurement = dict([(v, [measure, distance_list[i][v]]) for v, measure in graph_labels_list[i].items()])
sorted_neighbor = sorted(sorted_measurement.items(), key=lambda d: d[1], reverse=False)[:num_neighbor]
reorder_dict = dict(zip(sorted(sorted_measurement.keys()), range(len(sorted_measurement))))
X[:, i, :] = features[[reorder_dict[v] for v, measure in sorted_neighbor]].T
return X.reshape(num_channel, num_sample * num_neighbor)
示例14: set_node_attributes
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def set_node_attributes(G, name, values):
"""Set node attributes from dictionary of nodes and values
Parameters
----------
G : NetworkX Graph
name : string
Attribute name
values: dict
Dictionary of attribute values keyed by node. If `values` is not a
dictionary, then it is treated as a single attribute value that is then
applied to every node in `G`.
Examples
--------
>>> G = nx.path_graph(3)
>>> bb = nx.betweenness_centrality(G)
>>> nx.set_node_attributes(G, 'betweenness', bb)
>>> G.node[1]['betweenness']
1.0
"""
try:
values.items
except AttributeError:
# Treat `value` as the attribute value for each node.
values = dict(zip(G.nodes(), [values] * len(G)))
for node, value in values.items():
G.node[node][name] = value
示例15: test_K5
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import betweenness_centrality [as 别名]
def test_K5(self):
"""Betweenness centrality: K5"""
G=nx.complete_graph(5)
b=nx.betweenness_centrality(G,
weight=None,
normalized=False)
b_answer={0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}
for n in sorted(G):
assert_almost_equal(b[n],b_answer[n])