Spaces:
No application file
No application file
File size: 1,149 Bytes
480e694 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import pickle
import numpy as np
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
# Load model embeddings
with open("../models/product_embeddings.pkl", "rb") as f:
data = pickle.load(f)
# Load transformer model
model = SentenceTransformer('all-MiniLM-L6-v2')
def recommend_products(user_query, top_n=5):
"""Find similar products based on user search"""
query_embedding = model.encode(user_query).reshape(1, -1)
# Compute similarity scores
similarities = cosine_similarity(query_embedding, data["embeddings"])
top_indices = np.argsort(similarities[0])[-top_n:][::-1] # Get top matches
recommendations = []
for i in top_indices:
recommendations.append({
"search_query": data["search_queries"][i],
"product": data["product_names"][i],
"score": float(similarities[0][i])
})
return recommendations
# Example test
if __name__ == "__main__":
query = "gaming laptop"
results = recommend_products(query)
for r in results:
print(f"🔹 {r['product']} (Score: {r['score']:.2f})")
|