File size: 8,321 Bytes
a7cd1c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Fine-tune a pretrained PatchTST (ibm-granite/granite-timeseries-patchtst, Apache-2.0)
to classify each cow-day from a 14-day window of 8 ear-tag signals + 8 herd-context signals.
Also trains the gradient-boosting baseline on the same windows.

Run:  python simulate.py && python train.py      (needs base/patchtst, see README)
"""
import json
import os
import sys
import time

import numpy as np
import torch

from simulate import CLASSES, SIGNALS

WIN = 14
TRAIN_DAYS = (WIN - 1, 700)      # window end day t in [13, 700)
EVAL_DAYS = (750, 1000)          # 50-day gap so no window overlaps the training period
N_TEST_FARMS = 4
VAL_COW_FRAC = 0.15
CAPS = {"normal": 120_000}       # per-class sample cap; every other class capped at 40k
OTHER_CAP = 40_000
SEED = 0
DATA = os.environ.get("HS_DATA", "data")
MODEL = os.environ.get("HS_MODEL", "model")


def load(path=None):
    path = path or DATA
    return {k: np.load(f"{path}/{k}.npy") for k in ["X", "y", "farm", "thi", "heat_stress", "events"]}


def splits(farm, seed=SEED):
    rng = np.random.default_rng(seed)
    farms = np.unique(farm)
    test_farms = rng.choice(farms, N_TEST_FARMS, replace=False)
    is_test = np.isin(farm, test_farms)
    cows = np.arange(len(farm))
    tr_pool = cows[~is_test]
    val = rng.choice(tr_pool, int(len(tr_pool) * VAL_COW_FRAC), replace=False)
    train = np.setdiff1d(tr_pool, val)
    return dict(train=train, val=val, test=cows[is_test], test_farms=sorted(test_farms.tolist()))


def prepare(d, scale=None):
    """log1p for count/minute signals (relative changes), raw degC for drone thermal; herd medians."""
    Z = d["X"].copy()
    pos = [i for i, s in enumerate(SIGNALS) if s != "thermal_drone"]
    Z[:, :, pos] = np.log1p(Z[:, :, pos])
    F, D = int(d["farm"].max()) + 1, Z.shape[1]
    H = np.zeros((F, D, Z.shape[2]), np.float32)
    for f in range(F):
        H[f] = np.nanmedian(Z[d["farm"] == f], axis=0)   # herd = all tags on the farm that day
    if scale is None:  # robust per-signal day-to-day spread around each cow's own median
        s = Z[::10, :700]
        scale = np.nanstd(s - np.nanmedian(s, axis=1, keepdims=True), axis=(0, 1))
        scale = np.maximum(scale, 1e-3).astype(np.float32)
    return Z, H, scale


def windows(Z, H, farm, scale, cows, ts):
    """(n, 14, 16): cow signals minus her own baseline (first 7 days of the window), then the
    herd's median signals minus the herd baseline, both divided by the signal's typical spread."""
    idx = ts[:, None] + np.arange(-WIN + 1, 1)
    W = Z[cows[:, None], idx]
    Hh = H[farm[cows][:, None], idx]
    W = (W - np.nanmedian(W[:, :7], axis=1, keepdims=True)) / scale
    Hh = (Hh - np.nanmedian(Hh[:, :7], axis=1, keepdims=True)) / scale
    out = np.concatenate([W, Hh], axis=2)
    return np.nan_to_num(np.clip(out, -8, 8), nan=0.0).astype(np.float32)


def sample_train(y, cows, rng):
    t0, t1 = TRAIN_DAYS
    yy = y[cows, t0:t1]
    picks_c, picks_t = [], []
    for k, name in enumerate(CLASSES):
        ci, ti = np.nonzero(yy == k)
        n = min(len(ci), CAPS.get(name, OTHER_CAP))
        sel = rng.choice(len(ci), n, replace=False)
        picks_c.append(cows[ci[sel]])
        picks_t.append(ti[sel] + t0)
    true_prior = np.bincount(yy.ravel(), minlength=len(CLASSES)) / yy.size
    return np.concatenate(picks_c), np.concatenate(picks_t), true_prior


def build_model(base="base/patchtst"):
    from transformers import PatchTSTConfig, PatchTSTForClassification
    cfg = PatchTSTConfig.from_pretrained(base)
    # short daily series: 2-day patches, stride 1 -> 13 patches. The patch embedding and
    # positional table are re-initialised (shape change); the 3 transformer layers + CLS
    # token keep their pretrained weights; the classification head is new.
    cfg.update(dict(context_length=WIN, patch_length=2, patch_stride=1, num_input_channels=16,
                    num_targets=len(CLASSES), scaling=None, use_cls_token=True,
                    id2label=dict(enumerate(CLASSES)), label2id={c: i for i, c in enumerate(CLASSES)}))
    return PatchTSTForClassification.from_pretrained(base, config=cfg, ignore_mismatched_sizes=True)


@torch.no_grad()
def predict_proba(model, Xw, device, bs=4096):
    model.eval()
    out = []
    for i in range(0, len(Xw), bs):
        xb = torch.from_numpy(Xw[i:i + bs]).to(device)
        out.append(torch.softmax(model(past_values=xb).prediction_logits, -1).float().cpu().numpy())
    return np.concatenate(out)


def prior_correct(p, train_prior, true_prior):
    """Undo class-balanced sampling so alert rates match how often each state really occurs."""
    q = p * (np.asarray(true_prior) / np.asarray(train_prior))
    return q / q.sum(1, keepdims=True)


def main(epochs=3, bs=512, lr=5e-4):
    t_start = time.time()
    torch.manual_seed(SEED)
    rng = np.random.default_rng(SEED)
    d = load()
    sp = splits(d["farm"])
    Z, H, scale = prepare(d)
    cows, ts, true_prior = sample_train(d["y"], sp["train"], rng)
    Xtr = windows(Z, H, d["farm"], scale, cows, ts)
    ytr = d["y"][cows, ts].astype(np.int64)
    train_prior = np.bincount(ytr, minlength=len(CLASSES)) / len(ytr)
    print("train windows", len(ytr), dict(zip(CLASSES, np.bincount(ytr).tolist())))
    # small validation set: held-out cows on training farms, later period
    vc = rng.choice(sp["val"], 30_000)
    vt = rng.integers(*EVAL_DAYS, 30_000)
    Xva, yva = windows(Z, H, d["farm"], scale, vc, vt), d["y"][vc, vt]

    if "--gbm-only" in sys.argv:
        return train_gbm(Xtr, ytr)
    device = "mps" if torch.backends.mps.is_available() else "cpu"
    model = build_model().to(device)
    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
    steps = epochs * (len(ytr) // bs)
    sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.1)
    Xt, yt = torch.from_numpy(Xtr), torch.from_numpy(ytr)
    log = []
    for ep in range(epochs):
        model.train()
        perm = torch.randperm(len(yt))
        t0, tot = time.time(), 0.0
        for i in range(len(yt) // bs):
            b = perm[i * bs:(i + 1) * bs]
            loss = model(past_values=Xt[b].to(device), target_values=yt[b].to(device)).loss
            opt.zero_grad()
            loss.backward()
            opt.step()
            sched.step()
            tot += loss.item()
        p = prior_correct(predict_proba(model, Xva, device), train_prior, true_prior)
        from sklearn.metrics import f1_score
        f1 = f1_score(yva, p.argmax(1), average="macro", labels=range(1, len(CLASSES)))
        log.append(dict(epoch=ep + 1, train_loss=tot / (i + 1), val_macro_f1_events=float(f1),
                        sec=round(time.time() - t0, 1)))
        print(log[-1], flush=True)

    model.save_pretrained(MODEL)  # safetensors + config.json
    meta = dict(classes=CLASSES, signals=SIGNALS, window_days=WIN, input_channels=
                [f"cow_{s}" for s in SIGNALS] + [f"herd_{s}" for s in SIGNALS],
                scale=scale.tolist(), train_prior=train_prior.tolist(), true_prior=true_prior.tolist(),
                splits=dict(test_farms=sp["test_farms"], n_train_cows=len(sp["train"]),
                            n_val_cows=len(sp["val"]), n_test_cows=len(sp["test"]),
                            train_days=TRAIN_DAYS, eval_days=EVAL_DAYS),
                n_train_windows=int(len(ytr)), train_class_counts=np.bincount(ytr).tolist(),
                base_model="ibm-granite/granite-timeseries-patchtst", epochs=epochs, log=log)
    json.dump(meta, open(f"{MODEL}/herdsight_meta.json", "w"), indent=1)
    meta["train_seconds_patchtst"] = round(time.time() - t_start)
    json.dump(meta, open(f"{MODEL}/herdsight_meta.json", "w"), indent=1)


def train_gbm(Xtr, ytr):
    """Baseline (b): gradient boosting on the same flattened 14x16 windows (run: train.py --gbm-only)."""
    from joblib import dump
    from sklearn.ensemble import HistGradientBoostingClassifier
    t0 = time.time()
    gbm = HistGradientBoostingClassifier(max_iter=300, learning_rate=0.1, early_stopping=False,
                                         random_state=SEED)
    gbm.fit(Xtr.reshape(len(Xtr), -1), ytr)
    dump(gbm, f"{MODEL}/baseline_gbm.joblib")
    print("gbm train seconds", round(time.time() - t0))


if __name__ == "__main__":
    main()