데이터와 AI / NOTE 31

하이퍼파라미터 최적화

Hyperparameter Optimization

베이지안 최적화, 가우시안 과정과 획득함수를 살펴봅니다.

♫ 이 문서 듣기

개념에서 수식으로

먼저 이해할 내용

학습률이나 층수처럼 학습 전에 정하는 값도 결과에 영향을 준다. 그러나 각 설정을 실제로 평가하는 데 비용이 들면 모든 조합을 시도하기 어렵다. 이 글은 지금까지의 관측으로 성능을 추정하고 다음에 평가할 설정을 고르는 과정을 다룬다.

기호를 먼저 읽기

x
이번에 시험할 설정 또는 입력 위치
f(x), y
알고 싶은 성능과 잡음을 포함한 관측값
μ(x), σ(x)
예측한 성능의 중심과 불확실성
a(x)
다음 평가 위치를 고르는 획득함수
rₜ, R_T
한 번의 선택 손해와 그 누적값
O, T
Neural Process 구간의 관측 집합과 예측할 입력 집합

이 글의 흐름

평가 목표와 탐색 공간을 정하고, 대리모델로 평균과 불확실성을 추정한다. 획득함수로 다음 설정을 고르는 반복을 읽은 뒤, 함수의 분포를 학습하는 Neural Process와 연결한다.

주제와 표기

Hyperparameter Optimization

Bayesian optimization

Optimization of Black-Box Functions

평가할 수 있지만 내부 식은 모르는 함수를 다룬다

f(x)의 수식을 직접 사용할 수 없더라도 x를 넣고 결과 y를 관측할 수 있다. 원문은 잡음 ε가 더해지는 평가를 두고, 제한된 평가 횟수 안에서 좋은 설정을 찾는 문제를 정의한다. 최댓값을 찾는 설정과 검증 손실을 최소화하는 설정은 목표 방향을 구별한다.

Interested in finding the global maximizer
x=argmaxxXf[x]
where f[x] can only be evaluated via queries to a black - box that provides noisy outputs of the form yt ~ [f[xt], σnoise^2]
yt=f[xt]+ϵt
xtyt
a closed - form expression of f[x] is not available , or
a nonlinear and generally non - convex function f[x] whose derivatives are unavailable, or
but expensive noisy evaluations at query points are available

Regret

Instantaneous regret

선택으로 놓친 성능을 측정한다

rₜ는 최적 성능과 이번 선택 성능의 차이이다. 이를 더한 R_T는 탐색 과정 전체의 손해이고, 가장 좋은 관측과 비교하는 단순 regret은 최종 선택의 품질에 관련된다. 두 지표는 같은 정보를 요약하는 것이 아니다.

rt=f[x]f[xt]

Cumulative regret (in the bandit setting)

RT=t=1Trt=t=1T(f[x]f[xt])

Simple regret: (in the optimization setting)

ST=mintTrt=f[x]maxxtf[xt]

No regret algorithms in the bandit setting: limTRTT=0

Note that ST≤1/TRT

Hyperparameter Optimization

학습할 가중치와 탐색할 설정을 나눈다

가중치는 학습 과정에서 조정되지만, 학습률·층수·배치 크기 같은 설정은 별도의 탐색 대상으로 놓을 수 있다. 각 후보를 평가한 결과를 다시 다음 후보 선택에 사용한다. 원문에 등장하는 응용·서비스 사례는 탐색 문제의 예시이며 현재 서비스 현황이나 실제 임상 절차를 안내하는 내용은 아니다.

Hyperparameters xt

Validationlossf[xt]
Learning rate
#layers, #nodes, Neural Architecture
Kernel size in CNN
Batch size
Grid Search, Random Search

SigOput

Observed model performance↔Suggested Hyperparameters

Objective

Generalization loss

Search space

Hyperparameter settings

Observations

Empirical loss on test set

Automated machine learning

Objective

Generalization loss

Search space

Feature processing methods
algorithm selection
Hyperparameter settings

Observations

Empirical loss on test set

Clinical drug trials in healthcare

Objective

Drug effectiveness

Search space

ingredients
concentrations

Observations

improved or not

Active user modeling

Objective

Ask right questions

Search space (x)

Attributes of a user query

Observations (f[x])

Response from the human

Hyperparameters

Model parameters

설정 공간을 체계적으로 탐색한다

Grid Search는 미리 정한 격자를, Random Search는 무작위 후보를 평가하는 방식이다. AutoML은 특징 처리·모델 선택·설정 탐색을 함께 다루는 더 넓은 작업으로 소개된다. 자동화의 범위와 실제 평가 목표를 구별해 읽는다.

Parameters (that describe the model) learned during training
Weights in linear models, neural networks, kernel machines

Hyperparameters

Parameters that can be set arbitrarily by users before starting training
Trade - off parameters in reqularization, initial values, learning rates, kernel width, number of layers, number of nodes, and so on

Auto ML ⊃ Hyperparameter Optimization ⊃ Neural Architecture Search

Search over Configuration Space

How can we find the best configuration of hyperparameters ?

Grid serach

Random serach

Any more efficient method in terms of the number of eveluations?

⇒Bayesian optimization

AutoML

Automate ML tasks by deploying ML into ML itself

Feature processing

Model/algorithm selection

Hyperparameter tuning

Many companies are using AutoML

Google

기존 사례와 현재 실행 코드를 구별한다

이 구간의 회사명과 코드 조각은 원문 작성 당시 자동화 도구의 예이다. model.fit과 predict는 학습과 예측의 단계를 보여준다. 여기의 호출 형식을 현재 라이브러리에서 그대로 실행 가능한 최신 API로 보장하지 않는다.

Cloud AutoML

Facebook

AI that builds AI (Asimo : automatically produces improved versions of current versions)

Microsoft

in Azure Machine Learning

Amazon

AutoGluon

AutoGluon: Introduced by Amazon in January, 2020

An open - source library that empowers developers to easily build Automatic Machine Learning (AutoML) models

Democratizes the task of ML

Easily can train and deploy high - accuracy models
Only requires a few lines of code
Cab be customized toward specific use cases
Carries out automatic hyperparameter tuning, model selection, architecture search, and data processing
model = task . fit (data) →model . predict (new_data)
#AutoGluon Classifier
predictor = task . fit (train_data = train_data, label = label_column, output_directory = dir)
y_pred = predictor . predict (test_data_nolab)

Bayesian Optimization

Surrogate function

성능의 추정과 다음 실험의 선택을 분리한다

대리모델은 지금까지의 (x,y)로 아직 평가하지 않은 위치의 성능을 추정한다. 획득함수는 이 추정의 평균과 불확실성으로 다음 평가 위치를 고른다. 대리모델의 출력을 실제 측정 성능으로 혼동하지 않는다.

Use a probabilistic model for the latent function f[] to guide the search, given D1:t = {(x1, y1), …, (xt, yt)} (for instance, GP regression)
수식

Auquisition function

Determine where next to sample from the objective function, balancing exploitation and exploration
Choose the next x where the posterior mean μ[x] is high (exploitation) and the posterior variance σ2[x] is high (exploration)

Surrogate model

원본 도해
Bayesian optimization provides an efficient approach in terms of the number of function evaluations required .

GP regression

Regression

GP의 평균과 분산을 각각 읽는다

예측 평균 식은 관측값 y를 커널 관계에 따라 결합한다. 예측 분산 식은 원래의 불확실성에서 관측으로 설명된 부분을 빼는 구조이다. K는 관측 위치끼리의 관계이고 k(x)는 새 위치와 관측 위치의 관계이므로 두 대상을 구별한다.

Parametric regression
Nonparametric

Random function = Gaussian Process

Treat the latent vector as parameters
f=(f[x1],,f[xN])TRN
Infer the value of f[x] at any location x∈X, given past obserations D1:t, which is Gaussian with marginal mean and variance given by
μt[x]=kt[x]T(Kt+σnoise2I)1yt
σt2[x]=k(x,x)kt[x]T(Kt+σnoise2I)1kt[x]
GP[μ[x],[x,x]] = (mean function, covariance function)

Choice of Kernels

Squared exponential kernel (Gaussian kernel)

커널은 위치 사이의 유사성을 정한다

제곱지수 커널에서는 두 입력이 멀어질수록 지수항의 영향이 작아진다. 길이 척도 ℓ는 입력 거리의 기준을 조절한다. Matérn 구간은 추가적인 매끄러움 계수를 포함하며, 특수함수의 세부 형태는 원문의 정의 범위에서 확인한다.

k[xi,xj]=σf2exp[122|xixj|2],(forisotropicmodel)
or
k[xi,xj]=σf2exp[122(xixj)T1(xixj)]
where ∑ = diag (ℓ_1, …, ℓ_D), (for anisotropic model)

Matern Kernel

k[xi,xj]=21νΓ[ν](2ν|xixj|I)νHν(2ν|xixj|I)
where ν is a smoothness parameter, ℓ is a length - scale parameter I, Γ[] is the gamma function, and Hν is a modified Bessel function

Few Things about GP

Pros

예측 불확실성과 계산 비용을 함께 본다

GP의 장점과 한계를 읽은 뒤, Random Forest와 신경망 등 다른 대리모델의 역할을 비교한다. 선택 기준은 평균을 잘 맞추는지뿐 아니라 불확실성을 어떤 방식으로 다루는지이다. 원문의 장단점을 모든 데이터에 대한 성능 보장으로 바꾸어 읽지 않는다.

Good uncertainty estimates
Generality in the sense that GP with a choice of reasonable kernel can approximate a broad class of functions

Cons

Notscalable(standardGPregressionrequiresO(N3))
Limited by kernels

Besides GP regression, as surrogate models, you can also use

Random forests

Good : Fast & Parallelizable training
Bad : Empirical confidence bounds & Poor extrapolation

Neural networks

Learn f by a NN
Augment the last layer by Bayesian linear regression
Compute the uncertainty estimate by marginalizing out the output weights

Alternative Surrogate Model: Random Forests

Exact GP
SPGP
SSGP
Random Forest

More alternative surrogate models include

Mondrian forest regression

Stochastic processes for random partitioning

Neural processes

Combine the best of neural networks and Gaussian processes

Algorithm Outline: Bayesian Optimization

선택·평가·추정 갱신을 반복한다

현재 대리모델에서 획득함수가 큰 x를 고른다. 실제 함수를 평가해 y를 얻고, 이를 데이터 집합에 추가한 뒤 평균과 분산을 다시 계산한다. 이 반복의 결과가 유한한 평가 횟수에서 참된 전역 최적점임을 무조건 보장하는 것은 아니다.

Input : Initial data D1:1 = {(x1, y1)}, limit T∈N>1
output:Aglobalmaximizerx
for t = 1, 2, …, T - 2 do
Find xt+1 that maximizes the acquisition function over the current GP : xt+1 = argmaxx a[xD1:t]
Sample the objective function : yt+1 = f[xt+1] + ϵt+1
Augment the data : D1:t+1 = {D1:t, (xt+1, yt+1)}
UpdatetheGP,computingμt+1[x],σt+12[x]:μt+1[x]=kt+1[x]T(Kt+1+ρ2I)1yt+1
σt+12[x]=k[x,x]kt+1[x]T(Kt+1+ρ2I)1kt+1[x]
end for
returnx=argmaxx{x1,,xT}μT[x]

Handling Categorical or Integer-Valued Variables

Spearmint

Integer-valued variables

실수·정수·범주형 변수는 허용 값이 다르다

층수는 정수이고 모델 종류는 범주형 값이다. 실수 공간에서 고른 후보를 단순히 반올림하거나 숫자로 부호화하면 원래의 탐색 의미와 달라질 수 있다. 원문에 적힌 방법별로 후보의 표현과 평가 가능한 값을 구별한다.

Rounding after optimizing the acquisition function

Categorical variables

One - hot encoding

A naive approach

1. Optimize the acquisition function a[] assuming all variables take real values
수식

BayesOpt

Encodes the categorical variable as an integer variable (no one - hot encoding)
Uses an ARD kernel with a fixed spatial scale on that dimension that is so small that neighboring integer values have virtually no effect on each other

A navie approach

1. Optimize the acquisition function a[] assuming all varables take real values
수식

Acquisition Functions

획득함수는 실험 결과의 기대 효용이다

아직 y를 모르므로 가능한 결과마다의 효용을 예측분포로 평균한다. 이 평균이 a(x)이고, 이를 크게 하는 x를 다음 후보로 고른다. 따라서 실제 성능 f(x)와 다음 실험의 가치 a(x)는 다른 함수이다.

Given D1:t = {(x1, y1), …, (xt, yt)}, we determine the next evaluation location xt+1 via optimizing the acquisition function a[xD1:t]
xt+1=argmaxxXa[xD1:t]
The acquisition function a[xD1:t] should be high in areas where the maximum is most likely to lie given the current data . (exploitation)
수식

Utility Function

Consider a utility function, u : RD×R|→R, which maps
an arbitrary query point x,
its corresponding function value y = f[x]
to a measure of quality of the experiment
Given data points observed so far D1:t, the acquisition function is the expected utility of a query point x,
a[xD1:t]=u[x,y;ξ]p[yx,D1:t]dy
where
u[x,y;ξ] : utility function (ξ is a setting of hyperparameters)
p[yx,D1:t] : a belief p over the unknown outcome y revealed when evaluating at x

Utility and Acquisition Functions

Probability of Improvement (PI)

개선 확률과 개선 크기는 다르다

PI는 기준을 넘는지에 관심을 두고, EI는 넘는 경우 얼마나 개선되는지까지 본다. UCB 형태는 평균과 불확실성에 가중치를 두어 합친다. 세 방법을 모두 같은 점수라고 보기보다 각각 무엇을 높이려는지 확인한다.

u[x,y;ξ]=I(y>α)

Expected Improvement (EI)

u[x,y;ξ]=(yα)I(y>α)=ReLU[yα]

GP Upper Confidence Bound (GP-UCB)

u[x,y;ξ]=μ+βσ

Expected Improvement

기대개선은 나빠지는 결과를 0으로 둔다

max(y−y*,0)은 현재 최선보다 좋아지는 부분만 남기는 함수이다. 이를 가능한 y의 분포로 평균하면 기대개선이 된다. 원문 중간 적분에서 max 또는 개선 구간이 빠져 보이는 줄을 모든 실수 구간의 단순 평균 차이와 같다고 해석하지 않는다.

Expected Improvement w . r . t . the best observed objective value y^* so far is defined as
EI=Ep[y][max[yy,0]]
=max[yy,0]N[yy¯,σ2]dy
EI=max[yy,0]N[yy¯,σ2]dy
=(yy)N[yy¯,σ2]dy
=yN[yy¯,σ2]dyyN[yy¯,σ2]dy
=y¯Φ(y¯yσ)+σϕ(y¯yσ)yΦ(y¯yσ)
=(y¯y)Φ(y¯yσ)+σϕ(y¯yσ)
where Φ[] is the cumulative distribution function and ϕ[] is the probability density for the standard normal distribution

Exploration-Exploitation Trade-Off in EI

불확실성을 고려하되 정의를 일관되게 유지한다

평균이 좋은 곳은 활용할 가치가 있고, 분산이 큰 곳은 새 정보가 있을 수 있다. EI와 UCB는 이를 다른 방식으로 조합한다. 원문의 z 보조식에는 자기참조처럼 보이는 항이 있으므로, 그 식을 그대로 완성된 수치 계산식으로 확정하지 않는다.

EI[x] = {{{(μ[x] - μ[x] - ξ) Φ[z] + σ[x] ϕ[z], if σ[x] >0}, {0, if σ[x] = 0}}
z = {{{(μ[x] - μ[x] - ξ)/σ[x] + σ[x] ϕ[z], if σ[x] >0}, {0, if σ[x] = 0}}

GP-UCB

Trade - off between posterior mean (exploitation) and posterior variance (exploration) calculated by GP regression
GP - USB chooses
xt=argmaxxX(μt1[x]+νβtσt1[x])
수식
RT=t=1T(f[x]f[xt])

Compressed Sensing

NAS in practice

모델 탐색과 여러 분류기의 결합을 연결한다

NAS 항목은 구조 후보를 평가하는 문제이고, Soft Voting 식은 여러 분류기의 범주 확률을 가중합하는 문제이다. 합산한 확률 점수에서 가장 큰 범주를 선택한다는 argmax의 역할을 확인한다. 가중치 w와 범주 첨자 k는 서로 다른 대상을 나타낸다.

Random Search combined with cheap evaluation strategies is an effective method for neural architecture search

Application to Soft-Voting in Ensemble

y^t=argmaxkjwjpk,nj
where pk,nj denotes the base classifier j ' s prediction that the input xt is a member of class k

Neural Process

Generative query network (GQN)

Generalizations of GQN framework

하나의 함수와 함수들의 분포를 구별한다

Neural Process 구간은 관측에 따라 가능한 함수가 달라지는 모델을 다룬다. 신경망·GP·CNP·NP의 비교는 하나의 예측함수, 예측분포, 일관된 함수 표본을 서로 구별하기 위한 것이다. 여러 결과를 출력한다는 사실만으로 같은 종류의 불확실성을 표현하는 것은 아니다.

Conditional neural process (CNP)
Neural process (NP)
Attentive neural process (ANP)
Combine the benefits of both neural networks and GPs

Wanted

A model which represents a distribution over functions

Gaussian Processes

Nonparametric Bayesian method for learning a distribution over a wide class of nonlinear functions
Data - efficient
Inference requires O (N^3)

(non-Bayesian) deep neural networks (DNNs)

Learn a single function from a training set
Learn amount of data
More scalable than GPs for inference

Neural processes

NN - based probabilistic model to represent a distribution over functions, combining the best of two worlds

Generative Query Network

관측한 점들로 아직 보지 않은 위치를 예측한다

GQN은 다른 관점의 관측으로 새로운 관점의 결과를 예측하는 예이다. CNP에서는 O가 관측된 입력·출력 쌍이고 T가 예측할 입력 집합이다. 같은 x라도 관측에 포함되었는지 예측 대상인지에 따라 역할이 다르다.

GQNs learn to predict what 3D scenes look like viewed from a new position given some context observations of that scene from other viewpoints

Conditional Neural Processes

Motivation

CNPs combine benefits of NNs and GPs

the flexibility of stochastic processes such as GPs
structured as neural networks and trained via gradient descent from data directly

Supervised Learning: Data Description

Observed data

O={(xn,yn)n=1,,N}

Target inputs

T={xnn=N+1,,N+M}

Underlying ground truth function

f:XY

Task

Predict the output values f[x] for every x∈T given O

Supervised Learning

g[xn]
Parameterized approximating function (e . g ., neural networks)

CNP

Embedding

관측을 표현으로 바꾸고 하나로 모은다

각 (xₙ,yₙ)을 h로 임베딩하여 rₙ을 만든다. 이를 순서에 영향받지 않는 집계 a로 모아 r을 얻고, 예측할 x와 r을 함께 넣어 출력한다. 관측점 수가 달라도 고정된 표현으로 요약하려는 구조이다.

h[xn,yn]

Aggregation

r=a[r1,,rN]

Parameterized approximating function (e.g., neural networks)

g[xn,r]

GP vs CNP

Gaussian processes

Assumption made on P is that all finite sets of functional evaluations of f are jointly Gaussian distributed
Predictive distribution P[f[T]O,T] has a simple analytic form defined by prior assumption on the pairwise correlation structure specified via a kernel function
Pros : Data - efficient
Cons : Difficult to design appropriate priors and computationally expensive O ((N + M)^2)

Conditional neural processes

Directly parameterize conditional stochastic processes without imposing consistency w . r . t . some prior processes
Parametrize distributions over f[T], given a distributed representation of O of fixed dimensionality

CNP: Model

예측값 대신 예측분포의 계수를 출력한다

CNP의 Qθ는 관측과 목표 입력을 조건으로 결과의 분포를 정의한다. gθ가 내는 φₙ은 그 분포의 매개변수이며, 회귀 예에서는 평균과 분산이다. 이 평균·분산은 관측값 자체가 아니라 모델이 계산한 예측의 중심과 불확실성이다.

CNP is a conditional stochastic process Qθ that defines distributions over f[x] for inputs x∈T
Qθ[f[T]O,T]P[f[T]O,T]
Qθ is required to be permutation - invariant
Qθ[f[T]O,T]=Qθ[π[f[T]]O,π[T]]
CNPs are scalable, achieving a running time complexity of O (N + M) for makeing M predictions with N observations

CNP: Architecture

Architecture

Encoder·Aggregator·Decoder를 순서대로 계산한다

각 관측을 rₙ으로 바꾼 뒤 평균 집계로 r을 얻는다. 목표 입력과 r에서 φₙ을 구해 예측분포를 구성한다. 집계가 입력 순서에 무관하다는 것과 목표 출력의 위치가 입력과 함께 바뀐다는 것을 구별한다.

rn=hθ[xn,yn],(xn,yn)O
r=a[r1,,rN]
ϕn=gθ[xn,r],xnT

ϕn are parameters for Qθ

Qθ[f[x]O,xn]=Q[f[xn]ϕn]
For regression tasks, use ϕn to parameterize the mean and variance of Gaussian distribution : ϕn = (μn, σn2)
For classification, ϕn parameterizes the logits of the class probabilities pk over the k classes of a categorical distribution

The mean aggregation is used

a[r1,,rN]=1Nn=1Nrn

Neural Processes

Motivation

잠재변수를 통해 가능한 함수의 변화를 나타낸다

NP는 요약 r에서 잠재변수 z의 분포를 정하고, x와 z를 조건으로 출력분포를 만든다. 같은 관측에서도 z에 따라 연결된 예측이 달라질 수 있다는 관점이다. 마지막 학습 ELBO의 구체적인 식은 그림에만 있으므로, 해당 식의 세부 항까지 확인한 것으로 설명하지 않는다.

NP=LatentvariablemodelversionofCNP
NN GP CNP NP
Can fit more than one function at test time(distribution over functions) x O O O
Computationally cheap at test time O x O O
Can sample entire coherent functions x O x O

Neural Networks vs Gaussian Processes

NNs

A parametric model that is tuned via gradient descent

GPs

A probabilistic model that defines a distribution over possible functions (probabilistic, data - efficient, but computationally intensive)

Architecture

Encoder

rn=hθ[xn,yn],(fn,yn)O

Aggregator

r = a[r1,,rN] parameterizes the mean and variance of latent Gaussian random variable z, i . e ., z ~ N[μ[r],Iσ2[r]]

Conditional decoder

ϕn = gθ[xn,z], ∀xn∈T, parameterizes the output distribution (either a Gaussian or a categorical distribution)

Training

ELBO is given by
수식

정리하면

좋아 보이는 설정을 더 조사하는 것과 아직 잘 모르는 설정을 탐색하는 것은 다른 목적이다. 두 목적을 어떻게 조합할지 정하는 것이 이 문서의 중심이다.