Tìm các diễn đàn phổ biến nhất theo ngày: II
Làm rất tốt ở bài trước — bạn đã viết mã để tạo danh sách đồ thị chuỗi thời gian. Giờ, bạn sẽ hoàn tất bài đó — tức là bạn sẽ tìm xem mỗi ngày có bao nhiêu diễn đàn đạt điểm phổ biến nhất!
Một việc bạn sẽ làm ở đây là “dictionary comprehension” để lọc một dictionary. Nó rất giống với list comprehension để lọc danh sách, chỉ khác là cú pháp trông như thế này: {key: val for key, val in dict.items() if ...}. Hãy ghi nhớ điều đó!
Bài tập này là một phần của khóa học
Phân tích mạng nâng cao với Python
Hướng dẫn bài tập
- Lấy degree centrality bằng
nx.bipartite.degree_centrality(), vớiG_subvàforum_nodeslàm đối số. - Lọc dictionary để chỉ còn các degree centrality của diễn đàn. Cặp
key: valtrong biểu thức đầu ra phải làn, dc. Lặp quadc.items()và kiểm trancó thuộcforum_nodeshay không. - Xác định (các) diễn đàn phổ biến nhất — tức là có degree centrality cao nhất (
max(forum_dcs.values())) và giá trị DC của nó không bằng 0. - Thêm các giá trị
dccao nhất vàohighest_dcs. - Tạo biểu đồ!
- Dùng list comprehension cho biểu đồ đầu tiên, trong đó bạn lặp qua
most_popular_forums(một danh sách các danh sách) dùngforumslàm biến lặp. Biểu thức đầu ra nên là số lượng diễn đàn phổ biến nhất, tính bằnglen(). - Với biểu đồ thứ hai, dùng
highest_dcsvàplt.plot()để trực quan hóa điểm degree centrality cao nhất.
- Dùng list comprehension cho biểu đồ đầu tiên, trong đó bạn lặp qua
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
# 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()