Instructions to use clfegg/content_based_recommend with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use clfegg/content_based_recommend with Transformers:
# Load model directly from transformers import ContentBasedRecommender model = ContentBasedRecommender.from_pretrained("clfegg/content_based_recommend", dtype="auto") - Notebooks
- Google Colab
- Kaggle
| from typing import Dict, List, Any | |
| import pickle | |
| import os | |
| import __main__ | |
| import numpy as np | |
| import pandas as pd | |
| class ContentBasedRecommender: | |
| def __init__(self, train_data): | |
| self.train_data = train_data | |
| def predict(self, user_id, k=10): | |
| user_books = set(self.train_data[self.train_data['user_id'] == user_id]['book_id']) | |
| similar_books = set().union(*(self.train_data[self.train_data['book_id'] == book_id]['similar_books'].iloc[0] for book_id in user_books)) | |
| recommended_books = list(similar_books - user_books) | |
| return np.random.choice(recommended_books, size=min(k, len(recommended_books)), replace=False).tolist() | |
| __main__.ContentBasedRecommender = ContentBasedRecommender | |
| class EndpointHandler: | |
| def __init__(self, path=""): | |
| model_path = os.path.join(path, "model.pkl") | |
| with open(model_path, 'rb') as f: | |
| self.model = pickle.load(f) | |
| def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]: | |
| # Extract the 'inputs' from the data | |
| inputs = data.get('inputs', {}) | |
| # If inputs is a string (for single user_id input), convert it to a dict | |
| if isinstance(inputs, str): | |
| inputs = {'user_id': inputs} | |
| user_id = inputs.get('user_id') | |
| k = inputs.get('k', 10) # Default to 10 if not provided | |
| if user_id is None: | |
| return [{"error": "user_id is required"}] | |
| try: | |
| recommended_books = self.model.predict(user_id, k=k) | |
| return [{"recommended_books": recommended_books}] | |
| except Exception as e: | |
| return [{"error": str(e)}] | |
| def load_model(model_path): | |
| handler = EndpointHandler(model_path) | |
| return handler |