File size: 10,370 Bytes
9166aef
9031b79
 
 
 
 
 
9166aef
 
 
 
 
 
 
 
 
 
 
 
9031b79
 
 
 
9166aef
 
9031b79
 
9166aef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9031b79
9166aef
9031b79
9166aef
 
 
 
 
 
 
9031b79
9166aef
 
 
 
 
9031b79
 
 
 
9166aef
 
9031b79
 
 
 
 
 
 
9166aef
 
 
 
 
 
 
 
 
 
9031b79
 
9166aef
9031b79
9166aef
9031b79
9166aef
 
9031b79
9166aef
720e732
9166aef
 
 
 
 
 
9031b79
 
 
9166aef
 
 
9031b79
9166aef
9031b79
9166aef
9031b79
9166aef
 
 
 
 
 
 
9031b79
9166aef
 
9031b79
9166aef
 
9031b79
9166aef
 
9031b79
9166aef
 
9031b79
9166aef
 
 
9031b79
 
9166aef
9031b79
9166aef
 
 
9031b79
 
 
9166aef
 
 
9031b79
 
9166aef
9031b79
9166aef
 
 
 
 
 
9031b79
9166aef
9031b79
9166aef
9031b79
9166aef
9031b79
9166aef
9031b79
 
9166aef
9031b79
 
9166aef
9031b79
 
 
9166aef
 
9031b79
 
 
 
9166aef
9031b79
9166aef
 
 
 
 
 
 
9031b79
 
9166aef
 
 
 
 
 
9031b79
 
 
 
 
 
 
 
 
 
 
 
9166aef
9031b79
 
9166aef
9031b79
 
9166aef
9031b79
 
 
 
9166aef
9031b79
 
 
9166aef
 
 
 
 
 
 
 
9031b79
9166aef
 
 
 
 
 
 
 
9031b79
 
9166aef
 
9031b79
9166aef
9031b79
9166aef
 
 
 
9031b79
 
 
9166aef
9031b79
9166aef
 
 
 
 
 
 
 
 
9031b79
 
 
 
9166aef
 
 
 
 
 
9031b79
 
9166aef
9031b79
9166aef
9031b79
 
9166aef
9031b79
 
9166aef
 
9031b79
 
 
 
 
 
9166aef
 
 
9031b79
 
 
9166aef
9031b79
9166aef
 
9031b79
 
 
 
 
9166aef
 
 
9031b79
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
"""
Machine Learning Training Pipeline for the Romio Recommender System.
Includes:
- PyTorch Dataset
- Training & validation loops
- ML metrics (MSE, MAE, Precision@K, Recall@K, NDCG)
- Model checkpoint saving and loading
"""

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
import numpy as np
from typing import List, Dict, Tuple, Any
from tqdm import tqdm
import json


# ============================================================
# Dataset
# ============================================================

class RecommendationDataset(Dataset):
    """
    PyTorch Dataset for user → plan recommendation training.
    Returns numerical features, interest IDs, user sequences, and labels.
    """

    def __init__(
        self,
        user_ids: List[str],
        plan_ids: List[str],
        labels: List[float],
        plans_dict: Dict,
        interactions_dict: Dict,
        plan_embeddings: Dict,
        feature_extractor,
    ):
        self.user_ids = user_ids
        self.plan_ids = plan_ids
        self.labels = labels
        self.plans_dict = plans_dict
        self.interactions_dict = interactions_dict
        self.plan_embeddings = plan_embeddings
        self.feature_extractor = feature_extractor

    def __len__(self):
        return len(self.user_ids)

    def __getitem__(self, idx):
        user_id = self.user_ids[idx]
        plan_id = self.plan_ids[idx]
        label = self.labels[idx]

        # Extract plan features
        plan = self.plans_dict.get(plan_id, {})
        interest_ids, numeric_features = self.feature_extractor.extract_plan_features(plan)

        # Extract user sequence (recent interactions)
        user_interactions = self.interactions_dict.get(user_id, [])
        user_sequence = self.feature_extractor.extract_user_interaction_sequence(
            user_interactions, self.plan_embeddings
        )

        return {
            "plan_interests": interest_ids,
            "plan_numerical": numeric_features,
            "user_sequence": user_sequence,
            "label": torch.tensor(label, dtype=torch.float32),
        }


# ============================================================
# Trainer
# ============================================================

class MLTrainer:
    """
    Complete ML training utility.
    Handles:
    - Training loop (forward, backward, optimizer)
    - Validation loop
    - Loss tracking
    - Evaluation metrics
    - Early stopping
    """

    def __init__(
        self,
        model: nn.Module,
        device: str = "cuda" if torch.cuda.is_available() else "cpu",
    ):
        self.model = model.to(device)
        self.device = device

        # Regression loss (predicting scores)
        self.criterion = nn.MSELoss()

        # Standard Adam optimizer
        self.optimizer = optim.Adam(
            self.model.parameters(), lr=0.001, weight_decay=1e-5
        )

        # Reduce LR if validation loss stops improving
        self.scheduler = optim.lr_scheduler.ReduceLROnPlateau(
            self.optimizer, mode="min", factor=0.5, patience=3
        )

        self.train_losses = []
        self.val_losses = []
        self.metrics_history = []

    # --------------------------------------------------------
    # Training loop (one epoch)
    # --------------------------------------------------------
    def train_epoch(self, train_loader: DataLoader, epoch: int) -> float:
        self.model.train()
        total_loss = 0.0
        count = 0

        progress = tqdm(train_loader, desc=f"Epoch {epoch}")

        for batch in progress:
            plan_interests = batch["plan_interests"].to(self.device)
            plan_numerical = batch["plan_numerical"].to(self.device)
            user_sequence = batch["user_sequence"].to(self.device)
            labels = batch["label"].to(self.device)

            self.optimizer.zero_grad()

            # Forward pass
            predictions = self.model(plan_interests, plan_numerical, user_sequence)

            # Loss
            loss = self.criterion(predictions, labels)

            # Backpropagation
            loss.backward()

            # Prevent unstable gradients
            torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=1.0)

            # Weight update
            self.optimizer.step()

            total_loss += loss.item()
            count += 1
            progress.set_postfix({"loss": loss.item()})

        avg_loss = total_loss / count
        self.train_losses.append(avg_loss)
        return avg_loss

    # --------------------------------------------------------
    # Validation / metric computation
    # --------------------------------------------------------
    def evaluate(self, val_loader: DataLoader, k: int = 10) -> Dict[str, float]:
        self.model.eval()

        preds = []
        labels = []
        total_loss = 0.0
        batches = 0

        with torch.no_grad():
            for batch in val_loader:
                plan_interests = batch["plan_interests"].to(self.device)
                plan_numerical = batch["plan_numerical"].to(self.device)
                user_sequence = batch["user_sequence"].to(self.device)
                y_true = batch["label"].to(self.device)

                y_pred = self.model(plan_interests, plan_numerical, user_sequence)

                loss = self.criterion(y_pred, y_true)
                total_loss += loss.item()
                batches += 1

                preds.extend(y_pred.cpu().numpy())
                labels.extend(y_true.cpu().numpy())

        preds = np.array(preds)
        labels = np.array(labels)

        # Basic metrics
        mse = np.mean((preds - labels) ** 2)
        mae = np.mean(np.abs(preds - labels))
        rmse = np.sqrt(mse)

        # Ranking metrics
        precision = self._precision_at_k(preds, labels, k)
        recall = self._recall_at_k(preds, labels, k)
        ndcg = self._ndcg_at_k(preds, labels, k)

        avg_val_loss = total_loss / batches
        self.val_losses.append(avg_val_loss)

        metrics = {
            "val_loss": avg_val_loss,
            "mse": mse,
            "mae": mae,
            "rmse": rmse,
            "precision@k": precision,
            "recall@k": recall,
            "ndcg@k": ndcg,
        }

        self.metrics_history.append(metrics)
        return metrics

    # --------------------------------------------------------
    # Ranking metric helpers
    # --------------------------------------------------------
    def _precision_at_k(self, predictions, labels, k: int) -> float:
        top_k = np.argsort(predictions)[-k:]
        relevant = sum(labels[i] >= 3.5 for i in top_k)
        return relevant / k

    def _recall_at_k(self, predictions, labels, k: int) -> float:
        top_k = np.argsort(predictions)[-k:]
        relevant_total = sum(labels >= 3.5)
        if relevant_total == 0:
            return 0.0
        relevant_in_top = sum(labels[i] >= 3.5 for i in top_k)
        return relevant_in_top / relevant_total

    def _ndcg_at_k(self, predictions, labels, k: int) -> float:
        top_k = np.argsort(predictions)[-k:][::-1]

        dcg = sum(labels[idx] / np.log2(i + 2) for i, idx in enumerate(top_k))
        ideal = sorted(labels, reverse=True)[:k]
        idcg = sum(rel / np.log2(i + 2) for i, rel in enumerate(ideal))
        return 0.0 if idcg == 0 else dcg / idcg

    # --------------------------------------------------------
    # Full training with early stopping
    # --------------------------------------------------------
    def train(
        self,
        train_loader: DataLoader,
        val_loader: DataLoader,
        n_epochs: int = 50,
        early_stopping_patience: int = 10,
    ):
        best_val_loss = float("inf")
        patience = 0

        for epoch in range(1, n_epochs + 1):
            train_loss = self.train_epoch(train_loader, epoch)
            metrics = self.evaluate(val_loader)
            self.scheduler.step(metrics["val_loss"])

            if metrics["val_loss"] < best_val_loss:
                best_val_loss = metrics["val_loss"]
                patience = 0
                # Keep model checkpoint safe
                self.save_checkpoint("model/artifacts/best_model.pth")
            else:
                patience += 1

            if patience >= early_stopping_patience:
                break

        return self.train_losses, self.val_losses, self.metrics_history

    # --------------------------------------------------------
    # Checkpoint handling
    # --------------------------------------------------------
    def save_checkpoint(self, path: str):
        """Save model weights and training history."""
        checkpoint = {
            "model_state_dict": self.model.state_dict(),
            "optimizer_state_dict": self.optimizer.state_dict(),
            "train_losses": self.train_losses,
            "val_losses": self.val_losses,
            "metrics_history": self.metrics_history,
        }
        torch.save(checkpoint, path)

# ============================================================
# Train/validation split
# ============================================================

def create_train_val_split(
    user_ids: List[str],
    plan_ids: List[str],
    labels: List[float],
    val_ratio: float = 0.2,
    random_seed: int = 42,
):
    """Randomly split interaction data into training and validation sets."""
    np.random.seed(random_seed)
    n = len(user_ids)

    indices = np.random.permutation(n)
    val_size = int(n * val_ratio)

    val_idx = indices[:val_size]
    train_idx = indices[val_size:]

    return (
        [user_ids[i] for i in train_idx],
        [plan_ids[i] for i in train_idx],
        [labels[i] for i in train_idx],
        [user_ids[i] for i in val_idx],
        [plan_ids[i] for i in val_idx],
        [labels[i] for i in val_idx],
    )


# ============================================================
# Example usage (debug mode only)
# ============================================================

if __name__ == "__main__":
    from neural_models import CompleteRecommenderModel

    model = CompleteRecommenderModel(
        n_interests=20,
        n_categories=50,
        embedding_dim=64
    )

    trainer = MLTrainer(model)

    print("ML training pipeline initialized.")