プリンキピア

第19章ハイパーパラメータ最適化

19.1.1. The Optimization Problem19.1.1 最適化問題

We will start with a simple toy problem: searching for the learning rate of the multi-class logistic regression model SoftmaxRegression from Section 4.5 to minimize the validation error on the Fashion MNIST dataset. While other hyperparameters like batch size or number of epochs are also worth tuning, we focus on learning rate alone for simplicity.
英語のヒント
簡単なおもちゃの問題から始める。つまり、Fashion MNISTのデータセットでの検証誤差を最小化するように、4.5節の多クラスロジスティック回帰モデルSoftmaxRegressionの学習率を探す。バッチの大きさやエポック数のようなほかのハイパーパラメータも調整する価値があるが、簡単にするため学習率だけに焦点を当てる。
import numpy as np
import torch
from scipy import stats
from torch import nn
from d2l import torch as d2l
Before we can run HPO, we first need to define two ingredients: the objective function and the configuration space.
英語のヒント
HPOを実行する前に、まず二つの材料、つまり目的関数と設定空間を定義する必要がある。

19.1.1.1. The Objective Function19.1.1.1 目的関数

The performance of a learning algorithm can be seen as a function f:𝒳→ℝ that maps from the hyperparameter space 𝐱∈𝒳 to the validation loss. For every evaluation of f(𝐱), we have to train and validate our machine learning model, which can be time and compute intensive in the case of deep neural networks trained on large datasets. Given our criterion f(𝐱) our goal is to find 𝐱⋆∈argmin𝐱∈𝒳f(𝐱).
英語のヒント
学習アルゴリズムの性能は、ハイパーパラメータ空間𝐱∈𝒳から検証損失への写像である関数f:𝒳→ℝとみなせる。f(𝐱)を評価するたびに、機械学習モデルを訓練し検証しなければならず、大きなデータセットで訓練する深層ニューラルネットワークの場合は、時間と計算を大量に要しうる。基準f(𝐱)が与えられたとき、目標は𝐱⋆∈argmin𝐱∈𝒳f(𝐱)を見つけることである。
There is no simple way to compute gradients of f with respect to 𝐱, because it would require to propagate the gradient through the entire training process. While there is recent work (Franceschi et al., 2017, Maclaurin et al., 2015) to drive HPO by approximate “hypergradients”, none of the existing approaches are competitive with the state-of-the-art yet, and we will not discuss them here. Furthermore, the computational burden of evaluating f requires HPO algorithms to approach the global optimum with as few samples as possible.
英語のヒント
𝐱についてのfの勾配を計算する簡単な方法はない。訓練の過程全体を通じて勾配を伝播させる必要があるからである。近似的な「ハイパー勾配」でHPOを進める最近の研究(Franceschi et al., 2017、Maclaurin et al., 2015)もあるが、既存のやり方はどれもまだ最先端の方法に太刀打ちできず、ここでは論じない。さらに、fを評価する計算の負担のため、HPOのアルゴリズムはできるだけ少ない標本で大域的な最適値に近づく必要がある。
The training of neural networks is stochastic (e.g., weights are randomly initialized, mini-batches are randomly sampled), so that our observations will be noisy: y∼f(𝐱)+ϵ, where we usually assume that the ϵ∼N(0,σ) observation noise is Gaussian distributed.
英語のヒント
ニューラルネットワークの訓練は確率的である(たとえば、重みはランダムに初期化され、ミニバッチはランダムに抜き出される)ので、観測にはノイズが乗る。つまりy∼f(𝐱)+ϵであり、ここでふつう、観測ノイズϵ∼N(0,σ)はガウス分布に従うと仮定する。
Faced with all these challenges, we usually try to identify a small set of well performing hyperparameter configurations quickly, instead of hitting the global optima exactly. However, due to large computational demands of most neural networks models, even this can take days or weeks of compute. We will explore in Section 19.4 how we can speed-up the optimization process by either distributing the search or using cheaper-to-evaluate approximations of the objective function.
英語のヒント
こうした難題すべてに直面して、ふつうは大域的な最適値を正確に当てる代わりに、性能のよいハイパーパラメータの設定の小さな集合をすばやく見つけようとする。しかし、たいていのニューラルネットワークのモデルは大きな計算を要するので、これでさえ何日も何週間もの計算がかかりうる。19.4節では、探索を分散させるか、目的関数の評価がより安価な近似を使うことで、最適化の過程をどう速められるかを探る。
We begin with a method for computing the validation error of a model.
英語のヒント
まず、モデルの検証誤差を計算する方法から始める。
class HPOTrainer(d2l.Trainer):  #@save
    def validation_error(self):
        self.model.eval()
        accuracy = 0
        val_batch_idx = 0
        for batch in self.val_dataloader:
            with torch.no_grad():
                x, y = self.prepare_batch(batch)
                y_hat = self.model(x)
                accuracy += self.model.accuracy(y_hat, y)
            val_batch_idx += 1
        return 1 -  accuracy / val_batch_idx
We optimize validation error with respect to the hyperparameter configuration config, consisting of the learning_rate. For each evaluation, we train our model for max_epochs epochs, then compute and return its validation error:
英語のヒント
learning_rateからなるハイパーパラメータの設定configについて、検証誤差を最適化する。評価のたびに、モデルをmax_epochsエポック訓練し、それからその検証誤差を計算して返す。
def hpo_objective_softmax_classification(config, max_epochs=8):
    learning_rate = config["learning_rate"]
    trainer = d2l.HPOTrainer(max_epochs=max_epochs)
    data = d2l.FashionMNIST(batch_size=16)
    model = d2l.SoftmaxRegression(num_outputs=10, lr=learning_rate)
    trainer.fit(model=model, data=data)
    return trainer.validation_error().detach().numpy()

19.1.1.2. The Configuration Space19.1.1.2 設定空間

Along with the objective function f(𝐱), we also need to define the feasible set 𝐱∈𝒳 to optimize over, known as configuration space or search space. For our logistic regression example, we will use:
英語のヒント
目的関数f(𝐱)とともに、最適化の対象となる実行可能な集合𝐱∈𝒳も定義する必要がある。これは設定空間あるいは探索空間として知られる。ロジスティック回帰の例では、次を使う。
config_space = {"learning_rate": stats.loguniform(1e-4, 1)}
Here we use the use the loguniform object from SciPy, which represents a uniform distribution between -4 and -1 in the logarithmic space. This object allows us to sample random variables from this distribution.
英語のヒント
ここでは、SciPyのloguniformオブジェクトを使う。これは、対数空間での-4から-1の間の一様分布を表す。このオブジェクトを使えば、この分布から確率変数を抜き出せる。
Each hyperparameter has a data type, such as float for learning_rate, as well as a closed bounded range (i.e., lower and upper bounds). We usually assign a prior distribution (e.g, uniform or log-uniform) to each hyperparameter to sample from. Some positive parameters, such as learning_rate, are best represented on a logarithmic scale as optimal values can differ by several orders of magnitude, while others, such as momentum, come with linear scale.
英語のヒント
各ハイパーパラメータには、learning_rateのfloatのようなデータ型と、閉じた有界な範囲(つまり下限と上限)がある。ふつうは、抜き出すための事前分布(たとえば一様分布や対数一様分布)を各ハイパーパラメータに割り当てる。learning_rateのような正のパラメータの中には、最適な値が何桁も異なりうるので対数スケールで表すのがいちばんよいものがあり、一方、モメンタムのようなほかのパラメータは線形スケールで扱う。
Below we show a simple example of a configuration space consisting of typical hyperparameters of a multi-layer perceptron including their type and standard ranges.
英語のヒント
以下に、多層パーセプトロンの典型的なハイパーパラメータからなる設定空間の簡単な例を、その型と標準的な範囲とともに示す。
: Example configuration space of multi-layer perceptron
英語のヒント
:多層パーセプトロンの設定空間の例
Table 19.1.1表19.1.1
label:tab_example_configspace
英語のヒント
label:tab_example_configspace
Name名前Type型Hyperparameter Rangesハイパーパラメータの範囲log-scale対数スケール
learning rate学習率float浮動小数点数:math:` [10^{-6},10^{-1}]`[10⁻⁶, 10⁻¹]yesはい
batch sizeバッチの大きさinteger整数[8,256]yesはい
momentumモメンタムfloat浮動小数点数[0,0.99]noいいえ
activation function活性化関数categoricalカテゴリ:mat h:{textrm{tanh} , textrm{relu}}{tanh, relu}
number of unitsユニット数integer整数[32,1024]yesはい
number of layers層の数integer整数[1,6]noいいえ
In general, the structure of the configuration space 𝒳 can be complex and it can be quite different from ℝd. In practice, some hyperparameters may depend on the value of others. For example, assume we try to tune the number of layers for a multi-layer perceptron, and for each layer the number of units. The number of units of the l-th layer is relevant only if the network has at least l+1 layers. These advanced HPO problems are beyond the scope of this chapter. We refer the interested reader to (Baptista and Poloczek, 2018, Hutter et al., 2011, Jenatton et al., 2017).
英語のヒント
一般に、設定空間𝒳の構造は複雑になりえて、ℝdとはかなり異なりうる。実際には、ほかのハイパーパラメータの値に依存するハイパーパラメータもある。たとえば、多層パーセプトロンの層の数と、各層のユニットの数を調整しようとするとしよう。l-th層のユニットの数は、ネットワークが少なくともl+1層をもつときにだけ意味をもつ。こうした高度なHPOの問題はこの章の範囲を超える。興味のある読者には(Baptista and Poloczek, 2018、Hutter et al., 2011、Jenatton et al., 2017)を勧める。
The configuration space plays an important role for hyperparameter optimization, since no algorithms can find something that is not included in the configuration space. On the other hand, if the ranges are too large, the computation budget to find well performing configurations might become infeasible.
英語のヒント
設定空間はハイパーパラメータ最適化で重要な役割を果たす。設定空間に含まれていないものは、どのアルゴリズムも見つけられないからである。一方、範囲が大きすぎると、性能のよい設定を見つけるための計算の予算が実行不可能なほどになるかもしれない。