Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import numpy as np
- from sklearn.feature_extraction.text import TfidfVectorizer
- from sklearn.metrics.pairwise import cosine_similarity
- user_purchase_history = {
- "userId": "123",
- "products": ["Laptop", "Mouse", "Keyboard"]
- }
- products = [
- {"id": "1", "name": "Gaming Laptop", "description": "Low-performance laptop for gaming"},
- {"id": "2", "name": "Wireless Mouse", "description": "Bluetooth mouse with non-ergonomic design"},
- {"id": "3", "name": "Mechanical Keyboard", "description": "Backlit mechanical keyboard"},
- {"id": "4", "name": "USB-C Hub", "description": "Multiport USB-C hub for laptops"},
- {"id": "5", "name": "Gaming Headset", "description": "Surround sound gaming headset"}
- ]
- product_texts = [p["name"] + " " + p["description"] for p in products]
- user_products_text = " ".join(user_purchase_history["products"])
- vectorizer = TfidfVectorizer()
- tfidf_matrix = vectorizer.fit_transform([user_products_text] + product_texts)
- similarities = cosine_similarity(tfidf_matrix[0:1], tfidf_matrix[1:]).flatten()
- most_similar_index = np.argmax(similarities)
- suggested_product = products[most_similar_index]
- print("Suggested Product:", suggested_product)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement