प्रोडक्ट्स के लिए सेमान्टिक सर्च
अब अपने find_n_closest() फंक्शन को काम में लेने का समय है! आप एक टेस्ट क्वेरी पर अपना सेमान्टिक प्रोडक्ट सर्च आज़माएँगे, और आपके द्वारा मॉडल को दिए गए enriched डेटा के आधार पर, सेमान्टिक रूप से सबसे मिलते-जुलते पाँच प्रोडक्ट्स की sorted लिस्ट निकालेंगे.
पिछले अभ्यास में बनाए गए find_n_closest() फंक्शन की झलक याद दिला दें:
def find_n_closest(query_vector, embeddings, n=3):
distances = []
for index, embedding in enumerate(embeddings):
distance = spatial.distance.cosine(query_vector, embedding)
distances.append({"distance": distance, "index": index})
distances_sorted = sorted(distances, key=lambda x: x["distance"])
return distances_sorted[0:n]
आपने पहले जो create_embeddings() फंक्शन बनाया था, वह भी उपलब्ध है. याद रखें, यह कुछ टेक्स्ट लेता है और प्रत्येक टेक्स्ट के लिए एम्बेडिंग्स (embedding — वेक्टर रूप में निरूपण) वाली लिस्ट-की-लिस्ट लौटाता है. आपने पहले जो products डिक्शनरी और product_embeddings बनाए थे, वे भी लोड किए जा चुके हैं.
यह अभ्यास पाठ्यक्रम का हिस्सा है
OpenAI API के साथ Embeddings परिचय
अभ्यास निर्देश
query_textसे क्वेरी वेक्टर बनाएँ.find_n_closest()फंक्शन का उपयोग करके सबसे पास की पाँच दूरियाँ और उनके संबंधित इंडेक्स खोजें.hitsपर लूप चलाएँ औरhitsलिस्ट में हर'index'पर मौजूद प्रोडक्ट निकालें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# Create the query vector from query_text
query_text = "computer"
query_vector = ____[0]
# Find the five closest distances
hits = ____
print(f'Search results for "{query_text}"')
for hit in hits:
# Extract the product at each index in hits
product = products[____]
print(product["title"])