File size: 1,518 Bytes
5a7104f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Next Signal inference (NumPy only): embed inertial windows and classify them with the released probe.

Usage:
    python inference.py --selftest
    from inference import load, embed, classify
"""
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)

import numpy as np  # noqa: E402

import signal_core as sg  # noqa: E402
from nlrt import load_model  # noqa: E402


def load(path=os.path.join(HERE, "model.json")):
    return load_model(path)


def embed(spec, windows):
    """windows: (N, 9, 128) raw UCI-HAR style inertial windows -> (N, 64) self-supervised embeddings."""
    m = spec["meta"]
    return sg.encode(spec["nets"]["encoder"], sg.normalise(windows, m["mean"], m["std"]))


def classify(spec, windows, budget=50):
    """Activity probabilities (N, 6) from the frozen encoder + linear probe trained with `budget` labels per class."""
    return sg.probe_proba(spec["meta"]["probes"]["ssl"][str(budget)], embed(spec, windows))


def _selftest():
    spec = load()
    with open(os.path.join(HERE, "selftest.json"), encoding="utf-8") as f:
        t = json.load(f)
    P = classify(spec, np.asarray(t["windows"]), t["budget"])
    diff = float(np.abs(P - np.asarray(t["expected_proba"])).max())
    ok = diff < 1e-6
    print(json.dumps({"passed": ok, "max_abs_diff": diff, "n_windows": len(t["windows"])}))
    return ok


if __name__ == "__main__":
    if "--selftest" in sys.argv:
        sys.exit(0 if _selftest() else 1)
    print(__doc__)