Track II · DL Fundamentals · 01/07

퍼셉트론에서 MLP로From perceptron to MLP

선형 모델이 XOR에서 막히는 이유와 은닉층·비선형성이 그 벽을 넘는 방식. ReLU 네트워크가 조각별 선형 함수라는 사실에서 보편 근사 정리와 깊이의 이점까지 직접 그려 보며 설명할 수 있게 된다.Why linear models get stuck on XOR, and how a hidden layer plus a nonlinearity gets past that wall. Starting from the fact that a ReLU network is a piecewise linear function, you will be able to draw and explain the universal approximation theorem and the benefit of depth.

35 분min perceptron · MLP · ReLU · universal approximation · depth 먼저 볼 것:Before this: 선형 모델Linear models

Every model in Track I was linear. Multiply the input xx by weights, add them up, and if needed apply a sigmoid or softmax at the end. These models have convex losses, are easy to interpret, and are fast. But the only decision boundary they can represent is a single hyperplane. This lesson looks at where that wall is, and at how a tiny addition — a hidden layer and a nonlinear activation — tears it down completely. The punchline first: a ReLU network is “a piecewise linear function that learns its kinks”, and with enough kinks it can imitate any continuous function.

The perceptron and its limits

Rosenblatt’s perceptron (1958) is the simplest artificial neuron.

y^=step⁡(w⊤x+b)={1w⊤x+b>00otherwise\hat y = \operatorname{step}(w^\top x + b) = \begin{cases} 1 & w^\top x + b > 0 \\ 0 & \text{otherwise} \end{cases}

The decision boundary w⊤x+b=0w^\top x + b = 0 is a hyperplane (a line in 2-D). The perceptron learning rule — for every misclassified example, w←w+(y−y^) xw \leftarrow w + (y - \hat y)\,x — is proven to converge in a finite number of steps if the data are linearly separable. The trouble is that condition.

The most famous counterexample is XOR. Inputs (0,0),(1,1)(0,0), (1,1) are class 0, and (0,1),(1,0)(0,1), (1,0) are class 1. Suppose a single line could separate them.

(0,0)→0:b≤0(1,1)→0:w1+w2+b≤0(1,0)→1:w1+b>0(0,1)→1:w2+b>0\begin{aligned} (0,0)\to 0:&\quad b \le 0 \\ (1,1)\to 0:&\quad w_1 + w_2 + b \le 0 \\ (1,0)\to 1:&\quad w_1 + b > 0 \\ (0,1)\to 1:&\quad w_2 + b > 0 \end{aligned}

Adding the bottom two gives w1+w2+2b>0w_1 + w_2 + 2b > 0; adding the top two gives w1+w2+2b≤0w_1 + w_2 + 2b \le 0. A contradiction. Swapping the activation for a sigmoid and training with cross-entropy (logistic regression) does not help: the boundary is still a line, so the result is the same. After Minsky and Papert laid out such limits systematically in Perceptrons (1969), research on single-layer networks went quiet for a while.

The hidden layer: a layer that builds its own features

The fix is to slip a layer between input and output. A multilayer perceptron (MLP) with one hidden layer is

h=ϕ(W1x+b1),y^=w2⊤h+b2h = \phi(W_1 x + b_1), \qquad \hat y = w_2^\top h + b_2

where ϕ\phi is a nonlinear activation function applied elementwise. XOR is solved exactly by two hidden ReLUs (ϕ(z)=max⁡(0,z)\phi(z) = \max(0, z)).

h1=relu⁡(x1+x2),h2=relu⁡(x1+x2−1),y^=h1−2h2h_1 = \operatorname{relu}(x_1 + x_2), \quad h_2 = \operatorname{relu}(x_1 + x_2 - 1), \quad \hat y = h_1 - 2h_2

Plug in the four points: (0,0)→0(0,0)\to 0, (0,1)→1(0,1)\to 1, (1,0)→1(1,0)\to 1, (1,1)→2−2=0(1,1)\to 2 - 2 = 0. What the hidden layer did was redraw the input space. In the original space (0,1)(0,1) and (1,0)(1,0) sat on opposite corners of a diagonal, but in (h1,h2)(h_1, h_2) space both become the same point (1,0)(1, 0). In that space a single line separates the classes. This is where the view comes from that training a neural network is ultimately “finding a representation in which the problem is linearly solvable”.

NumPy XOR: impossible linearly, exact with two ReLUs
import numpy as np

relu = lambda z: np.maximum(z, 0)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([0, 1, 1, 0], dtype=float)

# 1) The best a linear model can do: the least-squares solution
A = np.c_[X, np.ones(4)]
w, *_ = np.linalg.lstsq(A, y, rcond=None)
print("linear least-squares predictions:", np.round(A @ w, 3), " ← all 0.5, separates nothing")

# 2) Two hidden ReLUs solve it exactly
W1 = np.array([[1, 1], [1, 1]], dtype=float)  # both units look at x1 + x2
b1 = np.array([0, -1], dtype=float)           # only the kink location differs
w2 = np.array([1, -2], dtype=float)
H = relu(X @ W1.T + b1)
print("hidden representation h (rows = the 4 inputs):\n", H)
print("output h·w2 :", H @ w2)

# 3) Remove the activation? The two layers collapse into one
print("2 layers without activation = 1 linear layer. equivalent weights:", w2 @ W1, " equivalent bias:", w2 @ b1)
 

Why it has to be nonlinear

Without an activation, stacking any number of layers is useless, because a composition of linear maps is a linear map.

W2(W1x+b1)+b2=(W2W1)⏟W x+(W2b1+b2)⏟bW_2(W_1 x + b_1) + b_2 = \underbrace{(W_2 W_1)}_{W}\,x + \underbrace{(W_2 b_1 + b_2)}_{b}

A 100-layer linear network is still just one Wx+bWx + b (its training dynamics differ, though: a deep linear network is a non-convex optimisation problem, which makes it an interesting object of study). So the expressive power comes entirely from ϕ\phi. What counts as a good ϕ\phi has changed over time.

ActivationFormulaProperties
sigmoid1/(1+e−z)1/(1+e^{-z})Output in (0,1)(0,1). The gradient approaches 0 at both ends, so learning stalls in deep networks
tanhtanh⁡z\tanh zZero-centred. Still saturates at both ends
ReLUmax⁡(0,z)\max(0, z)Gradient exactly 1 on the positive side. Cheap to compute, and deep networks train. Gradient 0 on the negative side (“dead ReLU”)
GELUz Φ(z)z\,\Phi(z)A smoothed ReLU. The default in the BERT and GPT families
SiLU/Swishz σ(z)z\,\sigma(z)Shaped much like GELU. A building block of SwiGLU in the LLaMA family

Φ\Phi is the standard normal CDF. Of these, ReLU is the easiest to look inside theoretically. Let us dissect it.

A ReLU network is a piecewise linear function

Write a one-hidden-layer ReLU network with a 1-D input:

f(x)=c+∑j=1Najrelu⁡(wjx+bj)f(x) = c + \sum_{j=1}^{N} a_j \operatorname{relu}(w_j x + b_j)

Each term ajrelu⁡(wjx+bj)a_j\operatorname{relu}(w_j x + b_j) is a “hockey stick” that bends once, at x=kj=−bj/wjx = k_j = -b_j/w_j. Passing that point changes the slope of ff by aj∣wj∣a_j |w_j|. Therefore

  • ff is continuous and piecewise linear, with at most NN kinks and at most N+1N+1 pieces.
  • Conversely, any continuous piecewise linear function with NN kinks can be written exactly with NN units (plus one linear term if needed): start from the slope of the first piece and, at each kink, set aja_j to the change in slope Δsj\Delta s_j.

In short, one hidden unit = one kink. What training does is move the kink locations (kjk_j) and slope changes (aja_j) to fit the data. Try it yourself in the figure below.

Track I의 모델은 모두 선형이었다. 입력 xx에 가중치를 곱해 더하고, 필요하면 마지막에 sigmoid나 softmax를 씌운다. 이 모델들은 볼록한 손실을 가지고, 해석이 쉽고, 빠르다. 그러나 표현할 수 있는 결정 경계가 초평면 하나뿐이다. 이 레슨은 그 벽이 어디에 있는지, 그리고 은닉층(hidden layer)과 비선형 활성화 라는 아주 작은 추가가 그 벽을 어떻게 완전히 허무는지를 본다. 결론부터 말하면, ReLU 네트워크는 “꺾임점을 학습하는 조각별 선형 함수”이고, 꺾임점을 충분히 많이 쓰면 어떤 연속함수든 흉내 낼 수 있다.

퍼셉트론과 그 한계

Rosenblatt의 퍼셉트론(perceptron, 1958) 은 가장 단순한 인공 뉴런이다.

y^=step⁡(w⊤x+b)={1w⊤x+b>00otherwise\hat y = \operatorname{step}(w^\top x + b) = \begin{cases} 1 & w^\top x + b > 0 \\ 0 & \text{otherwise} \end{cases}

결정 경계 w⊤x+b=0w^\top x + b = 0은 초평면(2-D에서는 직선)이다. 퍼셉트론 학습 규칙 — 틀린 예제마다 w←w+(y−y^) xw \leftarrow w + (y - \hat y)\,x — 은 데이터가 선형 분리 가능하면 유한 번 안에 수렴한다는 것이 증명되어 있다. 문제는 그 조건이다.

가장 유명한 반례가 XOR이다. 입력 (0,0),(1,1)(0,0), (1,1)은 클래스 0, (0,1),(1,0)(0,1), (1,0)은 클래스 1. 직선 하나로 나눌 수 있다고 가정해 보자.

(0,0)→0:b≤0(1,1)→0:w1+w2+b≤0(1,0)→1:w1+b>0(0,1)→1:w2+b>0\begin{aligned} (0,0)\to 0:&\quad b \le 0 \\ (1,1)\to 0:&\quad w_1 + w_2 + b \le 0 \\ (1,0)\to 1:&\quad w_1 + b > 0 \\ (0,1)\to 1:&\quad w_2 + b > 0 \end{aligned}

아래 두 식을 더하면 w1+w2+2b>0w_1 + w_2 + 2b > 0, 위 두 식을 더하면 w1+w2+2b≤0w_1 + w_2 + 2b \le 0. 모순이다. 활성화를 sigmoid로 바꾸고 cross-entropy로 학습해도(로지스틱 회귀) 경계가 직선이라는 사실은 그대로이므로 결과는 같다. Minsky와 Papert가 『Perceptrons』(1969)에서 이런 한계를 체계적으로 정리한 뒤, 단층 신경망 연구는 한동안 위축되었다.

은닉층: 특징을 스스로 만드는 층

해결책은 입력과 출력 사이에 층을 하나 끼우는 것이다. 다층 퍼셉트론(multilayer perceptron, MLP) 의 은닉층 하나짜리 형태는

h=ϕ(W1x+b1),y^=w2⊤h+b2h = \phi(W_1 x + b_1), \qquad \hat y = w_2^\top h + b_2

이고, ϕ\phi는 원소별로 적용되는 비선형 활성화 함수(activation function) 다. XOR은 은닉 ReLU(ϕ(z)=max⁡(0,z)\phi(z) = \max(0, z)) 두 개로 정확히 풀린다.

h1=relu⁡(x1+x2),h2=relu⁡(x1+x2−1),y^=h1−2h2h_1 = \operatorname{relu}(x_1 + x_2), \quad h_2 = \operatorname{relu}(x_1 + x_2 - 1), \quad \hat y = h_1 - 2h_2

네 점을 넣어 보면 (0,0)→0(0,0)\to 0, (0,1)→1(0,1)\to 1, (1,0)→1(1,0)\to 1, (1,1)→2−2=0(1,1)\to 2 - 2 = 0. 은닉층이 한 일은 입력 공간을 다시 그리는 것 이다. 원래 공간에서 (0,1)(0,1)과 (1,0)(1,0)은 대각선 반대편에 있었지만, (h1,h2)(h_1, h_2) 공간에서는 둘 다 (1,0)(1, 0)으로 같은 점이 된다. 그 공간에서는 직선 하나로 나뉜다. 신경망 학습이란 결국 “선형으로 풀리는 표현을 찾는 일”이라는 관점이 여기서 나온다.

NumPy XOR: 선형으로는 불가능, ReLU 두 개면 정확히
import numpy as np

relu = lambda z: np.maximum(z, 0)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([0, 1, 1, 0], dtype=float)

# 1) 선형 모델의 최선: 최소제곱 해
A = np.c_[X, np.ones(4)]
w, *_ = np.linalg.lstsq(A, y, rcond=None)
print("선형 최소제곱 예측:", np.round(A @ w, 3), " ← 전부 0.5, 아무것도 구분 못 함")

# 2) 은닉 ReLU 두 개면 정확히 풀린다
W1 = np.array([[1, 1], [1, 1]], dtype=float)  # 두 유닛 모두 x1 + x2를 본다
b1 = np.array([0, -1], dtype=float)           # 꺾이는 위치만 다르다
w2 = np.array([1, -2], dtype=float)
H = relu(X @ W1.T + b1)
print("은닉 표현 h (행 = 입력 4개):\n", H)
print("출력 h·w2 :", H @ w2)

# 3) 활성화를 빼면? 두 층이 한 층으로 접힌다
print("활성화 없는 2층 = 선형 1층. 등가 가중치:", w2 @ W1, " 등가 편향:", w2 @ b1)
 

왜 비선형이어야 하는가

활성화를 빼면 몇 층을 쌓아도 소용이 없다. 선형 사상의 합성은 선형 사상이기 때문이다.

W2(W1x+b1)+b2=(W2W1)⏟W x+(W2b1+b2)⏟bW_2(W_1 x + b_1) + b_2 = \underbrace{(W_2 W_1)}_{W}\,x + \underbrace{(W_2 b_1 + b_2)}_{b}

100층짜리 선형 네트워크도 결국 Wx+bWx + b 하나다(다만 학습 동역학은 다르다. 깊은 선형 네트워크는 비볼록 최적화 문제가 되어 연구 대상으로는 흥미롭다). 그러니 표현력은 전적으로 ϕ\phi에서 온다. 무엇이 좋은 ϕ\phi인가는 역사적으로 바뀌어 왔다.

활성화식특징
sigmoid1/(1+e−z)1/(1+e^{-z})출력 (0,1)(0,1). 양 끝에서 기울기가 0에 가까워져 깊은 망에서 학습이 막힌다
tanhtanh⁡z\tanh z0 중심. 여전히 양 끝에서 포화(saturation)
ReLUmax⁡(0,z)\max(0, z)양수 쪽 기울기가 정확히 1. 계산이 싸고 깊은 망이 학습된다. 음수 쪽은 기울기 0 (“죽은 ReLU”)
GELUz Φ(z)z\,\Phi(z)ReLU를 매끄럽게 만든 꼴. BERT·GPT 계열의 기본값
SiLU/Swishz σ(z)z\,\sigma(z)GELU와 비슷한 모양. LLaMA 계열 SwiGLU의 구성 요소

Φ\Phi는 표준정규 누적분포다. 이 중 ReLU가 이론적으로 가장 들여다보기 쉽다. 이제 그것을 해부한다.

ReLU 네트워크는 조각별 선형 함수다

입력이 1차원인 은닉층 하나짜리 ReLU 네트워크를 쓰면

f(x)=c+∑j=1Najrelu⁡(wjx+bj)f(x) = c + \sum_{j=1}^{N} a_j \operatorname{relu}(w_j x + b_j)

각 항 ajrelu⁡(wjx+bj)a_j\operatorname{relu}(w_j x + b_j)는 x=kj=−bj/wjx = k_j = -b_j/w_j에서 한 번 꺾이는 “하키 스틱”이다. 그 점을 지나며 ff의 기울기가 aj∣wj∣a_j |w_j|만큼 바뀐다. 따라서

  • ff는 연속이고 조각별 선형이며, 꺾임점은 최대 NN개, 조각은 최대 N+1N+1개다.
  • 거꾸로, 꺾임점이 NN개인 연속 조각별 선형 함수는 무엇이든 유닛 NN개(와 필요하면 선형항 하나)로 정확히 쓸 수 있다. 첫 조각의 기울기에서 시작해 꺾임점마다 기울기 변화량 Δsj\Delta s_j를 aja_j로 주면 된다.

즉 은닉 유닛 하나 = 꺾임 하나 다. 학습이 하는 일은 꺾임 위치(kjk_j)와 기울기 변화량(aja_j)을 데이터에 맞게 옮기는 것이다. 아래 그림에서 직접 해 보자.

조각 수pieces – MSE – 최대 오차max error –
Top: the grey dashed line is the target, the red line is the ReLU network f(x) = c + Σ aj·relu(x − kj). Drag the points to change the kink positions (kj) and heights. Bottom: the same function split into per-unit contributions aj·relu(x − kj). Each unit makes one kink and changes the slope there by aj. Doubling N cuts the max error to roughly 1/4 (for a smooth target the error ∝ 1/N²). 위: 회색 점선이 목표, 빨간 선이 ReLU 네트워크 f(x) = c + Σ aj·relu(x − kj). 점을 끌어 꺾임 위치(kj)와 높이를 바꿔 보세요. 아래: 같은 함수를 유닛별 기여 aj·relu(x − kj)로 쪼갠 것. 한 유닛은 꺾임 하나를 만들고, 그 점에서 기울기를 aj만큼 바꾼다. N을 두 배로 늘리면 최대 오차가 대략 1/4로 준다(매끄러운 목표에서 오차 ∝ 1/N²).

Check a few things.

  1. Switch the target to |x| − 1 and set N = 2. Move the middle kink to 0 and the error becomes exactly 0. This function needs only one kink.
  2. On sin, double N from 4 → 8 → 16: the maximum error drops by roughly 4× each time.
  3. For the step-like tanh, evenly spaced kinks are wasteful. Gather two kinks near 0 and press least-squares fit again: with the same N the error drops sharply. This shows why placing units “where they are needed” — that is, learning the first-layer weights — matters.

In 2-D and beyond: folding regions

With a dd-dimensional input, one unit “folds” space along the hyperplane wj⊤x+bj=0w_j^\top x + b_j = 0. The NN hyperplanes of one hidden layer cut space into convex regions, and inside each region ff is linear. The number of regions that NN hyperplanes carve Rd\mathbb{R}^d into is at most

∑i=0d(Ni)\sum_{i=0}^{d} \binom{N}{i}

a degree-dd polynomial in NN. Stacking layers changes the story. The next layer folds the already-folded space again, so the number of regions can grow exponentially in depth (Montúfar et al., 2014). In the ReLU panel of the figure below, the boundary looks like a polygon made of straight segments — that is exactly this region structure.

몇 가지를 확인해 보자.

  1. 목표를 |x| − 1로 바꾸고 N = 2로 두자. 가운데 꺾임점을 0으로 옮기면 오차가 정확히 0이 된다. 꺾임 하나면 충분한 함수다.
  2. sin 에서 N을 4 → 8 → 16으로 두 배씩 늘리면 최대 오차가 대략 4배씩 준다.
  3. 계단에 가까운 tanh 는 꺾임점을 균등하게 두면 비효율적이다. 꺾임점 두 개를 0 근처로 모으고 다시 최소제곱 맞춤을 누르면 같은 N으로 오차가 크게 준다. 유닛을 “필요한 곳에” 두는 것, 즉 첫 층 가중치를 학습하는 것이 왜 중요한지 보여 준다.

2차원 이상에서: 영역을 접는다

입력이 dd차원이면 유닛 하나는 초평면 wj⊤x+bj=0w_j^\top x + b_j = 0을 따라 공간을 “접는다”. 은닉층 하나의 NN개 초평면이 공간을 여러 볼록 영역으로 자르고, 각 영역 안에서 ff는 선형이다. 초평면 NN개가 Rd\mathbb{R}^d를 나누는 영역의 수는 최대

∑i=0d(Ni)\sum_{i=0}^{d} \binom{N}{i}

로, NN에 대해 dd차 다항식이다. 층을 쌓으면 이야기가 달라진다. 다음 층은 이미 접힌 공간을 또 접으므로, 영역 수가 깊이에 대해 지수적으로 늘 수 있다(Montúfar et al., 2014). 아래 그림의 ReLU 패널에서 경계가 직선 조각들로 이어진 다각형으로 보이는 것이 바로 이 영역 구조다.

선형 (φ 없음)linear (no φ)
tanh
ReLU
step 0Adam, lr 0.03, 전체 배치, 같은 초기 난수full batch, same initial seed
The three networks differ only in the activation function; data, width, initialisation seed and optimiser are the same. Press ▶ Train and compare the decision boundaries. The linear one is a single straight line no matter how many layers you stack. The ReLU boundary is a polygon glued from straight pieces, while tanh bends smoothly. On the spiral, cut the width to 2–3 and even the nonlinear networks fail. Width is the budget for expressive power. 세 네트워크는 활성화 함수만 다르다. 데이터·너비·초기화 난수·옵티마이저가 같다. ▶ 학습을 누르고 경계를 비교해 보세요. 선형은 몇 층을 쌓아도 직선 하나다. ReLU의 경계는 직선 조각을 이어 붙인 다각형이고, tanh는 매끄럽게 휜다. 나선에서 너비를 2–3으로 줄이면 비선형 네트워크도 실패한다. 너비가 표현력의 예산이다.

The universal approximation theorem

Generalising the logic of the ReLU figure gives the following theorem.

Cybenko (1989) and Hornik et al. (1989) proved it for the sigmoid; Leshno et al. (1993) proved the form “not being a polynomial is both sufficient and necessary”. (Why polynomials fail: adding up any number of degree-pp polynomial activations still gives only a degree-pp polynomial.)

For a 1-D ReLU the proof is the figure itself. If gg is twice differentiable on [α,β][\alpha, \beta], the error of the linear interpolant with kinks spaced h=(β−α)/Nh = (\beta - \alpha)/N apart is

sup⁡x∣f(x)−g(x)∣≤h28sup⁡x∣g′′(x)∣=O ⁣(1N2)\sup_x |f(x) - g(x)| \le \frac{h^2}{8} \sup_x |g''(x)| = O\!\left(\frac{1}{N^2}\right)

(the maximum of the interpolation error 12(x−xj)(xj+1−x) g′′(ξ)\tfrac12 (x - x_j)(x_{j+1} - x)\,g''(\xi) on each interval). That is why doubling N in the figure cut the error to 1/4.

Let us compare in code how the theorem’s existence proof differs from an actual approximation. (a) places the kinks evenly; (b) draws the hidden layer’s (w,b)(w, b) at random and fits only the output layer by least squares (random features). Both solve the output layer with plain linear regression, no backpropagation.

NumPy Wider networks shrink the approximation error
import numpy as np
rng = np.random.default_rng(0)
relu = lambda z: np.maximum(z, 0)

target = lambda x: np.sin(1.6 * x)
x = np.linspace(-3, 3, 2000)
y = target(x)

print("width N | (a) even kinks, max error | (b) random hidden layer, max error")
for N in [2, 4, 8, 16, 32, 64]:
    # (a) place kinks k_j evenly and fit only the output layer (c, a_j) by least squares
    k = np.linspace(-3, 3, N + 1)[:-1]
    Phi = np.c_[np.ones_like(x), relu(x[:, None] - k[None, :])]
    a, *_ = np.linalg.lstsq(Phi, y, rcond=None)
    err_a = np.abs(Phi @ a - y).max()
    # (b) draw the hidden layer (w, b) at random and fit only the output layer (random features)
    w = rng.normal(size=N)
    b = rng.uniform(-3, 3, size=N) * np.abs(w)
    Phi = np.c_[np.ones_like(x), relu(np.outer(x, w) + b)]
    a, *_ = np.linalg.lstsq(Phi, y, rcond=None)
    err_b = np.abs(Phi @ a - y).max()
    print(f"{N:7d} | {err_a:25.5f} | {err_b:12.5f}")
print("\n(a): doubling N cuts the error to about 1/4 → O(1/N²)")
 

With random kinks (b), bad luck clusters the kinks and the result is much worse at the same N. That an untrained first layer wastes units, and that training the first layer needs gradients, is the motivation for the next lesson (backpropagation).

Depth vs width

If one hidden layer can approximate anything, why stack deep? Because some functions can be represented with far fewer units. Telgarsky’s (2016) example is clean. The tent map on [0,1][0,1]

t(x)=2relu⁡(x)−4relu⁡(x−12)t(x) = 2\operatorname{relu}(x) - 4\operatorname{relu}(x - \tfrac12)

is a layer of two ReLUs; it maps [0,1][0,1] to [0,1][0,1], going up once and back down. Composing it kk times, t(k)t^{(k)} is a sawtooth with 2k−12^{k-1} teeth, i.e. 2k2^k linear pieces. Depth kk and width 2 — 2k2k units in total — make 2k2^k pieces. A one-hidden-layer ReLU network, by contrast, makes at most N+1N+1 pieces from NN units in 1-D, so it needs 2k−12^k - 1 units.

NumPy Stacking tent maps doubles the number of pieces
import numpy as np
relu = lambda z: np.maximum(z, 0)

def tent(x):           # tent map [0,1] → [0,1]: a layer of two ReLUs
    return 2 * relu(x) - 4 * relu(x - 0.5)

def count_pieces(fx, x):
    slope = np.diff(fx) / np.diff(x)
    return 1 + int(np.sum(np.abs(np.diff(slope)) > 1e-6))

x = np.linspace(0, 1, 2**12 + 1)    # 2^k+1 points so the kinks land on the grid
f = x.copy()
for depth in range(1, 9):
    f = tent(f)
    print(f"depth {depth}: {2*depth:2d} ReLUs → {count_pieces(f, x):4d} linear pieces")
print("\nA one-hidden-layer ReLU network needs at least 255 units to make 256 pieces.")
 

Of course this is an existence proof, and the sawtooth is an artificial function. Still, the intuition remains: depth is reuse of computation. Upper layers reuse the features (the folded space) built by lower layers, so functions with compositional structure — edges → textures → parts → objects in an image, tokens → phrases → meaning in a sentence — can be represented with few parameters. The price is that training gets harder, and the tools that fix that (initialisation, normalisation, residual connections) are the subject of this track’s third lesson.

확인 문제Check yourself

A continuous piecewise linear function defined on all of ℝ has 7 kinks, and its leftmost piece is flat (slope 0). With a 1-D input and a one-hidden-layer ReLU network (with an output bias), what is the minimum number of hidden units needed to represent it exactly?

One unit makes one kink, and it cannot change the slope anywhere it has no kink. So fewer than 7 is impossible, and 7 is enough: at each kink kjk_j, ajrelu⁡(x−kj)a_j\operatorname{relu}(x - k_j) supplies the slope change Δsj\Delta s_j. Had the leftmost piece’s slope been nonzero, more units would be needed for that linear term — e.g. two, as in x=relu⁡(x)−relu⁡(−x)x = \operatorname{relu}(x) - \operatorname{relu}(-x).

In PyTorch: an MLP in one line

Doing the same experiment in PyTorch, autograd computes the gradients. In the next lesson we build that autograd ourselves.

PyTorch Training XOR with an nn.Sequential MLP 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn

torch.manual_seed(0)
X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
y = torch.tensor([[0.], [1.], [1.], [0.]])

def make(act):
    return nn.Sequential(nn.Linear(2, 8), act, nn.Linear(8, 1))

for name, act in [("identity", nn.Identity()), ("tanh", nn.Tanh()), ("relu", nn.ReLU())]:
    model = make(act)
    opt = torch.optim.Adam(model.parameters(), lr=0.05)
    for step in range(500):
        loss = nn.functional.binary_cross_entropy_with_logits(model(X), y)
        opt.zero_grad()
        loss.backward()
        opt.step()
    p = torch.sigmoid(model(X)).detach().squeeze()
    print(f"{name:8s} loss={loss.item():.4f}  p={p.numpy().round(2)}")
# identity stays at loss≈0.693 (=log 2), p≈0.5, because it is linear.
 

Summary

  • The boundary of a perceptron or logistic regression is a single hyperplane. XOR is not linearly separable.
  • A hidden layer redraws the input (representation learning) into a space where the problem is linearly solvable. Without an activation, stacked layers collapse into a single linear map.
  • A 1-D ReLU network is a continuous piecewise linear function, and one unit = one kink. In 2-D and beyond, hyperplanes cut space into linear regions.
  • Universal approximation: one hidden layer with a non-polynomial activation approximates any continuous function on a compact set to arbitrary precision. It says nothing about the width needed, trainability, or generalisation.
  • Depth reuses computation, so some functions need exponentially fewer units than with width alone (composed tent maps).

보편 근사 정리

ReLU 그림의 논리를 일반화하면 다음 정리가 된다.

sigmoid에 대해서는 Cybenko(1989)와 Hornik et al.(1989)이, “다항식이 아니면 충분하고 또 필요하다”는 형태는 Leshno et al.(1993)이 증명했다. (다항식이 안 되는 이유: 차수 pp 다항식 활성화를 몇 개 더해도 차수 pp 다항식밖에 안 나온다.)

1-D ReLU에서는 증명이 그림 그대로다. gg가 [α,β][\alpha, \beta]에서 두 번 미분 가능하면, 간격 h=(β−α)/Nh = (\beta - \alpha)/N으로 꺾임점을 둔 선형 보간의 오차는

sup⁡x∣f(x)−g(x)∣≤h28sup⁡x∣g′′(x)∣=O ⁣(1N2)\sup_x |f(x) - g(x)| \le \frac{h^2}{8} \sup_x |g''(x)| = O\!\left(\frac{1}{N^2}\right)

이다(각 구간에서 보간 오차 12(x−xj)(xj+1−x) g′′(ξ)\tfrac12 (x - x_j)(x_{j+1} - x)\,g''(\xi)의 최대값). 그림에서 N을 두 배로 할 때 오차가 1/4이 된 이유다.

정리의 존재 증명과 실제 근사가 어떻게 다른지 코드로 비교해 보자. (a)는 꺾임점을 균등하게 둔 경우, (b)는 은닉층의 (w,b)(w, b)를 무작위로 뽑고 출력층만 최소제곱으로 맞춘 경우(random features)다. 둘 다 역전파 없이, 선형 회귀만으로 출력층을 푼다.

NumPy 너비를 늘리면 근사 오차가 준다
import numpy as np
rng = np.random.default_rng(0)
relu = lambda z: np.maximum(z, 0)

target = lambda x: np.sin(1.6 * x)
x = np.linspace(-3, 3, 2000)
y = target(x)

print("너비 N | (a) 균등 꺾임 최대오차 | (b) 무작위 은닉층 최대오차")
for N in [2, 4, 8, 16, 32, 64]:
    # (a) 꺾임점 k_j를 균등하게 두고 출력층 (c, a_j)만 최소제곱
    k = np.linspace(-3, 3, N + 1)[:-1]
    Phi = np.c_[np.ones_like(x), relu(x[:, None] - k[None, :])]
    a, *_ = np.linalg.lstsq(Phi, y, rcond=None)
    err_a = np.abs(Phi @ a - y).max()
    # (b) 은닉층 (w, b)를 무작위로 뽑고 출력층만 최소제곱 (random features)
    w = rng.normal(size=N)
    b = rng.uniform(-3, 3, size=N) * np.abs(w)
    Phi = np.c_[np.ones_like(x), relu(np.outer(x, w) + b)]
    a, *_ = np.linalg.lstsq(Phi, y, rcond=None)
    err_b = np.abs(Phi @ a - y).max()
    print(f"{N:6d} | {err_a:22.5f} | {err_b:12.5f}")
print("\n(a): N이 두 배가 되면 오차가 약 1/4 → O(1/N²)")
 

무작위 꺾임점(b)은 운이 나쁘면 꺾임이 몰려서 같은 N에서 훨씬 나쁘다. 첫 층을 학습하지 않으면 유닛을 낭비한다는 것, 그리고 그 첫 층을 학습하려면 기울기가 필요하다는 것이 다음 레슨(역전파)의 동기다.

깊이 vs 너비

은닉층 하나로 무엇이든 근사할 수 있다면 왜 깊게 쌓는가? 같은 함수를 훨씬 적은 유닛으로 표현할 수 있는 경우가 있기 때문이다. Telgarsky(2016)의 예가 깔끔하다. [0,1][0,1] 위의 텐트 사상

t(x)=2relu⁡(x)−4relu⁡(x−12)t(x) = 2\operatorname{relu}(x) - 4\operatorname{relu}(x - \tfrac12)

은 ReLU 두 개로 된 층이고, [0,1][0,1]을 [0,1][0,1]로 보내며 한 번 올라갔다 내려온다. 이것을 kk번 합성한 t(k)t^{(k)}는 톱니가 2k−12^{k-1}개인 톱니파, 즉 선형 조각이 2k2^k개다. 깊이 kk·너비 2, 총 2k2k개의 유닛으로 2k2^k개의 조각을 만든다. 반면 은닉층 하나짜리 ReLU 네트워크는 1-D에서 유닛 NN개로 조각을 최대 N+1N+1개밖에 못 만드므로 2k−12^k - 1개의 유닛이 필요하다.

NumPy 텐트 사상을 쌓으면 조각 수가 2배씩
import numpy as np
relu = lambda z: np.maximum(z, 0)

def tent(x):           # [0,1] → [0,1] 텐트 사상: ReLU 두 개짜리 층
    return 2 * relu(x) - 4 * relu(x - 0.5)

def count_pieces(fx, x):
    slope = np.diff(fx) / np.diff(x)
    return 1 + int(np.sum(np.abs(np.diff(slope)) > 1e-6))

x = np.linspace(0, 1, 2**12 + 1)    # 꺾임점이 격자 위에 오도록 2^k+1개
f = x.copy()
for depth in range(1, 9):
    f = tent(f)
    print(f"깊이 {depth}: ReLU {2*depth:2d}개 → 선형 조각 {count_pieces(f, x):4d}개")
print("\n은닉층 하나짜리 ReLU 네트워크로 조각 256개를 만들려면 유닛이 최소 255개 필요하다.")
 

물론 이것은 존재 증명이고, 톱니파는 인공적인 함수다. 그래도 직관은 남는다. 깊이는 계산의 재사용 이다. 아래층이 만든 특징(접힌 공간)을 위층이 다시 쓰므로, 구성적(compositional) 구조를 가진 함수 — 이미지의 가장자리 → 무늬 → 부분 → 물체, 문장의 토큰 → 구 → 의미 — 를 적은 매개변수로 표현할 수 있다. 대가는 학습이 어려워진다는 것이고, 그 문제를 푸는 도구(초기화, 정규화, residual)가 이 트랙 세 번째 레슨의 주제다.

확인 문제Check yourself

실수 전체에서 정의된 연속 조각별 선형 함수가 꺾임점 7개를 가지고, 가장 왼쪽 조각은 평평하다(기울기 0). 입력 1차원, 은닉층 하나짜리 ReLU 네트워크(출력 편향 있음)로 이를 정확히 표현하려면 은닉 유닛이 최소 몇 개 필요한가?

유닛 하나가 꺾임 하나를 만들고, 꺾임이 없는 곳에서는 기울기를 바꾸지 못한다. 그러니 7개 미만은 불가능하고, 꺾임점 kjk_j마다 ajrelu⁡(x−kj)a_j\operatorname{relu}(x - k_j)로 기울기 변화량 Δsj\Delta s_j를 주면 7개로 충분하다. 가장 왼쪽 조각의 기울기가 0이 아니었다면 그 선형항을 위해 유닛이 더 필요하다. 예컨대 x=relu⁡(x)−relu⁡(−x)x = \operatorname{relu}(x) - \operatorname{relu}(-x)처럼 두 개로 만든다.

PyTorch로: MLP 한 줄 정의

같은 실험을 PyTorch로 하면 기울기는 autograd가 계산한다. 다음 레슨에서 그 autograd를 직접 만든다.

PyTorch nn.Sequential MLP로 XOR 학습 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn

torch.manual_seed(0)
X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
y = torch.tensor([[0.], [1.], [1.], [0.]])

def make(act):
    return nn.Sequential(nn.Linear(2, 8), act, nn.Linear(8, 1))

for name, act in [("identity", nn.Identity()), ("tanh", nn.Tanh()), ("relu", nn.ReLU())]:
    model = make(act)
    opt = torch.optim.Adam(model.parameters(), lr=0.05)
    for step in range(500):
        loss = nn.functional.binary_cross_entropy_with_logits(model(X), y)
        opt.zero_grad()
        loss.backward()
        opt.step()
    p = torch.sigmoid(model(X)).detach().squeeze()
    print(f"{name:8s} loss={loss.item():.4f}  p={p.numpy().round(2)}")
# identity는 loss≈0.693(=log 2), p≈0.5에 머문다. 선형이기 때문이다.
 

정리

  • 퍼셉트론과 로지스틱 회귀의 경계는 초평면 하나다. XOR은 선형 분리 불가능하다.
  • 은닉층은 입력을 다시 그려(표현 학습) 선형으로 풀리는 공간을 만든다. 활성화가 없으면 층을 쌓아도 선형 하나로 접힌다.
  • 1-D ReLU 네트워크는 연속 조각별 선형 함수이며, 유닛 하나 = 꺾임 하나 다. 2-D 이상에서는 초평면들이 공간을 선형 영역으로 자른다.
  • 보편 근사 정리: 비다항식 활성화의 은닉층 하나면 콤팩트 집합 위 연속함수를 임의 정밀도로 근사한다. 필요한 너비, 학습 가능성, 일반화에 대해서는 말하지 않는다.
  • 깊이는 계산을 재사용해, 어떤 함수는 너비 대비 지수적으로 적은 유닛으로 표현한다(텐트 사상 합성).

더 읽을거리Further reading