Download mind3d_trellis2/code/mapper/cls_compare.py from jamie33/926: direct link, hf CLI and curl.
- Browser
- Download file 3.04 kB
-
https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/cls_compare.py
- Command line
-
hf download hf://datasets/jamie33/926/mind3d_trellis2/code/mapper/cls_compare.py
-
curl -L -o cls_compare.py https://huggingface.co/datasets/jamie33/926/resolve/main/mind3d_trellis2/code/mapper/cls_compare.py
3.04 kB
| """Compare category decoders on the sub-01 test set (all from frozen fMRI features).""" | |
| import json | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from pca_tools import FEAT_DIR, load_tokens, split_ids, get_pca, project | |
| from ridge_pca import make_features | |
| O = "/home/hubin/trellis_work/outputs" | |
| def main(): | |
| train_ids, test_ids, fit_idx, val_idx = split_ids() | |
| fit_ids = [train_ids[i] for i in fit_idx] | |
| cats = sorted({i.split("/")[0] for i in train_ids}) | |
| lab = lambda ids: torch.tensor([cats.index(i.split("/")[0]) for i in ids], device="cuda") | |
| y_fit, y_test = lab(fit_ids), lab(test_ids) | |
| pca = get_pca() | |
| coef_fit = project(torch.from_numpy(load_tokens(fit_ids)).cuda(), pca, 64) | |
| cat_coef = torch.stack([coef_fit[y_fit == c].mean(0) for c in range(len(cats))]) | |
| res = {} | |
| for name in ["ridge_k64", "ridge_k64_rescaled"]: | |
| tok = torch.from_numpy(np.load(f"{O}/ridge/{name}/tokens.npy")).cuda() | |
| c = project(tok, pca, 64) | |
| res[f"{name}: nearest category centroid"] = (torch.cdist(c, cat_coef).argmin(1) == y_test).float().mean().item() | |
| sim = F.normalize(c, dim=1) @ F.normalize(coef_fit, dim=1).T | |
| for k in [1, 5, 15]: | |
| votes = F.one_hot(y_fit[sim.topk(k, 1).indices], len(cats)).sum(1) | |
| res[f"{name}: kNN-{k} vote"] = (votes.argmax(1) == y_test).float().mean().item() | |
| train_feats = np.load(f"{FEAT_DIR}/sub0001_train_feats.npy", mmap_mode="r") | |
| test_feats = np.load(f"{FEAT_DIR}/sub0001_test_feats.npy", mmap_mode="r") | |
| fit_t = torch.from_numpy(fit_idx).cuda() | |
| val_t = torch.from_numpy(val_idx).cuda() | |
| y_train = lab(train_ids) | |
| for kind in ["mean", "cls"]: | |
| x_tr = make_features(torch.from_numpy(np.ascontiguousarray(train_feats)).cuda(), kind) | |
| x_te = make_features(torch.from_numpy(np.ascontiguousarray(test_feats)).cuda(), kind) | |
| mu, sd = x_tr[fit_t].mean(0), x_tr[fit_t].std(0) + 1e-6 | |
| x_tr, x_te = (x_tr - mu) / sd, (x_te - mu) / sd | |
| best = None | |
| for wd in [1e-3, 1e-2, 1e-1, 1.0]: | |
| torch.manual_seed(0) | |
| lin = torch.nn.Linear(x_tr.shape[1], len(cats)).cuda() | |
| opt = torch.optim.AdamW(lin.parameters(), lr=1e-3, weight_decay=wd) | |
| for _ in range(300): | |
| loss = F.cross_entropy(lin(x_tr[fit_t]), y_train[fit_t]) | |
| opt.zero_grad() | |
| loss.backward() | |
| opt.step() | |
| with torch.no_grad(): | |
| va = (lin(x_tr[val_t]).argmax(1) == y_train[val_t]).float().mean().item() | |
| te = (lin(x_te).argmax(1) == y_test).float().mean().item() | |
| if best is None or va > best[0]: | |
| best = (va, te, wd) | |
| res[f"logistic ({kind} feats, wd={best[2]}): val {best[0]:.2f}"] = best[1] | |
| del x_tr, x_te | |
| torch.cuda.empty_cache() | |
| for k, v in res.items(): | |
| print(f"{v:.3f} {k}") | |
| json.dump(res, open(f"{O}/clsfirst/cls_compare.json", "w"), indent=1) | |
| if __name__ == "__main__": | |
| main() | |