Spaces:
Sleeping
Sleeping
Commit ·
720e732
1
Parent(s): 9166aef
Add plan embeddings and vocabulary files for model artifacts
Browse files- Created `plan_embeddings.npz` containing plan IDs and their corresponding embeddings.
- Added `vocabularies.json` to map interests and categories to their respective indices for model training.
Files changed (8)
123version https://git-lfs.github.com/spec/v1oid sha256:6f9fb299c63c902f291f563e6a789922c72d06546388e7c4a50ac2e3bfb69c6bsize 4393722123version https://git-lfs.github.com/spec/v1oid sha256:d8cabefa432f976a8517dffe4cac50358d071234787993502d1b327b054b129fsize 1470889123version https://git-lfs.github.com/spec/v1oid sha256:151343bc656e0477f089a5900fd19769efab27d3c4867569420d34bd0fe9e8f6size 14681{"interest_to_idx": {"1": 0, "2": 1, "3": 2, "4": 3, "5": 4}, "category_to_idx": {"BBQ Joint": 0, "Baby Store": 1, "Bike Rental": 2, "Breakfast Spot": 3, "Coffee Shop": 4, "Creperie": 5, "Deli": 6, "French Restaurant": 7, "Grilled Meat Restaurant": 8, "Health and Beauty Service": 9, "Herbs and Spices Store": 10, "Hotel": 11, "Peruvian Restaurant": 12, "Platform": 13, "Rail Station": 14, "Seafood Restaurant": 15, "Social Club": 16, "South American Restaurant": 17, "Spanish Restaurant": 18, "Structure": 19, "Tapas Restaurant": 20, "Tram Station": 21}, "idx_to_interest": {"0": "1", "1": "2", "2": "3", "3": "4", "4": "5"}, "idx_to_category": {"0": "BBQ Joint", "1": "Baby Store", "2": "Bike Rental", "3": "Breakfast Spot", "4": "Coffee Shop", "5": "Creperie", "6": "Deli", "7": "French Restaurant", "8": "Grilled Meat Restaurant", "9": "Health and Beauty Service", "10": "Herbs and Spices Store", "11": "Hotel", "12": "Peruvian Restaurant", "13": "Platform", "14": "Rail Station", "15": "Seafood Restaurant", "16": "Social Club", "17": "South American Restaurant", "18": "Spanish Restaurant", "19": "Structure", "20": "Tapas Restaurant", "21": "Tram Station"}}14 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081092 unmodified lines1121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771 unmodified line1791801811821831841851 unmodified line18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725814 unmodified linesExtracts features from plans, places, and user interactionsfor the ML models"""def __init__(self):# These will be populated from actual dataself.interest_to_idx = {} # Maps interest ID to integer indexself.category_to_idx = {} # Maps place category to integer indexself.user_to_idx = {}self.plan_to_idx = {}# Reverse mappingsself.idx_to_interest = {}self.idx_to_category = {}def build_vocabularies(self, plans: List[Dict], places: List[Dict], interests: List[Dict]):"""Build mappings from IDs to indicesCall this during training to create vocabularies"""# Build interest vocabulary from your 'interests' table (not user_interest)for idx, interest in enumerate(interests):interest_id = str(interest['id'])self.interest_to_idx[interest_id] = idxself.idx_to_interest[idx] = interest_id# Build category vocabulary from placesunique_categories = set()for place in places:categories = json.loads(place.get('categories', '[]'))for cat in categories:cat_name = cat.get('name', '')if cat_name:unique_categories.add(cat_name)for idx, category in enumerate(sorted(unique_categories)):self.category_to_idx[category] = idxself.idx_to_category[idx] = categoryprint(f"[INFO] Built vocabularies:")print(f" - {len(self.interest_to_idx)} interests")print(f" - {len(self.category_to_idx)} place categories")return {'n_interests': len(self.interest_to_idx),'n_categories': len(self.category_to_idx)}def extract_plan_features(self,plan: Dict[str, Any],places_data: List[Dict[str, Any]] = None) -> Tuple[torch.Tensor, torch.Tensor]:"""Extract features from a plan for ML modelArgs:plan: Plan data from Supabaseplaces_data: Optional list of places in this planReturns:interest_ids: tensor of shape [max_interests]numerical_features: tensor of shape [8]"""# Extract interest IDsinterest_ids_str = json.loads(plan.get('interestIds', '[]'))interest_indices = []for iid in interest_ids_str:iid_str = str(iid)if iid_str in self.interest_to_idx:interest_indices.append(self.interest_to_idx[iid_str])# Pad to max_interests (e.g., 5)max_interests = 5while len(interest_indices) < max_interests:interest_indices.append(0) # Paddinginterest_indices = interest_indices[:max_interests]interest_tensor = torch.tensor(interest_indices, dtype=torch.long)# Extract numerical featuresrating = float(plan.get('rating', 3.0))min_price = float(plan.get('minPrice', 0))max_price = float(plan.get('maxPrice', 100))min_dist = float(plan.get('minDist', 0))max_dist = float(plan.get('maxDist', 10))# Calculate derived featuresplace_ids = json.loads(plan.get('placeIds', '[]'))n_places = len(place_ids)# Get average place rating if places_data providedavg_place_rating = 3.5 # defaultif places_data:2 unmodified linesratings.append(3.5)if ratings:avg_place_rating = np.mean(ratings)price_range = max_price - min_pricedist_range = max_dist - min_distnumerical_features = torch.tensor([rating / 5.0, # Normalize to 0-1min_price / 1000.0, # Normalizemax_price / 1000.0,min_dist / 10.0,max_dist / 10.0,n_places / 10.0, # Normalizeavg_place_rating / 5.0,price_range / 1000.0], dtype=torch.float32)return interest_tensor, numerical_featuresdef extract_user_interaction_sequence(self,interactions: List[Dict[str, Any]],plan_embeddings: Dict[str, torch.Tensor],max_sequence_length: int = 20) -> torch.Tensor:"""Extract user's interaction history as a sequence"""sequences = []for interaction in interactions[-max_sequence_length:]:plan_id = str(interaction['plan_id'])# Get plan embedding (or use zeros if not found)if plan_id in plan_embeddings:plan_emb = plan_embeddings[plan_id]else:plan_emb = torch.zeros(64) # Default embedding size# Extract interaction featuresinteraction_type = interaction.get('interaction_type', 'view')rating = float(interaction.get('rating', 0)) / 5.0 # Normalizeis_bookmarked = 1.0 if interaction_type == 'bookmark' else 0.0duration = float(interaction.get('duration_seconds', 0)) / 300.0 # Normalize (5 min max)duration = min(duration, 1.0) # Cap at 1.0# Combine plan embedding with interaction featuresinteraction_features = torch.tensor([rating, is_bookmarked, duration])full_features = torch.cat([plan_emb, interaction_features])sequences.append(full_features)# Pad sequence if neededembedding_dim = 64 + 3 # plan_embedding + interaction featureswhile len(sequences) < max_sequence_length:sequences.append(torch.zeros(embedding_dim))# Stack into tensor [seq_len, feature_dim]sequence_tensor = torch.stack(sequences[:max_sequence_length])return sequence_tensordef prepare_training_batch(self,user_ids: List[str],1 unmodified linelabels: List[float],plans_dict: Dict[str, Dict],interactions_dict: Dict[str, List[Dict]],plan_embeddings: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:"""Prepare a batch of training data1 unmodified linebatch_plan_interests = []batch_plan_numerical = []batch_user_sequences = []for user_id, plan_id in zip(user_ids, plan_ids):# Get plan featuresplan = plans_dict.get(plan_id, {})interest_ids, numerical_features = self.extract_plan_features(plan)# Get user sequenceuser_interactions = interactions_dict.get(user_id, [])user_sequence = self.extract_user_interaction_sequence(user_interactions,plan_embeddings)batch_plan_interests.append(interest_ids)batch_plan_numerical.append(numerical_features)batch_user_sequences.append(user_sequence)# Stack into batchesplan_interest_batch = torch.stack(batch_plan_interests)plan_numerical_batch = torch.stack(batch_plan_numerical)user_sequence_batch = torch.stack(batch_user_sequences)labels_batch = torch.tensor(labels, dtype=torch.float32)return plan_interest_batch, plan_numerical_batch, user_sequence_batch, labels_batchdef create_negative_samples(self,user_id: str,positive_plan_ids: List[str],all_plan_ids: List[str],n_negative: int = 5) -> List[str]:"""Create negative samples for training"""unseen_plans = [pid for pid in all_plan_ids if pid not in positive_plan_ids]if len(unseen_plans) > n_negative:negative_samples = np.random.choice(unseen_plans, n_negative, replace=False).tolist()else:negative_samples = unseen_plansreturn negative_samplesdef save_vocabularies(self, path: str):"""Save vocabularies to disk"""import jsonvocab_data = {'interest_to_idx': self.interest_to_idx,'category_to_idx': self.category_to_idx,'idx_to_interest': self.idx_to_interest,'idx_to_category': self.idx_to_category}with open(path, 'w') as f:json.dump(vocab_data, f)print(f"[INFO] Saved vocabularies to {path}")def load_vocabularies(self, path: str):"""Load vocabularies from disk"""import jsonwith open(path, 'r') as f:vocab_data = json.load(f)self.interest_to_idx = vocab_data['interest_to_idx']self.category_to_idx = vocab_data['category_to_idx']self.idx_to_interest = {int(k): v for k, v in vocab_data['idx_to_interest'].items()}self.idx_to_category = {int(k): v for k, v in vocab_data['idx_to_category'].items()}print(f"[INFO] Loaded vocabularies from {path}")print(f" - {len(self.interest_to_idx)} interests")print(f" - {len(self.category_to_idx)} categories")14 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371382 unmodified lines1411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232241 unmodified line2262272282292302312321 unmodified line23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631714 unmodified linesExtracts features from plans, places, and user interactionsfor the ML models"""def __init__(self):# These will be populated from actual dataself.interest_to_idx = {} # Maps interest ID to integer indexself.category_to_idx = {} # Maps place category to integer indexself.user_to_idx = {}self.plan_to_idx = {}# Reverse mappingsself.idx_to_interest = {}self.idx_to_category = {}def build_vocabularies(self, plans: List[Dict], places: List[Dict], interests: List[Dict]):"""Build mappings from IDs to indicesCall this during training to create vocabularies"""# Build interest vocabulary from your 'interests' table (not user_interest)for idx, interest in enumerate(interests):interest_id = str(interest["id"])self.interest_to_idx[interest_id] = idxself.idx_to_interest[idx] = interest_id# Build category vocabulary from placesunique_categories = set()for place in places:raw_cats = place.get("categories", "[]")# ✅ Handle both string and list formats safelyif isinstance(raw_cats, str):categories = json.loads(raw_cats)elif isinstance(raw_cats, list):categories = raw_catselse:categories = []for cat in categories:cat_name = cat.get("name", "")if cat_name:unique_categories.add(cat_name)for idx, category in enumerate(sorted(unique_categories)):self.category_to_idx[category] = idxself.idx_to_category[idx] = categoryprint(f"[INFO] Built vocabularies:")print(f" - {len(self.interest_to_idx)} interests")print(f" - {len(self.category_to_idx)} place categories")return {"n_interests": len(self.interest_to_idx),"n_categories": len(self.category_to_idx),}def extract_plan_features(self, plan: Dict[str, Any], places_data: List[Dict[str, Any]] = None) -> Tuple[torch.Tensor, torch.Tensor]:"""Extract features from a plan for ML modelArgs:plan: Plan data from Supabaseplaces_data: Optional list of places in this planReturns:interest_ids: tensor of shape [max_interests]numerical_features: tensor of shape [8]"""# Extract interest IDs (support both JSON string and already-parsed list)raw_interest_ids = plan.get("interestIds", [])if isinstance(raw_interest_ids, str):try:interest_ids = json.loads(raw_interest_ids)except Exception:interest_ids = []elif isinstance(raw_interest_ids, list):interest_ids = raw_interest_idselse:interest_ids = []interest_indices = []for iid in interest_ids:iid_str = str(iid)if iid_str in self.interest_to_idx:interest_indices.append(self.interest_to_idx[iid_str])# Pad to max_interests (e.g., 5)max_interests = 5while len(interest_indices) < max_interests:interest_indices.append(0) # Paddinginterest_indices = interest_indices[:max_interests]interest_tensor = torch.tensor(interest_indices, dtype=torch.long)# Extract numerical featuresrating = float(plan.get("rating", 3.0))min_price = float(plan.get("minPrice", 0))max_price = float(plan.get("maxPrice", 100))min_dist = float(plan.get("minDist", 0))max_dist = float(plan.get("maxDist", 10))# Calculate derived features (support JSON string or list for placeIds)raw_place_ids = plan.get("placeIds", [])if isinstance(raw_place_ids, str):try:place_ids = json.loads(raw_place_ids)except Exception:place_ids = []elif isinstance(raw_place_ids, list):place_ids = raw_place_idselse:place_ids = []n_places = len(place_ids)# Get average place rating if places_data providedavg_place_rating = 3.5 # defaultif places_data:2 unmodified linesratings.append(3.5)if ratings:avg_place_rating = np.mean(ratings)price_range = max_price - min_pricedist_range = max_dist - min_distnumerical_features = torch.tensor([rating / 5.0, # Normalize to 0-1min_price / 1000.0, # Normalizemax_price / 1000.0,min_dist / 10.0,max_dist / 10.0,n_places / 10.0, # Normalizeavg_place_rating / 5.0,price_range / 1000.0,],dtype=torch.float32,)return interest_tensor, numerical_featuresdef extract_user_interaction_sequence(self,interactions: List[Dict[str, Any]],plan_embeddings: Dict[str, torch.Tensor],max_sequence_length: int = 20,) -> torch.Tensor:"""Extract user's interaction history as a sequence"""sequences = []for interaction in interactions[-max_sequence_length:]:plan_id = str(interaction["plan_id"])# Get plan embedding (or use zeros if not found)if plan_id in plan_embeddings:plan_emb = plan_embeddings[plan_id]else:plan_emb = torch.zeros(64) # Default embedding size# Extract interaction featuresinteraction_type = interaction.get("interaction_type", "view")# Defensive: rating may be None or non-numericraw_rating = interaction.get("rating", 0)try:if raw_rating is None:raw_rating = 0.0rating = float(raw_rating) / 5.0 # Normalizeexcept Exception:rating = 0.0is_bookmarked = 1.0 if interaction_type == "bookmark" else 0.0# Defensive: duration_seconds may be None or non-numericraw_duration = interaction.get("duration_seconds", 0)try:if raw_duration is None:raw_duration = 0.0duration = float(raw_duration) / 300.0except Exception:duration = 0.0# Normalize and cap (5 min max)duration = min(duration, 1.0)# Combine plan embedding with interaction featuresinteraction_features = torch.tensor([rating, is_bookmarked, duration])full_features = torch.cat([plan_emb, interaction_features])sequences.append(full_features)# Pad sequence if neededembedding_dim = 64 + 3 # plan_embedding + interaction featureswhile len(sequences) < max_sequence_length:sequences.append(torch.zeros(embedding_dim))# Stack into tensor [seq_len, feature_dim]sequence_tensor = torch.stack(sequences[:max_sequence_length])return sequence_tensordef prepare_training_batch(self,user_ids: List[str],1 unmodified linelabels: List[float],plans_dict: Dict[str, Dict],interactions_dict: Dict[str, List[Dict]],plan_embeddings: Dict[str, torch.Tensor],) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:"""Prepare a batch of training data1 unmodified linebatch_plan_interests = []batch_plan_numerical = []batch_user_sequences = []for user_id, plan_id in zip(user_ids, plan_ids):# Get plan featuresplan = plans_dict.get(plan_id, {})interest_ids, numerical_features = self.extract_plan_features(plan)# Get user sequenceuser_interactions = interactions_dict.get(user_id, [])user_sequence = self.extract_user_interaction_sequence(user_interactions, plan_embeddings)batch_plan_interests.append(interest_ids)batch_plan_numerical.append(numerical_features)batch_user_sequences.append(user_sequence)# Stack into batchesplan_interest_batch = torch.stack(batch_plan_interests)plan_numerical_batch = torch.stack(batch_plan_numerical)user_sequence_batch = torch.stack(batch_user_sequences)labels_batch = torch.tensor(labels, dtype=torch.float32)return (plan_interest_batch,plan_numerical_batch,user_sequence_batch,labels_batch,)def create_negative_samples(self,user_id: str,positive_plan_ids: List[str],all_plan_ids: List[str],n_negative: int = 5,) -> List[str]:"""Create negative samples for training"""unseen_plans = [pid for pid in all_plan_ids if pid not in positive_plan_ids]if len(unseen_plans) > n_negative:negative_samples = np.random.choice(unseen_plans, n_negative, replace=False).tolist()else:negative_samples = unseen_plansreturn negative_samplesdef save_vocabularies(self, path: str):"""Save vocabularies to disk"""import jsonvocab_data = {"interest_to_idx": self.interest_to_idx,"category_to_idx": self.category_to_idx,"idx_to_interest": self.idx_to_interest,"idx_to_category": self.idx_to_category,}with open(path, "w") as f:json.dump(vocab_data, f)print(f"[INFO] Saved vocabularies to {path}")def load_vocabularies(self, path: str):"""Load vocabularies from disk"""import jsonwith open(path, "r") as f:vocab_data = json.load(f)self.interest_to_idx = vocab_data["interest_to_idx"]self.category_to_idx = vocab_data["category_to_idx"]self.idx_to_interest = {int(k): v for k, v in vocab_data["idx_to_interest"].items()}self.idx_to_category = {int(k): v for k, v in vocab_data["idx_to_category"].items()}print(f"[INFO] Loaded vocabularies from {path}")print(f" - {len(self.interest_to_idx)} interests")print(f" - {len(self.category_to_idx)} categories")
256 unmodified lines257258259260261262263264265266267268269270271272273274275276277278279280281282256 unmodified linesprint(f"[INFO] Computing embeddings for {len(plans_to_embed)} plans")# Batch process plansfor plan in plans_to_embed:try:interest_ids, numerical_features = (self.feature_extractor.extract_plan_features(plan))interest_batch = interest_ids.unsqueeze(0).to(self.device)numerical_batch = numerical_features.unsqueeze(0).to(self.device)with torch.no_grad():plan_embedding = self.ml_model.encode_plan(interest_batch, numerical_batch)plan_id = str(plan["id"])self.plan_embeddings[plan_id] = plan_embedding.squeeze(0).cpu()except Exception as e:print(f"[WARN] Failed to embed plan {plan.get('id')}: {e}")def _fetch_all_plans(self) -> List[Dict]:"""Fetch all plans from Supabase"""256 unmodified lines257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293256 unmodified linesprint(f"[INFO] Computing embeddings for {len(plans_to_embed)} plans")# Batch process plans. When embedding single examples, BatchNorm layers# can warn/error if the model is in train mode and batch size == 1.# Temporarily set model to eval() while computing embeddings to avoid# "Expected more than 1 value per channel" warnings.was_training = self.ml_model.trainingtry:self.ml_model.eval()for plan in plans_to_embed:try:interest_ids, numerical_features = (self.feature_extractor.extract_plan_features(plan))interest_batch = interest_ids.unsqueeze(0).to(self.device)numerical_batch = numerical_features.unsqueeze(0).to(self.device)with torch.no_grad():plan_embedding = self.ml_model.encode_plan(interest_batch, numerical_batch)plan_id = str(plan["id"])self.plan_embeddings[plan_id] = plan_embedding.squeeze(0).cpu()except Exception as e:print(f"[WARN] Failed to embed plan {plan.get('id')}: {e}")finally:# restore previous modeif was_training:self.ml_model.train()def _fetch_all_plans(self) -> List[Dict]:"""Fetch all plans from Supabase"""
94 unmodified lines959697989910010194 unmodified lines# Learning rate schedulerself.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, mode="min", factor=0.5, patience=3, verbose=True)# Track metrics94 unmodified lines959697989910010194 unmodified lines# Learning rate schedulerself.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, mode="min", factor=0.5, patience=3)# Track metrics
94 unmodified lines959697989910010194 unmodified lines# Learning rate schedulerself.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, mode="min", factor=0.5, patience=3, verbose=True)# Track metrics94 unmodified lines959697989910010194 unmodified lines# Learning rate schedulerself.scheduler = optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, mode="min", factor=0.5, patience=3)# Track metrics
model/artifacts/best_model.pthAdded+3
model/artifacts/neural_model.pthAdded+3
model/artifacts/plan_embeddings.npzAdded+3
model/artifacts/vocabularies.jsonAdded+1
model/feature_extractor.py+153-94
model/recommender.py+27-16
model/trainer.py+1-1
train.py+1-1