"""4장 실습: 딥러닝과 PyTorch 기초.

이 파일 하나로 4장에서 다루는 것을 차례로 돌려 본다.

  1. numpy 로 직접 미분해서 하는 경사 하강 (선형 회귀)         → figures/ch04-linreg.png
  2. 텐서 · 모양(shape) · 브로드캐스팅
  3. 2층 신경망 역전파 손계산 ↔ PyTorch autograd 비교
  4. MLP 로 sin 곡선 맞추기 (학습 고리 5단계)                  → figures/ch04-mlp-sin.png
  5. 과적합 보기 (훈련 손실 ↓, 검증 손실 ↑)                     → figures/ch04-overfit.png
  6. 합성곱 출력 크기 확인
  7. 작은 CNN 으로 진자 그림에서 각도 읽기 (그림 → 숫자)         → figures/ch04-cnn-pendulum.png

실행:
    python ch04_basics.py            # 전체 (노트북 CPU 4스레드에서 약 3~6분)
    python ch04_basics.py --quick    # 축소판 (약 10초)
같은 폴더에 wm_envs.py 가 있어야 한다.
"""

from __future__ import annotations

import argparse
import os
import time

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn

from wm_envs import PixelPendulum


def pick_device() -> str:
    if torch.cuda.is_available():
        return "cuda"
    if torch.backends.mps.is_available():
        return "mps"
    return "cpu"


# ─────────────────────────────────────────────────────────────
# 1. numpy 로 하는 경사 하강: 선형 회귀
# ─────────────────────────────────────────────────────────────

# --8<-- [start:linreg_gd]
def linreg_gradient_descent(x, y, lr=0.05, steps=2000, verbose_steps=3):
    """ŷ = w·x + b 를 MSE 로 맞춘다. 기울기는 손으로 유도한 식을 그대로 쓴다.

    L  = (1/N) Σ (w·x_i + b − y_i)²
    ∂L/∂w = (2/N) Σ (w·x_i + b − y_i)·x_i
    ∂L/∂b = (2/N) Σ (w·x_i + b − y_i)
    """
    w, b = 0.0, 0.0  # 시작점: 아무것도 모르는 상태
    n = len(x)
    history = []  # (w, b, loss)
    for step in range(steps + 1):
        y_hat = w * x + b  # 예측 (N,)
        err = y_hat - y  # 잔차 (N,)
        loss = np.mean(err**2)  # MSE
        history.append((w, b, loss))
        if step < verbose_steps:
            dw = 2.0 / n * np.sum(err * x)
            db = 2.0 / n * np.sum(err)
            print(f"  step {step}: w={w:.4f} b={b:.4f} loss={loss:.4f}  dL/dw={dw:.4f} dL/db={db:.4f}")
        if step == steps:
            break
        dw = 2.0 / n * np.sum(err * x)  # ∂L/∂w
        db = 2.0 / n * np.sum(err)  # ∂L/∂b
        w = w - lr * dw  # 기울기 반대 방향으로 한 스텝
        b = b - lr * db
    return w, b, np.array(history)
# --8<-- [end:linreg_gd]


def part1_linreg(args):
    print("\n[1] numpy 경사 하강: 선형 회귀")
    # --8<-- [start:linreg_data]
    x = np.array([1.0, 2.0, 3.0])
    y = np.array([3.0, 5.0, 7.0])  # 정답 규칙: y = 2x + 1
    w, b, hist = linreg_gradient_descent(x, y, lr=0.05, steps=2000)
    print(f"  2000 스텝 뒤: w={w:.4f}, b={b:.4f}, loss={hist[-1, 2]:.2e}")
    # --8<-- [end:linreg_data]

    # 학습률에 따라 어떻게 달라지는지
    curves = {}
    for lr in [0.01, 0.05, 0.17, 0.19]:
        _, _, h = linreg_gradient_descent(x, y, lr=lr, steps=200, verbose_steps=0)
        curves[lr] = h[:, 2]
        print(f"  lr={lr:<5} 200 스텝 뒤 loss={h[-1, 2]:.3e}")

    fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
    ax = axes[0]
    ax.scatter(x, y, color="k", zorder=3, label="data")
    xs = np.linspace(0, 4, 50)
    for step, c in [(0, "#bbbbbb"), (1, "#9ecae1"), (2, "#4292c6"), (10, "#2171b5"), (2000, "#d94801")]:
        ww, bb, _ = hist[step]
        ax.plot(xs, ww * xs + bb, color=c, label=f"step {step}: y={ww:.2f}x+{bb:.2f}")
    ax.set_xlabel("x")
    ax.set_ylabel("y")
    ax.set_title("Gradient descent fits the line")
    ax.legend(fontsize=8)
    ax = axes[1]
    for lr, c in zip(curves, ["#9ecae1", "#2171b5", "#31a354", "#d94801"]):
        label = f"lr={lr}" + (" (diverges, clipped at 1e6)" if curves[lr][-1] > 1e6 else "")
        ax.semilogy(np.clip(curves[lr], 1e-12, 1e6), color=c, label=label)
    ax.set_xlabel("step")
    ax.set_ylabel("MSE loss (log scale)")
    ax.set_title("Effect of the learning rate")
    ax.legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(os.path.join(args.fig_dir, "ch04-linreg.png"), dpi=110)
    plt.close(fig)


# ─────────────────────────────────────────────────────────────
# 2. 텐서 · 모양 · 브로드캐스팅
# ─────────────────────────────────────────────────────────────

def part2_tensors(args):
    print("\n[2] 텐서 · 모양 · 브로드캐스팅")
    # --8<-- [start:tensors]
    a = torch.tensor([[1.0, 2.0, 3.0],
                      [4.0, 5.0, 6.0]])      # 모양 (2, 3): 2행 3열
    print("a.shape        :", tuple(a.shape))
    print("a[1, 2]        :", a[1, 2].item())   # 2번째 행, 3번째 열 (0부터 센다)
    print("a.sum(dim=0)   :", a.sum(dim=0).tolist())  # 행 방향으로 더하기 → (3,)
    print("a.mean(dim=1)  :", a.mean(dim=1).tolist())  # 열 방향으로 평균 → (2,)

    b = torch.tensor([10.0, 20.0, 30.0])     # 모양 (3,)
    print("a + b          :", (a + b).tolist())  # b 가 각 행에 '퍼져서' 더해진다

    c = torch.tensor([[100.0], [200.0]])     # 모양 (2, 1)
    print("a + c          :", (a + c).tolist())  # c 가 각 열에 퍼진다

    W = torch.randn(4, 3)                    # (출력 4, 입력 3) 가중치
    x = torch.randn(5, 3)                    # 데이터 5개, 각각 3차원
    print("(x @ W.T).shape:", tuple((x @ W.T).shape))  # (5, 4): 데이터마다 4차원 출력
    print("x.reshape(15).shape:", tuple(x.reshape(15).shape))
    print("x.unsqueeze(0).shape:", tuple(x.unsqueeze(0).shape))  # 맨 앞에 크기 1 축 추가
    # --8<-- [end:tensors]


# ─────────────────────────────────────────────────────────────
# 3. 2층 신경망: 손계산 역전파 ↔ autograd
# ─────────────────────────────────────────────────────────────

def sigmoid(z):
    return 1.0 / (1.0 + np.exp(-z))


def part3_backprop(args):
    print("\n[3] 2층 신경망 역전파: 손계산 vs autograd")
    # --8<-- [start:two_layer_manual]
    # 본문의 손계산과 똑같은 숫자
    x = np.array([1.0, 0.5])                 # 입력 (2,)
    W1 = np.array([[0.5, -0.4],
                   [0.3, 0.8]])              # 1층 가중치 (은닉 2, 입력 2)
    b1 = np.array([0.1, -0.2])               # 1층 편향 (2,)
    w2 = np.array([1.2, -0.7])               # 2층 가중치 (2,)
    b2 = 0.05                                # 2층 편향
    y = 1.0                                  # 정답

    # 순전파
    z = W1 @ x + b1                          # (2,)  z_j = Σ_i W1[j,i]·x_i + b1[j]
    h = sigmoid(z)                           # (2,)
    y_hat = w2 @ h + b2                      # 스칼라
    L = (y_hat - y) ** 2

    # 역전파 (연쇄 법칙을 뒤에서부터)
    dL_dyhat = 2 * (y_hat - y)
    dL_dw2 = dL_dyhat * h                    # ŷ = w2·h + b2 → ∂ŷ/∂w2 = h
    dL_db2 = dL_dyhat
    dL_dh = dL_dyhat * w2                    # ∂ŷ/∂h = w2
    dL_dz = dL_dh * h * (1 - h)              # σ'(z) = σ(z)(1 − σ(z))
    dL_dW1 = np.outer(dL_dz, x)              # ∂z_j/∂W1[j,i] = x_i
    dL_db1 = dL_dz

    print(f"  z={z}, h={np.round(h, 6)}, y_hat={y_hat:.6f}, L={L:.6f}")
    print("  [손계산] dL/dw2 =", np.round(dL_dw2, 6), " dL/db2 =", round(dL_db2, 6))
    print("  [손계산] dL/dW1 =", np.round(dL_dW1, 6).tolist(), " dL/db1 =", np.round(dL_db1, 6))
    # --8<-- [end:two_layer_manual]

    # --8<-- [start:two_layer_autograd]
    tx = torch.tensor(x)
    tW1 = torch.tensor(W1, requires_grad=True)   # requires_grad=True: 이 값에 대한 기울기를 구해 줘
    tb1 = torch.tensor(b1, requires_grad=True)
    tw2 = torch.tensor(w2, requires_grad=True)
    tb2 = torch.tensor(b2, requires_grad=True)

    t_yhat = tw2 @ torch.sigmoid(tW1 @ tx + tb1) + tb2   # 순전파만 쓰면
    t_L = (t_yhat - y) ** 2
    t_L.backward()                                       # 역전파는 PyTorch 가 알아서

    print("  [autograd] dL/dw2 =", np.round(tw2.grad.numpy(), 6), " dL/db2 =", round(tb2.grad.item(), 6))
    print("  [autograd] dL/dW1 =", np.round(tW1.grad.numpy(), 6).tolist(), " dL/db1 =", np.round(tb1.grad.numpy(), 6))
    same = np.allclose(tW1.grad.numpy(), dL_dW1) and np.allclose(tw2.grad.numpy(), dL_dw2)
    print("  두 결과가 같은가?", same)
    # --8<-- [end:two_layer_autograd]


# ─────────────────────────────────────────────────────────────
# 4. MLP 로 sin 곡선 맞추기
# ─────────────────────────────────────────────────────────────

# --8<-- [start:mlp_model]
class MLP(nn.Module):
    """입력 1개 → 은닉 64 → 은닉 64 → 출력 1개. 은닉층 활성 함수는 tanh."""

    def __init__(self, in_dim=1, hidden=64, out_dim=1, act=nn.Tanh):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, hidden), act(),
            nn.Linear(hidden, hidden), act(),
            nn.Linear(hidden, out_dim),
        )

    def forward(self, x):  # x: (N, in_dim)
        return self.net(x)  # (N, out_dim)
# --8<-- [end:mlp_model]


def part4_mlp(args, device):
    print("\n[4] MLP 로 sin 곡선 맞추기")
    g = torch.Generator().manual_seed(args.seed)
    # --8<-- [start:mlp_data]
    n = 256
    x_train = torch.rand(n, 1, generator=g) * 2 * np.pi - np.pi      # [-π, π] 에서 고르게
    y_train = torch.sin(x_train) + 0.05 * torch.randn(n, 1, generator=g)
    x_val = torch.rand(n, 1, generator=g) * 2 * np.pi - np.pi
    y_val = torch.sin(x_val) + 0.05 * torch.randn(n, 1, generator=g)
    x_train, y_train, x_val, y_val = (t.to(device) for t in (x_train, y_train, x_val, y_val))
    # --8<-- [end:mlp_data]

    torch.manual_seed(args.seed)
    steps = 300 if args.quick else 2000
    snapshots = {0: None, 100: None, 300: None, steps: None}
    xs = torch.linspace(-np.pi, np.pi, 200).unsqueeze(1).to(device)
    # --8<-- [start:train_loop]
    model = MLP().to(device)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
    loss_fn = nn.MSELoss()

    train_curve, val_curve = [], []
    for step in range(steps + 1):
        # (기록) 지금 모델로 그린 곡선을 몇 번 저장해 둔다
        if step in snapshots:
            with torch.no_grad():
                snapshots[step] = model(xs).cpu().numpy()
        if step == steps:
            break
        optimizer.zero_grad()              # ① 지난 스텝의 기울기를 지운다
        y_hat = model(x_train)             # ② 순전파: 예측
        loss = loss_fn(y_hat, y_train)     # ③ 손실 계산
        loss.backward()                    # ④ 역전파: 모든 매개변수의 기울기
        optimizer.step()                   # ⑤ 매개변수 갱신
        with torch.no_grad():              # 검증 손실: 기울기는 필요 없다
            val_loss = loss_fn(model(x_val), y_val)
        train_curve.append(loss.item())
        val_curve.append(val_loss.item())
        if step % 500 == 0 or step == steps - 1:
            print(f"  step {step:4d}  train {loss.item():.5f}  val {val_loss.item():.5f}")
    # --8<-- [end:train_loop]
    n_params = sum(p.numel() for p in model.parameters())
    print(f"  매개변수 개수: {n_params}")

    fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
    ax = axes[0]
    ax.scatter(x_train.cpu(), y_train.cpu(), s=6, color="#999999", label="train data")
    for (s, pred), c in zip(snapshots.items(), ["#cccccc", "#9ecae1", "#4292c6", "#d94801"]):
        ax.plot(xs.cpu(), pred, color=c, lw=2, label=f"step {s}")
    ax.set_title("MLP fitting sin(x)")
    ax.set_xlabel("x")
    ax.legend(fontsize=8)
    ax = axes[1]
    ax.semilogy(train_curve, color="#2171b5", label="train")
    ax.semilogy(val_curve, color="#d94801", label="validation", alpha=0.8)
    ax.set_xlabel("step")
    ax.set_ylabel("MSE (log scale)")
    ax.set_title("Loss curves")
    ax.legend(fontsize=8)
    fig.tight_layout()
    fig.savefig(os.path.join(args.fig_dir, "ch04-mlp-sin.png"), dpi=110)
    plt.close(fig)


# ─────────────────────────────────────────────────────────────
# 5. 과적합
# ─────────────────────────────────────────────────────────────

def part5_overfit(args, device):
    print("\n[5] 과적합: 데이터 12개에 큰 신경망")
    g = torch.Generator().manual_seed(args.seed + 1)
    # --8<-- [start:overfit]
    x_train = torch.rand(12, 1, generator=g) * 2 * np.pi - np.pi       # 데이터가 12개뿐
    y_train = torch.sin(x_train) + 0.3 * torch.randn(12, 1, generator=g)  # 잡음도 크다
    x_val = torch.linspace(-np.pi, np.pi, 200).unsqueeze(1)
    y_val = torch.sin(x_val) + 0.3 * torch.randn(200, 1, generator=g)

    results = {}
    for name, lam in [("no regularization", 0.0), ("L2 penalty 1e-2", 1e-2)]:
        torch.manual_seed(args.seed)
        model = MLP(hidden=256, act=nn.ReLU).to(device)   # 매개변수 약 6.6만 개 vs 데이터 12개
        opt = torch.optim.Adam(model.parameters(), lr=1e-3)
        tr, va = [], []
        for step in range(500 if args.quick else 4000):
            opt.zero_grad()
            mse = ((model(x_train.to(device)) - y_train.to(device)) ** 2).mean()
            # L2 정규화: 가중치 제곱합에 벌점 λ·Σw² 를 더해 '큰 가중치' 를 싫어하게 만든다
            l2 = sum((p**2).sum() for n, p in model.named_parameters() if "weight" in n)
            (mse + lam * l2).backward()
            opt.step()
            with torch.no_grad():
                vloss = ((model(x_val.to(device)) - y_val.to(device)) ** 2).mean()
            tr.append(mse.item())
            va.append(vloss.item())
        best = int(np.argmin(va))
        print(f"  {name:18s}: 마지막 train {tr[-1]:.4f}  마지막 val {va[-1]:.4f}  (val 최저 {va[best]:.4f} @ step {best})")
        with torch.no_grad():
            results[name] = (tr, va, model(x_val.to(device)).cpu().numpy())
    # --8<-- [end:overfit]

    fig, axes = plt.subplots(1, 2, figsize=(10, 3.8))
    ax = axes[0]
    ax.plot(x_val, torch.sin(x_val), color="k", lw=1, ls="--", label="true sin(x)")
    ax.scatter(x_train, y_train, color="k", zorder=3, label="12 train points")
    for (name, (_, _, pred)), c in zip(results.items(), ["#d94801", "#2171b5"]):
        ax.plot(x_val, pred, color=c, lw=2, label=name)
    ax.set_title("Overfitting: the model memorizes noise")
    ax.legend(fontsize=8)
    ax = axes[1]
    for (name, (tr, va, _)), c in zip(results.items(), ["#d94801", "#2171b5"]):
        ax.semilogy(tr, color=c, lw=1, alpha=0.6, label=f"train ({name})")
        ax.semilogy(va, color=c, lw=2, label=f"val ({name})")
    ax.set_xlabel("step")
    ax.set_ylabel("MSE (log scale)")
    ax.set_title("Train loss keeps falling, val loss rises")
    ax.legend(fontsize=7)
    fig.tight_layout()
    fig.savefig(os.path.join(args.fig_dir, "ch04-overfit.png"), dpi=110)
    plt.close(fig)


# ─────────────────────────────────────────────────────────────
# 6. 합성곱 출력 크기
# ─────────────────────────────────────────────────────────────

def part6_conv_shapes(args):
    print("\n[6] 합성곱 · 전치 합성곱 출력 크기")
    # --8<-- [start:conv_shapes]
    x = torch.zeros(1, 1, 64, 64)  # (배치 B, 채널 C, 높이 H, 너비 W)
    conv = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=4, stride=2, padding=1)
    print("Conv2d(k=4, s=2, p=1)        :", tuple(x.shape), "→", tuple(conv(x).shape))  # 64 → 32
    conv3 = nn.Conv2d(1, 8, kernel_size=3, stride=1, padding=1)
    print("Conv2d(k=3, s=1, p=1)        :", tuple(x.shape), "→", tuple(conv3(x).shape))  # 크기 유지
    conv5 = nn.Conv2d(1, 8, kernel_size=5, stride=1, padding=0)
    print("Conv2d(k=5, s=1, p=0)        :", tuple(x.shape), "→", tuple(conv5(x).shape))  # 64 → 60

    z = torch.zeros(1, 64, 4, 4)
    deconv = nn.ConvTranspose2d(64, 32, kernel_size=4, stride=2, padding=1)
    print("ConvTranspose2d(k=4, s=2, p=1):", tuple(z.shape), "→", tuple(deconv(z).shape))  # 4 → 8
    # --8<-- [end:conv_shapes]


# ─────────────────────────────────────────────────────────────
# 7. 작은 CNN: 진자 그림 → (cos θ, sin θ)
# ─────────────────────────────────────────────────────────────

# --8<-- [start:cnn_data]
def collect_frames(n_episodes, seed):
    """무작위 행동으로 진자를 돌리며 (그림, [cos θ, sin θ]) 쌍을 모은다."""
    env = PixelPendulum(seed=seed)
    rng = np.random.default_rng(seed)
    images, targets = [], []
    for _ in range(n_episodes):
        img = env.reset()
        done = False
        while not done:
            images.append(img)
            targets.append(env.state()[:2])  # 정답 [cos θ, sin θ] (학습의 '라벨')
            img, _, done = env.step(rng.uniform(-2, 2, size=1))
    x = torch.tensor(np.stack(images), dtype=torch.float32).unsqueeze(1) / 255.0  # (N, 1, 64, 64), 0~1
    y = torch.tensor(np.stack(targets), dtype=torch.float32)  # (N, 2)
    return x, y
# --8<-- [end:cnn_data]


# --8<-- [start:cnn_model]
class AngleCNN(nn.Module):
    """64×64 흑백 그림 → [cos θ, sin θ]. 8장 VAE 인코더의 축소판이다."""

    def __init__(self):
        super().__init__()
        self.features = nn.Sequential(
            nn.Conv2d(1, 16, 4, stride=2, padding=1), nn.ReLU(),   # (B, 16, 32, 32)
            nn.Conv2d(16, 32, 4, stride=2, padding=1), nn.ReLU(),  # (B, 32, 16, 16)
            nn.Conv2d(32, 64, 4, stride=2, padding=1), nn.ReLU(),  # (B, 64, 8, 8)
            nn.Conv2d(64, 64, 4, stride=2, padding=1), nn.ReLU(),  # (B, 64, 4, 4)
        )
        self.head = nn.Sequential(
            nn.Flatten(),                                          # (B, 1024)
            nn.Linear(64 * 4 * 4, 128), nn.ReLU(),
            nn.Linear(128, 2),                                     # (B, 2)
        )

    def forward(self, img):  # img: (B, 1, 64, 64)
        return self.head(self.features(img))
# --8<-- [end:cnn_model]


def part7_cnn(args, device):
    print("\n[7] 작은 CNN: 진자 그림 → (cos θ, sin θ)")
    t0 = time.time()
    x_train, y_train = collect_frames(8 if args.quick else 30, seed=args.seed)
    x_val, y_val = collect_frames(2 if args.quick else 10, seed=args.seed + 100)
    print(f"  훈련 그림 {len(x_train)}장, 검증 그림 {len(x_val)}장 (모으는 데 {time.time() - t0:.1f}초)")

    torch.manual_seed(args.seed)
    steps = 300 if args.quick else 3000
    # --8<-- [start:cnn_train]
    model = AngleCNN().to(device)
    opt = torch.optim.Adam(model.parameters(), lr=1e-3)
    x_val_d, y_val_d = x_val.to(device), y_val.to(device)
    for step in range(steps + 1):
        idx = torch.randint(0, len(x_train), (64,))          # 미니배치 64장을 무작위로
        xb, yb = x_train[idx].to(device), y_train[idx].to(device)
        loss = ((model(xb) - yb) ** 2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
        if step % 500 == 0:
            with torch.no_grad():
                val = ((model(x_val_d) - y_val_d) ** 2).mean().item()
            print(f"  step {step:4d}  train {loss.item():.5f}  val {val:.5f}")
    # --8<-- [end:cnn_train]
    print(f"  수집 + 학습 시간 {time.time() - t0:.1f}초 (장치: {device})")

    with torch.no_grad():
        pred = model(x_val_d).cpu().numpy()
    th_true = np.arctan2(y_val[:, 1].numpy(), y_val[:, 0].numpy())
    th_pred = np.arctan2(pred[:, 1], pred[:, 0])
    err_deg = np.degrees(np.abs((th_pred - th_true + np.pi) % (2 * np.pi) - np.pi))
    print(f"  검증 각도 오차: 평균 {err_deg.mean():.2f}°, 중앙값 {np.median(err_deg):.2f}°, 최대 {err_deg.max():.2f}°")

    fig = plt.figure(figsize=(10, 3.8))
    rng = np.random.default_rng(0)
    picks = rng.choice(len(x_val), 6, replace=False)
    for k, i in enumerate(picks):
        row, col = divmod(k, 3)
        ax = fig.add_axes([0.01 + col * 0.155, 0.52 - row * 0.47, 0.145, 0.40])  # 왼쪽 절반에 2×3 그림
        ax.imshow(x_val[i, 0], cmap="gray", vmin=0, vmax=1)
        c = 32 - 0.5
        for th, col_ in [(th_true[i], "#31a354"), (th_pred[i], "#d94801")]:
            ax.plot([c, c + 26 * np.sin(th)], [c, c - 26 * np.cos(th)], color=col_, lw=1.5)
        ax.set_title(f"err {err_deg[i]:.2f} deg", fontsize=8)
        ax.axis("off")
    ax = fig.add_axes([0.58, 0.14, 0.40, 0.76])
    ax.scatter(np.degrees(th_true), np.degrees(th_pred), s=3, alpha=0.4)
    ax.plot([-180, 180], [-180, 180], color="k", lw=0.8, ls="--")
    ax.set_xlabel("true angle (deg)")
    ax.set_ylabel("predicted angle (deg)")
    ax.set_title("CNN reads the angle from pixels\n(left: green=true, orange=predicted)", fontsize=9)
    fig.savefig(os.path.join(args.fig_dir, "ch04-cnn-pendulum.png"), dpi=110)
    plt.close(fig)


def main():
    parser = argparse.ArgumentParser(description="4장: 딥러닝과 PyTorch 기초")
    parser.add_argument("--quick", action="store_true", help="축소판으로 빠르게 돌려 보기")
    parser.add_argument("--fig-dir", default="figures", help="그림을 저장할 폴더")
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()
    os.makedirs(args.fig_dir, exist_ok=True)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    device = pick_device()
    print("장치:", device)

    t0 = time.time()
    part1_linreg(args)
    part2_tensors(args)
    part3_backprop(args)
    part4_mlp(args, device)
    part5_overfit(args, device)
    part6_conv_shapes(args)
    part7_cnn(args, device)
    print(f"\n전체 {time.time() - t0:.1f}초")


if __name__ == "__main__":
    main()
