File size: 3,559 Bytes
d1988f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)