始める無料で始める

日ごとの最も人気のあるフォーラムを見つける:II

前の演習お疲れさまでした。時系列のグラフリストを作成するコードを書きましたね。ここではその続きとして、日ごとに「最も人気のあるフォーラム」のスコアを獲得したフォーラムがいくつあったかを求めていきます!

ここで行うことの1つは、辞書をフィルタリングするための「辞書内包表記」です。これはリストをフィルタリングするリスト内包表記にとてもよく似ていますが、構文は {key: val for key, val in dict.items() if ...} のようになります。覚えておいてください!

この演習はコースの一部です

Python 中級ネットワーク解析

コースを見る

演習の手順

  • nx.bipartite.degree_centrality() を使い、引数に G_subforum_nodes を渡して次数中心性を計算します。
  • 辞書をフィルタリングして、フォーラムの次数中心性だけが残るようにします。出力の key: valn, dc、反復は dc.items() に対して行い、nforum_nodes に含まれているかを確認します。
  • 最も人気のあるフォーラムを特定します。これは次数中心性が最大(max(forum_dcs.values()))で、かつ DC の値が 0 でないものです。
  • 最大の dc 値を highest_dcs に追加します。
  • プロットを作成します!
    • 1つ目のプロットでは、most_popular_forums(リストのリスト)を forums を反復変数として走査するリスト内包表記を使います。出力式は len() で計算した「最も人気のあるフォーラムの数」です。
    • 2つ目のプロットでは、highest_dcsplt.plot() を使って、トップの次数中心性スコアを可視化します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Import necessary modules
from datetime import timedelta
import networkx as nx
import matplotlib.pyplot as plt

most_popular_forums = []
highest_dcs = []
curr_day = dayone 
td = timedelta(days=1)  

while curr_day < lastday:  
    if curr_day.day == 1:  
        print(curr_day)  
    G_sub = nx.Graph()
    G_sub.add_nodes_from(G.nodes(data=True))   
    G_sub.add_edges_from([(u, v, d) for u, v, d in G.edges(data=True) if d['date'] >= curr_day and d['date'] < curr_day + td])
    
    # Get the degree centrality 
    dc = ____
    # Filter the dictionary such that there's only forum degree centralities
    forum_dcs = {____:____ for ____, ____ in ____ if n in ____}
    # Identify the most popular forum(s) 
    most_popular_forum = [n for n, dc in ____ if dc == ____(____) and dc != 0] 
    most_popular_forums.append(most_popular_forum) 
    # Store the highest dc values in highest_dcs
    highest_dcs.append(max(____))
    
    curr_day += td  
    
plt.figure(1) 
plt.plot([len(____) for ____ in ____], color='blue', label='Forums')
plt.ylabel('Number of Most Popular Forums')
plt.show()

plt.figure(2)
plt.plot(____, color='orange', label='DC Score')
plt.ylabel('Top Degree Centrality Score')
plt.show()
コードを編集して実行