Every model in Track I was linear. Multiply the input 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.
The decision boundary is a hyperplane (a line in 2-D). The perceptron learning rule — for every misclassified example, — 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 are class 0, and are class 1. Suppose a single line could separate them.
Adding the bottom two gives ; adding the top two gives . 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
where is a nonlinear activation function applied elementwise. XOR is solved exactly by two hidden ReLUs ().
Plug in the four points: , , , . What the hidden layer did was redraw the input space. In the original space and sat on opposite corners of a diagonal, but in space both become the same point . 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”.
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.
A 100-layer linear network is still just one (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 . What counts as a good has changed over time.
| Activation | Formula | Properties |
|---|---|---|
| sigmoid | Output in . The gradient approaches 0 at both ends, so learning stalls in deep networks | |
| tanh | Zero-centred. Still saturates at both ends | |
| ReLU | Gradient exactly 1 on the positive side. Cheap to compute, and deep networks train. Gradient 0 on the negative side (“dead ReLU”) | |
| GELU | A smoothed ReLU. The default in the BERT and GPT families | |
| SiLU/Swish | Shaped much like GELU. A building block of SwiGLU in the LLaMA family |
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:
Each term is a “hockey stick” that bends once, at . Passing that point changes the slope of by . Therefore
- is continuous and piecewise linear, with at most kinks and at most pieces.
- Conversely, any continuous piecewise linear function with kinks can be written exactly with units (plus one linear term if needed): start from the slope of the first piece and, at each kink, set to the change in slope .
In short, one hidden unit = one kink. What training does is move the kink locations () and slope changes () to fit the data. Try it yourself in the figure below.
Track I의 모델은 모두 선형이었다. 입력 에 가중치를 곱해 더하고, 필요하면 마지막에 sigmoid나 softmax를 씌운다. 이 모델들은 볼록한 손실을 가지고, 해석이 쉽고, 빠르다. 그러나 표현할 수 있는 결정 경계가 초평면 하나뿐이다. 이 레슨은 그 벽이 어디에 있는지, 그리고 은닉층(hidden layer)과 비선형 활성화 라는 아주 작은 추가가 그 벽을 어떻게 완전히 허무는지를 본다. 결론부터 말하면, ReLU 네트워크는 “꺾임점을 학습하는 조각별 선형 함수”이고, 꺾임점을 충분히 많이 쓰면 어떤 연속함수든 흉내 낼 수 있다.
퍼셉트론과 그 한계
Rosenblatt의 퍼셉트론(perceptron, 1958) 은 가장 단순한 인공 뉴런이다.
결정 경계 은 초평면(2-D에서는 직선)이다. 퍼셉트론 학습 규칙 — 틀린 예제마다 — 은 데이터가 선형 분리 가능하면 유한 번 안에 수렴한다는 것이 증명되어 있다. 문제는 그 조건이다.
가장 유명한 반례가 XOR이다. 입력 은 클래스 0, 은 클래스 1. 직선 하나로 나눌 수 있다고 가정해 보자.
아래 두 식을 더하면 , 위 두 식을 더하면 . 모순이다. 활성화를 sigmoid로 바꾸고 cross-entropy로 학습해도(로지스틱 회귀) 경계가 직선이라는 사실은 그대로이므로 결과는 같다. Minsky와 Papert가 『Perceptrons』(1969)에서 이런 한계를 체계적으로 정리한 뒤, 단층 신경망 연구는 한동안 위축되었다.
은닉층: 특징을 스스로 만드는 층
해결책은 입력과 출력 사이에 층을 하나 끼우는 것이다. 다층 퍼셉트론(multilayer perceptron, MLP) 의 은닉층 하나짜리 형태는
이고, 는 원소별로 적용되는 비선형 활성화 함수(activation function) 다. 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)왜 비선형이어야 하는가
활성화를 빼면 몇 층을 쌓아도 소용이 없다. 선형 사상의 합성은 선형 사상이기 때문이다.
100층짜리 선형 네트워크도 결국 하나다(다만 학습 동역학은 다르다. 깊은 선형 네트워크는 비볼록 최적화 문제가 되어 연구 대상으로는 흥미롭다). 그러니 표현력은 전적으로 에서 온다. 무엇이 좋은 인가는 역사적으로 바뀌어 왔다.
| 활성화 | 식 | 특징 |
|---|---|---|
| sigmoid | 출력 . 양 끝에서 기울기가 0에 가까워져 깊은 망에서 학습이 막힌다 | |
| tanh | 0 중심. 여전히 양 끝에서 포화(saturation) | |
| ReLU | 양수 쪽 기울기가 정확히 1. 계산이 싸고 깊은 망이 학습된다. 음수 쪽은 기울기 0 (“죽은 ReLU”) | |
| GELU | ReLU를 매끄럽게 만든 꼴. BERT·GPT 계열의 기본값 | |
| SiLU/Swish | GELU와 비슷한 모양. LLaMA 계열 SwiGLU의 구성 요소 |
는 표준정규 누적분포다. 이 중 ReLU가 이론적으로 가장 들여다보기 쉽다. 이제 그것을 해부한다.
ReLU 네트워크는 조각별 선형 함수다
입력이 1차원인 은닉층 하나짜리 ReLU 네트워크를 쓰면
각 항 는 에서 한 번 꺾이는 “하키 스틱”이다. 그 점을 지나며 의 기울기가 만큼 바뀐다. 따라서
- 는 연속이고 조각별 선형이며, 꺾임점은 최대 개, 조각은 최대 개다.
- 거꾸로, 꺾임점이 개인 연속 조각별 선형 함수는 무엇이든 유닛 개(와 필요하면 선형항 하나)로 정확히 쓸 수 있다. 첫 조각의 기울기에서 시작해 꺾임점마다 기울기 변화량 를 로 주면 된다.
즉 은닉 유닛 하나 = 꺾임 하나 다. 학습이 하는 일은 꺾임 위치()와 기울기 변화량()을 데이터에 맞게 옮기는 것이다. 아래 그림에서 직접 해 보자.
Check a few things.
- 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.
- On sin, double N from 4 → 8 → 16: the maximum error drops by roughly 4× each time.
- 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 -dimensional input, one unit “folds” space along the hyperplane . The hyperplanes of one hidden layer cut space into convex regions, and inside each region is linear. The number of regions that hyperplanes carve into is at most
a degree- polynomial in . 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.
몇 가지를 확인해 보자.
- 목표를 |x| − 1로 바꾸고 N = 2로 두자. 가운데 꺾임점을 0으로 옮기면 오차가 정확히 0이 된다. 꺾임 하나면 충분한 함수다.
- sin 에서 N을 4 → 8 → 16으로 두 배씩 늘리면 최대 오차가 대략 4배씩 준다.
- 계단에 가까운 tanh 는 꺾임점을 균등하게 두면 비효율적이다. 꺾임점 두 개를 0 근처로 모으고 다시 최소제곱 맞춤을 누르면 같은 N으로 오차가 크게 준다. 유닛을 “필요한 곳에” 두는 것, 즉 첫 층 가중치를 학습하는 것이 왜 중요한지 보여 준다.
2차원 이상에서: 영역을 접는다
입력이 차원이면 유닛 하나는 초평면 을 따라 공간을 “접는다”. 은닉층 하나의 개 초평면이 공간을 여러 볼록 영역으로 자르고, 각 영역 안에서 는 선형이다. 초평면 개가 를 나누는 영역의 수는 최대
로, 에 대해 차 다항식이다. 층을 쌓으면 이야기가 달라진다. 다음 층은 이미 접힌 공간을 또 접으므로, 영역 수가 깊이에 대해 지수적으로 늘 수 있다(Montúfar et al., 2014). 아래 그림의 ReLU 패널에서 경계가 직선 조각들로 이어진 다각형으로 보이는 것이 바로 이 영역 구조다.
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- polynomial activations still gives only a degree- polynomial.)
For a 1-D ReLU the proof is the figure itself. If is twice differentiable on , the error of the linear interpolant with kinks spaced apart is
(the maximum of the interpolation error 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 at random and fits only the output layer by least squares (random features). Both solve the output layer with plain linear regression, no backpropagation.
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
is a layer of two ReLUs; it maps to , going up once and back down. Composing it times, is a sawtooth with teeth, i.e. linear pieces. Depth and width 2 — units in total — make pieces. A one-hidden-layer ReLU network, by contrast, makes at most pieces from units in 1-D, so it needs units.
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.
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 , supplies the slope change . Had the leftmost piece’s slope been nonzero, more units would be needed for that linear term — e.g. two, as in .
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.
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)이 증명했다. (다항식이 안 되는 이유: 차수 다항식 활성화를 몇 개 더해도 차수 다항식밖에 안 나온다.)
1-D ReLU에서는 증명이 그림 그대로다. 가 에서 두 번 미분 가능하면, 간격 으로 꺾임점을 둔 선형 보간의 오차는
이다(각 구간에서 보간 오차 의 최대값). 그림에서 N을 두 배로 할 때 오차가 1/4이 된 이유다.
정리의 존재 증명과 실제 근사가 어떻게 다른지 코드로 비교해 보자. (a)는 꺾임점을 균등하게 둔 경우, (b)는 은닉층의 를 무작위로 뽑고 출력층만 최소제곱으로 맞춘 경우(random features)다. 둘 다 역전파 없이, 선형 회귀만으로 출력층을 푼다.
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)의 예가 깔끔하다. 위의 텐트 사상
은 ReLU 두 개로 된 층이고, 을 로 보내며 한 번 올라갔다 내려온다. 이것을 번 합성한 는 톱니가 개인 톱니파, 즉 선형 조각이 개다. 깊이 ·너비 2, 총 개의 유닛으로 개의 조각을 만든다. 반면 은닉층 하나짜리 ReLU 네트워크는 1-D에서 유닛 개로 조각을 최대 개밖에 못 만드므로 개의 유닛이 필요하다.
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)가 이 트랙 세 번째 레슨의 주제다.
실수 전체에서 정의된 연속 조각별 선형 함수가 꺾임점 7개를 가지고, 가장 왼쪽 조각은 평평하다(기울기 0). 입력 1차원, 은닉층 하나짜리 ReLU 네트워크(출력 편향 있음)로 이를 정확히 표현하려면 은닉 유닛이 최소 몇 개 필요한가?
유닛 하나가 꺾임 하나를 만들고, 꺾임이 없는 곳에서는 기울기를 바꾸지 못한다. 그러니 7개 미만은 불가능하고, 꺾임점 마다 로 기울기 변화량 를 주면 7개로 충분하다. 가장 왼쪽 조각의 기울기가 0이 아니었다면 그 선형항을 위해 유닛이 더 필요하다. 예컨대 처럼 두 개로 만든다.
PyTorch로: MLP 한 줄 정의
같은 실험을 PyTorch로 하면 기울기는 autograd가 계산한다. 다음 레슨에서 그 autograd를 직접 만든다.
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
- Goodfellow, Bengio, Courville, Deep Learning §6.1–6.4 (MIT Press, 2016) — XOR 예제, 은닉 유닛 종류, 보편 근사와 깊이에 대한 표준 서술The standard account of the XOR example, kinds of hidden units, universal approximation and depth
- Cybenko, Approximation by Superpositions of a Sigmoidal Function (Math. Control Signals Systems, 1989) — 은닉층 하나짜리 sigmoid 네트워크의 보편 근사 정리 원 논문The original paper on universal approximation for one-hidden-layer sigmoid networks
- Leshno, Lin, Pinkus, Schocken, Multilayer Feedforward Networks with a Nonpolynomial Activation Function Can Approximate Any Function (Neural Networks, 1993) — 활성화가 다항식만 아니면 된다는 필요충분조건. ReLU도 포함된다The necessary and sufficient condition — the activation just must not be a polynomial. ReLU is included
- Telgarsky, Benefits of Depth in Neural Networks (COLT, 2016) — 텐트 사상 합성으로 깊이가 너비를 지수적으로 이기는 함수를 구성Builds, by composing tent maps, a function for which depth beats width exponentially
- Montúfar, Pascanu, Cho, Bengio, On the Number of Linear Regions of Deep Neural Networks (NeurIPS, 2014) — 깊은 ReLU 네트워크의 선형 영역 수가 깊이에 지수적으로 늘 수 있음을 보임Shows that the number of linear regions of a deep ReLU network can grow exponentially with depth
- Nielsen, Neural Networks and Deep Learning, Ch. 4: A visual proof that neural nets can compute any function — 이 레슨 첫 그림과 같은 발상(유닛으로 계단·혹 만들기)을 인터랙티브로 설명An interactive explanation of the same idea as this lesson's first figure (building steps and bumps out of units)
- Geva, Schuster, Berant, Levy, Transformer Feed-Forward Layers Are Key-Value Memories (EMNLP, 2021) — Transformer 안의 MLP를 key–value 기억으로 해석한 논문The paper that reads the MLP inside a Transformer as key–value memory