辨識三角關係
現在你已經學會 clique(完全子圖),是時候運用所知在網路中找出結構了。首先要鎖定的是三角形。我們會關注三角形,因為它是最簡單的複雜 clique。來寫幾個函式吧;這些練習會帶你走過網路演算法背後的基本邏輯。
在這個 Twitter 網路中,每個節點都有一個 'occupation' 標籤,代表該 Twitter 使用者的工作職業,分為 celebrity、politician 和 scientist。尋找三角形的演算法有一個潛在用途:判斷職業相似的使用者是否更可能彼此形成同一個 clique。
本練習屬於課程
Python 網路分析入門
練習說明
- 從
itertools匯入combinations。 - 撰寫函式
is_in_triangle(),帶有兩個參數G與n,用來檢查指定節點是否位於三角關係中。combinations(iterable, n)會從iterable產生大小為n的組合。在這裡很實用,因為你需要從list(G.neighbors(n))取得大小為2的組合。- 若要檢查兩個節點之間是否存在邊,使用
.has_edge(node1, node2)方法。若存在邊,表示該節點位於三角關係中,應回傳True。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
____
# Define is_in_triangle()
def is_in_triangle(G, n):
"""
Checks whether a node `n` in graph `G` is in a triangle relationship or not.
Returns a boolean.
"""
in_triangle = False
# Iterate over all possible triangle relationship combinations
for n1, n2 in ____:
# Check if an edge exists between n1 and n2
if ____:
in_triangle = ____
break
return in_triangle