Lecture 03 学习讲义
正文
工具
按问题查找
Lecture 03LAB 19 · 新域:捷径反转与少标签适配 · 实现代码

LAB 19 · 新域:捷径反转与少标签适配 · 实现代码

独立阅读

按问题继续

源域捷径、目标域反转、少标签适配与同预算scratch

展开完整实现代码
# Writable ephemeral workspace for detached readonly cloud runs.
import os, tempfile
os.chdir(tempfile.mkdtemp(prefix='lec03_lab22_'))

import numpy as np
def data(seed,n,environment):
    r=np.random.default_rng(seed); y=r.integers(0,2,n); sign=2*y-1
    x=np.c_[sign+r.normal(0,1.,n),environment*sign+r.normal(0,.15,n),np.ones(n)]
    return x,y
def train(x,y,w,steps,lr=.1,l2=.01):
    w=w.copy()
    for _ in range(steps):
        p=1/(1+np.exp(-np.clip(x@w,-30,30))); w-=lr*(x.T@(p-y)/len(y)+l2*np.r_[w[:2],0])
    return w
def acc(w,d): x,y=d; return float(((x@w>=0)==y).mean())
source=data(220,512,1); source_test=data(221,512,1); adapt=data(222,32,-1); target_test=data(223,512,-1)
w=train(*source,np.zeros(3),500); adapted=train(*adapt,w,150); scratch=train(*adapt,np.zeros(3),150)
print('source-trained weights stable/spurious/bias',w.round(3).tolist())
result={'source_holdout':acc(w,source_test),'target_zero_shot':acc(w,target_test),'target_adapt32':acc(adapted,target_test),'target_scratch32':acc(scratch,target_test)}
print(result); print('adaptation gain over zero-shot',round(result['target_adapt32']-result['target_zero_shot'],4),'transfer advantage vs scratch',round(result['target_adapt32']-result['target_scratch32'],4))
print('test seeds 221/223 never used by optimizer; adaptation seed222 only')