File size: 8,079 Bytes
4f2fd46 | 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 | """
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 |