ค้นหาฟอรัมยอดนิยมรายวัน: ตอนที่ 2
ทำได้ดีมากในแบบฝึกหัดที่แล้ว — ได้เขียนโค้ดสร้างรายการกราฟ time-series เสร็จแล้ว คราวนี้มาทำแบบฝึกหัดนี้ให้สมบูรณ์ด้วยการหาว่ามีกี่ฟอรัมที่ได้คะแนนฟอรัมยอดนิยมสูงสุดในแต่ละวัน!
หนึ่งในสิ่งที่จะทำในแบบฝึกหัดนี้คือการใช้ "dictionary comprehension" เพื่อกรองดิกชันนารี ซึ่งคล้ายกับ list comprehension มาก เพียงแต่ syntax จะมีรูปแบบดังนี้: {key: val for key, val in dict.items() if ...} จำไว้ด้วย!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การวิเคราะห์เครือข่ายระดับกลางใน Python
คำแนะนำการฝึกหัด
- คำนวณ degree centrality โดยใช้
nx.bipartite.degree_centrality()พร้อมส่งG_subและforum_nodesเป็นอาร์กิวเมนต์ - กรองดิกชันนารีให้เหลือเฉพาะ degree centrality ของฟอรัม คู่
key: valในนิพจน์เอาต์พุตควรเป็นn, dcโดยวนซ้ำผ่านdc.items()และตรวจสอบว่าnอยู่ในforum_nodes - ระบุฟอรัมที่ได้รับความนิยมสูงสุด ซึ่งต้องมี degree centrality สูงสุด (
max(forum_dcs.values())) และค่า DC ต้องไม่เป็นศูนย์ - Append ค่า
dcสูงสุดลงในhighest_dcs - สร้างกราฟ!
- ใช้ list comprehension สำหรับกราฟแรก โดยวนซ้ำผ่าน
most_popular_forums(ซึ่งเป็น list ของ list) โดยใช้forumsเป็นตัวแปรวนซ้ำ นิพจน์เอาต์พุตควรเป็น จำนวน ฟอรัมยอดนิยม ซึ่งคำนวณโดยใช้len() - สำหรับกราฟที่สอง ให้ใช้
highest_dcsและplt.plot()เพื่อแสดงผลคะแนน degree centrality สูงสุด
- ใช้ list comprehension สำหรับกราฟแรก โดยวนซ้ำผ่าน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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()