Feature Extraction
Transformers
Safetensors
English
setcon
imu
wearable-sensing
human-activity-recognition
zero-shot-classification
motion-language
time-series
custom_code
Instructions to use lschiweck/SetCon with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use lschiweck/SetCon with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="lschiweck/SetCon", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("lschiweck/SetCon", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 15,247 Bytes
0107764 | 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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | """The paper's SetCon numbers from the per-seed results of setcon.evaluate, compared with the printed values.
Seeds give mean and sample standard deviation (ddof 1). A number matches when it rounds to the printed digits.
"""
from __future__ import annotations
import json
import statistics
from pathlib import Path
import numpy as np
from .protocol import DATASETS, MEAN13, macro_f1
# Tab. 3: motion group of every Mean-13 class, from the class name only.
POSTURE, TRANSITION, LOCOMOTION, DIRECTION, HAND, WHOLE_BODY = (
"posture", "transition", "locomotion", "direction", "hand/arm", "other whole-body")
P, T, L, D, H, O = POSTURE, TRANSITION, LOCOMOTION, DIRECTION, HAND, WHOLE_BODY
VERTICAL = ("stair", "upstairs", "downstairs", "climbing", "elevator")
GROUP_OF_CLASS = {
"Opp_g": {"stand": P, "walk": L, "sit": P, "lie": P},
"UCIHAR": {"walk": L, "walk upstairs": D, "walk downstairs": D, "sit": P, "stand": P, "lay": P},
"MotionSense": {"downstairs": D, "jogging": L, "sit": P, "stand up": P, "upstairs": D, "walking": L},
"w-HAR": {"walk": L, "sit": P, "stand": P, "jump": O, "lie down": P, "stairs up": D, "stairs down": D},
"Shoaib": {"walking": L, "standing": P, "jogging": L, "sitting": P, "biking": O, "upstairs": D, "downstairs": D},
"realworld": {"lying": P, "jumping": O, "standing": P, "walking": L, "sitting": P, "climbing down": D,
"climbing up": D, "running": L},
"TNDA-HAR": {"sitting": P, "standing": P, "lying down": P, "ascending stairs": D, "descending stairs": D,
"riding": O, "walking": L, "jogging": L},
"PAMAP": {"lying": P, "sitting": P, "standing": P, "walking": L, "running": L, "cycling": O, "nordic walking": L,
"ascending stairs": D, "descending stairs": D, "vacuum cleaning": H, "ironing": H, "rope jumping": O},
"USCHAD": {"walk forward": L, "walk left": D, "walk right": D, "walk upstairs": D, "walk downstairs": D,
"run forward": L, "jump up": O, "sit": P, "stand": P, "sleep": P, "elevator up": D, "elevator down": D},
"ut-complex": {"walking": L, "standing": P, "jogging": L, "sitting": P, "biking": O, "upstairs": D,
"downstairs": D, "typing": H, "writing": H, "drinking coffee": H, "giving a talk": H, "smoking": H,
"eating": H},
"WISDM": {"walking": L, "jogging": L, "stairs": L, "sitting": P, "standing": P, "typing": H, "brushing teeth": H,
"eating soup": H, "eating chips": H, "eating pasta": H, "drinking cup": H, "eating sandwich": H,
"kicking ball": O, "playing ball": O, "dribbling ball": O, "writing": H, "clapping": H,
"folding clothes": H},
"DSADS": {"sitting": P, "standing": P, "lying on back": P, "lying on right side": P, "ascending stairs": D,
"descending stairs": D, "standing in an elevator still": P, "moving around in an elevator": O,
"walking slowly": L, "walking on a treadmill in flat positions)": L,
"walking on a treadmill in inclined positions)": L, "running on a treadmill fast": L,
"exercising on a stepper": O, "exercising on a cross trainer": O,
"cycling on an exercise bike in horizontal positions": O,
"cycling on an exercise bike in vertical positions": O, "rowing": O, "jumping": O,
"playing basketball": O},
"UTD-MHAD": {"right arm swipe to the left": D, "right arm swipe to the right": D, "right hand wave": H,
"two hand front clap": H, "right arm throw": H, "cross arms in the chest": H, "basketball shoot": H,
"right hand draw x": H, "right hand draw circle (clockwise)": D,
"right hand draw circle (counter clockwise)": D, "draw triangle": H, "bowling (right hand)": H,
"front boxing": H, "baseball swing from right": H, "tennis right hand forehand swing": H,
"arm curl (two arms)": H, "tennis serve": H, "two hand push": H, "right hand knock on door": H,
"right hand catch an object": H, "right hand pick up and throw": H, "jogging in place": L,
"walking in place": L, "sit to stand": T, "stand to sit": T,
"forward lunge (left foot forward)": O, "squat (two arms stretch out)": O},
}
TAB3_GROUPS = (("Posture", lambda g, c: g == P),
("Stairs, elevator", lambda g, c: g == D and any(w in c for w in VERTICAL)),
("Left/right, circle", lambda g, c: g == D and not any(w in c for w in VERTICAL)),
("Locomotion", lambda g, c: g == L), ("Hand and arm", lambda g, c: g == H),
("Other whole-body", lambda g, c: g == O))
POSTURE_NAMES = {"sit": {"sit", "sitting", "sitting relaxing"}, "stand": {"stand", "standing", "standing still"},
"lie": {"lying", "lying down", "lay", "lie", "lie down", "lying on back", "lying on right side",
"sleep"}}
# Printed values: (mean, sd or None, decimals).
PAPER_MAIN = {
"Tab. 1, 6 random windows: class-mean readout": (91.5, 0.2, 1),
"Tab. 1, 6 random windows: accuracy, names": (55.9, 0.4, 1),
"Tab. 1, 6 random windows: accuracy, anchors": (64.7, 0.6, 1),
"Tab. 1, 6 random windows: macro-F1, names": (50.2, 0.6, 1),
"Tab. 1, 6 random windows: macro-F1, anchors": (60.5, 0.5, 1),
"Tab. 1, 6 of 12 windows: class-mean readout": (91.6, 0.2, 1),
"Tab. 1, 6 of 12 windows: accuracy, names (abstract)": (56.6, 0.6, 1),
"Tab. 1, 6 of 12 windows: accuracy, anchors (abstract, Fig. 1)": (65.3, 0.4, 1),
"Tab. 1, 6 of 12 windows: macro-F1, names": (51.6, 0.7, 1),
"Tab. 1, 6 of 12 windows: macro-F1, anchors": (62.1, 0.4, 1),
}
PAPER_MORE = {
"Tab. 2, calibrator: names": (55.9, 0.4, 1),
"Tab. 2, calibrator: anchors": (64.7, 0.6, 1),
"Tab. 2, walking frame: names": (54.6, 0.2, 1),
"Tab. 2, walking frame: anchors": (62.7, 0.6, 1),
"Tab. 2, zeroed: names": (41.5, 0.7, 1),
"Tab. 2, zeroed: anchors": (48.0, 2.1, 1),
"Tab. 3, Posture": (53.3, 0.8, 1),
"Tab. 3, Stairs, elevator": (53.2, 1.8, 1),
"Tab. 3, Left/right, circle": (18.8, 3.8, 1),
"Tab. 3, Locomotion": (64.0, 4.7, 1),
"Tab. 3, Hand and arm": (17.8, 1.1, 1),
"Tab. 3, Other whole-body": (56.2, 2.5, 1),
"Sec. 4.3: zeroed reference, anchors, posture windows called lying (%)": (86, None, 0),
"Sec. 4.3: one context window, names": (53.7, None, 1),
"Sec. 4.3: scored windows without gait context (%)": (15, None, 0),
"Sec. 4.3: calibrator minus zeroed on those windows, names": (9.6, None, 1),
"Sec. 4.4: anchor gain (anchors minus names)": (8.7, None, 1),
"Sec. 4.4: descriptions added to the name (gain over names)": (6.3, None, 1),
"Sec. 4.4: class-mean readout minus names": (36, None, 0),
}
def msd(values):
values = [float(v) for v in values]
return dict(mean=float(np.mean(values)), sd=statistics.stdev(values) if len(values) > 1 else None,
per_seed=values)
class Results:
"""The per-seed result files of setcon.evaluate."""
def __init__(self, results_dir, seeds, eval_data):
self.dir = Path(results_dir)
self.seeds = list(seeds)
self.classes = {ds: json.loads((Path(eval_data) / "protocol" / "windows" / f"{ds}.json").read_text())["classes"]
for ds in DATASETS}
self._cache = {}
def load(self, seed, reading):
key = (seed, reading)
if key not in self._cache:
f = self.dir / f"seed{seed}" / f"{reading}.npz"
with np.load(f, allow_pickle=False) as z:
self._cache[key] = {k: z[k] for k in z.files}
return self._cache[key]
def has(self, reading):
return all((self.dir / f"seed{s}" / f"{reading}.npz").exists() for s in self.seeds)
def draws(self, seed, reading, ds, text):
"""[(scored mask, predictions on the scored windows, labels of the scored windows)] per draw."""
z = self.load(seed, reading)
y = z[f"{ds}/labels"]
return [(sc, z[f"{ds}/{text}"][k][sc], y[sc]) for k, sc in enumerate(z[f"{ds}/scored"])]
def dataset_metric(self, seed, reading, ds, text, metric):
if metric == "readout":
return float(np.mean(self.load(seed, reading)[f"{ds}/class_mean_readout"]))
vals = []
for _, p, y in self.draws(seed, reading, ds, text):
vals.append(100 * np.mean(p == y) if metric == "acc" else macro_f1(p, y, len(self.classes[ds])))
return float(np.mean(vals))
def mean13(self, reading, text, metric="acc"):
return msd([np.mean([self.dataset_metric(s, reading, d, text, metric) for d in MEAN13]) for s in self.seeds])
def class_recall(self, seed, reading, ds, text="names"):
rec = {}
draws = self.draws(seed, reading, ds, text)
for c, name in enumerate(self.classes[ds]):
vals = [100 * np.mean(p[y == c] == c) for _, p, y in draws if (y == c).any()]
if vals:
rec[name] = float(np.mean(vals))
return rec
def tab3(self, reading="six_random"):
out = {}
for gname, f in TAB3_GROUPS:
per_seed = []
for s in self.seeds:
vals = [v for d in MEAN13 for c, v in self.class_recall(s, reading, d).items()
if f(GROUP_OF_CLASS[d][c], c)]
per_seed.append(float(np.mean(vals)))
out[gname] = dict(**msd(per_seed), n_classes=len(vals))
return out
def posture_shares(self, reading, text="anchors"):
"""Share (%) of the sit / stand / lie windows predicted as sit / stand / lie: 7 Mean-13 sets with >= 20
windows of each posture, draws pooled, equal mean over sets, then over the three true postures."""
fam = lambda t: next((f for f, s in POSTURE_NAMES.items() if t in s), "other") # noqa: E731
labels = {d: self.load(self.seeds[0], reading)[f"{d}/labels"] for d in MEAN13}
sets = [d for d in MEAN13 if min(int((np.array([fam(t) for t in self.classes[d]])[labels[d]] == f).sum())
for f in ("sit", "stand", "lie")) >= 20]
shares = []
for s in self.seeds:
mats = []
for d in sets:
tf = np.array([fam(t) for t in self.classes[d]])
pf = np.array([("sit", "stand", "lie", "other").index(fam(t)) for t in self.classes[d]])
M = np.zeros((3, 4))
for i, true in enumerate(("sit", "stand", "lie")):
c = np.zeros(4)
for _, p, y in self.draws(s, reading, d, text):
c += np.bincount(pf[p[tf[y] == true]], minlength=4)
M[i] = 100 * c / c.sum()
mats.append(M)
shares.append(np.mean(mats, 0)[:, :3].mean(0))
S = np.array(shares)
return dict(datasets=sets, sit=msd(S[:, 0]), stand=msd(S[:, 1]), lie=msd(S[:, 2]))
def no_gait(self):
"""Windows of devices whose six context windows hold no gait window: share of all scored windows (Mean-13)
and accuracy of the calibrator reference minus the zeroed reference on them (names)."""
sub = tot = 0
gains = []
for i, s in enumerate(self.seeds):
co = cz = n = 0
for d in MEAN13:
zo, zz = self.load(s, "six_random"), self.load(s, "zeroed")
y = zo[f"{d}/labels"]
for k in range(len(zo[f"{d}/scored"])):
sc = zo[f"{d}/scored"][k]
assert np.array_equal(sc, zz[f"{d}/scored"][k])
unk = zo[f"{d}/no_walking_frame"][k][sc]
yy = y[sc]
co += int((zo[f"{d}/names"][k][sc][unk] == yy[unk]).sum())
cz += int((zz[f"{d}/names"][k][sc][unk] == yy[unk]).sum())
n += int(unk.sum())
if i == 0:
sub += int(unk.sum())
tot += int(sc.sum())
gains.append(100 * (co - cz) / n)
return dict(share=100 * sub / tot, windows=sub, all=tot, gain=msd(gains))
def main_numbers(R: Results):
out = {}
for reading, label in (("six_random", "6 random windows"), ("six_of_twelve", "6 of 12 windows")):
out[f"Tab. 1, {label}: class-mean readout"] = R.mean13(reading, "names", "readout")
out[f"Tab. 1, {label}: accuracy, names" + (" (abstract)" if reading == "six_of_twelve" else "")] = \
R.mean13(reading, "names")
out[f"Tab. 1, {label}: accuracy, anchors" + (" (abstract, Fig. 1)" if reading == "six_of_twelve" else "")] = \
R.mean13(reading, "anchors")
out[f"Tab. 1, {label}: macro-F1, names"] = R.mean13(reading, "names", "f1")
out[f"Tab. 1, {label}: macro-F1, anchors"] = R.mean13(reading, "anchors", "f1")
return out
def more_numbers(R: Results):
out = {}
for reading, label in (("six_random", "calibrator"), ("walking_frame", "walking frame"), ("zeroed", "zeroed")):
for text in ("names", "anchors"):
out[f"Tab. 2, {label}: {text}"] = R.mean13(reading, text)
for gname, v in R.tab3().items():
out[f"Tab. 3, {gname}"] = v
out["Sec. 4.3: zeroed reference, anchors, posture windows called lying (%)"] = R.posture_shares("zeroed")["lie"]
out["Sec. 4.3: one context window, names"] = R.mean13("one_window", "names")
ng = R.no_gait()
out["Sec. 4.3: scored windows without gait context (%)"] = dict(mean=ng["share"], sd=None, per_seed=[])
out["Sec. 4.3: calibrator minus zeroed on those windows, names"] = ng["gain"]
names, anchors = R.mean13("six_random", "names"), R.mean13("six_random", "anchors")
desc, readout = R.mean13("six_random", "names_descriptions"), R.mean13("six_random", "names", "readout")
diff = lambda a, b: msd([x - y for x, y in zip(a["per_seed"], b["per_seed"])]) # noqa: E731
out["Sec. 4.4: anchor gain (anchors minus names)"] = diff(anchors, names)
out["Sec. 4.4: descriptions added to the name (gain over names)"] = diff(desc, names)
out["Sec. 4.4: class-mean readout minus names"] = diff(readout, names)
return out
def compare(numbers, paper):
"""Rows (label, printed, recomputed, per seed, match) for every number with a printed value."""
rows = []
for label, (pm, psd, dec) in paper.items():
v = numbers[label]
got = f"{v['mean']:.{dec}f}" + (f" ± {v['sd']:.{dec}f}" if psd is not None else "")
printed = f"{pm:.{dec}f}" + (f" ± {psd:.{dec}f}" if psd is not None else "")
seeds = " / ".join(f"{x:.2f}" for x in v["per_seed"])
rows.append((label, printed, got, f"{v['mean']:.3f}" + (f" ± {v['sd']:.3f}" if v["sd"] is not None else ""),
seeds, got == printed))
return rows
def format_rows(rows):
w = max(len(r[0]) for r in rows)
lines = [f"{'number':<{w}} {'paper':>12} {'recomputed':>12} {'full precision':>16} seeds 1 / 2 / 3"]
for label, printed, got, full, seeds, ok in rows:
lines.append(f"{label:<{w}} {printed:>12} {got:>12} {full:>16} {seeds} {'ok' if ok else 'differs'}")
return "\n".join(lines)
|