gp_simulation_animation.py ダウンロード/コピー

gp_simulation_animation.py をダウンロード

gp_simulation_animation.py
gp_simulation_animation.py
  1"""
  2概要:
  3    ガウス過程回帰を用いた能動学習のアニメーションを生成するスクリプトです。
  4詳細説明:
  5    設定された探索モードに従ってデータ点を追加し、ガウス過程の予測平均と分散の推移をアニメーション化します。
  6    コマンドライン引数で探索モードや反復回数などを指定できます。
  7"""
  8import sys
  9import numpy as np
 10from scipy.stats import norm
 11
 12import matplotlib.pyplot as plt
 13from matplotlib.animation import FuncAnimation
 14from matplotlib.animation import PillowWriter
 15#from matplotlib.animation import FuncAnimation, FFMpegWriter
 16
 17
 18# mode = "random" / "std" / "max" / "ucb" / "ei" / "target" / "target_ucb" / "target_sq"
 19# target    : GP を元の y に対して作り、P(v0-eps < y < v0+eps) を最大化する。
 20# target_ucb: -abs(mu-v0) + kappa*std を最大化し、目標値探索に探索性を加える。
 21# target_sq : score = -(y-v0)^2 を GP で直接近似し、UCB を最大化する。
 22#mode = "random"
 23#mode = "std"
 24#mode = "max"
 25mode = "ucb"
 26
 27outfile = ""
 28#outfile = "gp_std_mode.gif"
 29nmaxiter = 20
 30v0 = 0.30
 31eps_target = 0.10
 32kappa = 2.0
 33
 34argv = sys.argv
 35nargs = len(argv)
 36if nargs >= 2: mode = argv[1]
 37if nargs >= 3: nmaxiter = int(argv[2])
 38if nargs >= 4: outfile = argv[3]
 39if nargs >= 5: v0 = float(argv[4])
 40if nargs >= 6: eps_target = float(argv[5])
 41
 42
 43plt.rcParams['font.family'] = 'MS Gothic'
 44plt.rcParams['axes.unicode_minus'] = False
 45
 46# ==== 真の関数 ====
 47def f_true(x):
 48    """
 49    概要:
 50        真の関数値を計算します。
 51    詳細説明:
 52        入力xに対して正弦波と余弦波の和を計算して返します。
 53    引数:
 54        :param x: 入力値。
 55        :type x: float または numpy.ndarray
 56    戻り値:
 57        :returns: 真の関数値。
 58        :rtype: float または numpy.ndarray
 59    """
 60    return np.sin(2 * np.pi * x) + 0.3 * np.cos(4 * np.pi * x)
 61
 62def target_square_score(y, v0):
 63    """
 64    概要:
 65        目標値との二乗誤差に基づくスコアを計算します。
 66    詳細説明:
 67        目標値に近いほど0に近づき、遠いほど負の大きな値になります。
 68    引数:
 69        :param y: 観測値。
 70        :type y: float または numpy.ndarray
 71        :param v0: 目標値。
 72        :type v0: float
 73    戻り値:
 74        :returns: 目標値v0からの負の二乗誤差。
 75        :rtype: float または numpy.ndarray
 76    """
 77    """目標値に近いほど大きい(最大値 0)スコア。"""
 78    return -(y - v0) ** 2
 79
 80# ==== RBFカーネル ====
 81def rbf_kernel(x1, x2, length_scale=0.2, sigma_f=1.0):
 82    """
 83    概要:
 84        RBFカーネル行列を計算します。
 85    詳細説明:
 86        2つの入力データ群に対して、指定されたlength_scaleとsigma_fを用いてカーネル行列を生成します。
 87    引数:
 88        :param x1: 第1の入力データ配列。
 89        :type x1: numpy.ndarray
 90        :param x2: 第2の入力データ配列。
 91        :type x2: numpy.ndarray
 92        :param length_scale: カーネルの長さスケールパラメータ。
 93        :type length_scale: float
 94        :param sigma_f: カーネルの信号分散パラメータ。
 95        :type sigma_f: float
 96    戻り値:
 97        :returns: 計算されたカーネル行列。
 98        :rtype: numpy.ndarray
 99    """
100    x1 = np.atleast_2d(x1).T
101    x2 = np.atleast_2d(x2).T
102    d2 = (x1 - x2.T) ** 2
103    return sigma_f**2 * np.exp(-0.5 * d2 / length_scale**2)
104
105# ==== ガウス過程回帰 ====
106def gp_posterior(x_train, y_train, x_test, noise_sigma,
107                 length_scale=0.2, sigma_f=1.0):
108    """
109    概要:
110        ガウス過程回帰の事後分布を計算します。
111    詳細説明:
112        訓練データを用いてテストデータに対する予測平均と予測分散を計算します。
113    引数:
114        :param x_train: 訓練データの入力。
115        :type x_train: numpy.ndarray
116        :param y_train: 訓練データの出力。
117        :type y_train: numpy.ndarray
118        :param x_test: テストデータの入力。
119        :type x_test: numpy.ndarray
120        :param noise_sigma: 観測ノイズの標準偏差。
121        :type noise_sigma: float
122        :param length_scale: RBFカーネルの長さスケール。
123        :type length_scale: float
124        :param sigma_f: RBFカーネルの信号分散。
125        :type sigma_f: float
126    戻り値:
127        :returns: 予測平均配列と予測分散配列のタプル。
128        :rtype: tuple
129    """
130
131    K = rbf_kernel(x_train, x_train, length_scale, sigma_f)
132    K_s = rbf_kernel(x_train, x_test, length_scale, sigma_f)
133    K_ss = rbf_kernel(x_test, x_test, length_scale, sigma_f)
134
135    K_y = K + (noise_sigma**2) * np.eye(len(x_train))
136
137    L = np.linalg.cholesky(K_y)
138    alpha = np.linalg.solve(L.T, np.linalg.solve(L, y_train))
139
140    mu = K_s.T @ alpha
141
142    v = np.linalg.solve(L, K_s)
143    cov = K_ss - v.T @ v
144    var = np.clip(np.diag(cov), 0, np.inf)
145
146    return mu, var
147
148# ==== 既存点に近すぎる場合のオフセット ====
149def avoid_duplicate(x_new, x_train, eps=1e-3):
150    """
151    概要:
152        新しい入力点が既存の点に近すぎる場合にオフセットを加えます。
153    詳細説明:
154        既存の訓練データとの距離がeps未満の場合、ランダムな微小な値を加算し範囲を0から1にクリップします。
155    引数:
156        :param x_new: 新たに提案された入力点。
157        :type x_new: float
158        :param x_train: 既存の訓練データの配列。
159        :type x_train: numpy.ndarray
160        :param eps: 重複と判定する距離の閾値。
161        :type eps: float
162    戻り値:
163        :returns: オフセット調整された新しい入力点。
164        :rtype: float
165    """
166    if len(x_train) == 0:
167        return x_new
168    while np.min(np.abs(x_train - x_new)) < eps:
169        x_new += np.random.uniform(-0.01, 0.01)
170        x_new = np.clip(x_new, 0.0, 1.0)
171    return x_new
172
173# ==== メイン ====
174def main(mode="random", nmaxiter=40, savefile="gp_animation.mp4",
175         v0=0.30, eps_target=0.10):
176    """
177    概要:
178        ガウス過程回帰のアニメーションを生成および実行します。
179    詳細説明:
180        指定された探索モードで新しいデータ点を逐次追加し、結果をプロットします。
181    引数:
182        :param mode: 探索モード。random, std, max, ucb, ei, target, target_ucb, target_sq のいずれかを指定します。
183        :type mode: str
184        :param nmaxiter: アニメーションの最大反復回数。
185        :type nmaxiter: int
186        :param savefile: 保存するアニメーションファイルのパス。空文字列の場合は保存しません。
187        :type savefile: str
188        :param v0: 探索の目標値。
189        :type v0: float
190        :param eps_target: 目標値の許容誤差。
191        :type eps_target: float
192    戻り値:
193        :returns: なし。
194        :rtype: None
195    例外:
196        :raises ValueError: 無効なモード文字列が指定された場合に発生します。
197    """
198    rng = np.random.default_rng(1)
199
200    x_data = []
201    y_data = []             # 実際に観測した元の y
202    model_data = []         # GP に学習させる量(通常は y、target_sq では score)
203    noise_sigma = 0.15
204
205    x_plot = np.linspace(0, 1, 200)
206    y_true = f_true(x_plot)
207    score_mode = (mode == "target_sq")
208    y_display_true = target_square_score(y_true, v0) if score_mode else y_true
209
210    fig, ax = plt.subplots(figsize=(8, 5))
211    ax.set_xlabel("x")
212    ax.set_ylabel("score = -(y-v0)^2" if score_mode else "y")
213
214    true_label = "真の score" if score_mode else "真の関数 f(x)"
215    ax.plot(x_plot, y_display_true, "k--", label=true_label)
216    scatter = ax.scatter([], [], color="black", label="観測データ")
217    mean_line, = ax.plot([], [], color="C0", label="GP 予測平均")
218
219    uncert_band = None
220
221    ax.legend(loc="upper right")
222    ax.set_xlim(0, 1)
223    if score_mode:
224        ax.set_ylim(-3.0, 0.4)
225    else:
226        ax.set_ylim(-2.0, 2.0)
227        if mode in ("target", "target_ucb"):
228            ax.axhspan(v0 - eps_target, v0 + eps_target,
229                       color="C2", alpha=0.12, label="目標範囲")
230            ax.axhline(v0, color="C2", ls=":", lw=1)
231            ax.legend(loc="upper right")
232
233    # ---- アニメーション更新 ----
234    def update(frame):
235        """
236        概要:
237            アニメーションの各フレームの状態を更新します。
238        詳細説明:
239            新しい入力点を選択して観測を行い、ガウス過程のモデルを更新した上で描画データを再設定します。
240        引数:
241            :param frame: アニメーションのフレーム番号。
242            :type frame: int
243        戻り値:
244            :returns: 更新された描画オブジェクトのタプル。
245            :rtype: tuple
246        """
247        nonlocal uncert_band, x_data, y_data, model_data
248
249        # 最初の1点はランダム
250        if len(x_data) == 0:
251            x_new = rng.uniform(0, 1)
252        else:
253            x_train = np.array(x_data)
254            y_train = np.array(model_data)
255            mu, var = gp_posterior(x_train, y_train, x_plot, noise_sigma)
256            std = np.sqrt(var)
257
258            if mode == "random":
259                x_new = rng.uniform(0, 1)
260
261            elif mode == "std":
262                idx = np.argmax(std)
263                x_new = x_plot[idx]
264
265            elif mode == "max":
266                idx = np.argmax(mu)
267                x_new = x_plot[idx]
268
269            elif mode == "ucb":
270                ucb = mu + kappa * std
271                idx = np.argmax(ucb)
272                x_new = x_plot[idx]
273
274            elif mode == "ei":
275                y_best = np.max(y_train)
276                improvement = mu - y_best
277                Z = improvement / (std + 1e-9)
278                ei = improvement * norm.cdf(Z) + std * norm.pdf(Z)
279                ei[std < 1e-12] = 0.0
280                idx = np.argmax(ei)
281                x_new = x_plot[idx]
282
283            elif mode == "target":
284                # 次の「観測値」が許容範囲に入る確率。
285                # var は潜在関数の予測分散なので、観測ノイズも加える。
286                sigma_pred = np.sqrt(var + noise_sigma**2)
287                p_target = (
288                    norm.cdf((v0 + eps_target - mu) / sigma_pred)
289                    - norm.cdf((v0 - eps_target - mu) / sigma_pred)
290                )
291                idx = np.argmax(p_target)
292                x_new = x_plot[idx]
293
294            elif mode == "target_ucb":
295                # 目標値への近さ(exploit)と、未測定領域の
296                # 不確かさ(explore)を同じ y の単位で加える。
297                target_ucb = -np.abs(mu - v0) + kappa * std
298                idx = np.argmax(target_ucb)
299                x_new = x_plot[idx]
300
301            elif mode == "target_sq":
302                # score = -(y-v0)^2 を直接 GP 化する比較用の方法。
303                # スコアを最大化する UCB を使う。
304                score_ucb = mu + kappa * std
305                idx = np.argmax(score_ucb)
306                x_new = x_plot[idx]
307
308            else:
309                raise ValueError(
310                    "mode must be random, std, max, ucb, ei, "
311                    "target, target_ucb, or target_sq"
312                )
313
314        # 既存点と近すぎる場合はオフセット
315        x_new = avoid_duplicate(x_new, np.array(x_data))
316
317        # 新しい観測値
318        y_new = f_true(x_new) + rng.normal(0.0, noise_sigma)
319
320        x_data.append(x_new)
321        y_data.append(y_new)
322        model_data.append(target_square_score(y_new, v0) if score_mode else y_new)
323
324        # ---- GP posterior 再計算 ----
325        x_train = np.array(x_data)
326        y_train = np.array(model_data)
327        mu, var = gp_posterior(x_train, y_train, x_plot, noise_sigma)
328        std = np.sqrt(var)
329
330        scatter.set_offsets(np.column_stack([x_train, y_train]))
331        mean_line.set_data(x_plot, mu)
332
333        if uncert_band is not None:
334            uncert_band.remove()
335
336        uncert_band = ax.fill_between(
337            x_plot,
338            mu - 2 * std,
339            mu + 2 * std,
340            color="C0",
341            alpha=0.2
342        )
343
344        ax.set_title(
345            f"mode={mode} | v0={v0:g}, eps={eps_target:g} | "
346            f"データ数 n = {len(x_train)}"
347        )
348        return scatter, mean_line, uncert_band
349
350    # ---- アニメーション作成 ----
351    anim = FuncAnimation(
352        fig,
353        update,
354        frames=nmaxiter,
355        interval=500,
356        blit=False,
357        repeat=False
358    )
359
360    # ---- 動画保存 ----
361    if savefile is None or savefile == "":
362        pass
363    else:
364    # GIF で保存
365        writer = PillowWriter(fps=2)
366        anim.save(savefile, writer=writer)
367# mp4に保存
368#        writer = FFMpegWriter(fps=2)
369#        anim.save(savefile, writer=writer)
370        print(f"Saved animation to {savefile}")
371
372    plt.tight_layout()
373    plt.show()
374
375if __name__ == "__main__":
376    main(mode=mode, nmaxiter=nmaxiter, savefile=outfile,
377         v0=v0, eps_target=eps_target)