จำแนกความรู้สึกของรีวิว
เมื่อคำนวณ embedding เรียบร้อยแล้ว ขั้นตอนต่อไปคือการคำนวณ cosine distance และดึงค่า label ที่ใกล้เคียงที่สุดออกมา
จะทำสิ่งนี้โดยนิยามฟังก์ชันชื่อ find_closest() ซึ่งใช้เปรียบเทียบ embedding ระหว่างเวกเตอร์หนึ่งกับเวกเตอร์อื่น ๆ หลายตัว แล้วคืนค่าระยะทางที่ใกล้ที่สุดพร้อม index ของมัน จากนั้นจะวนลูปผ่านรีวิวต่าง ๆ และใช้ find_closest() เพื่อหาระยะทางที่ใกล้ที่สุดของแต่ละรีวิว แล้วดึง label ที่จำแนกได้โดยใช้ index
ออบเจ็กต์ class_embeddings และ review_embeddings ที่สร้างไว้ในแบบฝึกหัดก่อนหน้า รวมถึง reviews และ sentiments พร้อมให้ใช้งานแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การสร้าง Embeddings ด้วย OpenAI API
คำแนะนำการฝึกหัด
- นิยามฟังก์ชันชื่อ
find_closest()ที่คืนค่าระยะทางและ index ของ embedding ที่ใกล้เคียงquery_vectorมากที่สุด - ใช้
find_closest()เพื่อหาระยะทางที่ใกล้ที่สุดระหว่าง embedding ของแต่ละรีวิวกับclass_embeddings - ใช้
'index'ของclosestเพื่อ subsetsentimentsและดึงค่า'label'ออกมา
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define a function to return the minimum distance and its index
def find_closest(query_vector, embeddings):
distances = []
for index, embedding in enumerate(embeddings):
dist = distance.cosine(____, ____)
distances.append({"distance": dist, "index": index})
return ____(distances, key=lambda x: x["distance"])
for index, review in enumerate(reviews):
# Find the closest distance and its index using find_closest()
closest = ____(review_embeddings[____], ____)
# Subset sentiments using the index from closest
label = ____
print(f'"{review}" was classified as {label}')