プリンキピア

第18章ガウス過程

18.3.5. Making Life Easy with GPyTorch18.3.5 GPyTorchで楽をする

As we have seen, it is actually pretty easy to implement basic Gaussian process regression entirely from scratch. However, as soon as we want to explore a variety of kernel choices, consider approximate inference (which is needed even for classification), combine GPs with neural networks, or even have a dataset larger than about 10,000 points, then an implementation from scratch becomes unwieldy and cumbersome. Some of the most effective methods for scalable GP inference, such as SKI (also known as KISS-GP), can require hundreds of lines of code implementing advanced numerical linear algebra routines.
英語のヒント
見てきたように、基本的なガウス過程回帰を完全に一から実装するのは実はかなり簡単である。しかし、さまざまなカーネルの選び方を探ったり、近似推論(分類でさえ必要になる)を考えたり、GPをニューラルネットワークと組み合わせたり、あるいはおよそ10,000点を超えるデータセットをもったりしたくなると、すぐに、一から書いた実装は扱いにくく面倒になる。SKI(KISS-GPとしても知られる)のような、大規模なGP推論のための最も効果的な方法のいくつかは、高度な数値線形代数のルーチンを実装する何百行ものコードを必要としうる。
In these cases, the GPyTorch library will make our lives a lot easier. We’ll be discussing GPyTorch more in future notebooks on Gaussian process numerics, and advanced methods. The GPyTorch library contains many examples. To get a feel for the package, we will walk through the simple regression example, showing how it can be adapted to reproduce our above results using GPyTorch. This may seem like a lot of code to simply reproduce the basic regression above, and in a sense, it is. But we can immediately use a variety of kernels, scalable inference techniques, and approximate inference, by only changing a few lines of code from below, instead of writing potentially thousands of lines of new code.
英語のヒント
こうした場合、GPyTorchライブラリを使えばずっと楽になる。GPyTorchについては、ガウス過程の数値計算と高度な方法についての今後のノートブックでさらに論じる。GPyTorchライブラリには多くの例が含まれている。このパッケージの感覚をつかむため、簡単な回帰の例を順に見ていき、GPyTorchを使って上の結果を再現するようにそれをどう手直しできるかを示す。上の基本的な回帰を再現するだけにしてはコードが多いように見えるかもしれないし、ある意味ではそのとおりである。しかし、何千行にもなりうる新しいコードを書く代わりに、下のコードを数行変えるだけで、さまざまなカーネル、大規模推論の技法、近似推論をすぐに使えるのである。
# First let's convert our data into tensors for use with PyTorch
train_x = torch.tensor(train_x)
train_y = torch.tensor(train_y)
test_y = torch.tensor(test_y)

# We are using exact GP inference with a zero mean and RBF kernel
class ExactGPModel(gpytorch.models.ExactGP):
    def __init__(self, train_x, train_y, likelihood):
        super(ExactGPModel, self).__init__(train_x, train_y, likelihood)
        self.mean_module = gpytorch.means.ZeroMean()
        self.covar_module = gpytorch.kernels.ScaleKernel(
            gpytorch.kernels.RBFKernel())

    def forward(self, x):
        mean_x = self.mean_module(x)
        covar_x = self.covar_module(x)
        return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)
This code block puts the data in the right format for GPyTorch, and specifies that we are using exact inference, as well the mean function (zero) and kernel function (RBF) that we want to use. We can use any other kernel very easily, by calling, for instance, gpytorch.kernels.matern_kernel(), or gpyotrch.kernels.spectral_mixture_kernel(). So far, we have only discussed exact inference, where it is possible to infer a predictive distribution without making any approximations. For Gaussian processes, we can only perform exact inference when we have a Gaussian likelihood; more specifically, when we assume that our observations are generated as a noise-free function represented by a Gaussian process, plus Gaussian noise. In future notebooks, we will consider other settings, such as classification, where we cannot make these assumptions.
英語のヒント
このコードブロックは、データをGPyTorchに合った形式にし、正確な推論を使うこと、そして使いたい平均関数(0)とカーネル関数(RBF)を指定する。たとえばgpytorch.kernels.matern_kernel()やgpyotrch.kernels.spectral_mixture_kernel()を呼び出せば、ほかのどんなカーネルもとても簡単に使える。ここまでは、何の近似もせずに予測分布を推論できる正確な推論だけを論じてきた。ガウス過程で正確な推論を行えるのは、ガウスの尤度をもつとき、もっと具体的には、観測が、ガウス過程で表されるノイズのない関数にガウスノイズを加えたものとして生成されると仮定するときだけである。今後のノートブックでは、分類のような、これらの仮定を置けないほかの設定を考える。
# Initialize Gaussian likelihood
likelihood = gpytorch.likelihoods.GaussianLikelihood()
model = ExactGPModel(train_x, train_y, likelihood)
training_iter = 50
# Find optimal model hyperparameters
model.train()
likelihood.train()
# Use the adam optimizer, includes GaussianLikelihood parameters
optimizer = torch.optim.Adam(model.parameters(), lr=0.1)
# Set our loss as the negative log GP marginal likelihood
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)
Here, we explicitly specify the likelihood we want to use (Gaussian), the objective we will use for training kernel hyperparameters (here, the marginal likelihood), and the procedure we we want to use for optimizing that objective (in this case, Adam). We note that while we are using Adam, which is a “stochastic” optimizer, in this case, it is full-batch Adam. Because the marginal likelihood does not factorize over data instances, we cannot use an optimizer over “mini-batches” of data and be guaranteed convergence. Other optimizers, such as L-BFGS, are also supported by GPyTorch. Unlike in standard deep learning, doing a good job of optimizing the marginal likelihood corresponds strongly with good generalization, which often inclines us towards powerful optimizers like L-BFGS, assuming they are not prohibitively expensive.
英語のヒント
ここでは、使いたい尤度(ガウス)、カーネルのハイパーパラメータの訓練に使う目的関数(ここでは周辺尤度)、そしてその目的関数を最適化するのに使いたい手順(この場合はAdam)を明示的に指定する。「確率的」な最適化手法であるAdamを使っているが、この場合はフルバッチのAdamであることに注意しよう。周辺尤度はデータの事例ごとに分解できないので、データの「ミニバッチ」に対する最適化手法を使って、しかも収束を保証することはできない。L-BFGSのようなほかの最適化手法も、GPyTorchでサポートされている。標準的な深層学習とは違って、周辺尤度をうまく最適化することはよい汎化と強く対応しており、そのため、法外に高くつかないかぎり、L-BFGSのような強力な最適化手法に傾くことが多い。
for i in range(training_iter):
    # Zero gradients from previous iteration
    optimizer.zero_grad()
    # Output from model
    output = model(train_x)
    # Calc loss and backprop gradients
    loss = -mll(output, train_y)
    loss.backward()
    if i % 10 == 0:
        print(f'Iter {i+1:d}/{training_iter:d} - Loss: {loss.item():.3f} '
              f'squared lengthscale: '
              f'{model.covar_module.base_kernel.lengthscale.item():.3f} '
              f'noise variance: {model.likelihood.noise.item():.3f}')
    optimizer.step()
Iter 1/50 - Loss: 1.000 squared lengthscale: 0.693 noise variance: 0.693
Iter 11/50 - Loss: 0.711 squared lengthscale: 0.490 noise variance: 0.312
Iter 21/50 - Loss: 0.451 squared lengthscale: 0.506 noise variance: 0.127
Iter 31/50 - Loss: 0.330 squared lengthscale: 0.485 noise variance: 0.055
Iter 41/50 - Loss: 0.344 squared lengthscale: 0.472 noise variance: 0.038
Here we actually run the optimization procedure, outputting the values of the loss every 10 iterations.
英語のヒント
ここで、実際に最適化の手順を実行し、10回の反復ごとに損失の値を出力する。
# Get into evaluation (predictive posterior) mode
test_x = torch.tensor(test_x)
model.eval()
likelihood.eval()
observed_pred = likelihood(model(test_x))
The above codeblock enables us to make predictions on our test inputs.
英語のヒント
上のコードブロックで、テスト入力に対して予測ができる。
with torch.no_grad():
    # Initialize plot
    f, ax = d2l.plt.subplots(1, 1, figsize=(4, 3))
    # Get upper and lower bounds for 95\% credible set (in this case, in
    # observation space)
    lower, upper = observed_pred.confidence_region()
    ax.scatter(train_x.numpy(), train_y.numpy())
    ax.plot(test_x.numpy(), test_y.numpy(), linewidth=2.)
    ax.plot(test_x.numpy(), observed_pred.mean.numpy(), linewidth=2.)
    ax.fill_between(test_x.numpy(), lower.numpy(), upper.numpy(), alpha=0.25)
    ax.set_ylim([-1.5, 1.5])
    ax.legend(['True Function', 'Predictive Mean', 'Observed Data',
               '95% Credible Set'])
Finally, we plot the fit.
英語のヒント
最後に、当てはまりをプロットする。
We see the fits are virtually identical. A few things to note: GPyTorch is working with squared length-scales and observation noise. For example, our learned noise standard deviation in the for scratch code is about 0.283. The noise variance found by GPyTorch is 0.81≈0.2832. In the GPyTorch plot, we also show the credible set in the observation space rather than the latent function space, to demonstrate that they indeed cover the observed datapoints.
英語のヒント
当てはまりは事実上同一であることがわかる。いくつか注意すべきことがある。GPyTorchは、二乗した長さスケールと観測ノイズを扱っている。たとえば、一から書いたコードで学習したノイズの標準偏差はおよそ0.283である。GPyTorchが見つけたノイズの分散は0.81≈0.2832である。GPyTorchのプロットでは、信用集合が観測したデータ点を実際に覆うことを示すため、信用集合を潜在的な関数の空間ではなく観測の空間で示している。