""" meta_learner_core.py — Shared MetaLearner class Imported by both meta_learner_trainer.py and meta_learner_inference.py. Keeping the class in one place means: - Pickle/joblib deserialisation always works regardless of which script instantiated the object, as long as both scripts import from here. - Any change to MetaLearner (new meta type, new attribute) is made once and takes effect in both training and inference automatically. Usage: from meta_learner_core import MetaLearner """ import numpy as np from scipy.optimize import minimize from sklearn.metrics import log_loss class MetaLearner: """ Unified wrapper for all supported meta-learner types. Supported meta_type values: lgbm — LightGBM classifier. Best with rich derived features (entropy, KL divergence). Can learn non-linear routing rules. logistic — Multinomial logistic regression with isotonic calibration. ridge — Ridge regression OvR + softmax normalisation. Fastest, rarely overfits. Strong baseline for pure probability stacking. weighted_avg — Nelder-Mead optimised blend weights. Most interpretable. Only blends the probability columns (not embedding dims). mlp — Small 3-layer MLP with dropout. Best when embedding features are included (exploits non-linear embedding geometry). n_prob_cols: Number of leading feature columns that are valid probability distributions (OOF probs + derived features from prob columns). Columns beyond this index (e.g. PCA embedding dims) are real-valued and NOT valid distributions — weighted_avg uses only the first n_prob_cols columns for blending. All other meta types use all columns. If None, defaults to X.shape[1] at fit time (backwards compatible when no embedding features are present). """ def __init__(self, meta_type: str, n_classes: int, seed: int = 42, n_prob_cols: int = None): self.meta_type = meta_type self.n_classes = n_classes self.seed = seed self.model = None self._weights = None # for weighted_avg self._n_prob_cols = n_prob_cols # ------------------------------------------------------------------------- def fit(self, X, y): if self.meta_type == "lgbm": import lightgbm as lgb self.model = lgb.LGBMClassifier( n_estimators=300, learning_rate=0.05, num_leaves=31, subsample=0.8, colsample_bytree=0.8, min_child_samples=20, class_weight="balanced", random_state=self.seed, n_jobs=-1, verbose=-1, ) self.model.fit(X, y) elif self.meta_type == "logistic": from sklearn.linear_model import LogisticRegression from sklearn.calibration import CalibratedClassifierCV base = LogisticRegression( C=1.0, max_iter=1000, random_state=self.seed, class_weight="balanced", multi_class="multinomial" ) self.model = CalibratedClassifierCV(base, method="isotonic", cv=3) self.model.fit(X, y) elif self.meta_type == "ridge": from sklearn.linear_model import Ridge from sklearn.preprocessing import OneHotEncoder self.model = Ridge(alpha=1.0) enc = OneHotEncoder(sparse_output=False) y_ohe = enc.fit_transform(y.reshape(-1, 1)) self.model.fit(X, y_ohe) elif self.meta_type == "weighted_avg": n_prob = self._n_prob_cols if self._n_prob_cols is not None else X.shape[1] n_prob = (n_prob // self.n_classes) * self.n_classes # snap to model boundary X_prob = X[:, :n_prob] n_models = n_prob // self.n_classes if n_models <= 1: self._weights = np.array([1.0]) else: self._weights = self._optimise_weights(X_prob, y, n_models) self._n_prob_cols = n_prob elif self.meta_type == "mlp": import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset n_in = X.shape[1] hidden = min(256, max(64, n_in // 2)) net = nn.Sequential( nn.Linear(n_in, hidden), nn.ReLU(), nn.Dropout(0.4), nn.Linear(hidden, hidden // 2), nn.ReLU(), nn.Dropout(0.3), nn.Linear(hidden // 2, self.n_classes), ) opt = torch.optim.Adam(net.parameters(), lr=1e-3, weight_decay=1e-4) sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=100) loss_fn = nn.CrossEntropyLoss() X_t = torch.tensor(X, dtype=torch.float32) y_t = torch.tensor(y, dtype=torch.long) dl = DataLoader(TensorDataset(X_t, y_t), batch_size=256, shuffle=True) net.train() for _ in range(100): for xb, yb in dl: opt.zero_grad() loss_fn(net(xb), yb).backward() opt.step() sched.step() net.eval() self.model = net return self # ------------------------------------------------------------------------- def _optimise_weights(self, X, y, n_models): """Nelder-Mead simplex on softmax-normalised weights.""" n_classes = self.n_classes def objective(w): w_s = np.exp(w) / np.exp(w).sum() blended = np.zeros((len(X), n_classes)) for i, wi in enumerate(w_s): blended += wi * X[:, i * n_classes:(i + 1) * n_classes] blended = np.clip(blended, 1e-7, 1.0) blended /= blended.sum(axis=1, keepdims=True) return log_loss(y, blended) res = minimize(objective, np.ones(n_models), method="Nelder-Mead", options={"maxiter": 5000, "xatol": 1e-5}) best_w = np.exp(res.x) / np.exp(res.x).sum() return best_w # ------------------------------------------------------------------------- def predict_proba(self, X): if self.meta_type == "mlp": import torch self.model.eval() with torch.no_grad(): logits = self.model(torch.tensor(X, dtype=torch.float32)) return torch.softmax(logits, dim=1).numpy() if self.meta_type == "weighted_avg": blended = np.zeros((len(X), self.n_classes)) for i, wi in enumerate(self._weights): blended += wi * X[:, i * self.n_classes:(i + 1) * self.n_classes] blended = np.clip(blended, 1e-7, 1.0) return blended / blended.sum(axis=1, keepdims=True) elif self.meta_type == "ridge": raw = self.model.predict(X) raw = np.clip(raw, 1e-7, None) return raw / raw.sum(axis=1, keepdims=True) else: return self.model.predict_proba(X) # ------------------------------------------------------------------------- def get_feature_importances(self): if self.meta_type == "lgbm": return self.model.feature_importances_ elif self.meta_type == "logistic": try: return np.abs( self.model.calibrated_classifiers_[0].estimator.coef_ ).mean(axis=0) except Exception: return None elif self.meta_type == "ridge": return np.abs(self.model.coef_).mean(axis=0) elif self.meta_type == "weighted_avg": return np.repeat(self._weights, self.n_classes) elif self.meta_type == "mlp": return None return None