Spaces:
Sleeping
Sleeping
Download model/neural_models.py from marcolouis/romio_explore_ai_api: direct link, hf CLI and curl.
- Browser
- Download file 9.19 kB
-
https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/model/neural_models.py
- Command line
-
hf download hf://spaces/marcolouis/romio_explore_ai_api/model/neural_models.py
-
curl -L -o neural_models.py https://huggingface.co/spaces/marcolouis/romio_explore_ai_api/resolve/main/model/neural_models.py
9.19 kB
| """ | |
| Neural Network Models for Plan Recommendation | |
| These models learn patterns from data using real machine learning. | |
| """ | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from typing import Dict, List, Tuple | |
| import numpy as np | |
| class PlanEmbeddingNetwork(nn.Module): | |
| """ | |
| Model #1: Learns a vector representation (embedding) for each plan. | |
| The embedding captures: | |
| - The plan's interests | |
| - Numerical features (price, rating, distance...) | |
| - Patterns learned during training | |
| These embeddings help the system compare plans and understand similarity. | |
| """ | |
| def __init__( | |
| self, | |
| n_interests: int = 20, | |
| n_categories: int = 50, | |
| embedding_dim: int = 64, | |
| hidden_dim: int = 128, | |
| ): | |
| super().__init__() | |
| # Embedding lookup for interests | |
| self.interest_embedding = nn.Embedding(n_interests, embedding_dim) | |
| # Embedding lookup for place categories (currently not used directly) | |
| self.category_embedding = nn.Embedding(n_categories, embedding_dim) | |
| # Neural network layers combine interest embeddings + numerical features | |
| self.fc1 = nn.Linear(embedding_dim + 8, hidden_dim) # +8 = numerical features | |
| self.bn1 = nn.BatchNorm1d(hidden_dim) | |
| self.dropout1 = nn.Dropout(0.3) | |
| self.fc2 = nn.Linear(hidden_dim, embedding_dim) | |
| self.bn2 = nn.BatchNorm1d(embedding_dim) | |
| # Final projection to get the plan embedding | |
| self.output = nn.Linear(embedding_dim, embedding_dim) | |
| self._init_weights() | |
| def _init_weights(self): | |
| """Initialize weights for stable training.""" | |
| for m in self.modules(): | |
| if isinstance(m, nn.Linear): | |
| nn.init.xavier_uniform_(m.weight) | |
| if m.bias is not None: | |
| nn.init.zeros_(m.bias) | |
| elif isinstance(m, nn.Embedding): | |
| nn.init.normal_(m.weight, mean=0, std=0.1) | |
| def forward(self, interest_ids, numerical_features): | |
| """ | |
| Build the plan embedding. | |
| Args: | |
| interest_ids: [batch, max_interests] | |
| numerical_features: [batch, 8] | |
| Returns: | |
| Tensor [batch, embedding_dim] representing each plan | |
| """ | |
| # Convert interest IDs β embeddings | |
| interest_embeds = self.interest_embedding(interest_ids) | |
| # Average multiple interest embeddings β one vector | |
| interest_vector = interest_embeds.mean(dim=1) | |
| # Combine interest info + numerical features | |
| x = torch.cat([interest_vector, numerical_features], dim=1) | |
| # Pass through neural layers | |
| x = self.fc1(x) | |
| x = self.bn1(x) | |
| x = F.relu(x) | |
| x = self.dropout1(x) | |
| x = self.fc2(x) | |
| x = self.bn2(x) | |
| x = F.relu(x) | |
| # Final embedding | |
| plan_embedding = self.output(x) | |
| return plan_embedding | |
| class UserPreferenceNetwork(nn.Module): | |
| """ | |
| Model #2: Learns a representation of a user's preferences. | |
| This model processes: | |
| - User interaction history (sequence) | |
| - Plan embeddings + interaction metadata | |
| LSTM learns patterns over time, | |
| Attention identifies important interactions. | |
| """ | |
| def __init__(self, embedding_dim: int = 64, lstm_hidden: int = 128, attention_heads: int = 4): | |
| super().__init__() | |
| # LSTM processes sequence of interactions | |
| self.lstm = nn.LSTM( | |
| input_size=embedding_dim + 3, # plan embedding + [rating, bookmark, duration] | |
| hidden_size=lstm_hidden, | |
| num_layers=2, | |
| batch_first=True, | |
| dropout=0.2, | |
| ) | |
| # Attention lets the model "focus" on important interactions | |
| self.attention = nn.MultiheadAttention( | |
| embed_dim=lstm_hidden, num_heads=attention_heads, dropout=0.1 | |
| ) | |
| # Map LSTM output β final user embedding | |
| self.fc1 = nn.Linear(lstm_hidden, embedding_dim) | |
| self.fc2 = nn.Linear(embedding_dim, embedding_dim) | |
| self._init_weights() | |
| def _init_weights(self): | |
| """Initialize linear layers.""" | |
| for m in self.modules(): | |
| if isinstance(m, nn.Linear): | |
| nn.init.xavier_uniform_(m.weight) | |
| if m.bias is not None: | |
| nn.init.zeros_(m.bias) | |
| def forward(self, interaction_sequence): | |
| """ | |
| Encode a user's behavior history. | |
| Args: | |
| interaction_sequence: [batch, seq_len, embedding_dim+3] | |
| Returns: | |
| user_preference_vector: [batch, embedding_dim] | |
| """ | |
| # LSTM extracts sequential patterns | |
| lstm_out, _ = self.lstm(interaction_sequence) | |
| # Prepare for attention: [seq_len, batch, hidden_dim] | |
| lstm_out_t = lstm_out.transpose(0, 1) | |
| # Attention highlights important interactions | |
| attn_out, _ = self.attention(lstm_out_t, lstm_out_t, lstm_out_t) | |
| # Use final attention timestep as summary | |
| final_output = attn_out[-1, :, :] | |
| # Map to user preference vector | |
| x = F.relu(self.fc1(final_output)) | |
| user_preference = self.fc2(x) | |
| return user_preference | |
| class ScorePredictor(nn.Module): | |
| """ | |
| Model #3: Predicts how much a specific user will like a specific plan. | |
| Inputs: | |
| - User embedding | |
| - Plan embedding | |
| Output: | |
| - Score 0β5 (predicted interest level) | |
| """ | |
| def __init__(self, embedding_dim: int = 64): | |
| super().__init__() | |
| # Fully connected layers for scoring | |
| self.fc1 = nn.Linear(embedding_dim * 2, 128) | |
| self.bn1 = nn.BatchNorm1d(128) | |
| self.dropout1 = nn.Dropout(0.3) | |
| self.fc2 = nn.Linear(128, 64) | |
| self.bn2 = nn.BatchNorm1d(64) | |
| self.dropout2 = nn.Dropout(0.2) | |
| self.fc3 = nn.Linear(64, 32) | |
| self.fc4 = nn.Linear(32, 1) | |
| self._init_weights() | |
| def _init_weights(self): | |
| """Initialize linear layers.""" | |
| for m in self.modules(): | |
| if isinstance(m, nn.Linear): | |
| nn.init.xavier_uniform_(m.weight) | |
| if m.bias is not None: | |
| nn.init.zeros_(m.bias) | |
| def forward(self, user_embedding, plan_embedding): | |
| """ | |
| Merge user + plan embeddings to compute a preference score. | |
| """ | |
| # Combine both embeddings | |
| x = torch.cat([user_embedding, plan_embedding], dim=1) | |
| # Deep neural layers | |
| x = self.fc1(x) | |
| x = self.bn1(x) | |
| x = F.relu(x) | |
| x = self.dropout1(x) | |
| x = self.fc2(x) | |
| x = self.bn2(x) | |
| x = F.relu(x) | |
| x = self.dropout2(x) | |
| x = F.relu(self.fc3(x)) | |
| # Predict a score in range 0β5 | |
| score = 5.0 * torch.sigmoid(self.fc4(x)) | |
| return score.squeeze() | |
| class CompleteRecommenderModel(nn.Module): | |
| """ | |
| Main model combining all components: | |
| - PlanEmbeddingNetwork β encodes each plan | |
| - UserPreferenceNetwork β encodes each user | |
| - ScorePredictor β predicts how much the user will like the plan | |
| This is a full end-to-end recommendation model. | |
| """ | |
| def __init__(self, n_interests=20, n_categories=50, embedding_dim=64): | |
| super().__init__() | |
| self.plan_encoder = PlanEmbeddingNetwork( | |
| n_interests=n_interests, | |
| n_categories=n_categories, | |
| embedding_dim=embedding_dim, | |
| ) | |
| self.user_encoder = UserPreferenceNetwork(embedding_dim=embedding_dim) | |
| self.score_predictor = ScorePredictor(embedding_dim=embedding_dim) | |
| def forward(self, plan_interest_ids, plan_numerical_features, user_interaction_history): | |
| """Full prediction pipeline.""" | |
| plan_emb = self.plan_encoder(plan_interest_ids, plan_numerical_features) | |
| user_emb = self.user_encoder(user_interaction_history) | |
| score = self.score_predictor(user_emb, plan_emb) | |
| return score | |
| def encode_plan(self, plan_interest_ids, plan_numerical_features): | |
| """Encode plan only.""" | |
| return self.plan_encoder(plan_interest_ids, plan_numerical_features) | |
| def encode_user(self, user_interaction_history): | |
| """Encode user only.""" | |
| return self.user_encoder(user_interaction_history) | |
| def predict_score(self, user_embedding, plan_embedding): | |
| """Score user-plan pair.""" | |
| return self.score_predictor(user_embedding, plan_embedding) | |
| # Demonstration block | |
| if __name__ == "__main__": | |
| print("=" * 50) | |
| print("DEMONSTRATING THIS IS REAL MACHINE LEARNING") | |
| print("=" * 50) | |
| model = CompleteRecommenderModel() | |
| # Count parameters (proof of ML) | |
| params = sum(p.numel() for p in model.parameters() if p.requires_grad) | |
| print(f"\nModel has {params:,} trainable parameters\n") | |
| # Example input | |
| batch_size = 4 | |
| plan_interests = torch.randint(0, 20, (batch_size, 3)) | |
| plan_features = torch.randn(batch_size, 8) | |
| user_history = torch.randn(batch_size, 10, 67) | |
| with torch.no_grad(): | |
| scores = model(plan_interests, plan_features, user_history) | |
| print(f"Predicted scores for {batch_size} users: {scores.tolist()}") | |
| print("=" * 50) | |