เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

ค้นหาฟอรัมยอดนิยมรายวัน: ตอนที่ 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 สูงสุด

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# 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()
แก้ไขและรันโค้ด