import networkx as nx
import numpy as np
np.random.seed(0)
N = 100
p = 0.6
G = nx.fast_gnp_random_graph(N, p, seed=0)
def np_normalize_dict(input_dict):
"""
input_dict: {node_name: centrality_float}에서
value를 normalize하여 리턴.
"""
vs = np.array(list(input_dict.values()))
vs /= np.linalg.norm(vs)
return {k: v for k, v in zip(input_dict.keys(), vs)}
def custom_subgraph_centrality(inputG):
"""
- node subgraph_centrality는 node `n`으로부터 다시 node `n`까지 도달하는 closed walk들에 대해서
length의 역수를 weight로 주고 그 walk들을 합한 것을 말함.
- 따라서, adjancency matrix을 dot product로 곱해가면서 diagonal을 계산해서 합치면 됨.
- 단, np.matrix의 경우 **2로 해도 알아서 dot product를 해주지만, np.array의 경우는 그렇지 않음.
"""
def np_arr_power(input_np_arr, n=2):
# input_np_arr 의 power
R = input_np_arr.copy()
for i in range(0, n):
R = np.dot(R, input_np_arr)
return R
########################
M = nx.to_numpy_array(inputG)
R = M.copy()
for i in range(2, 5):
#print(f"== {i}")
R +=np_arr_power(M, i)/i
return {k: v for k, v in zip(inputG, np.diagonal(R))}
#=============================================
custom_subgraph_cent = np_normalize_dict(
custom_subgraph_centrality(G)
)
nx_subgraph_cent = np_normalize_dict(
nx.subgraph_centrality(G)
)
for i, n in enumerate(G):
print(
f"Node: {n:2d}, nx_subgraph_cent: {nx_subgraph_cent[n]:.5f}, custom_subgraph_cent: {custom_subgraph_cent[n]:.5f}"
)
if i>5:
break
Node: 0, nx_subgraph_cent: 0.09892, custom_subgraph_cent: 0.09889
Node: 1, nx_subgraph_cent: 0.10808, custom_subgraph_cent: 0.10810
Node: 2, nx_subgraph_cent: 0.10096, custom_subgraph_cent: 0.10092
Node: 3, nx_subgraph_cent: 0.10192, custom_subgraph_cent: 0.10192
Node: 4, nx_subgraph_cent: 0.11996, custom_subgraph_cent: 0.11995
Node: 5, nx_subgraph_cent: 0.09283, custom_subgraph_cent: 0.09281
Node: 6, nx_subgraph_cent: 0.09199, custom_subgraph_cent: 0.09199
댓글남기기