แนะนำผู้ร่วมแก้ไขที่ยังไม่เคยทำงานร่วมกัน
ขั้นตอนสุดท้าย เราจะนำแนวคิด open triangles มาใช้แนะนำผู้ใช้ GitHub ที่ควรจะร่วมมือกัน!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การวิเคราะห์เครือข่ายเบื้องต้นด้วย Python
คำแนะนำการฝึกหัด
- รวบรวมรายชื่อผู้ใช้ GitHub ที่ควรได้รับการแนะนำให้ร่วมมือกัน โดยดำเนินการดังนี้:
- ใน
forloop แรก ให้วนซ้ำผ่านโหนดทั้งหมดในGพร้อม metadata (โดยระบุdata=True) - ใน
forloop ที่สอง ให้วนซ้ำผ่านชุดสามเหลี่ยมที่เป็นไปได้ทั้งหมด ซึ่งระบุได้โดยใช้ฟังก์ชันcombinations()กำหนดsizeเป็น2 - หาก
n1และn2ไม่มี edge เชื่อมกัน แสดงว่าควรแนะนำให้ทั้งสองโหนด (ผู้ใช้) ร่วมมือกัน ให้เพิ่มค่าในดิกชันนารีrecommendedที่คีย์(n1), (n2)โดยตรวจสอบว่าn1และn2มี edge หรือไม่ได้ด้วยเมธอด.has_edge()
- ใน
- ใช้ list comprehension เพื่อระบุคู่ผู้ใช้ 10 อันดับแรกที่ควรได้รับการแนะนำให้ร่วมมือกัน กำหนดให้ iterable คือคู่ key-value ของดิกชันนารี
recommended(เข้าถึงได้ด้วยเมธอด.items()) และเงื่อนไขจะเป็นจริงเมื่อcountมากกว่า 10 อันดับแรกในall_countsโดยall_countsเรียงลำดับจากน้อยไปมาก จึงเข้าถึง 10 อันดับแรกได้ด้วยall_counts[-10]
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import necessary modules
from itertools import combinations
from collections import defaultdict
# Initialize the defaultdict: recommended
recommended = defaultdict(int)
# Iterate over all the nodes in G
for n, d in ____:
# Iterate over all possible triangle relationship combinations
for n1, n2 in ____(list(G.neighbors(n)), ____):
# Check whether n1 and n2 do not have an edge
if not G.has_edge(____, ____):
# Increment recommended
____[(____, ____)] += 1
# Identify the top 10 pairs of users
all_counts = sorted(recommended.values())
top10_pairs = [pair for pair, count in ____ if ____ > ____]
print(top10_pairs)