Study/Graph Neural Network

NetworkX Tutorial

Kisung Moon 2021. 3. 29. 10:22

NetworkX는 가장 많이 쓰이는 그래프 패키지 중 하나이다.

1. Setup

!pip install networkx

2. Graph

- NetworkX는 directed와 undirected graph와 같은 다양한 유형의 graph를 저장할 수 있는 여러 클래스를 제공한다. 그리고 multigraph(directed와 undirected 모두)를 만드는 클래스를 제공한다.

* graph type에 관한 정보

# undirected graph G 생성
G = nx.Graph()
print(G.is_directed())


# directed graph H 생성 
H = nx.DiGraph()
print(H.is_directed())

# graph level attribute 추가
G.graph["Name"] = "Bar"
print(G.graph)
False
True
{'Name': 'Bar'}

3. Node

- node(attribute를 가진)는 쉽게 graph에 추가된다.

# feature 0, label0의 attribute를 가진 1개의 node 0 추가
G.add_node(0, feature=0, label=0)

# node 0의 attribute 출력
node_0_attr = G.nodes[0]
print("Node 0 has the attributes {}".format(node_0_attr))
Node 0 has the attributes {'feature': 0, 'label': 0}
# attribute를 가진 node 1, 2 추가
G.add_nodes_from([
  (1, {"feature": 1, "label": 1}),
  (2, {"feature": 2, "label": 2})
])
# 모든 node loop 돌기
# data=True 를 설정하면 node들의 attribute를 리턴한다.
for node in G.nodes(data=True):
  print(node)

# node의 개수 얻기
num_nodes = G.number_of_nodes()
print("G has {} nodes".format(num_nodes))
(0, {'feature': 0, 'label': 0})
(1, {'feature': 1, 'label': 1})
(2, {'feature': 2, 'label': 2})
G has 3 nodes

4. Edge

- node 처럼, edge도 graph에 쉽게 추가된다.

# edge weight가 0.5인 edge(0, 1) 하나 추가
G.add_edge(0, 1, weight=0.5)

# edge (0, 1)의 attribute 얻기
edge_0_1_attr = G.edges[(0, 1)]
print("Edge (0, 1) has the attributes {}".format(edge_0_1_attr))
Edge (0, 1) has the attributes {'weight': 0.5}
# edge weights를 가진 여러 edge 추가
G.add_edges_from([
  (1, 2, {"weight": 0.3}),
  (2, 0, {"weight": 0.1})
])

# 모든 edge loop 돌기
# 여기서 data=True를 입력하지 않으면, edge 들만 리턴된다.
for edge in G.edges():
  print(edge)

# edge의 개수 얻기
num_edges = G.number_of_edges()
print("G has {} edges".format(num_edges))
(0, 1)
(0, 2)
(1, 2)
G has 3 edges

5. Visualization

# Graph 그리기
nx.draw(G, with_labels = True)

6. Node Degree and Neighbor

node_id = 1

# node 1의 degree
print("Node {} has degree {}".format(node_id, G.degree[node_id]))

# node 1의 neighbor 얻기
for neighbor in G.neighbors(node_id):
  print("Node {} has neighbor {}".format(node_id, neighbor))
Node 1 has degree 2
Node 1 has neighbor 0
Node 1 has neighbor 2

7. Other Functionalities

- NeworkX는 또한 다양한 graph를 연구하는 데 유용한 도구들을 제공한다.

num_nodes = 4
# graph와 같은 새로운 path를 생성하고 directed graph로 변경
G = nx.DiGraph(nx.path_graph(num_nodes))
nx.draw(G, with_labels = True)

# PageRank 얻기 얻기
pr = nx.pagerank(G, alpha=0.8)
pr
{0: 0.17857162031103999,
 1: 0.32142837968896,
 2: 0.32142837968896,
 3: 0.17857162031103999}

Reference

CS224W(2021)