"""Minimal zero-shot example on real data: a smartphone on the waist (UCI-HAR test split, participant 2). 1. load SetCon (seed 1) through transformers 2. turn the phone's raw windows into model windows (gravity canonicalization, 20 Hz, 10 s) 3. estimate the phone's setup reference from six unlabeled windows of the same participant 4. embed one window and classify it against the CLIP ViT-B/32 embeddings of the class names python examples/zero_shot.py --unimts-dir (see setcon/data.py for the download) """ import argparse import json import sys from pathlib import Path import numpy as np import torch sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from setcon import load_model, processing # noqa: E402 ap = argparse.ArgumentParser() ap.add_argument("--unimts-dir", required=True) ap.add_argument("--window", type=int, default=150, help="window of participant 2 to classify (0-301)") a = ap.parse_args() device = "cuda" if torch.cuda.is_available() else "cpu" model = load_model(seed=1, device=device) # UCI-HAR: 50 Hz, columns 3-5 angular velocity (rad/s), 6-8 total acceleration (g). Participant 2 = windows 0-301. d = Path(a.unimts_dir) / "UCIHAR" X = np.load(d / "X_test.npy")[:302].astype(np.float64) y = np.load(d / "y_test.npy")[:302] classes = [" ".join(v) for v in json.loads((d / "UCIHAR.json").read_text())["label_dictionary"].values()] windows = processing.prepare_device(acc=X[:, :, 6:9] * 9.80665, gyro=X[:, :, 3:6], fs=50) # (302, 200, 9) # Setup reference from six unlabeled windows of the same device; they are not classified. context = np.random.default_rng(0).choice(len(windows), 6, replace=False) ref = model.estimate_reference(windows[context], site="c_spine1") print(f"setup reference estimated, tilt uncertainty {ref['tilt_sigma_deg']:.1f} deg") windows = processing.set_reference(windows, ref["reference"]) x = processing.place_devices({"c_spine1": windows}) # (302, 200, 22, 9) # Class names in the CLIP ViT-B/32 text space (the frozen text encoder SetCon was aligned with). import clip # noqa: E402 clip_model, _ = clip.load("ViT-B/32", device=device) with torch.no_grad(): text = clip_model.encode_text(clip.tokenize(classes, truncate=True).to(device)).float() text = torch.nn.functional.normalize(text, dim=-1).cpu().numpy() z = model.embed(x[a.window:a.window + 1]) # (1, 512) scores = z @ text.T print(f"window {a.window}: predicted '{classes[int(scores.argmax())]}', true '{classes[int(y[a.window])]}'") print("cosine per class:", ", ".join(f"{c} {s:.3f}" for c, s in zip(classes, scores[0]))) scored = np.setdiff1d(np.arange(len(x)), context) pred = (model.embed(x[scored]) @ text.T).argmax(1) print(f"participant 2, {len(scored)} windows: accuracy {100 * np.mean(pred == y[scored]):.1f} % with class names")