import networkx as nx
import numpy as np
np.random.seed(0)
N = 50
G = nx.fast_gnp_random_graph(n=N, p=0.5)
#G = nx.scale_free_graph(N)
G = nx.Graph(G)
##################################
# nx.triangles(G, n)
# node `n`을 포함한 삼각형의 수를 리턴
print("== nx.trianbles(G, n)")
for i, n in enumerate(G):
print(f"Node {n} triangle count: {nx.triangles(G, n)}")
if i>2:
break
print("=="*20)
##################################
# Transitivity는 완성된 삼각형의 수 / 미완성 삼각형(edge2개)
# 전이성(A=>B=>C)가 그래프에 있음을 파악하며, 보통 복잡한 네트워크, small-world에서는 높게 나타남.
print("== nx.transitivity(G)")
print(f"nx.transitivity(G): {nx.transitivity(G):0.4f}")
print("==" * 20)
##################################
# clustering
def custom_clustering(G, target_node):
# node clustering:
# target_node의 nbr들에 의해 발생할 수 있는 triangle과 실제 존재하는 triangle의 비율
triangle_count = nx.triangles(G, target_node)
target_node_nbr_count = len(G[target_node])
possible_triangle_count = (target_node_nbr_count-1)*(target_node_nbr_count)/2
if possible_triangle_count == 0:
return 0
else:
return triangle_count/possible_triangle_count
print("== nx.clustering(G, n)")
for n in G:
# custom_clusgering과 nx.clustering은 동일함.
print(f"nx.clustering(G, n): {nx.clustering(G, n):0.4f}")
break
print("==" * 20)
##################################
# average clustering
# 모든 node clustering coef의 평균.
print(f"nx.average_clustering(G): {nx.average_clustering(G):0.5f}")
avg_clustering = sum([nx.clustering(G, n) for n in G])/len(G)
print(f"avg_clustering : {avg_clustering:0.5f}")
print("=="*20)
== nx.trianbles(G, n)
Node 0 triangle count: 142
Node 1 triangle count: 111
Node 2 triangle count: 178
Node 3 triangle count: 162
========================================
== nx.transitivity(G)
nx.transitivity(G): 0.4951
========================================
== nx.clustering(G, n)
nx.clustering(G, n): 0.4733
========================================
nx.average_clustering(G): 0.49588
avg_clustering : 0.49588
댓글남기기