ฟังก์ชันแนะนำภาพยนตร์
ในแบบฝึกหัดนี้ เราจะสร้างฟังก์ชันแนะนำภาพยนตร์ชื่อ get_recommendations() ตามที่ได้กล่าวถึงในบทเรียนและแบบฝึกหัดก่อนหน้า ฟังก์ชันนี้รับพารามิเตอร์ได้แก่ ชื่อภาพยนตร์ เมทริกซ์ cosine similarity และ mapping ระหว่างชื่อกับ index ของภาพยนตร์ จากนั้นส่งออกรายการชื่อภาพยนตร์ 10 เรื่องที่คล้ายกับเรื่องต้นฉบับมากที่สุด (ไม่รวมเรื่องต้นฉบับ)
ชุดข้อมูล metadata ที่ประกอบด้วยชื่อและเนื้อเรื่องย่อของภาพยนตร์ได้ถูกเตรียมไว้ให้แล้ว โดยแสดงแถวแรกของชุดข้อมูลไว้ที่คอนโซล
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Feature Engineering for NLP in Python
คำแนะนำการฝึกหัด
- ดึง index ของภาพยนตร์ที่ตรงกับชื่อที่กำหนด โดยใช้คีย์
titleของindices - ดึงภาพยนตร์ที่คล้ายกันมากที่สุด 10 เรื่องจาก
sim_scoresแล้วบันทึกกลับไปที่sim_scores
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Generate mapping between titles and index
indices = pd.Series(metadata.index, index=metadata['title']).drop_duplicates()
def get_recommendations(title, cosine_sim, indices):
# Get index of movie that matches title
idx = ____[____]
# Sort the movies based on the similarity scores
sim_scores = list(enumerate(cosine_sim[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
# Get the scores for 10 most similar movies
sim_scores = sim_scores[____]
# Get the movie indices
movie_indices = [i[0] for i in sim_scores]
# Return the top 10 most similar movies
return metadata['title'].iloc[movie_indices]