| 1 | import os |
| 2 | from pathlib import Path |
| 3 | |
| 4 | import matplotlib.pyplot as plt |
| 5 | import torch |
| 6 | from maml import X_RANGE, K, sample_points, sample_task |
| 7 | |
| 8 | torch.manual_seed(0) |
| 9 | torch.set_num_threads(1) # 스레드 수에 따라 소수점 끝자리가 달라지지 않게 고정한다 |
| 10 | |
| 11 | print("1) 과제 하나 = (진폭 a, 위상 b) 한 쌍: sample_task()") |
| 12 | tasks = [sample_task() for _ in range(5)] |
| 13 | for i, (a, b) in enumerate(tasks): |
| 14 | print( |
| 15 | f" 과제 {i}: a = {a.item():.3f}, b = {b.item():.3f} → y = {a.item():.3f}·sin(x + {b.item():.3f})" |
| 16 | ) |
| 17 | many = [sample_task() for _ in range(10000)] |
| 18 | a_all = torch.cat([a for a, _ in many]) |
| 19 | b_all = torch.cat([b for _, b in many]) |
| 20 | print( |
| 21 | f" 10,000개를 뽑아 보면 a 는 {a_all.min():.2f} ~ {a_all.max():.2f}, b 는 {b_all.min():.2f} ~ {b_all.max():.2f} (π = 3.14)" |
| 22 | ) |
| 23 | print() |
| 24 | |
| 25 | print(f"2) 과제에서 점 {K}개 받기: sample_points(a, b, K)") |
| 26 | a, b = tasks[0] |
| 27 | x, y = sample_points(a, b, K) |
| 28 | print( |
| 29 | f" x: {tuple(x.shape)}, y: {tuple(y.shape)} ← (점 개수, 1). nn.Linear(1, ...) 에 바로 넣을 수 있는 모양" |
| 30 | ) |
| 31 | print(" x y a·sin(x + b)") |
| 32 | for xi, yi in zip(x.flatten(), y.flatten()): |
| 33 | print(f" {xi.item():7.3f} {yi.item():7.3f} {(a * torch.sin(xi + b)).item():7.3f}") |
| 34 | print( |
| 35 | f" x 는 -{X_RANGE:.0f} ~ {X_RANGE:.0f} 에서 무작위로 뽑는다. 모델이 받는 것은 이 x, y 뿐이다. a 와 b 는 알려 주지 않는다" |
| 36 | ) |
| 37 | print() |
| 38 | |
| 39 | print("3) 같은 과제에서 한 번 더 부르면 다른 점이 나온다") |
| 40 | x2, _ = sample_points(a, b, K) |
| 41 | print(" 첫 번째 x:", " ".join(f"{v:6.2f}" for v in x.flatten().tolist())) |
| 42 | print(" 두 번째 x:", " ".join(f"{v:6.2f}" for v in x2.flatten().tolist())) |
| 43 | print(" → 6단계에서 첫 묶음을 '서포트', 두 번째 묶음을 '쿼리'로 쓴다") |
| 44 | print() |
| 45 | |
| 46 | print(f"4) 과제 5개와 과제마다 받는 점 {K}개") |
| 47 | grid = torch.linspace(-X_RANGE, X_RANGE, 200) |
| 48 | plt.figure(figsize=(8, 4)) |
| 49 | for i, (a, b) in enumerate(tasks): |
| 50 | x, y = sample_points(a, b, K) |
| 51 | plt.plot( |
| 52 | grid, |
| 53 | a * torch.sin(grid + b), |
| 54 | color=f"C{i}", |
| 55 | alpha=0.6, |
| 56 | label=f"a={a.item():.1f}, b={b.item():.1f}", |
| 57 | ) |
| 58 | plt.plot(x, y, "o", color=f"C{i}") |
| 59 | plt.title(f"5 tasks: y = a sin(x + b), {K} points each") |
| 60 | plt.xlabel("x") |
| 61 | plt.ylabel("y") |
| 62 | plt.legend(fontsize=8, ncol=5, loc="upper center", bbox_to_anchor=(0.5, -0.16)) |
| 63 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 64 | image_dir.mkdir(parents=True, exist_ok=True) |
| 65 | plt.savefig(image_dir / "tasks.png", dpi=100, bbox_inches="tight") |
| 66 | print("[[image:tasks]]") |
| 67 | print(" → 곡선은 정답이고, 모델에게 주어지는 것은 같은 색 점 5개뿐이다") |