プリンキピア

第18章ガウス過程

18.3.4. Worked Example from Scratch18.3.4 一から作る例

Let’s create some regression data, and then fit the data with a GP, implementing every step from scratch. We’ll sample data from
英語のヒント
回帰のデータを作り、それからすべての段階を一から実装してGPでデータに当てはめよう。データを次から抜き出す。
y(x)=sin⁡(x)+12sin⁡(4x)+ϵ,(18.3.8)
with ϵ∼𝒩(0,σ2). The noise free function we wish to find is f(x)=sin⁡(x)+12sin⁡(4x). We’ll start by using a noise standard deviation σ=0.25.
英語のヒント
ここで、ϵ∼𝒩(0,σ2)である。見つけたいノイズのない関数はf(x)=sin⁡(x)+12sin⁡(4x)である。まず、ノイズの標準偏差σ=0.25を使う。
def data_maker1(x, sig):
    return np.sin(x) + 0.5 * np.sin(4 * x) + np.random.randn(x.shape[0]) * sig

sig = 0.25
train_x, test_x = np.linspace(0, 5, 50), np.linspace(0, 5, 500)
train_y, test_y = data_maker1(train_x, sig=sig), data_maker1(test_x, sig=0.)

d2l.plt.scatter(train_x, train_y)
d2l.plt.plot(test_x, test_y)
d2l.plt.xlabel("x", fontsize=20)
d2l.plt.ylabel("Observations y", fontsize=20)
d2l.plt.show()
Here we see the noisy observations as circles, and the noise-free function in blue that we wish to find.
英語のヒント
ここでは、ノイズのある観測を丸で、見つけたいノイズのない関数を青で示している。
Now, let’s specify a GP prior over the latent noise-free function, f(x)∼𝒢𝒫(m,k). We’ll use a mean function m(x)=0, and an RBF covariance function (kernel)
英語のヒント
では、ノイズのない潜在的な関数の上のGPの事前分布f(x)∼𝒢𝒫(m,k)を指定しよう。平均関数m(x)=0と、次のRBF共分散関数(カーネル)を使う。
k(xi,xj)=a2exp⁡(−12ℓ2||x−x′||2).(18.3.9)
mean = np.zeros(test_x.shape[0])
cov = d2l.rbfkernel(test_x, test_x, ls=0.2)
We have started with a length-scale of 0.2. Before we fit the data, it is important to consider whether we have specified a reasonable prior. Let’s visualize some sample functions from this prior, as well as the 95% credible set (we believe there’s a 95% chance that the true function is within this region).
英語のヒント
長さスケール0.2から始めた。データに当てはめる前に、妥当な事前分布を指定したかどうかを考えることが大切である。この事前分布からの見本の関数をいくつかと、95%信用集合(真の関数がこの領域の中にある見込みが95%だと考える)を可視化しよう。
prior_samples = np.random.multivariate_normal(mean=mean, cov=cov, size=5)
d2l.plt.plot(test_x, prior_samples.T, color='black', alpha=0.5)
d2l.plt.plot(test_x, mean, linewidth=2.)
d2l.plt.fill_between(test_x, mean - 2 * np.diag(cov), mean + 2 * np.diag(cov),
                 alpha=0.25)
d2l.plt.show()
Do these samples look reasonable? Are the high-level properties of the functions aligned with the type of data we are trying to model?
英語のヒント
これらの標本は妥当に見えるか。関数の高水準の性質は、モデル化しようとしているデータの種類に合っているか。
Now let’s form the mean and variance of the posterior predictive distribution at any arbitrary test point x∗.
英語のヒント
では、任意のテスト点x∗での事後予測分布の平均と分散を作ろう。
f¯∗=K(x,x∗)T(K(x,x)+σ2I)−1y(18.3.10)
V(f∗)=K(x∗,x∗)−K(x,x∗)T(K(x,x)+σ2I)−1K(x,x∗)(18.3.11)
Before we make predictions, we should learn our kernel hyperparameters θ and noise variance σ2. Let’s initialize our length-scale at 0.75, as our prior functions looked too quickly varying compared to the data we are fitting. We’ll also guess a noise standard deviation σ of 0.75.
英語のヒント
予測をする前に、カーネルのハイパーパラメータθとノイズの分散σ2を学習すべきである。事前分布の関数は、当てはめようとしているデータに比べて変化が速すぎるように見えたので、長さスケールを0.75に初期化しよう。ノイズの標準偏差σも0.75と見積もる。
In order to learn these parameters, we will maximize the marginal likelihood with respect to these parameters.
英語のヒント
これらのパラメータを学習するため、これらのパラメータについて周辺尤度を最大化する。
log⁡p(y|X)=log⁡∫p(y|f,X)p(f|X)df(18.3.12)
log⁡p(y|X)=−12yT(K(x,x)+σ2I)−1y−12log⁡|K(x,x)+σ2I|−n2log⁡2π(18.3.13)
Perhaps our prior functions were too quickly varying. Let’s guess a length-scale of 0.4. We’ll also guess a noise standard deviation of 0.75. These are simply hyperparameter initializations — we will learn these parameters from the marginal likelihood.
英語のヒント
事前分布の関数は、おそらく変化が速すぎた。長さスケールを0.4と見積もろう。ノイズの標準偏差も0.75と見積もる。これらは単にハイパーパラメータの初期値である。これらのパラメータは周辺尤度から学習する。
ell_est = 0.4
post_sig_est = 0.5

def neg_MLL(pars):
    K = d2l.rbfkernel(train_x, train_x, ls=pars[0])
    kernel_term = -0.5 * train_y @ \
        np.linalg.inv(K + pars[1] ** 2 * np.eye(train_x.shape[0])) @ train_y
    logdet = -0.5 * np.log(np.linalg.det(K + pars[1] ** 2 * \
                                         np.eye(train_x.shape[0])))
    const = -train_x.shape[0] / 2. * np.log(2 * np.pi)

    return -(kernel_term + logdet + const)


learned_hypers = optimize.minimize(neg_MLL, x0=np.array([ell_est,post_sig_est]),
                                   bounds=((0.01, 10.), (0.01, 10.)))
ell = learned_hypers.x[0]
post_sig_est = learned_hypers.x[1]
In this instance, we learn a length-scale of 0.299, and a noise standard deviation of 0.24. Note that the learned noise is extremely close to the true noise, which helps indicate that our GP is a very well-specified to this problem.
英語のヒント
この例では、長さスケール0.299とノイズの標準偏差0.24が学習される。学習したノイズは真のノイズにきわめて近いことに注意しよう。これは、このGPがこの問題によく合った設定になっていることを示す手がかりになる。
In general, it is crucial to put careful thought into selecting the kernel and initializing the hyperparameters. While marginal likelihood optimization can be relatively robust to initialization, it is not immune to poor initializations. Try running the above script with a variety of initializations and see what results you find.
英語のヒント
一般に、カーネルを選びハイパーパラメータを初期化することには、慎重に考えを注ぐことが決定的に重要である。周辺尤度の最適化は初期化に対して比較的頑健でありうるが、悪い初期化の影響を免れるわけではない。上のスクリプトをさまざまな初期化で実行して、どんな結果になるかを見てみよ。
Now, let’s make predictions with these learned hypers.
英語のヒント
では、学習したこれらのハイパーパラメータで予測をしよう。
K_x_xstar = d2l.rbfkernel(train_x, test_x, ls=ell)
K_x_x = d2l.rbfkernel(train_x, train_x, ls=ell)
K_xstar_xstar = d2l.rbfkernel(test_x, test_x, ls=ell)

post_mean = K_x_xstar.T @ np.linalg.inv((K_x_x + \
                post_sig_est ** 2 * np.eye(train_x.shape[0]))) @ train_y
post_cov = K_xstar_xstar - K_x_xstar.T @ np.linalg.inv((K_x_x + \
                post_sig_est ** 2 * np.eye(train_x.shape[0]))) @ K_x_xstar

lw_bd = post_mean - 2 * np.sqrt(np.diag(post_cov))
up_bd = post_mean + 2 * np.sqrt(np.diag(post_cov))

d2l.plt.scatter(train_x, train_y)
d2l.plt.plot(test_x, test_y, linewidth=2.)
d2l.plt.plot(test_x, post_mean, linewidth=2.)
d2l.plt.fill_between(test_x, lw_bd, up_bd, alpha=0.25)
d2l.plt.legend(['Observed Data', 'True Function', 'Predictive Mean', '95% Set on True Func'])
d2l.plt.show()
We see the posterior mean in orange almost perfectly matches the true noise free function! Note that the 95% credible set we are showing is for the latent noise free (true) function, and not the data points. We see that this credible set entirely contains the true function, and does not seem overly wide or narrow. We would not want nor expect it to contain the data points. If we wish to have a credible set for the observations, we should compute
英語のヒント
オレンジの事後平均は、真のノイズのない関数にほとんど完全に一致している!示している95%信用集合は、データ点ではなく、ノイズのない潜在的な(真の)関数についてのものであることに注意しよう。この信用集合は真の関数を完全に含み、広すぎも狭すぎもしないように見える。データ点を含むことを望みも期待もしない。観測についての信用集合がほしければ、次を計算すべきである。
lw_bd_observed = post_mean - 2 * np.sqrt(np.diag(post_cov) + post_sig_est ** 2)
up_bd_observed = post_mean + 2 * np.sqrt(np.diag(post_cov) + post_sig_est ** 2)
There are two sources of uncertainty, epistemic uncertainty, representing reducible uncertainty, and aleatoric or irreducible uncertainty. The epistemic uncertainty here represents uncertainty about the true values of the noise free function. This uncertainty should grow as we move away from the data points, as away from the data there are a greater variety of function values consistent with our data. As we observe more and more data, our beliefs about the true function become more confident, and the epistemic uncertainty disappears. The aleatoric uncertainty in this instance is the observation noise, since the data are given to us with this noise, and it cannot be reduced.
英語のヒント
不確かさには二つの源がある。減らすことのできる不確かさを表す認識論的不確かさと、偶然的な、つまり減らせない不確かさである。ここでの認識論的不確かさは、ノイズのない関数の真の値についての不確かさを表す。データから離れたところでは、データと整合する関数の値がより多様にあるので、この不確かさはデータ点から離れるにつれて大きくなるはずである。データをどんどん観測するにつれて、真の関数についての信念はより確かになり、認識論的不確かさは消えていく。この例での偶然的不確かさは観測ノイズである。データはこのノイズとともに与えられ、それは減らせないからである。
The epistemic uncertainty in the data is captured by variance of the latent noise free function np.diag(post_cov). The aleatoric uncertainty is captured by the noise variance post_sig_est**2.
英語のヒント
データの認識論的不確かさは、ノイズのない潜在的な関数の分散np.diag(post_cov)でとらえられる。偶然的不確かさは、ノイズの分散post_sig_est**2でとらえられる。
Unfortunately, people are often careless about how they represent uncertainty, with many papers showing error bars that are completely undefined, no clear sense of whether we are visualizing epistemic or aleatoric uncertainty or both, and confusing noise variances with noise standard deviations, standard deviations with standard errors, confidence intervals with credible sets, and so on. Without being precise about what the uncertainty represents, it is essentially meaningless.
英語のヒント
残念なことに、人々は不確かさをどう表すかについてしばしば不注意であり、多くの論文が、まったく定義されていない誤差棒を示し、認識論的不確かさと偶然的不確かさのどちらを可視化しているのか、あるいは両方なのかがはっきりせず、ノイズの分散とノイズの標準偏差、標準偏差と標準誤差、信頼区間と信用集合などを混同している。不確かさが何を表すのかを正確にしないかぎり、それは本質的に無意味である。
In the spirit of playing close attention to what our uncertainty represents, it is crucial to note that we are taking two times the square root of our variance estimate for the noise free function. Since our predictive distribution is Gaussian, this quantity enables us to form a 95% credible set, representing our beliefs about the interval which is 95% likely to contain the ground truth function. The noise variance is living on a completely different scale, and is much less interpretable.
英語のヒント
不確かさが何を表すかに細心の注意を払うという精神で言えば、ここではノイズのない関数についての分散の推定値の平方根の2倍をとっていることに注意することが決定的に重要である。予測分布はガウス分布なので、この量によって95%信用集合を作れる。これは、真の関数を95%の見込みで含む区間についての信念を表す。ノイズの分散はまったく異なる尺度の上にあり、はるかに解釈しにくい。
Finally, let’s take a look at 20 posterior samples. These samples tell us what types of functions we believe might fit our data, a posteriori.
英語のヒント
最後に、20個の事後分布の標本を見てみよう。これらの標本は、事後的に、どんな種類の関数がデータに当てはまりうると考えるかを教えてくれる。
post_samples = np.random.multivariate_normal(post_mean, post_cov, size=20)
d2l.plt.scatter(train_x, train_y)
d2l.plt.plot(test_x, test_y, linewidth=2.)
d2l.plt.plot(test_x, post_mean, linewidth=2.)
d2l.plt.plot(test_x, post_samples.T, color='gray', alpha=0.25)
d2l.plt.fill_between(test_x, lw_bd, up_bd, alpha=0.25)
plt.legend(['Observed Data', 'True Function', 'Predictive Mean', 'Posterior Samples'])
d2l.plt.show()
In basic regression applications, it is most common to use the posterior predictive mean and standard deviation as a point predictor and metric for uncertainty, respectively. In more advanced applications, such as Bayesian optimization with Monte Carlo acquisition functions, or Gaussian processes for model-based RL, it often necessary to take posterior samples. However, even if not strictly required in the basic applications, these samples give us more intuition about the fit we have for the data, and are often useful to include in visualizations.
英語のヒント
基本的な回帰の応用では、事後予測平均と標準偏差を、それぞれ点予測量と不確かさの尺度として使うのが最もふつうである。モンテカルロ獲得関数を使ったベイズ最適化や、モデルベースRLのためのガウス過程のような、もっと高度な応用では、事後分布の標本をとる必要があることが多い。しかし、基本的な応用では厳密には必要でなくても、これらの標本はデータへの当てはまりについてもっと直観を与えてくれ、可視化に含めると役立つことが多い。