setu-neural-eeg / scripts /advanced_classical.py
arushsinghal's picture
Add files using upload-large-folder tool
4fcc185 verified
Raw History Blame Contribute Delete
1.81 kB
import os
os.environ.setdefault('MPLCONFIGDIR',os.path.abspath('.cache/matplotlib'))
import numpy as np,json,joblib,time
from pathlib import Path
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from classical import features,metrics
from bci_data import cached,preprocess,montage
def run(selection="distributed"):
from controls import ranks
for n in ([64,32,16,8] if selection=="distributed" else [32,16,8]):
for s in range(1,16):
name=f'strict_svm_{selection}_{n}_sub-{s:02d}';out=Path('experiments')/(name+'.json')
if out.exists():continue
x,y,names=cached(s,'train');v,z,_=cached(s,'validation');idx=np.sort(ranks(x,y)[:n]) if selection=="trainrank" else montage(names,n,selection);a=features(preprocess(x,idx),'bandpower');b=features(preprocess(v,idx),'bandpower');best=None;search=[]
for c in [.1,1,10,100]:
for gamma in ['scale',.001,.01]:
m=make_pipeline(StandardScaler(),SVC(C=c,gamma=gamma,probability=True,random_state=2026,class_weight='balanced'));m.fit(a,y);met=metrics(z,m.predict(b));search.append({'C':c,'gamma':gamma,**met})
if best is None or met['balanced_accuracy']>best[0]:best=(met['balanced_accuracy'],m,c,gamma,met)
joblib.dump({'model':best[1],'indices':idx,'kind':'svm','names':names,'subject':s},f'checkpoints/{name}.joblib');out.write_text(json.dumps({'name':name,'model':'svm','channels':n,'montage':selection,'subject':s,'split':'validation','metrics':best[4],'C':best[2],'gamma':best[3],'search':search},indent=2));print(name,best[0],flush=True)
if __name__=='__main__':
from experiment_guard import assert_tuning_open
assert_tuning_open()
import argparse
p=argparse.ArgumentParser();p.add_argument('--montage',default='distributed');a=p.parse_args();run(a.montage)