計算投影
現在輪到你實作:把二分圖投影到其中一個分割上的節點。這能幫助你熟悉在二分圖與其單分圖投影之間轉換。回想影片中的說明,「投影」是指把圖投影到某個分割上時,該分割內節點的連結情形,是以它們與另一個分割中節點的連結為條件所得到的。更具體地說,可以把它想成「根據共同購買行為來衡量顧客之間的連結」。
先給一個關於 list comprehension 的提示。list comprehension 可以包含條件,如果你想依節點型別過濾圖,可以這樣寫:[n for n, d in G.nodes(data=True) if d['key'] == 'some_value']。
本練習屬於課程
Python 網路分析進階
練習說明
- 使用 list comprehension 準備
people節點清單。若G中某節點n的'bipartite'關鍵字等於'people',就把該節點納入清單。 - 透過迭代 G 的節點並「包含」中繼資料來準備
clubs節點清單。此處要注意,你需要檢查中繼資料字典d的'bipartite'關鍵字是否等於'clubs'。注意:這只是建立節點清單的另一種方式。你不一定要迭代中繼資料——也可以用建立people節點清單的相同做法,改為檢查'clubs'。我們在這裡要求你採用另一種方式,是為了讓你兩種方法都能練習到。 - 使用
nx.bipartite.projected_graph()計算 people 與 clubs 的投影。將結果分別儲存為peopleG與clubsG。- 這個函式需要兩個引數:圖
G與節點清單。
- 這個函式需要兩個引數:圖
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Prepare the nodelists needed for computing projections: people, clubs
# This exercise shows you two ways to do it, one with `data=True` and one without.
people = [n for n in G.nodes() if G.nodes[____]['____'] == '____']
clubs = [n for n, d in G.nodes(data=True) if d['____'] == '____']
# Compute the people and clubs projections: peopleG, clubsG
peopleG = ____
clubsG = ____