Temmar et al. (2025), LINK: multi-day training (Figure 5A)¶
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 | Here |
|---|---|
| fig5a-multiday-short-term | tested on 12 day-0 sessions, 1 and 5 training sessions |
| fig5a-long-term-decay | tested on the same models |
| fig5b-finetune | blocked, too large (see the attempt record) |
Why a subset. Each LSTM takes 75 to 210 s to train when four train at once on this runner, depending on the run: 75 s in round 1 and 202 to 210 s in round 2; the cell below prints this run's times. The paper trains 5 LSTMs on each of 283 day-0 sessions, 1415 fits, 7 to 21 hours at those times with four at once, over the 60-minute limit of a notebook. The criteria of both Figure 5A claims compare only 1 and 5 training sessions, so only those two are trained, on 12 day-0 sessions spread evenly over the eligible ones, chosen before any result was seen: 24 fits.
import os, time, resource
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import multiprocessing as mp
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from scipy.optimize import curve_fit
import link
T0 = time.time()
ITERS = int(os.environ.get("LINK_DEV_ITERS", link.LSTM_ITERS)) # 2000 (paper); lowered only while developing
N_DAY0 = int(os.environ.get("LINK_DEV_NDAY0", "12")) # 12 day-0 sessions (see above)
EVAL_EVERY = 5 # score every 5th test bin (cost)
HORIZON = 180 # paper, Section 4.3: evaluated on all sessions within 180 days of day 0
A = link.assets()
counts = A.groupby("date").size()
single = A[A["date"].map(counts) == 1].reset_index(drop=True) # paper, Section 4.3: days with two sessions excluded
eligible = single.index[10:-1] # and the first 10 sessions; the last, with no later session to test on, is left out
print(f"{len(A)} sessions; on single-session days {len(single)}; eligible day-0 sessions {len(eligible)} "
f"(the Figure 5A legend reports 283 days)")
day0_idx = eligible[np.linspace(0, len(eligible) - 1, N_DAY0).round().astype(int)]
print("day-0 sessions:", [single["date"][i].date().isoformat() for i in day0_idx])
312 sessions; on single-session days 294; eligible day-0 sessions 283 (the Figure 5A legend reports 283 days) day-0 sessions: ['2020-03-02', '2020-11-05', '2021-03-22', '2021-06-08', '2021-07-28', '2021-09-14', '2022-01-24', '2022-04-11', '2022-08-01', '2022-10-12', '2023-03-10', '2023-06-21']
Load the sessions needed¶
For each day 0, its training sessions (the latest 1 or 5 single-session days up to and including day 0) and every single-session day within 180 days after it.
need = set()
for i in day0_idx:
need.update(range(i - 4, i + 1))
d0 = single["date"][i]
need.update(single.index[(single["date"] >= d0) & (single["date"] <= d0 + pd.Timedelta(days=HORIZON))])
need = sorted(need)
def load(i):
s = link.read_session(single["asset_id"][i], tcr=False)
(xtr, ytr), (xte, yte) = link.split(s)
return i, {"date": single["date"][i], "xtr": xtr, "ytr": ytr, "xte": xte, "yte": yte}
t = time.time()
with ThreadPoolExecutor(4) as ex:
SES = dict(ex.map(load, need))
print(f"loaded {len(SES)} sessions in {time.time() - t:.0f} s; peak memory "
f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
loaded 282 sessions in 335 s; peak memory 3.24 GB
L3 = pd.DataFrame([{"date": v["date"], "train_bins": len(v["xtr"]), "test_bins": len(v["xte"])} for v in SES.values()])
print("sessions loaded:", len(L3), "| by year:", L3["date"].dt.year.value_counts().sort_index().to_dict())
print("training bins %d to %d, test bins %d to %d" % (L3["train_bins"].min(), L3["train_bins"].max(), L3["test_bins"].min(), L3["test_bins"].max()))
print("SBP (stored units): %.3f to %.3f" % (min(v["xte"].min() for v in SES.values()), max(v["xte"].max() for v in SES.values())))
yk = np.vstack([v["yte"] for v in SES.values()])
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}")
sessions loaded: 282 | by year: {2020: 31, 2021: 115, 2022: 91, 2023: 45}
training bins 16632 to 27756, test bins 4093 to 7497
SBP (stored units): 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
Train and evaluate¶
The LSTM and its training are those of decoding.ipynb (Appendix C.1). For k training sessions the
training bins of the k sessions are z-scored together (one mean and SD per channel), the windows never
cross a session boundary, and the model sees 2000 batches in all. Every model is then evaluated on the
hold-out trials of each session within 180 days after day 0, with input normalisation held at the
training parameters (Appendix C.1, "For the analyses in Figure 5"; norm "train"). As the variant the
criterion names, each model is also evaluated with the normalisation refit on the test session's
training trials, as the code's multi-day trainer does (norm "test"). The code variant's other
differences (90/10 split, no noise, skipping only the first 5 sessions) would need the models retrained
and are not run.
def task(arg):
i, k = arg
t0 = time.time()
tr = [SES[j] for j in range(i - k + 1, i + 1)]
mu, sd = link.zparams(np.concatenate([s["xtr"] for s in tr]))
segs = [(((s["xtr"] - mu) / sd).astype(np.float32), s["ytr"]) for s in tr]
state, onorm = link.lstm_train(segs, seed=42, iters=ITERS)
fit_s = time.time() - t0
d0 = SES[i]["date"]
rows = []
for j, s in SES.items():
rel = (s["date"] - d0).days
if j < i or rel > HORIZON:
continue
for norm, (m_, s_) in (("train", (mu, sd)), ("test", link.zparams(s["xtr"]))):
p = link.lstm_predict(state, onorm, ((s["xte"] - m_) / s_).astype(np.float32), every=EVAL_EVERY)
rows.append({"day0": d0, "k": k, "test": s["date"], "rel": rel, "norm": norm,
"r2": link.r2_per_output(s["yte"][::EVAL_EVERY], p).mean()})
return {"rows": rows, "fit_s": fit_s, "span_days": (d0 - tr[0]["date"]).days, "k": k, "day0": d0}
t = time.time()
with ProcessPoolExecutor(4, mp_context=mp.get_context("fork")) as ex:
RES = list(ex.map(task, [(i, k) for i in day0_idx for k in (1, 5)]))
fits = np.array([r["fit_s"] for r in RES])
print(f"{len(RES)} fits in {(time.time() - t) / 60:.1f} min; seconds per fit {fits.min():.0f} to {fits.max():.0f}")
MD = pd.DataFrame([row for r in RES for row in r["rows"]])
spans = [r["span_days"] for r in RES if r["k"] == 5]
print("days spanned by the 5 training sessions: %d to %d" % (min(spans), max(spans)))
print("evaluations per model: %d to %d" % (MD.groupby(["day0", "k", "norm"]).size().min(), MD.groupby(["day0", "k", "norm"]).size().max()))
24 fits in 24.2 min; seconds per fit 191 to 197 days spanned by the 5 training sessions: 7 to 24 evaluations per model: 2 to 80
fig5a-multiday-short-term¶
Training the LSTM on up to five consecutive past sessions reduces the initial drop in performance within about 5 days of training and improves performance over time, but slightly lowers day-0 performance.
rows = []
CURVE = {}
for norm in ("train", "test"):
M_ = MD[MD["norm"] == norm]
curve = M_.groupby(["k", "rel"])["r2"].mean().unstack(0)
CURVE[norm] = curve
for k in (1, 5):
c = curve[k].dropna()
d0 = c.get(0, np.nan)
near = c.loc[1:5].mean()
rows.append({"norm": norm, "k": k, "day0 R2": d0, "mean R2 days 1-5": near, "drop": d0 - near,
"mean days 6-30": c.loc[6:30].mean(), "mean days 31-180": c.loc[31:180].mean(),
"relative days with data 1-5": int(c.loc[1:5].notna().sum())})
T = pd.DataFrame(rows)
print(T.round(4).to_string(index=False))
for norm in ("train", "test"):
a, b = T[(T["norm"] == norm) & (T["k"] == 1)].iloc[0], T[(T["norm"] == norm) & (T["k"] == 5)].iloc[0]
print(f"norm {norm}: days 1-5 higher with 5 sessions: {b['mean R2 days 1-5'] > a['mean R2 days 1-5']}; "
f"drop smaller: {b['drop'] < a['drop']}; day 0 lower: {b['day0 R2'] < a['day0 R2']}")
for norm in ("train", "test"):
per = MD[MD["norm"] == norm].pivot_table(index=["day0", "test"], columns="k", values="r2")
per["rel"] = [(t - d).days for d, t in per.index]
for lab, sel in (("day 0", per["rel"] == 0), ("days 1-5", per["rel"].between(1, 5)),
("days 6-180", per["rel"].between(6, 180))):
d = per[sel]
print(f"norm {norm}, paired, {lab}: {len(d)} evaluations, 5 sessions higher in {(d[5] > d[1]).mean():.3f}, "
f"mean difference {(d[5] - d[1]).mean():+.4f}")
per = MD[MD["norm"] == "train"].pivot_table(index=["day0", "test"], columns="k", values="r2")
per["rel"] = [(t - d).days for d, t in per.index]
print("per day 0 (day-0 R2, k=1 / k=5):")
print(per[per["rel"] == 0][[1, 5]].round(3).to_string())
norm k day0 R2 mean R2 days 1-5 drop mean days 6-30 mean days 31-180 relative days with data 1-5 train 1 0.5868 -0.5020 1.0888 -0.6077 -0.4705 5 train 5 0.5404 -0.2508 0.7913 -0.4539 -0.5919 5 test 1 0.5868 0.3719 0.2149 0.2661 0.1838 5 test 5 0.5031 0.4176 0.0855 0.3421 0.2725 5 norm train: days 1-5 higher with 5 sessions: True; drop smaller: True; day 0 lower: True norm test: days 1-5 higher with 5 sessions: True; drop smaller: True; day 0 lower: True norm train, paired, day 0: 12 evaluations, 5 sessions higher in 0.083, mean difference -0.0463 norm train, paired, days 1-5: 16 evaluations, 5 sessions higher in 0.812, mean difference +0.2682 norm train, paired, days 6-180: 474 evaluations, 5 sessions higher in 0.523, mean difference -0.0718 norm test, paired, day 0: 12 evaluations, 5 sessions higher in 0.083, mean difference -0.0837 norm test, paired, days 1-5: 16 evaluations, 5 sessions higher in 0.750, mean difference +0.0518 norm test, paired, days 6-180: 474 evaluations, 5 sessions higher in 0.869, mean difference +0.0864 per day 0 (day-0 R2, k=1 / k=5): k 1 5 day0 test 2020-03-02 2020-03-02 0.529 0.505 2020-11-05 2020-11-05 0.677 0.635 2021-03-22 2021-03-22 0.540 0.517 2021-06-08 2021-06-08 0.631 0.580 2021-07-28 2021-07-28 0.594 0.569 2021-09-14 2021-09-14 0.485 0.501 2022-01-24 2022-01-24 0.542 0.521 2022-04-11 2022-04-11 0.583 0.459 2022-08-01 2022-08-01 0.631 0.491 2022-10-12 2022-10-12 0.626 0.588 2023-03-10 2023-03-10 0.529 0.480 2023-06-21 2023-06-21 0.674 0.641
Result: reproduced, on 12 day-0 sessions, under both normalisations. With input normalisation held at the training parameters (Appendix C.1, the criterion's reading), five training sessions against one raise the mean R2 over relative days 1 to 5 from -0.502 to -0.251, shrink the drop from day 0 to those days from 1.089 to 0.791, and lower day-0 R2 from 0.587 to 0.540 (lower on 11 of 12 day-0 sessions); paired over the 16 evaluations at 1 to 5 days, five sessions are better in 81% of them. With the normalisation refit on each test session, as the code's trainer does, the same three hold: 0.372 to 0.418 at days 1 to 5, a drop of 0.215 against 0.086, and day 0 lower, 0.587 against 0.503. Under that reading R2 after day 0 is positive (mean 0.27 over days 31 to 180 with five sessions), near the values of Figure 5A; under the training-day reading it is negative.
fig5a-long-term-decay¶
Double-exponential fits to the single-session and five-session conditions over 0 to 180 days show steeper decay for single-session training; the initial decay decreases with more training sessions, but the long-term decay is not significantly affected.
def dexp(x, a, b, c, d):
return a * np.exp(b * x) + c * np.exp(d * x)
P0 = {"criterion": {1: (0.374, 0.00365, 0.134, 0.140), 5: (0.374, 0.00365, 0.134, 0.140)},
# the fitted curves printed in the Figure 5A panel (read from the figure, as the verifier reported them)
"legend": {1: (0.229, -0.183, 0.268, -0.006), 5: (0.134, -0.140, 0.374, -0.004)}}
FITS = {}
for norm in ("train", "test"):
for start in ("criterion", "legend"):
fitres = {}
for k in (1, 5):
c = CURVE[norm][k].dropna()
x = c.index.to_numpy(float)
try:
p, cov = curve_fit(dexp, x, c.to_numpy(), p0=P0[start][k], maxfev=10000)
se = np.sqrt(np.diag(cov))
fast, slow = (1, 3) if abs(p[1]) > abs(p[3]) else (3, 1)
res = c.to_numpy() - dexp(x, *p)
fitres[k] = {"params": p, "se": se, "fast": fast, "slow": slow, "drop5": dexp(0, *p) - dexp(5, *p),
"rmse": float(np.sqrt(np.mean(res ** 2)))}
print(f"norm {norm}, start {start}, k={k}: a={p[0]:.4f} b={p[1]:.4f} c={p[2]:.4f} d={p[3]:.5f}; initial rate "
f"{p[fast]:.4f} (95% {p[fast] - 1.96 * se[fast]:.4f} to {p[fast] + 1.96 * se[fast]:.4f}); long-term rate "
f"{p[slow]:.5f} (95% {p[slow] - 1.96 * se[slow]:.5f} to {p[slow] + 1.96 * se[slow]:.5f}); predicted drop "
f"day 0 to 5 {fitres[k]['drop5']:.4f}; residual RMS {fitres[k]['rmse']:.4f}; points {len(c)}")
except Exception as e:
print(f"norm {norm}, start {start}, k={k}: fit failed: {e}")
FITS[(norm, start)] = fitres
if len(fitres) == 2:
f1, f5 = fitres[1], fitres[5]
lo = lambda f, j: f["params"][j] - 1.96 * f["se"][j]
hi = lambda f, j: f["params"][j] + 1.96 * f["se"][j]
overlap = not (hi(f1, f1["slow"]) < lo(f5, f5["slow"]) or hi(f5, f5["slow"]) < lo(f1, f1["slow"]))
print(f" norm {norm}, start {start}: initial rate more negative for k=1:", f1["params"][f1["fast"]] < f5["params"][f5["fast"]],
"| larger predicted drop to day 5 for k=1:", f1["drop5"] > f5["drop5"],
"| long-term rate intervals overlap:", overlap,
"| long-term rate difference (k=1 minus k=5): %.5f" % (f1["params"][f1["slow"]] - f5["params"][f5["slow"]]))
fig, axs = plt.subplots(1, 2, figsize=(11, 3))
for ax, norm in zip(axs, ("train", "test")):
for k in (1, 5):
c = CURVE[norm][k].dropna()
ax.plot(c.index, c, ".", ms=3, label=f"{k} session(s)")
if k in FITS[(norm, "criterion")]:
xx = np.arange(0, HORIZON + 1)
ax.plot(xx, dexp(xx, *FITS[(norm, "criterion")][k]["params"]))
ax.set_title(f"normalisation: {norm} day"); ax.set_xlabel("days after day 0"); ax.set_ylabel("R2"); ax.legend()
plt.show()
for norm in ("train", "test"):
print("plotted mean R2, norm %s: %.3f to %.3f" % (norm, np.nanmin(CURVE[norm].to_numpy()), np.nanmax(CURVE[norm].to_numpy())))
norm train, start criterion, k=1: a=-0.6103 b=-0.0029 c=-0.0000 d=0.18015; initial rate 0.1802 (95% -0.4923 to 0.8526); long-term rate -0.00291 (95% -0.00576 to -0.00006); predicted drop day 0 to 5 -0.0088; residual RMS 0.3951; points 172 norm train, start criterion, k=5: a=-2.8562 b=0.0120 c=2.4955 d=0.01263; initial rate 0.0126 (95% -1.5790 to 1.6042); long-term rate 0.01198 (95% -1.47872 to 1.50268); predicted drop day 0 to 5 0.0137; residual RMS 0.6486; points 172 norm train, start criterion: initial rate more negative for k=1: False | larger predicted drop to day 5 for k=1: False | long-term rate intervals overlap: True | long-term rate difference (k=1 minus k=5): -0.01489 norm train, start legend, k=1: a=1.2610 b=-0.9059 c=-0.6557 d=-0.00326; initial rate -0.9059 (95% -2.0915 to 0.2796); long-term rate -0.00326 (95% -0.00565 to -0.00087); predicted drop day 0 to 5 1.2368; residual RMS 0.3833; points 172 norm train, start legend, k=5: a=0.6904 b=-0.1824 c=-0.5276 d=0.00104; initial rate -0.1824 (95% -0.6180 to 0.2531); long-term rate 0.00104 (95% -0.00284 to 0.00493); predicted drop day 0 to 5 0.4159; residual RMS 0.6473; points 172 norm train, start legend: initial rate more negative for k=1: True | larger predicted drop to day 5 for k=1: True | long-term rate intervals overlap: True | long-term rate difference (k=1 minus k=5): -0.00431 norm test, start criterion, k=1: a=0.2985 b=-0.0040 c=-0.0002 d=0.03379; initial rate 0.0338 (95% -0.0952 to 0.1628); long-term rate -0.00395 (95% -0.00827 to 0.00037); predicted drop day 0 to 5 0.0059; residual RMS 0.1099; points 172 norm test, start criterion, k=5: a=0.3729 b=-0.0014 c=-0.0097 d=0.01385; initial rate 0.0138 (95% -0.0720 to 0.0997); long-term rate -0.00136 (95% -0.01142 to 0.00870); predicted drop day 0 to 5 0.0032; residual RMS 0.0890; points 172 norm test, start criterion: initial rate more negative for k=1: False | larger predicted drop to day 5 for k=1: True | long-term rate intervals overlap: True | long-term rate difference (k=1 minus k=5): -0.00259 norm test, start legend, k=1: a=0.2618 b=-0.6009 c=0.2935 d=-0.00460; initial rate -0.6009 (95% -1.5275 to 0.3257); long-term rate -0.00460 (95% -0.00636 to -0.00285); predicted drop day 0 to 5 0.2555; residual RMS 0.1081; points 172 norm test, start legend, k=5: a=0.1242 b=-0.5347 c=0.3743 d=-0.00314; initial rate -0.5347 (95% -1.9089 to 0.8395); long-term rate -0.00314 (95% -0.00414 to -0.00215); predicted drop day 0 to 5 0.1215; residual RMS 0.0891; points 172 norm test, start legend: initial rate more negative for k=1: True | larger predicted drop to day 5 for k=1: True | long-term rate intervals overlap: True | long-term rate difference (k=1 minus k=5): -0.00146
plotted mean R2, norm train: -3.982 to 0.587 plotted mean R2, norm test: -0.283 to 0.587
Result: not reproduced, under the criterion's starting values; the outcome rests on them. Started from the criterion's initial values (0.374, 0.00365, 0.134, 0.140), the fits with the training day's normalisation are degenerate: for one session a component of near-zero amplitude with rate 0.180 is the "initial" one, and for five sessions two components of opposing amplitude grow. The initial rate is not more negative for one session and the predicted drop to day 5 is not larger (-0.009 against 0.014). With the test day's normalisation the initial rate is still not more negative for one session (0.034 against 0.014), though the predicted drop is larger (0.006 against 0.003). Started from the values printed in the Figure 5A panel (negative rates), the fits have lower residuals and all three conditions hold under both normalisations: training day, initial rate -0.906 against -0.182, drop to day 5 1.237 against 0.416, long-term rates -0.0033 (-0.0057 to -0.0009) and 0.0010 (-0.0028 to 0.0049), intervals overlapping; test day, -0.601 against -0.535, drop 0.256 against 0.122, long-term rates -0.0046 (-0.0064 to -0.0029) and -0.0031 (-0.0041 to -0.0022), overlapping. The initial rates are not well determined from these 12 day-0 sessions: in all four fits from the panel's values their 95% intervals include zero and overlap widely (training day -2.09 to 0.28 against -0.62 to 0.25; test day -1.53 to 0.33 against -1.91 to 0.84). The long-term intervals overlap in every fit. Residual RMS is 0.38 to 0.65 with the training day's normalisation and 0.09 to 0.11 with the test day's.
Summary¶
| Claim | Outcome |
|---|---|
| fig5a-multiday-short-term | reproduced (12 day-0 sessions, both normalisations) |
| fig5a-long-term-decay | not reproduced under the criterion's starting values; reproduced from the starting values of the Figure 5A panel |
| fig5b-finetune | blocked, too large (not in this notebook) |
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: 12 of the 283 day-0 sessions, and only 1 and 5 training sessions, for time; scored on every 5th test bin; of the code's variant of the multi-day trainer, only the refit of input normalisation on the test data is run (the 90/10 split and the training without noise are not).
What was found about the dataset: dropping the 9 two-session days, the first 10 sessions and the last session (which has no later session) leaves 283 day-0 sessions, the count in the Figure 5A legend.
print(f"notebook time {(time.time() - T0) / 60:.1f} min; peak memory {resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6:.2f} GB")
notebook time 29.8 min; peak memory 3.25 GB