| 1 | import copy |
| 2 | import os |
| 3 | from pathlib import Path |
| 4 | |
| 5 | import matplotlib.pyplot as plt |
| 6 | import torch |
| 7 | import torch.nn.functional as F |
| 8 | from maml import X_RANGE, K, Regressor, sample_points, sample_task |
| 9 | |
| 10 | torch.manual_seed(0) |
| 11 | torch.set_num_threads(1) # 스레드 수에 따라 소수점 끝자리가 달라지지 않게 고정한다 |
| 12 | |
| 13 | print("1) 모델: 숫자 하나(x)를 받아 숫자 하나(y)를 낸다") |
| 14 | model = Regressor() |
| 15 | a, b = sample_task() |
| 16 | x_s, y_s = sample_points(a, b, K) |
| 17 | print(f" 입력 {tuple(x_s.shape)} → 출력 {tuple(model(x_s).shape)}") |
| 18 | for name, p in model.named_parameters(): |
| 19 | print(f" {name:<13} {tuple(p.shape)!s:<9} {p.numel():5,d}개") |
| 20 | print(f" {'합계':<11} {'':<9} {sum(p.numel() for p in model.parameters()):5,d}개") |
| 21 | print() |
| 22 | |
| 23 | |
| 24 | def train_on_support(model, x_s, y_s, steps, lr=0.01): |
| 25 | """보통 방식: 모델을 복사해 서포트 점 5개로 SGD를 steps 번 한다.""" |
| 26 | net = copy.deepcopy(model) |
| 27 | optimizer = torch.optim.SGD(net.parameters(), lr=lr) |
| 28 | for _ in range(steps): |
| 29 | loss = F.mse_loss(net(x_s), y_s) |
| 30 | optimizer.zero_grad() |
| 31 | loss.backward() |
| 32 | optimizer.step() |
| 33 | return net |
| 34 | |
| 35 | |
| 36 | print(f"2) 보통 방식: 무작위 초깃값에서 점 {K}개로 경사하강 (SGD, 학습률 0.01)") |
| 37 | print(f" 과제: a = {a.item():.2f}, b = {b.item():.2f}") |
| 38 | x_all, y_all = sample_points(a, b, 100) # 같은 과제의 다른 점 100개. 함수 전체를 맞췄는지 잰다 |
| 39 | print(" 걸음 점 5개의 MSE 새 점 100개의 MSE") |
| 40 | for steps in (0, 1, 5, 10): |
| 41 | net = train_on_support(model, x_s, y_s, steps) |
| 42 | with torch.no_grad(): |
| 43 | print( |
| 44 | f" {steps:4d} {F.mse_loss(net(x_s), y_s).item():10.3f} {F.mse_loss(net(x_all), y_all).item():14.3f}" |
| 45 | ) |
| 46 | print() |
| 47 | |
| 48 | print("3) 과제 200개로 평균을 내도 마찬가지다") |
| 49 | steps_list = (0, 1, 5, 10) |
| 50 | errors = torch.zeros(len(steps_list)) |
| 51 | for _ in range(200): |
| 52 | ta, tb = sample_task() |
| 53 | xs, ys = sample_points(ta, tb, K) |
| 54 | xq, yq = sample_points(ta, tb, 100) |
| 55 | for i, steps in enumerate(steps_list): |
| 56 | net = train_on_support(model, xs, ys, steps) |
| 57 | with torch.no_grad(): |
| 58 | errors[i] += F.mse_loss(net(xq), yq).item() / 200 |
| 59 | print(" 걸음 " + "".join(f"{s:8d}" for s in steps_list)) |
| 60 | print(" 새 점 100개의 MSE " + "".join(f"{e:8.3f}" for e in errors.tolist())) |
| 61 | print(" → 10걸음을 가도 오차가 줄지 않는다") |
| 62 | print() |
| 63 | |
| 64 | print("4) 그러면 오래 학습하면 되나? 같은 점 5개로 2,000걸음") |
| 65 | print(" 걸음 점 5개의 MSE 새 점 100개의 MSE") |
| 66 | nets = {} |
| 67 | for steps in (10, 100, 2000): |
| 68 | nets[steps] = train_on_support(model, x_s, y_s, steps) |
| 69 | with torch.no_grad(): |
| 70 | print( |
| 71 | f" {steps:4d} {F.mse_loss(nets[steps](x_s), y_s).item():10.3f} {F.mse_loss(nets[steps](x_all), y_all).item():14.3f}" |
| 72 | ) |
| 73 | print(" → 점 5개는 거의 정확히 지나가지만, 점이 없는 곳의 오차는 그대로 남는다") |
| 74 | |
| 75 | grid = torch.linspace(-X_RANGE, X_RANGE, 200).view(-1, 1) |
| 76 | plt.figure(figsize=(8, 4)) |
| 77 | plt.plot(grid, a * torch.sin(grid + b), "r--", label="ground truth") |
| 78 | plt.plot(x_s, y_s, "g^", markersize=9, label=f"support points (K={K})") |
| 79 | with torch.no_grad(): |
| 80 | plt.plot(grid, model(grid), ":", color="tab:blue", label="random init (0 steps)") |
| 81 | plt.plot(grid, nets[10](grid), "-.", color="tab:blue", label="10 SGD steps") |
| 82 | plt.plot(grid, nets[2000](grid), "-", color="tab:blue", label="2000 SGD steps") |
| 83 | plt.title("Ordinary training from a random init, 5 points only") |
| 84 | plt.legend(fontsize=8) |
| 85 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 86 | image_dir.mkdir(parents=True, exist_ok=True) |
| 87 | plt.savefig(image_dir / "ordinary.png", dpi=100, bbox_inches="tight") |
| 88 | print("[[image:ordinary]]") |
| 89 | print( |
| 90 | " → 점 5개만으로는 '이것이 사인 함수'라는 것을 알 수 없다. 그 지식을 초깃값에 미리 넣어 두려는 것이 MAML이다" |
| 91 | ) |