Temmar et al. (2025), LINK: same-day and cross-day decoding (Figure 4, Appendix C.1)¶
Paper: doi:10.52202/085713-4642. Dataset: DANDI:001201, version 0.261026.1912, streamed (the most recent
published version; the paper cites none, and the three published versions hold the same assets, see
signals.ipynb). Claims file: claims/temmar-2025.yaml. Code read: github.com/chesteklab/LINK_dataset at
5e1c36a.
| Claim | Tested here |
|---|---|
| fig4a-sameday-stable | RR on all 312 sessions, the LSTM on every 16th session |
| fig4a-lstm-beats-rr | on every session with an LSTM: every 16th, and the 12 with the highest RR R2 |
| fig4bc-dof-accuracy | RR on all sessions, LSTM on its sessions |
| fig4d-cross-day-decay | RR and LSTM decoders of the LSTM sessions, tested on every session within 100 days |
| suppc1-shuffle-baseline | RR on all sessions, LSTM on its sessions |
| fig2a-irregular-shifts | all days, with the R2 above |
Why a subset for the LSTM. One LSTM of the paper's size (2000 iterations, batch 64, 20 bins, 300 hidden
units) takes 77 to 223 s to train when four train at once on this runner, depending on the run: 77 s in
round 1 and 207 to 223 s in round 2; the cell below prints this run's time of each fit and its estimate for
all sessions. At those times 312 fits, four at a time, take 1.7 to 4.8 hours, over the 60-minute limit of a
notebook. The LSTM is therefore trained on every 16th session in date order (20 sessions), chosen before any result was
seen; the claims on trends and distributions over the dataset are tested on those. After round 1 of the
verification, 12 sessions are added for fig4a-lstm-beats-rr: those with the highest RR R2 not already
among the 20, where an LSTM is likeliest to fall below RR, chosen by that rule before their result. An
LSTM on the 42 other sessions from July to November 2022 is 11 more rounds of four fits, 14 to 41 minutes
at those times; at round 2's times that would take this notebook (48 minutes then) over its limit, so
the LSTM part of fig2a-irregular-shifts is also run in window.ipynb, on 24 of the 42 with the 20
every-16th sessions refit there as the reference. Ridge regression is cheap and runs on
every session.
import os, time, resource
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from concurrent.futures import ThreadPoolExecutor
from scipy import stats
import link
T0 = time.time()
SUBSET = int(os.environ.get("LINK_SUBSET", "0")) # 0 = every session; set only while developing
ITERS = int(os.environ.get("LINK_DEV_ITERS", link.LSTM_ITERS)) # 2000 (paper); lowered only while developing
LSTM_EVERY = 16 # every 16th session gets an LSTM (see above)
EVAL_EVERY = 5 # cross-day evaluations score every 5th test bin (cost; same-day uses every bin)
MAX_OFFSET = 100 # paper, Section 4.3: hold-outs within 100 days of training
A = link.assets()
if SUBSET:
A = A.iloc[np.linspace(0, len(A) - 1, SUBSET).astype(int)].reset_index(drop=True)
print(len(A), "sessions; LSTM iterations", ITERS)
312 sessions; LSTM iterations 2000
Load and fit ridge regression¶
Per session: the first 300 trials train and the remaining 75 test (Appendix C.1). SBP is z-scored per channel on the training bins. Ridge regression (alpha 0.1, intercept, 8 bins of history, 768 inputs) is fit with that normalisation (Appendix C.1) and, as a variant, on the raw SBP as the code does.
def load(i):
r = A.iloc[i]
s = link.read_session(r["asset_id"], tcr=False)
(xtr, ytr), (xte, yte) = link.split(s)
mu, sd = link.zparams(xtr)
rr = link.rr_fit(((xtr - mu) / sd).astype(np.float32), ytr)
rr_raw = link.rr_fit(xtr, ytr)
rec = {"i": i, "date": r["date"], "style": s["style"], "path": r["path"],
"n_train_bins": len(xtr), "n_test_bins": len(xte),
"n_test_trials": len(s["trials"]) - link.N_TRAIN_TRIALS,
"mu": mu, "sd": sd, "rr": rr, "rr_raw": rr_raw, "xte": xte, "yte": yte,
"sbp_mean": s["sbp"].astype(np.float64).mean(0), "n_bins": len(s["sbp"]),
"test_trial_index": s["trial_index"][link.N_TRAIN_TRIALS:] - s["trial_index"][link.N_TRAIN_TRIALS]}
rec["xtr_z"] = ((xtr - mu) / sd).astype(np.float32) # kept for every session: the extra LSTMs are chosen after the RR fits
rec["ytr"] = ytr
return rec
t = time.time()
with ThreadPoolExecutor(4) as ex:
SES = list(ex.map(load, range(len(A))))
first = A["date"].min()
for s in SES:
s["day"] = (s["date"] - first).days
print(f"loaded and fit RR on {len(SES)} sessions in {time.time() - t:.0f} s; "
f"peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
print("test trials per session:", pd.Series([s["n_test_trials"] for s in SES]).value_counts().to_dict(),
"| test bins: %d to %d" % (min(s["n_test_bins"] for s in SES), max(s["n_test_bins"] for s in SES)))
print("training bins: %d to %d" % (min(s["n_train_bins"] for s in SES), max(s["n_train_bins"] for s in SES)))
loaded and fit RR on 312 sessions in 652 s; peak memory 6.49 GB
test trials per session: {75: 312} | test bins: 4093 to 7497
training bins: 16632 to 27756
SS = pd.DataFrame([{"date": s["date"], "style": s["style"], "n_test_trials": s["n_test_trials"]} for s in SES])
print("sessions by style:", SS["style"].value_counts().to_dict(), "| by year:", SS["date"].dt.year.value_counts().sort_index().to_dict())
print("days:", SS["date"].nunique(), "| sessions with an LSTM:", sum(1 for s in SES if s["i"] % LSTM_EVERY == 0))
print("test trials per session:", SS["n_test_trials"].value_counts().to_dict())
print("hold-out SBP (stored units, microvolts): %.3f to %.3f" % (min(s["xte"].min() for s in SES), max(s["xte"].max() for s in SES)))
yk = np.vstack([s["yte"] for s in SES])
for n, a, b in zip(link.KIN_NAMES, yk.min(0), yk.max(0)):
print(f" hold-out {n}: {a:.3f} to {b:.3f}")
print("training-bin SD per channel: %.3f to %.3f (no channel constant)" % (min(s["sd"].min() for s in SES), max(s["sd"].max() for s in SES)))
sessions by style: {'CO': 156, 'RD': 156} | by year: {2020: 43, 2021: 117, 2022: 107, 2023: 45}
days: 303 | sessions with an LSTM: 20
test trials per session: {75: 312}
hold-out SBP (stored units, microvolts): 0.056 to 250.587
hold-out idx_pos: 0.000 to 1.000
hold-out mrs_pos: 0.000 to 1.000
hold-out idx_vel: -0.290 to 0.448
hold-out mrs_vel: -0.407 to 0.341
training-bin SD per channel: 0.137 to 14.173 (no channel constant)
def z(x, mu, sd):
return ((x - mu) / sd).astype(np.float32)
for s in SES:
s["r2_rr"] = link.r2_per_output(s["yte"], link.rr_predict(s["rr"], z(s["xte"], s["mu"], s["sd"])))
s["r2_rr_raw"] = link.r2_per_output(s["yte"], link.rr_predict(s["rr_raw"], s["xte"]))
print("same-day RR R2 (mean of 4 outputs): median %.3f, range %.3f to %.3f" %
(np.median([s["r2_rr"].mean() for s in SES]), min(s["r2_rr"].mean() for s in SES), max(s["r2_rr"].mean() for s in SES)))
same-day RR R2 (mean of 4 outputs): median 0.296, range 0.127 to 0.467
Train the LSTMs¶
Each LSTM is trained as Appendix C.1 and the claim's criterion give (96 inputs, 300 hidden units, one layer, linear readout of the four outputs at the last of 20 bins; Adam, batch 64, 2000 iterations, learning rate linear from 2e-4 to 1e-5, weight decay 0.001; outputs z-scored on the training data; white noise of SD 0.1 per bin and a bias of SD 0.2 per sequence and channel), seed 42 as in the code. Each worker then evaluates its decoder on its own hold-out, on the shuffled hold-out (suppc1), and on the hold-out of every session within 100 days under both normalisations of fig4d (every 5th bin).
LSTM_IDX = [s["i"] for s in SES if s["i"] % LSTM_EVERY == 0]
TEST = {s["i"]: (s["day"], s["xte"], s["yte"], s["mu"], s["sd"]) for s in SES}
def shuffles(x_raw, y, mu, sd, tti, rng):
"""The hold-out shuffles of suppc1-shuffle-baseline: (a) permute the raw bins of SBP, then build the
history; (b) permute whole input windows; and (trials) permute whole trials; kinematics are permuted
separately in each case."""
n = len(y)
pa, pk = rng.permutation(n), rng.permutation(n)
out = {"a": (x_raw[pa], y[pk], None)}
out["b"] = (x_raw, y[pk], rng.permutation(n)) # window permutation applied to the predictions
bounds = np.append(tti, n)
tr = [np.arange(bounds[j], bounds[j + 1]) for j in range(len(tti))]
o1 = np.concatenate([tr[j] for j in rng.permutation(len(tr))])
o2 = np.concatenate([tr[j] for j in rng.permutation(len(tr))])
out["trials"] = (x_raw[o1], y[o2], None)
return out
def lstm_task(i, seed=42, cross=True):
t0 = time.time()
s = SES_BY_I[i]
state, onorm = link.lstm_train([(s["xtr_z"], s["ytr"])], seed=seed, iters=ITERS)
fit_s = time.time() - t0
res = {"i": i, "seed": seed, "fit_s": fit_s}
p = link.lstm_predict(state, onorm, z(s["xte"], s["mu"], s["sd"]))
res["r2"] = link.r2_per_output(s["yte"], p)
if not cross:
return res
rng = np.random.default_rng(0)
sh = {}
for k, (xs, ys, perm) in shuffles(s["xte"], s["yte"], s["mu"], s["sd"], s["test_trial_index"], rng).items():
pr = link.lstm_predict(state, onorm, z(xs, s["mu"], s["sd"]))
if perm is not None:
pr = pr[perm]
sh[k] = link.r2_per_output(ys, pr).mean()
res["shuffle"] = sh
cr = []
for j, (day, xte, yte, mu, sd) in TEST.items():
off = day - s["day"]
if abs(off) > MAX_OFFSET:
continue
sel = slice(None, None, EVAL_EVERY)
for norm, (m_, s_) in (("train", (s["mu"], s["sd"])), ("test", (mu, sd))):
pr = link.lstm_predict(state, onorm, z(xte, m_, s_), every=EVAL_EVERY)
cr.append({"dec": i, "test": j, "offset": off, "norm": norm, "decoder": "LSTM",
"r2": link.r2_per_output(yte[sel], pr).mean()})
res["cross"] = cr
res["total_s"] = time.time() - t0
return res
SES_BY_I = {s["i"]: s for s in SES}
import multiprocessing as mp
from concurrent.futures import ProcessPoolExecutor
t = time.time()
with ProcessPoolExecutor(4, mp_context=mp.get_context("fork")) as ex:
LRES = list(ex.map(lstm_task, LSTM_IDX))
fits = np.array([r["fit_s"] for r in LRES])
print(f"{len(LRES)} LSTMs in {(time.time() - t) / 60:.1f} min; seconds per fit {fits.min():.0f} to {fits.max():.0f} "
f"(median {np.median(fits):.0f}); estimate for all {len(SES)} sessions at 4 in parallel: "
f"{len(SES) * np.median(fits) / 4 / 3600:.1f} h of fitting alone")
for r in LRES:
SES_BY_I[r["i"]]["r2_lstm"] = r["r2"]
20 LSTMs in 22.7 min; seconds per fit 192 to 208 (median 196); estimate for all 312 sessions at 4 in parallel: 4.2 h of fitting alone
Further LSTMs¶
Same training, on the 12 sessions with the highest RR same-day R2 that are not among the 20. They are scored on their own hold-out only (no shuffles or cross-day tests).
rr_rank = sorted((s for s in SES if s["i"] not in set(LSTM_IDX)), key=lambda s: -s["r2_rr"].mean())
TOP_IDX = [s["i"] for s in rr_rank[:12]]
WIN_IDX = [s["i"] for s in SES if pd.Timestamp("2022-07-01") <= s["date"] <= pd.Timestamp("2022-11-30") and s["i"] not in set(LSTM_IDX)]
EXTRA_IDX = sorted(TOP_IDX)
t = time.time()
with ProcessPoolExecutor(4, mp_context=mp.get_context("fork")) as ex:
XRES = list(ex.map(lstm_task, EXTRA_IDX, [42] * len(EXTRA_IDX), [False] * len(EXTRA_IDX)))
for r in XRES:
SES_BY_I[r["i"]]["r2_lstm"] = r["r2"]
xf = np.array([r["fit_s"] for r in XRES])
print(f"{len(XRES)} further LSTMs on the highest-RR sessions ({len(set(TOP_IDX) & set(WIN_IDX))} of them in July to November 2022) "
f"in {(time.time() - t) / 60:.1f} min; seconds per fit {xf.min():.0f} to {xf.max():.0f}")
print("RR R2 of the 12 highest-RR sessions: %.3f to %.3f" % (min(SES_BY_I[i]["r2_rr"].mean() for i in TOP_IDX), max(SES_BY_I[i]["r2_rr"].mean() for i in TOP_IDX)))
12 further LSTMs on the highest-RR sessions (3 of them in July to November 2022) in 10.0 min; seconds per fit 192 to 201 RR R2 of the 12 highest-RR sessions: 0.390 to 0.467
fig4a-sameday-stable¶
Same-day decoding accuracy (R2 averaged across the four outputs on the 75 hold-out trials) remains relatively stable over the dataset, with most shifts shared by RR and LSTM.
SD = pd.DataFrame([{"i": s["i"], "date": s["date"], "day": s["day"], "style": s["style"],
"rr": s["r2_rr"].mean(), "rr_raw": s["r2_rr_raw"].mean(),
"lstm": s["r2_lstm"].mean() if "r2_lstm" in s else np.nan,
**{f"rr_{n}": v for n, v in zip(link.KIN_NAMES, s["r2_rr"])},
**{f"lstm_{n}": v for n, v in zip(link.KIN_NAMES, s.get("r2_lstm", [np.nan] * 4))}} for s in SES])
SD["set"] = ["every 16th" if i in set(LSTM_IDX) else ("highest RR" if i in set(TOP_IDX) else "") for i in SD["i"]]
SD["window"] = SD["i"].isin(WIN_IDX) | (SD["date"].between("2022-07-01", "2022-11-30") & SD["i"].isin(LSTM_IDX))
LALL = SD.dropna(subset=["lstm"])
L = LALL[LALL["i"].isin(LSTM_IDX)]
for name, d, col in (("RR, all sessions", SD, "rr"), ("RR without scaler (code), all sessions", SD, "rr_raw"),
("RR, LSTM sessions", L, "rr"), ("LSTM", L, "lstm")):
r = link.linfit(d["day"], d[col])
print(f"{name}: n = {len(d)}, median R2 {d[col].median():.3f} (range {d[col].min():.3f} to {d[col].max():.3f}), "
f"slope {r.slope * 365.25:+.4f} per year, p = {r.pvalue:.2g}")
pc = stats.pearsonr(L["rr"], L["lstm"])
print(f"Pearson r between RR and LSTM same-day R2 over {len(L)} sessions: {pc.statistic:.3f}, p = {pc.pvalue:.2g}")
pc2 = stats.pearsonr(LALL["rr"], LALL["lstm"])
print(f"variant, every session with an LSTM (n = {len(LALL)}, not a sample of the dataset: it adds the 12 highest-RR "
f"sessions): Pearson r {pc2.statistic:.3f}, p = {pc2.pvalue:.2g}")
print("by year (median R2):")
print(SD.groupby(SD["date"].dt.year)[["rr", "rr_raw", "lstm"]].median().round(3).to_string())
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(SD["date"], SD["rr"], ".", ms=3, label="RR")
ax.plot(L["date"], L["lstm"], "o", ms=4, label="LSTM")
ax.set_ylabel("same-day R2"); ax.legend(); plt.show()
print("plotted R2 range: %.3f to %.3f" % (min(SD["rr"].min(), L["lstm"].min()), max(SD["rr"].max(), L["lstm"].max())))
RR, all sessions: n = 312, median R2 0.296 (range 0.127 to 0.467), slope +0.0020 per year, p = 0.58
RR without scaler (code), all sessions: n = 312, median R2 0.294 (range 0.127 to 0.466), slope +0.0019 per year, p = 0.58
RR, LSTM sessions: n = 20, median R2 0.290 (range 0.211 to 0.400), slope -0.0165 per year, p = 0.11
LSTM: n = 20, median R2 0.591 (range 0.514 to 0.666), slope +0.0064 per year, p = 0.56
Pearson r between RR and LSTM same-day R2 over 20 sessions: 0.582, p = 0.007
variant, every session with an LSTM (n = 32, not a sample of the dataset: it adds the 12 highest-RR sessions): Pearson r 0.807, p = 2.4e-08
by year (median R2):
rr rr_raw lstm
date
2020 0.302 0.300 0.609
2021 0.290 0.288 0.606
2022 0.305 0.300 0.652
2023 0.299 0.299 0.635
plotted R2 range: 0.127 to 0.666
Result: reproduced, with the LSTM on 20 of 312 sessions. Same-day R2 shows no decline: the RR slope over all 312 sessions is +0.0020 per year (p = 0.58) and the LSTM slope over its 20 every-16th sessions +0.0064 per year (p = 0.56). The two decoders' R2 correlate across those 20 sessions (Pearson r = 0.582, p = 0.007); over all 32 sessions with an LSTM, which add the 12 highest-RR sessions and so are not a sample of the dataset, r = 0.807 (p = 2.4e-08). RR without input normalisation, as the code fits it, gives the same slope (+0.0019 per year, p = 0.58). Median R2 is 0.296 for RR and 0.591 for the LSTM. The by-year LSTM medians include the 12 added sessions.
fig4a-lstm-beats-rr¶
The LSTM outperformed ridge regression in same-day decoding on every day.
LB = LALL.assign(diff=LALL["lstm"] - LALL["rr"])
for lab, d in (("every 16th", LB[LB["i"].isin(LSTM_IDX)]), ("12 highest RR", LB[LB["i"].isin(TOP_IDX)]),
("of these, in July-November 2022", LB[LB["i"].isin(WIN_IDX)])):
print(f"{lab}: {len(d)} sessions, LSTM above RR on {(d['diff'] > 0).sum()}, difference {d['diff'].min():.3f} to {d['diff'].max():.3f}")
worse = LB[LB["diff"] <= 0]
print(f"LSTM above RR on {(LB['diff'] > 0).sum()} of {len(LB)} sessions ({(LB['diff'] > 0).mean():.3f}); "
f"difference median {LB['diff'].median():.3f}, range {LB['diff'].min():.3f} to {LB['diff'].max():.3f}")
print("highest RR R2 among the sessions with an LSTM: %.3f; highest over all 312: %.3f" % (LB["rr"].max(), SD["rr"].max()))
print("sessions where RR is not below the LSTM:", worse[["date", "style", "rr", "lstm"]].to_dict("records"))
if len(worse):
with ProcessPoolExecutor(4, mp_context=mp.get_context("fork")) as ex:
extra = list(ex.map(lstm_task, [i for i in worse["i"] for _ in (1, 2)],
[sd_ for _ in worse["i"] for sd_ in (1, 2)], [False] * (2 * len(worse))))
for r in extra:
print(f" session {SES_BY_I[r['i']]['date'].date()} seed {r['seed']}: LSTM R2 {r['r2'].mean():.3f} "
f"(RR {SES_BY_I[r['i']]['r2_rr'].mean():.3f})")
every 16th: 20 sessions, LSTM above RR on 20, difference 0.223 to 0.385 12 highest RR: 12 sessions, LSTM above RR on 12, difference 0.182 to 0.300 of these, in July-November 2022: 3 sessions, LSTM above RR on 3, difference 0.260 to 0.272 LSTM above RR on 32 of 32 sessions (1.000); difference median 0.288, range 0.182 to 0.385 highest RR R2 among the sessions with an LSTM: 0.467; highest over all 312: 0.467 sessions where RR is not below the LSTM: []
Result: reproduced on the 32 sessions tested. The LSTM's same-day R2 is above RR's on 20 of 20 every-16th sessions (by 0.223 to 0.385) and on all 12 sessions with the highest RR R2 outside them (RR 0.390 to 0.467, LSTM higher by 0.182 to 0.300), 32 of 32 in all, so no session needed the extra seeds. The 12 include the session with the highest RR R2 of all 312 (0.467). The other 280 sessions were not tested with the LSTM.
fig4bc-dof-accuracy¶
Decoding of finger positions is more accurate than of velocities, and MRS predictions are more accurate than IDX predictions.
for dec, d in (("rr", SD), ("rr (LSTM sessions)", L), ("lstm", L)):
p = dec.split()[0]
med = {n: d[f"{p}_{n}"].median() for n in link.KIN_NAMES}
pos_gt_vel = min(med["idx_pos"], med["mrs_pos"]) > max(med["idx_vel"], med["mrs_vel"])
mrs_gt = med["mrs_pos"] > med["idx_pos"] and med["mrs_vel"] > med["idx_vel"]
f_pos = ((d[f"{p}_idx_pos"] > d[f"{p}_idx_vel"]) & (d[f"{p}_mrs_pos"] > d[f"{p}_mrs_vel"])).mean()
f_mrs = ((d[f"{p}_mrs_pos"] > d[f"{p}_idx_pos"]) & (d[f"{p}_mrs_vel"] > d[f"{p}_idx_vel"])).mean()
print(f"{dec} (n = {len(d)}): medians " + ", ".join(f"{n} {v:.3f}" for n, v in med.items()))
print(f" positions above velocities: {pos_gt_vel}; MRS above IDX for position and velocity: {mrs_gt}; "
f"fraction of sessions with position > velocity for both fingers {f_pos:.3f}, MRS > IDX for both {f_mrs:.3f}")
rr (n = 312): medians idx_pos 0.316, mrs_pos 0.362, idx_vel 0.220, mrs_vel 0.286 positions above velocities: True; MRS above IDX for position and velocity: True; fraction of sessions with position > velocity for both fingers 0.628, MRS > IDX for both 0.506 rr (LSTM sessions) (n = 20): medians idx_pos 0.300, mrs_pos 0.379, idx_vel 0.202, mrs_vel 0.285 positions above velocities: True; MRS above IDX for position and velocity: True; fraction of sessions with position > velocity for both fingers 0.650, MRS > IDX for both 0.600 lstm (n = 20): medians idx_pos 0.645, mrs_pos 0.663, idx_vel 0.480, mrs_vel 0.576 positions above velocities: True; MRS above IDX for position and velocity: True; fraction of sessions with position > velocity for both fingers 0.750, MRS > IDX for both 0.600
Result: reproduced. For RR (312 sessions) the median R2 is 0.316 and 0.362 for IDX and MRS position against 0.220 and 0.286 for velocity; for the LSTM (20 sessions) 0.645 and 0.663 against 0.480 and 0.576. Both orderings hold for both decoders. Per session the orderings hold less often: position above velocity for both fingers in 62.8% (RR) and 75.0% (LSTM) of sessions, MRS above IDX for both in 50.6% and 60.0%.
fig4d-cross-day-decay¶
Decoders tested on hold-out sets of other days within 100 days of training lose accuracy sharply in the short term, with the decay stabilising at longer offsets; neither RR nor LSTM generalises well, the LSTM is better at every offset, and both follow a similar decay.
The decoders are those of the LSTM sessions, for both RR and LSTM, so the two curves come from the same training days; each is tested on every session within 100 days, scored on every 5th test bin. Readings: offset (a) signed or (b) absolute; normalisation (i) the training day's or (ii) the test day's own training-trial parameters.
rr_rows = []
for s in [SES_BY_I[i] for i in LSTM_IDX]:
for j, (day, xte, yte, mu, sd) in TEST.items():
off = day - s["day"]
if abs(off) > MAX_OFFSET:
continue
for norm, (m_, s_) in (("train", (s["mu"], s["sd"])), ("test", (mu, sd))):
pr = link.rr_predict(s["rr"], z(xte, m_, s_))
rr_rows.append({"dec": s["i"], "test": j, "offset": off, "norm": norm, "decoder": "RR",
"r2": link.r2_per_output(yte[::EVAL_EVERY], pr[::EVAL_EVERY]).mean()})
CR = pd.concat([pd.DataFrame(rr_rows), pd.DataFrame([c for r in LRES for c in r["cross"]])], ignore_index=True)
CR["subset"] = CR["dec"].isin(LSTM_IDX)
print("evaluations:", CR.groupby(["decoder", "norm"]).size().to_dict())
evaluations: {('LSTM', 'test'): 1088, ('LSTM', 'train'): 1088, ('RR', 'test'): 1088, ('RR', 'train'): 1088}
def curve(d, absolute):
off = d["offset"].abs() if absolute else d["offset"]
return d.groupby(off)["r2"].agg(["mean", "sem", "size"])
summary = []
for absolute in (False, True):
for norm in ("train", "test"):
c_l = curve(CR[(CR["decoder"] == "LSTM") & (CR["norm"] == norm)], absolute)
c_r = curve(CR[(CR["decoder"] == "RR") & CR["subset"] & (CR["norm"] == norm)], absolute)
both = c_l.add_suffix("_l").join(c_r.add_suffix("_r"), how="inner")
better = (both["mean_l"] > both["mean_r"]).mean()
res = {}
for lab, c in (("LSTM", c_l), ("RR", c_r)):
m = c["mean"]
o = m.index.to_series()
d0 = m.get(0, np.nan)
near = m[(o.abs() >= 1) & (o.abs() <= 5)].mean()
far = m[(o.abs() >= 90) & (o.abs() <= 100)].mean()
res[lab] = (d0, near, far)
sharp = all(res[k][0] - res[k][1] > res[k][1] - res[k][2] for k in res)
rcorr = stats.pearsonr(both["mean_l"] / res["LSTM"][0], both["mean_r"] / res["RR"][0]).statistic
summary.append({"offset": "absolute" if absolute else "signed", "norm": norm, "offsets": len(both),
"LSTM better at fraction": round(better, 3),
"LSTM day0 / 1-5 / 90-100": "%.3f / %.3f / %.3f" % res["LSTM"],
"RR day0 / 1-5 / 90-100": "%.3f / %.3f / %.3f" % res["RR"],
"sharp then stable": sharp, "r(normalised curves)": round(rcorr, 3)})
print(pd.DataFrame(summary).to_string(index=False))
print("evaluations per offset (LSTM, signed): median %d, offsets with data %d of 201" % (
curve(CR[(CR["decoder"] == "LSTM") & (CR["norm"] == "train")], False)["size"].median(),
len(curve(CR[(CR["decoder"] == "LSTM") & (CR["norm"] == "train")], False))))
fig, ax = plt.subplots(figsize=(7, 3))
for lab in ("LSTM", "RR"):
c = curve(CR[(CR["decoder"] == lab) & CR["subset"] & (CR["norm"] == "train")], False)
ax.plot(c.index, c["mean"], ".-", ms=3, label=lab)
ax.set_xlabel("test day minus training day"); ax.set_ylabel("R2"); ax.legend(); plt.show()
c = CR[CR["subset"] & (CR["norm"] == "train")]
print("plotted per-offset means: %.3f to %.3f (no point outside the axes; axes auto-scaled)" % (
c.groupby(["decoder", "offset"])["r2"].mean().min(), c.groupby(["decoder", "offset"])["r2"].mean().max()))
offset norm offsets LSTM better at fraction LSTM day0 / 1-5 / 90-100 RR day0 / 1-5 / 90-100 sharp then stable r(normalised curves) signed train 199 1.0 0.585 / -0.528 / -0.805 0.293 / -13.397 / -17.851 True 0.526 signed test 199 1.0 0.583 / 0.393 / 0.183 0.294 / 0.113 / -0.006 False 0.887 absolute train 101 1.0 0.585 / -0.622 / -0.816 0.293 / -16.742 / -16.116 True 0.391 absolute test 101 1.0 0.583 / 0.376 / 0.186 0.294 / 0.088 / -0.005 True 0.903 evaluations per offset (LSTM, signed): median 5, offsets with data 199 of 201
plotted per-offset means: -436.570 to 0.585 (no point outside the axes; axes auto-scaled)
Result: reproduced, under the readings of absolute offset and test-day normalisation. For the 20 decoders of each type, each tested on every session within 100 days, the LSTM's mean R2 is above RR's at all 101 absolute offsets. The LSTM falls from 0.583 on day 0 to 0.376 at 1 to 5 days and 0.186 at 90 to 100 days, and RR from 0.294 to 0.088 and -0.005, so both drop more in the first five days than over the next 85 to 95. The two curves, each divided by its day-0 value, correlate with r = 0.903. Under the other readings the LSTM is also better at every offset, but the shapes correlate less (r = 0.887 signed with test-day normalisation, 0.526 and 0.391 with the training day's normalisation). With the training day's normalisation RR's mean R2 over the 1-to-5-day and 90-to-100-day offsets is -13.4 to -17.9, and single offsets reach a mean of -436.6, and the signed test-day curves do not meet the sharp-then-stable part. So the outcome rests on the readings named.
suppc1-shuffle-baseline¶
With neural and behavioural hold-out data shuffled independently on one session, RR gives an average R2 of -0.166 and the LSTM of -0.156.
rows = []
for s in SES:
rng = np.random.default_rng(0)
for k, (xs, ys, perm) in shuffles(s["xte"], s["yte"], s["mu"], s["sd"], s["test_trial_index"], rng).items():
pr = link.rr_predict(s["rr"], z(xs, s["mu"], s["sd"]))
if perm is not None:
pr = pr[perm]
rows.append({"i": s["i"], "reading": k, "decoder": "RR", "r2": link.r2_per_output(ys, pr).mean()})
for r in LRES:
for k, v in r["shuffle"].items():
rows.append({"i": r["i"], "reading": k, "decoder": "LSTM", "r2": v})
SH = pd.DataFrame(rows)
SH["lstm_session"] = SH["i"].isin(LSTM_IDX)
print(SH.groupby(["decoder", "reading"])["r2"].describe()[["count", "50%", "min", "max"]].round(4).to_string())
print("RR on the LSTM sessions only:")
print(SH[SH["lstm_session"] & (SH["decoder"] == "RR")].groupby("reading")["r2"].median().round(4).to_string())
W = SH[SH["lstm_session"]].pivot_table(index="i", columns=["decoder", "reading"], values="r2")
tol = {"RR": (-0.166, 0.0166), "LSTM": (-0.156, 0.0156)}
for rd in ("a", "b", "trials"):
inr = {d: (W[(d, rd)] - tol[d][0]).abs() <= tol[d][1] for d in tol}
print(f"reading {rd}: of the {len(W)} LSTM sessions, RR within tolerance on {int(inr['RR'].sum())}, LSTM on "
f"{int(inr['LSTM'].sum())}, both on {int((inr['RR'] & inr['LSTM']).sum())}")
rra = SH[(SH["decoder"] == "RR") & (SH["reading"] == "a")]["r2"]
print("RR, reading (a), all %d sessions: within tolerance on %d (%.3f)" % (len(rra), ((rra + 0.166).abs() <= 0.0166).sum(), ((rra + 0.166).abs() <= 0.0166).mean()))
count 50% min max
decoder reading
LSTM a 20.0 -0.1540 -0.2418 -0.1187
b 20.0 -0.5963 -0.7112 -0.4906
trials 20.0 -0.5333 -0.6802 -0.4400
RR a 312.0 -0.2230 -0.3632 -0.1487
b 312.0 -0.4103 -0.6052 -0.2646
trials 312.0 -0.4093 -0.6070 -0.2260
RR on the LSTM sessions only:
reading
a -0.2114
b -0.3832
trials -0.3709
reading a: of the 20 LSTM sessions, RR within tolerance on 1, LSTM on 8, both on 1
reading b: of the 20 LSTM sessions, RR within tolerance on 0, LSTM on 0, both on 0
reading trials: of the 20 LSTM sessions, RR within tolerance on 0, LSTM on 0, both on 0
RR, reading (a), all 312 sessions: within tolerance on 33 (0.106)
Result: partially reproduced. Shuffled hold-out data give negative R2 for both decoders under every reading. Under reading (a), raw bins permuted, the LSTM's median over its 20 sessions is -0.154, within the tolerance of -0.156, but RR's median over 312 sessions is -0.223, outside the tolerance of -0.166 +- 0.0166. Single sessions can match: RR is within tolerance on 33 of 312 sessions (0.106), and of the 20 LSTM sessions RR is within tolerance on 1, the LSTM on 8, and both on 1. Under reading (b), whole windows permuted, the medians are -0.410 (RR) and -0.596 (LSTM), and whole trials give -0.409 and -0.533; no LSTM session has either value within tolerance under those readings.
fig2a-irregular-shifts¶
Groups of channels show irregular SBP shifts in some periods, for example from about July to November 2022, and these shifts did not affect overall decoding performance.
The LSTM part is run on more window sessions in window.ipynb.
day_mean = {}
for s in SES:
a = day_mean.setdefault(s["date"], [np.zeros(96), 0])
a[0] += s["sbp_mean"] * s["n_bins"]; a[1] += s["n_bins"]
DM = pd.DataFrame({d: v[0] / v[1] for d, v in day_mean.items()}).T.sort_index()
def shift_counts(by_sessions):
out = []
for n, d in enumerate(DM.index):
if by_sessions:
win = DM.iloc[max(0, n - 30):n] # variant: the preceding 30 recording days
else:
win = DM[(DM.index < d) & (DM.index >= d - pd.Timedelta(days=30))]
if len(win) < 3:
out.append(np.nan); continue
med = win.median(); mad = (win - med).abs().median()
out.append(int(((DM.loc[d] - med).abs() > 3 * mad.where(mad > 0, np.nan)).sum()))
return pd.Series(out, index=DM.index)
SHF = shift_counts(False)
inwin = (SHF.index >= "2022-07-01") & (SHF.index <= "2022-11-30")
print("days in July to November 2022:", inwin.sum(), "| max channels shifting on one day there:", SHF[inwin].max(),
"| days with >= 5:", int((SHF[inwin] >= 5).sum()))
print("outside that window: days with >= 5 shifting channels: %d of %d (max %s)" % (
(SHF[~inwin] >= 5).sum(), SHF[~inwin].notna().sum(), SHF[~inwin].max()))
print("days with >= 5 shifting channels by year:", SHF[SHF >= 5].groupby(SHF[SHF >= 5].index.year).size().to_dict())
for lab, S_ in (("30 calendar days (main)", SHF), ("variant, 30 preceding recording days", shift_counts(True))):
iw = (S_.index >= "2022-07-01") & (S_.index <= "2022-11-30")
print(f"{lab}: shifting channels per day, median {S_[iw].median():.1f} in the window against {S_[~iw].median():.1f} outside; "
f"days with >= 5: {(S_[iw] >= 5).sum() / S_[iw].notna().sum():.3f} of window days, {(S_[~iw] >= 5).sum() / S_[~iw].notna().sum():.3f} of other days; "
f"days with >= 20: {(S_[iw] >= 20).sum() / S_[iw].notna().sum():.3f} and {(S_[~iw] >= 20).sum() / S_[~iw].notna().sum():.3f}")
print("shifting channels per day by quarter (median):", {str(k): v for k, v in SHF.groupby(SHF.index.to_period("Q")).median().items()})
wsel = SD["date"].between("2022-07-01", "2022-11-30")
lo, hi = np.percentile(SD["rr"], [10, 90])
print(f"rr: sessions in window {wsel.sum()}, median R2 there {SD.loc[wsel, 'rr'].median():.3f}; "
f"10th to 90th percentile over all {len(SD)} sessions {lo:.3f} to {hi:.3f}")
ev = SD[SD["i"].isin(LSTM_IDX)]
lo, hi = np.percentile(ev["lstm"], [10, 90])
lw = SD[wsel].dropna(subset=["lstm"])
print(f"lstm: sessions in window with an LSTM {len(lw)} of {wsel.sum()}, median R2 there {lw['lstm'].median():.3f}; "
f"10th to 90th percentile over the {len(ev)} every-16th sessions (the sample of all sessions) {lo:.3f} to {hi:.3f}")
lw3 = lw[lw["i"].isin(LSTM_IDX)]
print(f" as in round 1, the {len(lw3)} window sessions among the every-16th: median {lw3['lstm'].median():.3f}")
lo2, hi2 = np.percentile(LALL["lstm"], [10, 90])
print(f" variant, percentiles over every session with an LSTM (n = {len(LALL)}): {lo2:.3f} to {hi2:.3f}")
print(f" LSTM minus RR in the window: median {(lw['lstm'] - lw['rr']).median():.3f}; over the every-16th sessions {(ev['lstm'] - ev['rr']).median():.3f}")
days in July to November 2022: 42 | max channels shifting on one day there: 66.0 | days with >= 5: 38
outside that window: days with >= 5 shifting channels: 237 of 243 (max 83.0)
days with >= 5 shifting channels by year: {2020: 35, 2021: 108, 2022: 90, 2023: 42}
30 calendar days (main): shifting channels per day, median 17.0 in the window against 20.0 outside; days with >= 5: 0.974 of window days, 0.975 of other days; days with >= 20: 0.462 and 0.531
variant, 30 preceding recording days: shifting channels per day, median 13.0 in the window against 12.0 outside; days with >= 5: 0.952 of window days, 0.903 of other days; days with >= 20: 0.357 and 0.213
shifting channels per day by quarter (median): {'2020Q1': 26.0, '2020Q2': nan, '2020Q3': 33.0, '2020Q4': 31.0, '2021Q1': 26.5, '2021Q2': 18.0, '2021Q3': 15.0, '2021Q4': 21.0, '2022Q1': 30.0, '2022Q2': 18.0, '2022Q3': 18.0, '2022Q4': 14.0, '2023Q1': 20.0, '2023Q2': 22.0}
rr: sessions in window 45, median R2 there 0.321; 10th to 90th percentile over all 312 sessions 0.220 to 0.360
lstm: sessions in window with an LSTM 6 of 45, median R2 there 0.659; 10th to 90th percentile over the 20 every-16th sessions (the sample of all sessions) 0.529 to 0.651
as in round 1, the 3 window sessions among the every-16th: median 0.652
variant, percentiles over every session with an LSTM (n = 32): 0.560 to 0.693
LSTM minus RR in the window: median 0.287; over the every-16th sessions 0.301
Result: reproduced, with the LSTM part from window.ipynb. By the criterion's rule, 38 of 42 days from July to November 2022 have five or more channels shifting on the same day (up to 66), so the shift part holds. The rule does not single out that period: 0.974 of the window's days and 0.975 of the other days with a 30-day baseline have five or more, and the median count is 17 in the window against 20 outside; with the 30 preceding recording days as the baseline, 0.952 against 0.903 and 13 against 12. Decoding in the window: RR's median same-day R2 there (0.321, 45 sessions) is inside the 10th to 90th percentile range of all sessions (0.220 to 0.360). The LSTM's median over the 3 window sessions among the every-16th is 0.652, just above the 90th percentile of the 20 every-16th sessions (0.651), so on these 3 sessions alone that part would fail, in the direction of better decoding. With the 3 window sessions among the 12 highest-RR sessions added, a selection biased towards high R2, the median is 0.659. The LSTM's margin over RR in the window (median 0.287) is close to its margin over the every-16th sessions (0.301). Over all 32 sessions with an LSTM, a set that is not a sample of the dataset, the 10th to 90th percentile range is 0.560 to 0.693, which would contain 0.652. window.ipynb runs the LSTM part on 27 window sessions, where the median (0.641) is inside the range, so both parts of the criterion hold. The outcome was partially reproduced after round 2; the third verification round agreed with the change to reproduced. The pass is narrow (0.010 below the 90th percentile, 18 window sessions unfitted), and the shift part holds on almost every day, so the criterion's rule does not pick out the period; this is asked of a reader.
Summary¶
| Claim | Outcome |
|---|---|
| fig4a-sameday-stable | reproduced (LSTM on 20 sessions) |
| fig4a-lstm-beats-rr | reproduced on the 32 sessions tested |
| fig4bc-dof-accuracy | reproduced |
| fig4d-cross-day-decay | reproduced under one pair of readings |
| suppc1-shuffle-baseline | partially reproduced |
| fig2a-irregular-shifts | reproduced, with the LSTM part from window.ipynb |
A failure to reproduce here may be a failure of this attempt, not of the paper: see the reasoning and the differences from the paper's method.
How the analysis differs from the paper's: the LSTM is trained on 20 of the 312 sessions (every 16th), and on the 12 other sessions with the highest RR R2 for fig4a-lstm-beats-rr, for time; cross-day R2 is scored on every 5th test bin; the cross-day curves use the decoders of those 20 sessions for both RR and the LSTM; the LSTM's noise is 0.1 white and 0.2 bias as the Methods state, while the code passes them the other way round; the test set is the 75 trials after the first 300, to the end of the file.
What was found about the dataset: every session has 375 trials, so the 300/75 split is exact; same-day decoding is stable across the 3.5 years.
print(f"notebook time {(time.time() - T0) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
notebook time 44.2 min; peak memory 6.49 GB