[Day21] 그래프 이론 기초 & 그래프 패턴

 

 

중요

NetworkX

방향성이 없는 그래프와 방향성이 있는 그래프 객체 만들기

import networkx as nx
import matplotlib.pyplot as plt
G= nx.Graph()                                   # 방향성이 없는 그래프
DiGraph = nx.DiGraph()                          # 방향성이 있는 그래프

 

 

📌 node 추가 하기

print("###### Add Node to Graph ######")                    
print("# Add node 1")                                      
G.add_node(1)                                               # 정점 1 추가
print("Num of nodes in G : " + str(G.number_of_nodes()))    # 정점의 수 반환
print("Graph : " + str(G.nodes)+ "\n")                      # 정점의 목록 반환

결과:

###### Add Node to Graph ######
# Add node 1
Num of nodes in G : 1
Graph : [1]
  • 그래프에서 node의 추가하는 함수는 add_node()이다.
  • number_of_nodes()는 node의 개수를 반환 해 준다.
  • nodes라는 속성은 현재 Graph에 들어있는 node를 반환해 준다.

 

print("# Add vertex 2 ~ 10")                        # 정점 2 ~ 10 추가
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
print("Num of nodes in G : " + str(G.number_of_nodes()))
print("Graph : " + str(G.nodes) + "\n")

결과:

# Add vertex 2 ~ 10
Num of nodes in G : 10
Graph : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • add_nodes_from함수를 통해서 여러 개의 node를 한번에 추가할 수 있다.

 

 

📌 node 제거 하기

# 노드 제거
G.remove_node(3)
print("Num of nodes in G : " + str(G.number_of_nodes()))
print("Graph : " + str(G.nodes) + "\n")

결과:

Num of nodes in G : 9
Graph : [1, 2, 4, 5, 6, 7, 8, 9, 10]

 

 

📌 edge 추가 하기

#엣지 추가
G.add_edge(1, 4)
G.add_edge(1, 2)
G.add_edge(2, 4)

# 여러개 한번에 추가하기
G.add_edges_from([(2, 5), (5, 6),(1, 5)])

# 결과 확인
print("Num of edges in G : " + str(G.number_of_edges()))
print("Graph : " + str(G.edges) + "\n")

결과:

Num of edges in G : 6
Graph : [(1, 4), (1, 2), (1, 5), (2, 4), (2, 5), (5, 6)]
  • add_edge로 edge를 추가한다.
  • add_edges_from를 통해서 여러 개의 edge를 추가할 수 있다.
  • node와 마찬가지로 number_of_edges()함수와 edges속성으로 edge의 개수와 현재edge들을 확인 할 수 있다.

 

 

📌 edge 제거 하기

#엣지 제거
G.remove_edge(1, 2)

# 결과 확인
print("Num of edges in G : " + str(G.number_of_edges()))
print("Graph : " + str(G.edges) + "\n")

결과:

Num of edges in G : 5
Graph : [(1, 4), (1, 5), (2, 4), (2, 5), (5, 6)]
  • remove_edge()함수를 통해 제거하고 싶은 edge를 제거 할 수 있다.

 

 

📌 여러 정보 확인

# degree
print(G.degree)
>>> [(1, 2), (2, 2), (4, 2), (5, 3), (6, 1), (7, 0), (8, 0), (9, 0), (10, 0)]

#인접
print(G.adj)
>>> {1: {4: {}, 5: {}}, 2: {4: {}, 5: {}}, 4: {1: {}, 2: {}}, 5: {2: {}, 6: {}, 1: {}}, 6: {5: {}}, 7: {}, 8: {}, 9: {}, 10: {}}

#요약
print(nx.info(G))
>>> Name: 
>>> Type: Graph
>>> Number of nodes: 9
>>> Number of edges: 5
>>> Average degree:   1.1111

 

 

📌 그래프 그리기

#그래프 그리기
nx.draw(G, with_labels = True, font_weigth = "bold")

image-20210222223746491

 

 

피어세션

  • (무지) word2vec
  • (찰스) skip...

 

git

  • Pull request 안에서 comment, approve, request change를 review를 실행하여 확인함.
  • 각 기능 및 용도를 실습하였다.

+ Recent posts