| 1 | import contextlib |
| 2 | import difflib |
| 3 | import inspect |
| 4 | import io |
| 5 | import json |
| 6 | import os |
| 7 | import unicodedata |
| 8 | from pathlib import Path |
| 9 | |
| 10 | import gru |
| 11 | import lstm |
| 12 | import matplotlib.pyplot as plt |
| 13 | import numpy as np |
| 14 | import rnn |
| 15 | import torch |
| 16 | from _common import evaluate, load_kospi, read_kospi, train |
| 17 | |
| 18 | from ptintro import set_seed |
| 19 | |
| 20 | torch.set_num_threads(1) # 스레드 수에 따라 소수점 끝자리가 달라지지 않게 고정한다 |
| 21 | SERIES_DIR = Path(__file__).resolve().parent.parent |
| 22 | device = torch.device("cpu") |
| 23 | image_dir = Path(os.environ["IMAGE_DIR"]) |
| 24 | image_dir.mkdir(parents=True, exist_ok=True) |
| 25 | |
| 26 | |
| 27 | def pad(text, width): |
| 28 | """한글은 화면에서 두 칸을 차지하므로 그만큼 빼고 공백을 채운다.""" |
| 29 | wide = sum(unicodedata.east_asian_width(ch) in "WF" for ch in text) |
| 30 | return text + " " * max(0, width - len(text) - wide) |
| 31 | |
| 32 | |
| 33 | def code_lines(obj): |
| 34 | """주석과 docstring 을 뺀 코드 줄만 꺼낸다.""" |
| 35 | lines = [] |
| 36 | for line in inspect.getsource(obj).splitlines(): |
| 37 | code = line.split(" #")[0].rstrip() |
| 38 | if code.strip() and not code.strip().startswith(("#", '"""')): |
| 39 | lines.append(code) |
| 40 | return lines |
| 41 | |
| 42 | |
| 43 | def rmse(a, b): |
| 44 | return float(np.sqrt(np.mean((a - b) ** 2))) |
| 45 | |
| 46 | |
| 47 | print("1) rnn.py 의 VanillaRNN 과 gru.py 의 GRU 에서 다른 줄 (주석은 빼고 비교)") |
| 48 | for line in difflib.ndiff(code_lines(rnn.VanillaRNN), code_lines(gru.GRU)): |
| 49 | if line.startswith(("- ", "+ ")): |
| 50 | print(f" {line[0]} {line[2:].strip()}") |
| 51 | print( |
| 52 | " → 클래스 이름과 층의 종류만 다르다. GRU 는 셀 상태가 없어서 h0 하나만 넘기고 hn 하나만 받는다" |
| 53 | ) |
| 54 | print() |
| 55 | |
| 56 | print("2) 세 층의 모양과 파라미터 수 (입력 4, 은닉 8, 2층)") |
| 57 | data = load_kospi() |
| 58 | x = data.x_train[:3] |
| 59 | models = {"RNN": (rnn, rnn.VanillaRNN), "LSTM": (lstm, lstm.LSTM), "GRU": (gru, gru.GRU)} |
| 60 | print(" 모델 순환층이 돌려주는 것 파라미터 수") |
| 61 | for name, (module, cls) in models.items(): |
| 62 | model = cls(data.input_size, module.HIDDEN_SIZE, module.NUM_LAYERS, module.SEQUENCE_LENGTH) |
| 63 | layer = next(model.children()) # self.rnn / self.lstm / self.gru |
| 64 | with torch.no_grad(): |
| 65 | out, state = layer(x) |
| 66 | if isinstance(state, tuple): |
| 67 | shapes = f"out {tuple(out.shape)}, (hn {tuple(state[0].shape)}, cn {tuple(state[1].shape)})" |
| 68 | else: |
| 69 | shapes = f"out {tuple(out.shape)}, hn {tuple(state.shape)}" |
| 70 | n_layer = sum(p.numel() for p in layer.parameters()) |
| 71 | n_all = sum(p.numel() for p in model.parameters()) |
| 72 | print(f" {name:<5} {shapes:<52} {n_all:5d} = {n_layer // 256} × 256 + 41") |
| 73 | print( |
| 74 | " → 식의 벌 수가 RNN 1, GRU 3, LSTM 4 다. GRU 는 게이트 둘(리셋, 업데이트)과 후보 하나를 계산한다" |
| 75 | ) |
| 76 | print() |
| 77 | |
| 78 | print("3) gru.main() 실행: 완성본 그대로 300 에폭 (두 점선 사이가 main() 이 찍은 것)") |
| 79 | print("-" * 60) |
| 80 | gru.main() |
| 81 | print("-" * 60) |
| 82 | print() |
| 83 | |
| 84 | print("4) 같은 시드(42)로 학습한 세 모델의 테스트 구간 예측을 한 그림에") |
| 85 | results = {} |
| 86 | for name, (module, cls) in models.items(): |
| 87 | set_seed(42) |
| 88 | data = load_kospi(module.SEQUENCE_LENGTH, module.N_TRAIN) |
| 89 | model = cls(data.input_size, module.HIDDEN_SIZE, module.NUM_LAYERS, module.SEQUENCE_LENGTH) |
| 90 | with contextlib.redirect_stdout(io.StringIO()): |
| 91 | train(model, data, device, num_epochs=module.NUM_EPOCHS) |
| 92 | results[name] = evaluate(model, data, device) |
| 93 | truth = results["RNN"]["테스트_정답"] |
| 94 | lo, hi = data.y_scaler.data_min_[0], data.y_scaler.data_max_[0] |
| 95 | fig, ax = plt.subplots(figsize=(8, 4.2)) |
| 96 | ax.plot(truth, "k--", linewidth=1.2, label="actual") |
| 97 | for name, color in (("RNN", "tab:blue"), ("LSTM", "tab:red"), ("GRU", "tab:green")): |
| 98 | ax.plot(results[name]["테스트"], color=color, linewidth=0.9, label=name) |
| 99 | ax.axhspan(lo, hi, color="gray", alpha=0.12, label="range seen in training") |
| 100 | ax.set_xlabel("trading day in the test period") |
| 101 | ax.set_ylabel("KOSPI close") |
| 102 | ax.set_title("test period, seed 42") |
| 103 | ax.legend(fontsize=8) |
| 104 | fig.savefig(image_dir / "three-models.png", dpi=100, bbox_inches="tight") |
| 105 | print("[[image:three-models]]") |
| 106 | print(" 모델 학습 RMSE 테스트 RMSE") |
| 107 | for name, result in results.items(): |
| 108 | print( |
| 109 | f" {name:<5} {rmse(result['학습'], result['학습_정답']):5.1f} {rmse(result['테스트'], truth):5.1f}" |
| 110 | ) |
| 111 | print(" → 회색 띠(학습 때 본 범위) 안에서는 세 선이 실제와 함께 움직인다") |
| 112 | print( |
| 113 | " → 띠 아래로 급락한 구간에서 LSTM(빨강)이 가장 덜 내려간다. 띠 위에서는 셋 다 실제에 못 미친다" |
| 114 | ) |
| 115 | print() |
| 116 | |
| 117 | print("5) 시드 10개로 다시: 완성본 설정 그대로 모델마다 10번씩 학습 (미리 돌려 저장해 둔 결과)") |
| 118 | kospi = json.loads((SERIES_DIR / "full_run_kospi.json").read_text()) |
| 119 | seeds = kospi["seeds"] |
| 120 | print(f" 시드 {seeds}, 각 {kospi['epochs']} 에폭. 값은 테스트 RMSE(포인트)") |
| 121 | print(" 모델 " + "".join(f"{s:>6d}" for s in seeds) + " 평균 표준편차 최소 최대") |
| 122 | table = {} |
| 123 | for name in models: |
| 124 | rows = [r for r in kospi["rows"] if r["model"] == name] |
| 125 | table[name] = rows |
| 126 | v = np.array([r["test_rmse"] for r in rows]) |
| 127 | print( |
| 128 | f" {name:<5} " |
| 129 | + "".join(f"{t:6.1f}" for t in v) |
| 130 | + f" {v.mean():5.1f} {v.std(ddof=1):5.1f} {v.min():5.1f} {v.max():5.1f}" |
| 131 | ) |
| 132 | close = read_kospi()[1][:, 0] |
| 133 | naive = rmse(close[204:-1], close[205:]) |
| 134 | print(f" (기준) 어제 종가 그대로: {naive:.1f}") |
| 135 | means = {name: np.mean([r["test_rmse"] for r in rows]) for name, rows in table.items()} |
| 136 | order = sorted(means, key=means.get) |
| 137 | print( |
| 138 | f" → 테스트 RMSE 평균은 {order[0]} {means[order[0]]:.1f} < {order[1]} {means[order[1]]:.1f} < {order[2]} {means[order[2]]:.1f} 순이다" |
| 139 | ) |
| 140 | lstm_min = min(r["test_rmse"] for r in table["LSTM"]) |
| 141 | others_max = max(r["test_rmse"] for n in ("RNN", "GRU") for r in table[n]) |
| 142 | print( |
| 143 | f" → LSTM 의 가장 좋은 시드({lstm_min:.1f})가 RNN·GRU 의 가장 나쁜 시드({others_max:.1f})보다 나쁘다. 시드 탓이 아니다" |
| 144 | ) |
| 145 | rnn_v = np.array([r["test_rmse"] for r in table["RNN"]]) |
| 146 | gru_v = np.array([r["test_rmse"] for r in table["GRU"]]) |
| 147 | print( |
| 148 | f" → RNN 과 GRU 는 평균 차이가 {abs(rnn_v.mean() - gru_v.mean()):.1f} 이고 표준편차가 {rnn_v.std(ddof=1):.1f}, {gru_v.std(ddof=1):.1f} 이다. " |
| 149 | f"같은 시드끼리 견주면 10번 가운데 {int((gru_v < rnn_v).sum())}번은 GRU 가 낫다" |
| 150 | ) |
| 151 | print(" → 세 모델 모두 어떤 시드에서도 '어제 종가 그대로'보다 낫지 않다") |
| 152 | |
| 153 | fig, ax = plt.subplots(figsize=(7, 3.6)) |
| 154 | for k, (name, color) in enumerate((("RNN", "tab:blue"), ("LSTM", "tab:red"), ("GRU", "tab:green"))): |
| 155 | v = [r["test_rmse"] for r in table[name]] |
| 156 | ax.scatter([k] * len(v), v, color=color, alpha=0.7) |
| 157 | ax.hlines(np.mean(v), k - 0.25, k + 0.25, color=color) |
| 158 | ax.axhline(naive, color="gray", linestyle=":", label="yesterday's close as the prediction") |
| 159 | ax.set_xticks(range(3), ["RNN", "LSTM", "GRU"]) |
| 160 | ax.set_ylabel("test RMSE (points)") |
| 161 | ax.set_title("10 seeds per model (bar = mean)") |
| 162 | ax.legend(fontsize=8) |
| 163 | fig.savefig(image_dir / "seeds.png", dpi=100, bbox_inches="tight") |
| 164 | print("[[image:seeds]]") |
| 165 | print() |
| 166 | |
| 167 | print( |
| 168 | "6) 차이는 어디서 나오나: 테스트 정답이 학습 때 본 범위의 안 / 아래 / 위에 있는 날로 나눈 RMSE (시드 10개 평균)" |
| 169 | ) |
| 170 | print(" 모델 학습 구간 테스트 전체 범위 안(128일) 범위 아래(31일) 범위 위(67일)") |
| 171 | for name, rows in table.items(): |
| 172 | avg = {k: np.mean([r[k] for r in rows]) for k in rows[0] if k.endswith("rmse") or "rmse_" in k} |
| 173 | print( |
| 174 | f" {name:<5} {avg['train_rmse']:5.1f} {avg['test_rmse']:5.1f} {avg['test_rmse_inside']:5.1f}" |
| 175 | f" {avg['test_rmse_below']:5.1f} {avg['test_rmse_above']:5.1f}" |
| 176 | ) |
| 177 | print(" → 학습 구간과 '범위 안'에서는 세 모델이 몇 포인트 안에서 같다") |
| 178 | print( |
| 179 | " → 차이는 '범위 아래', 곧 학습 때 본 적 없는 급락 구간에서 난다. 과거를 기억하는 능력과는 상관없는 곳이다" |
| 180 | ) |
| 181 | print() |
| 182 | |
| 183 | print("7) 기억 과제 전체 표 (미리 돌려 저장해 둔 결과)") |
| 184 | memory = json.loads((SERIES_DIR / "full_run_memory.json").read_text()) |
| 185 | labels = { |
| 186 | "RNN": "nn.RNN", |
| 187 | "LSTM": "nn.LSTM (기본 초기화)", |
| 188 | "LSTM+forget": f"nn.LSTM (망각 편향 {memory['forget_bias']:.0f})", |
| 189 | "GRU": "nn.GRU", |
| 190 | } |
| 191 | print( |
| 192 | f" 첫 시점의 값을 마지막 시점에 답하기. {memory['steps']:,}번 갱신. " |
| 193 | f"시드 {len(memory['seeds'])}개 가운데 테스트 MSE 가 0.05 아래로 내려간 수" |
| 194 | ) |
| 195 | print(f" {pad('층', 26)}" + "".join(pad(f"길이 {n}", 11) for n in memory["lengths"])) |
| 196 | for kind, label in labels.items(): |
| 197 | cells = [] |
| 198 | for length in memory["lengths"]: |
| 199 | mses = next( |
| 200 | r["test_mse"] for r in memory["rows"] if r["model"] == kind and r["length"] == length |
| 201 | ) |
| 202 | cells.append(f"{sum(m < 0.05 for m in mses)} / {len(mses)}") |
| 203 | print(f" {pad(label, 26)}" + "".join(f"{c:<11}" for c in cells)) |
| 204 | print(" → 과거를 오래 들고 가야 하는 과제에서는 순서가 다르다") |
| 205 | print( |
| 206 | " → KOSPI 에서 가장 나빴던 LSTM 이, 망각 게이트를 열어 두면 길이 60 을 푸는 유일한 모델이다" |
| 207 | ) |
| 208 | print( |
| 209 | " → 기본 초기화 그대로의 nn.LSTM 은 길이 30 에서 RNN 보다도 못하다. GRU 는 손대지 않고도 길이 30 까지 푼다" |
| 210 | ) |
| 211 | print(" → 이 표는 1,500번 갱신했을 때의 결과다. 더 오래 학습하면 달라질 수 있다") |