LNPBench / code /src /lnpbench /models /classical.py
eduzrh's picture
LNPBench: code, caches, results and figures
d1988f5 verified
Raw History Blame Contribute Delete
3.56 kB
"""Classical baselines: fingerprint MLP, gradient-boosted trees, random forest."""
from __future__ import annotations
from typing import Sequence
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..store import FeatureStore
from ..trainer import NeuralModel, TrainConfig
class FingerprintMLPModule(nn.Module):
"""Shallow baseline: Morgan fingerprint + formulation context -> MLP."""
def __init__(self, fp_dim: int, ctx_dim: int, hidden: int = 512, dropout: float = 0.2,
drop_ctx: bool = False):
super().__init__()
self.drop_ctx = drop_ctx
self.net = nn.Sequential(
nn.Linear(fp_dim + ctx_dim, hidden), nn.SiLU(), nn.Dropout(dropout),
nn.Linear(hidden, hidden // 2), nn.SiLU(), nn.Dropout(dropout),
nn.Linear(hidden // 2, 1),
)
def forward(self, batch):
ctx = batch["ctx"]
if self.drop_ctx:
ctx = torch.zeros_like(ctx)
z = torch.cat([batch["fp"], ctx], dim=-1)
return {"y_hat": self.net(z).squeeze(-1)}
def compute_loss(self, batch, out, epoch=0, n_epochs=1):
loss = F.mse_loss(out["y_hat"], batch["y"])
return loss, {"mse": float(loss.detach())}
class FingerprintMLP(NeuralModel):
name = "mlp_fp"
def build(self, store: FeatureStore, cfg: TrainConfig) -> nn.Module:
return FingerprintMLPModule(store.il_fp.shape[1], store.ctx_dim, **self.kwargs)
def need(self) -> Sequence[str]:
return ("y", "fp", "ctx")
class SklearnModel:
"""Adapter so that tabular models share the benchmark interface."""
name = "sklearn"
def __init__(self, factory, use_cpp: bool = True, use_desc: bool = True,
drop_ctx: bool = False):
self.factory = factory
self.use_cpp = use_cpp
self.use_desc = use_desc
self.drop_ctx = drop_ctx
def _features(self, store: FeatureStore, idx: np.ndarray) -> np.ndarray:
parts = [store.ratios[idx]] if self.drop_ctx else [store.ctx[idx], store.ratios[idx]]
if self.use_desc:
parts.append(store.il_desc[store.il_id[idx]])
if self.use_cpp:
parts.append(store.il_cpp[store.il_id[idx]])
X = np.concatenate(parts, axis=1)
return np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0)
def fit(self, store, train_idx, val_idx, cfg: TrainConfig):
self.model = self.factory()
X = self._features(store, train_idx)
self.model.fit(X, store.y[train_idx])
return {"best_val_spearman": float("nan")}
def predict(self, store, idx):
return self.model.predict(self._features(store, idx)).astype(np.float64)
def make_xgboost(**kwargs):
from xgboost import XGBRegressor
params = dict(
n_estimators=600, max_depth=6, learning_rate=0.05, subsample=0.8,
colsample_bytree=0.6, min_child_weight=3, reg_lambda=1.0, n_jobs=8,
tree_method="hist", random_state=0,
)
params.update(kwargs)
return XGBRegressor(**params)
def make_random_forest(**kwargs):
from sklearn.ensemble import RandomForestRegressor
params = dict(n_estimators=400, max_depth=None, min_samples_leaf=2, n_jobs=8, random_state=0)
params.update(kwargs)
return RandomForestRegressor(**params)
def make_extra_trees(**kwargs):
from sklearn.ensemble import ExtraTreesRegressor
params = dict(n_estimators=400, min_samples_leaf=2, n_jobs=8, random_state=0)
params.update(kwargs)
return ExtraTreesRegressor(**params)