"""Fine-tune all BERT parameters for SMS spam classification. No test-based selection.""" import argparse, csv, hashlib, json, pathlib, random, time import numpy as np import torch from torch.utils.data import DataLoader, Dataset from transformers import AutoTokenizer, AutoModelForSequenceClassification from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix ROOT=pathlib.Path(__file__).resolve().parents[1] def scores(y,p): return {'accuracy':accuracy_score(y,p),'macro_f1':f1_score(y,p,average='macro',zero_division=0), 'spam_precision':precision_score(y,p,zero_division=0),'spam_recall':recall_score(y,p,zero_division=0), 'spam_f1':f1_score(y,p,zero_division=0),'confusion_matrix':confusion_matrix(y,p,labels=[0,1]).tolist()} class SMS(Dataset): def __init__(self,rows,tok):self.rows=rows;self.tok=tok def __len__(self):return len(self.rows) def __getitem__(self,i): text,y=self.rows[i] out=self.tok(text,truncation=True,padding='max_length',max_length=96,return_tensors='pt') return {**{k:v.squeeze(0) for k,v in out.items()},'labels':torch.tensor(y)} def evaluate(model,loader,device): model.eval(); ys=[]; ps=[]; probs=[] with torch.inference_mode(): for batch in loader: ys.extend(batch.pop('labels').tolist()) prob=model(**{k:v.to(device) for k,v in batch.items()}).logits.softmax(-1).cpu() ps.extend(prob.argmax(-1).tolist());probs.extend(prob[:,1].tolist()) return scores(ys,ps),ps,probs def main(): ap=argparse.ArgumentParser();ap.add_argument('--model',default=str(ROOT.parent/'.作业缓存/bert-tiny'));ap.add_argument('--epochs',type=int,default=4) args=ap.parse_args(); seed=42 random.seed(seed);np.random.seed(seed);torch.manual_seed(seed);torch.cuda.manual_seed_all(seed);torch.set_num_threads(4) device='cuda' if torch.cuda.is_available() else 'cpu' raw=(ROOT/'data/SMSSpamCollection').read_text(encoding='utf-8').splitlines();groups={} for line in raw: label,text=line.split('\t',1);groups.setdefault(text.strip(),set()).add(int(label=='spam')) rows=sorted((t,next(iter(labels))) for t,labels in groups.items() if len(labels)==1) train,rest=train_test_split(rows,test_size=.30,stratify=[r[1] for r in rows],random_state=seed) val,test=train_test_split(rest,test_size=.50,stratify=[r[1] for r in rest],random_state=seed) split_stats={} for name,data in [('train',train),('validation',val),('test',test)]: with (ROOT/f'data/{name}.csv').open('w',encoding='utf-8',newline='') as f: w=csv.writer(f);w.writerow(['text','label']);w.writerows(data) split_stats[name]={'size':len(data),'spam':sum(y for _,y in data),'ham':sum(y==0 for _,y in data)} tok=AutoTokenizer.from_pretrained(args.model) model=AutoModelForSequenceClassification.from_pretrained(args.model,num_labels=2,id2label={0:'ham',1:'spam'},label2id={'ham':0,'spam':1}).to(device) trainloader=DataLoader(SMS(train,tok),batch_size=32,shuffle=True,generator=torch.Generator().manual_seed(seed)) valloader=DataLoader(SMS(val,tok),batch_size=64);testloader=DataLoader(SMS(test,tok),batch_size=64) before,_,_=evaluate(model,testloader,device) opt=torch.optim.AdamW(model.parameters(),lr=5e-5,weight_decay=.01) best=-1; history=[];start=time.time() out=ROOT/'space/model';out.mkdir(parents=True,exist_ok=True) for epoch in range(args.epochs): model.train();total=0;count=0 for batch in trainloader: opt.zero_grad(set_to_none=True) loss=model(**{k:v.to(device) for k,v in batch.items()}).loss loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),1.0);opt.step() total+=loss.item()*len(batch['labels']);count+=len(batch['labels']) metric,_,_=evaluate(model,valloader,device) entry={'epoch':epoch+1,'train_loss':total/count,'validation':metric};history.append(entry);print(json.dumps(entry),flush=True) if metric['macro_f1']>best: best=metric['macro_f1'];best_epoch=epoch+1;model.save_pretrained(out);tok.save_pretrained(out) model=AutoModelForSequenceClassification.from_pretrained(out).to(device) final,ps,probs=evaluate(model,testloader,device) with (ROOT/'results/tuning_predictions.csv').open('w',encoding='utf-8',newline='') as f: w=csv.writer(f);w.writerow(['text','gold','prediction','spam_probability']) w.writerows((t,y,p,prob) for (t,y),p,prob in zip(test,ps,probs)) result={'seed':seed,'device':device,'torch':torch.__version__,'base_model':args.model,'dataset':'UCI SMS Spam Collection', 'raw_rows':len(raw),'unique_unambiguous_rows':len(rows),'split':split_stats,'parameters':sum(p.numel() for p in model.parameters()), 'hyperparameters':{'lr':5e-5,'batch_size':32,'max_length':96,'epochs':args.epochs,'optimizer':'AdamW','weight_decay':.01}, 'random_head_before_finetuning':before,'majority_baseline':scores([y for _,y in test],[0]*len(test)), 'history':history,'selected_epoch':best_epoch,'test':final,'seconds':time.time()-start, 'weights_sha256':hashlib.sha256((out/'model.safetensors').read_bytes()).hexdigest()} (ROOT/'results/tuning_metrics.json').write_text(json.dumps(result,indent=2,ensure_ascii=False),encoding='utf-8') print('TEST',json.dumps(final),flush=True) if __name__=='__main__':main()