# Exercice 1 : noyau Matern52 au lieu de RBF -- solution.
# Tout est identique a la section 3 (donut 16 points, prior LogNormal(0, 0.5) sur ls,
# lien logit, NUTS 400/400, 2 chaines, seed 42) : seul le noyau change.
# --- Etape 0 : pourquoi le Matern52 est "moins lisse" (tirages du prior en 1D, ls = 1).
x_1d = np.linspace(0, 5, 120)[:, None]
K_rbf_1d = pm.gp.cov.ExpQuad(1, ls=1.0)(x_1d).eval()
K_mat_1d = pm.gp.cov.Matern52(1, ls=1.0)(x_1d).eval()
rng_ex1 = np.random.default_rng(0)
z = rng_ex1.standard_normal((len(x_1d), 3)) # memes bruits blancs pour les deux noyaux
jitter = 1e-8 * np.eye(len(x_1d))
draws_rbf = np.linalg.cholesky(K_rbf_1d + jitter) @ z
draws_mat = np.linalg.cholesky(K_mat_1d + jitter) @ z
fig, axes = plt.subplots(1, 2, figsize=(12, 3), sharey=True)
for ax, draws, titre in [(axes[0], draws_rbf, "ExpQuad (RBF), ls = 1"),
(axes[1], draws_mat, "Matern52, ls = 1")]:
ax.plot(x_1d, draws, lw=1.2)
ax.set_title(titre); ax.set_xlabel("x")
axes[0].set_ylabel("f(x)")
fig.suptitle("Memes bruits blancs, deux noyaux : le Matern52 produit des fonctions plus rugueuses", y=1.03)
plt.tight_layout(); plt.show()
# Rugosite mesuree : energie moyenne de la derivee seconde discrete des tirages.
rugosite = lambda d: float(np.mean(np.diff(d, n=2, axis=0) ** 2))
print(f"Rugosite des tirages du prior (moyenne de (f'')^2 discrete) : "
f"RBF = {rugosite(draws_rbf):.2e} | Matern52 = {rugosite(draws_mat):.2e} "
f"(x{rugosite(draws_mat) / rugosite(draws_rbf):.1f})")
# --- Etape 1 : le modele de la section 3, noyau Matern52.
with pm.Model() as matern_model:
ls_m = pm.LogNormal("ls", mu=0.0, sigma=0.5)
cov_m = pm.gp.cov.Matern52(input_dim=2, ls=ls_m)
gp_m = pm.gp.Latent(cov_func=cov_m)
f_m = gp_m.prior("f", X=X_donut)
pm.Bernoulli("y", logit_p=f_m, observed=y_donut)
# --- Etape 2 : memes reglages NUTS que la section 3.
with matern_model:
idata_matern = pm.sample(400, tune=400, chains=2, cores=1, random_seed=42,
target_accept=0.95, progressbar=False)
n_div_m = int(idata_matern.sample_stats.diverging.sum().item())
ls_rbf_mean = float(idata.posterior["ls"].mean())
ls_mat_mean = float(idata_matern.posterior["ls"].mean())
print(f"\nDivergences NUTS (Matern52) : {n_div_m} (cible : 0)")
print(f"ls posterieur moyen : RBF = {ls_rbf_mean:.2f} | Matern52 = {ls_mat_mean:.2f}")
# --- Etape 3 : predictions sur la grille 20x20 de la section 4, puis comparaison.
# (X_grid a ete redefini en section 6 : on reconstruit la grille de la section 4.)
grid_ex1 = np.linspace(-2, 2, 20)
G1_ex1, G2_ex1 = np.meshgrid(grid_ex1, grid_ex1)
X_grid_ex1 = np.column_stack([G1_ex1.ravel(), G2_ex1.ravel()])
assert np.allclose(G1_ex1, G1) and P.shape == G1_ex1.shape # meme grille que P (RBF)
with matern_model:
gp_m.conditional("f_grid", Xnew=X_grid_ex1)
gp_m.conditional("f_test", Xnew=test_points)
gp_m.conditional("f_oos", Xnew=X_test)
ppc_m = pm.sample_posterior_predictive(idata_matern, var_names=["f_grid", "f_test", "f_oos"],
random_seed=42, progressbar=False)
# Bras RBF hors-echantillon (meme modele qu'en section 3, juste un nouveau conditionnel).
with gp_model:
gp.conditional("f_oos_rbf", Xnew=X_test)
ppc_rbf_oos = pm.sample_posterior_predictive(idata, var_names=["f_oos_rbf"],
random_seed=42, progressbar=False)
def _post(ppc_obj, nom):
"""Tirages (n_draws, n_points) d'une variable du posterior predictif."""
v = ppc_obj.posterior_predictive[nom].values
return v.reshape(-1, v.shape[-1])
f_grid_m = _post(ppc_m, "f_grid")
P_m = _sigmoid(f_grid_m.mean(axis=0)).reshape(G1_ex1.shape)
S_m = f_grid_m.std(axis=0).reshape(G1_ex1.shape)
p_test_m = _sigmoid(_post(ppc_m, "f_test").mean(axis=0))
f_train_m = idata_matern.posterior["f"].values.reshape(-1, X_donut.shape[0])
acc_train_m = ((_sigmoid(f_train_m.mean(axis=0)) > 0.5) == y_donut).mean()
def _logloss(p, y):
p = np.clip(p, 1e-9, 1 - 1e-9)
return float(-np.mean(y * np.log(p) + (1 - y) * np.log(1 - p)))
p_oos = {"RBF": _sigmoid(_post(ppc_rbf_oos, "f_oos_rbf").mean(axis=0)),
"Matern52": _sigmoid(_post(ppc_m, "f_oos").mean(axis=0))}
# Figure : probabilite RBF | probabilite Matern52 | ecart et frontieres superposees.
fig, axes = plt.subplots(1, 3, figsize=(17, 5))
for ax, champ, titre in [(axes[0], P, f"RBF (section 4) : ls = {ls_rbf_mean:.2f}"),
(axes[1], P_m, f"Matern52 : ls = {ls_mat_mean:.2f}")]:
cf = ax.contourf(G1_ex1, G2_ex1, champ, levels=np.linspace(0, 1, 11), cmap="RdBu_r", alpha=0.7)
ax.contour(G1_ex1, G2_ex1, champ, levels=[0.5], colors="k", linewidths=1.5)
ax.set_title(f"P(classe 1) -- {titre}")
cs = axes[2].contourf(G1_ex1, G2_ex1, np.abs(P_m - P), levels=12, cmap="Greys")
fig.colorbar(cs, ax=axes[2], label="|P_Matern - P_RBF|")
axes[2].contour(G1_ex1, G2_ex1, P, levels=[0.5], colors="C0", linewidths=2)
axes[2].contour(G1_ex1, G2_ex1, P_m, levels=[0.5], colors="C3", linewidths=2, linestyles="--")
axes[2].plot([], [], c="C0", lw=2, label="frontiere RBF")
axes[2].plot([], [], c="C3", lw=2, ls="--", label="frontiere Matern52")
axes[2].legend(loc="upper right", fontsize=8)
axes[2].set_title("Ecart des probabilites et frontieres P = 0.5")
for ax in axes:
ax.scatter(X_donut[y_donut == 0, 0], X_donut[y_donut == 0, 1], c="C0", s=60, edgecolors="k", zorder=3)
ax.scatter(X_donut[y_donut == 1, 0], X_donut[y_donut == 1, 1], c="C3", s=60, marker="s",
edgecolors="k", zorder=3)
ax.set_xlabel("x1"); ax.set_aspect("equal")
axes[0].set_ylabel("x2")
fig.suptitle("Exercice 1 : noyau Matern52 contre noyau RBF sur le donut", y=1.0)
plt.tight_layout(); plt.show()
# Tableau de comparaison (memes donnees, memes reglages : seul le noyau differe).
grad_rbf = np.mean(np.hypot(*np.gradient(P, grid_ex1, grid_ex1)))
grad_mat = np.mean(np.hypot(*np.gradient(P_m, grid_ex1, grid_ex1)))
print("\n=== RBF vs Matern52 (donut, 16 points d'entrainement) ===")
print(f"{'':34s}{'RBF':>10s}{'Matern52':>12s}")
print(f"{'ls posterieur moyen':34s}{ls_rbf_mean:10.2f}{ls_mat_mean:12.2f}")
print(f"{'divergences NUTS':34s}{n_div:10d}{n_div_m:12d}")
print(f"{'exactitude training':34s}{acc:10.3f}{acc_train_m:12.3f}")
print(f"{'exactitude OOS (200 pts, sect. 6)':34s}"
f"{((p_oos['RBF'] > 0.5) == y_test).mean():10.3f}{((p_oos['Matern52'] > 0.5) == y_test).mean():12.3f}")
print(f"{'log-loss OOS':34s}{_logloss(p_oos['RBF'], y_test):10.3f}{_logloss(p_oos['Matern52'], y_test):12.3f}")
print(f"{'ecart-type moyen de f* (grille)':34s}{S.mean():10.3f}{S_m.mean():12.3f}")
print(f"{'|grad P| moyen (grille)':34s}{grad_rbf:10.3f}{grad_mat:12.3f}")
print("\nPoints test (section 4) : P(classe 1)")
for tp, pr, pm_ in zip(test_points, p_test, p_test_m):
print(f" x={tp} : RBF = {pr:.2f} | Matern52 = {pm_:.2f}")
print(f"\nAccord des champs : corr = {np.corrcoef(P.ravel(), P_m.ravel())[0, 1]:.3f} | "
f"|Delta p| moyen = {np.abs(P - P_m).mean():.3f} | max = {np.abs(P - P_m).max():.3f}")
matern_result = {"idata": idata_matern, "p_grid": P_m, "sd_grid": S_m, "p_test": p_test_m,
"p_oos": p_oos["Matern52"], "ls_mean": ls_mat_mean}