import time4.2 다층 퍼셉트론 구현
4.1절 에서는 XOR 문제를 풀기 위해 2-유닛 ReLU 신경망의 가중치를 직접 설계했습니다. 이제 미니배치 SGD가 Fashion-MNIST 이미지로부터 은닉 특성을 직접 학습하도록 해 보겠습니다. \(d = 784\) 개의 입력 픽셀과 \(q = 10\) 개의 클래스 로짓 사이에 \(h = 256\) 개의 ReLU 유닛으로 이루어진 단일 은닉층을 삽입하면, 매개변수 수와 이미지당 FLOPs가 소프트맥스 회귀(\(7{,}850\) 개)의 26배인 \(203{,}530\) 개로 늘어납니다.
이 절에서는 이 2층 MLP를 처음부터 직접(MLPScratch) 구현하고 프레임워크의 Sequential 컨테이너를 사용해 간결하게(MLP) 구현한 뒤, 세 가지 간단한 훈련 전 무결성 점검으로 초기화 직후의 신경망을 검증하고, 학습 곡선과 에포크당 GPU 실행 시간을 소프트맥스 회귀와 일대일로 비교하며, 은닉 유닛들이 \(\mathbf{W}^{(1)}\) 에 학습한 가중치 패턴을 살펴봅니다.
4.2.1 처음부터 구현하기
4.2.1.1 매개변수와 순전파
각 \(28 \times 28\) 이미지를 \(d = 784\) 개의 특성으로 평탄화하면, 은닉 유닛 \(h = 256\) 개와 출력 \(q = 10\) 개를 가진 은닉층 1개짜리 MLP (그림 4.2.1)는 네 개의 매개변수 텐서를 할당합니다:
\[\mathbf{W}^{(1)} \in \mathbb{R}^{784 \times 256}, \quad \mathbf{b}^{(1)} \in \mathbb{R}^{256}, \quad \mathbf{W}^{(2)} \in \mathbb{R}^{256 \times 10}, \quad \mathbf{b}^{(2)} \in \mathbb{R}^{10}. \tag{4.2.1}\]
소프트맥스 회귀와 통제된 일대일 비교를 하기 위해 두 가중치 행렬은 \(\mathcal{N}(0, 0.01^2)\) 에서 추출하고 두 편향은 \(0\) 으로 초기화합니다 (4.4절 에서는 은닉 유닛 간 대칭을 깨기 위해 왜 무작위 초기화가 필수적인지, 그리고 He 초기화가 std=0.01 을 어떻게 개선하는지 살펴볼 것입니다):
class MLPScratch(d2l.Classifier):
"""An MLP with one hidden layer, implemented from scratch."""
def __init__(self, num_inputs, num_outputs, num_hiddens, lr, std=0.01):
super().__init__()
self.save_hyperparameters()
self.W1 = nn.Parameter(d2l.normal(0, std, (num_inputs, num_hiddens)))
self.b1 = nn.Parameter(d2l.zeros(num_hiddens))
self.W2 = nn.Parameter(d2l.normal(0, std, (num_hiddens, num_outputs)))
self.b2 = nn.Parameter(d2l.zeros(num_outputs))class MLPScratch(d2l.Classifier):
"""An MLP with one hidden layer, implemented from scratch."""
def __init__(self, num_inputs, num_outputs, num_hiddens, lr, std=0.01):
super().__init__()
self.save_hyperparameters()
self.W1 = self.add_weight(name='W1', shape=(num_inputs, num_hiddens),
initializer=self.normal())
self.b1 = self.add_weight(name='b1', shape=(num_hiddens,),
initializer='zeros')
self.W2 = self.add_weight(name='W2', shape=(num_hiddens, num_outputs),
initializer=self.normal())
self.b2 = self.add_weight(name='b2', shape=(num_outputs,),
initializer='zeros')
def normal(self):
# A new initializer for each weight matrix: one initializer object
# returns the same values every time it is called
return tf.keras.initializers.RandomNormal(stddev=self.std)class MLPScratch(d2l.Classifier):
"""An MLP with one hidden layer, implemented from scratch."""
def __init__(self, num_inputs, num_outputs, num_hiddens, lr, std=0.01,
rngs=None):
super().__init__()
self.save_hyperparameters(ignore=['rngs'])
rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
self.W1 = nnx.Param(
rngs.params.normal((num_inputs, num_hiddens)) * std)
self.b1 = nnx.Param(jnp.zeros(num_hiddens))
self.W2 = nnx.Param(
rngs.params.normal((num_hiddens, num_outputs)) * std)
self.b2 = nnx.Param(jnp.zeros(num_outputs))class MLPScratch(d2l.Classifier):
"""An MLP with one hidden layer, implemented from scratch."""
def __init__(self, num_inputs, num_outputs, num_hiddens, lr, std=0.01):
super().__init__()
self.save_hyperparameters()
normal, zero = init.Normal(std), init.Zero()
self.W1 = gluon.Parameter('W1', shape=(num_inputs, num_hiddens),
init=normal)
self.b1 = gluon.Parameter('b1', shape=(num_hiddens,), init=zero)
self.W2 = gluon.Parameter('W2', shape=(num_hiddens, num_outputs),
init=normal)
self.b2 = gluon.Parameter('b2', shape=(num_outputs,), init=zero)
self.initialize()다음으로 X 에 불리언 마스크 X > 0 을 곱해 양수 원소는 그대로 통과시키고 음수 원소는 0으로 만드는 원소별 활성화 함수 relu(X) 를 직접 구현합니다:
TensorFlow에서는 부동소수점 텐서와 불리언 텐서를 바로 곱할 수 없으므로 먼저 마스크를 X.dtype 으로 형변환합니다.
def relu(X):
return X * (X > 0)def relu(X):
return X * tf.cast(X > 0, X.dtype)def relu(X):
return X * (X > 0)def relu(X):
return X * (X > 0)이어서 각 이미지 미니배치를 (-1, self.num_inputs) 로 평탄화하고 \(\mathbf{H} = \mathrm{relu}(\mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)})\) 을 계산하는 은닉층 연산을 hidden(self, X) 로 분리하면, forward(self, X) 는 단순히 원시 클래스 로짓 \(\mathbf{O} = \mathbf{H}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}\) 만 반환하면 됩니다(이 로짓은 Classifier.loss 가 직접 입력받아 처리합니다):
@d2l.add_to_class(MLPScratch)
def hidden(self, X):
X = d2l.reshape(X, (-1, self.num_inputs)) # One flattened image per row
return relu(d2l.matmul(X, self.W1) + self.b1)
@d2l.add_to_class(MLPScratch)
def forward(self, X):
return d2l.matmul(self.hidden(X), self.W2) + self.b2 # The logits@d2l.add_to_class(MLPScratch)
def hidden(self, X):
X = d2l.reshape(X, (-1, self.num_inputs)) # One flattened image per row
return relu(d2l.matmul(X, self.W1) + self.b1)
@d2l.add_to_class(MLPScratch)
def forward(self, X):
return d2l.matmul(self.hidden(X), self.W2) + self.b2 # The logits@d2l.add_to_class(MLPScratch)
def hidden(self, X):
X = d2l.reshape(X, (-1, self.num_inputs)) # One flattened image per row
return relu(d2l.matmul(X, self.W1) + self.b1)
@d2l.add_to_class(MLPScratch)
def forward(self, X):
return d2l.matmul(self.hidden(X), self.W2) + self.b2 # The logits@d2l.add_to_class(MLPScratch)
def hidden(self, X):
X = d2l.reshape(X, (-1, self.num_inputs)) # One flattened image per row
return relu(d2l.matmul(X, self.W1.data()) + self.b1.data())
@d2l.add_to_class(MLPScratch)
def forward(self, X):
return d2l.matmul(self.hidden(X), self.W2.data()) + self.b2.data()4.2.1.2 훈련 전 점검
긴 훈련을 시작하기에 앞서, 훈련되지 않은 신경망에 이미지 8장짜리 작은 슬라이스를 통과시키면 단 몇 밀리초 만에 세 가지 불변 조건을 검증할 수 있습니다:
- 형상:
H의 형상은(8, 256)이고O의 형상은(8, 10)입니다. - 초기 손실: 0에 가까운 가중치는 0에 가까운 로짓(\(\hat{y}_j \approx 1/10\))을 만드므로 초기 교차 엔트로피 손실은 \(\log 10 \approx 2.303\) 부근에 놓입니다.
- 활성 ReLU 비율: 편향이 0이고 가중치가 대칭 분포를 따르면 은닉 사전 활성화값의 약 \(50\%\) 가 양수가 됩니다.
data = d2l.FashionMNIST(batch_size=256)
model = MLPScratch(num_inputs=784, num_outputs=10, num_hiddens=256, lr=0.1)
X, y = next(iter(data.train_dataloader()))
X, y = X[:8], y[:8] # Eight images suffice for the checks
H, O = model.hidden(X), model(X)
active = d2l.reduce_mean(d2l.astype(H > 0, d2l.float32))
print('H:', H.shape, 'O:', O.shape)
print(f'loss {d2l.numpy(model.loss(O, y)):.3f}, '
f'fraction of active units {d2l.numpy(active):.2f}')H: torch.Size([8, 256]) O: torch.Size([8, 10])
loss 2.300, fraction of active units 0.52
H: (8, 256) O: (8, 10)
loss 2.297, fraction of active units 0.52
H: (8, 256) O: (8, 10)
loss 2.294, fraction of active units 0.48
H: (8, 256) O: (8, 10)
loss 2.300, fraction of active units 0.50
4.2.1.3 훈련
이제 미니배치 크기 \(256\), 학습률 \(\eta = 0.1\) 로 Fashion-MNIST에서 MLPScratch 를 \(30\) 에포크 동안 훈련합니다(GPU가 있을 때 Trainer 가 이를 활용하도록 num_gpus=1 을 전달합니다):
trainer = d2l.Trainer(max_epochs=30, num_gpus=1)
trainer.fit(model, data)4.2.2 간결한 구현
각 프레임워크의 Sequential 컨테이너와 내장 선형 층 및 ReLU 층을 사용하면 수동으로 매개변수 배열을 선언하지 않고도 단 몇 줄로 똑같은 아키텍처를 표현할 수 있습니다(MLPScratch 와 일치시키기 위해 가중치는 \(\mathcal{N}(0, 0.01^2)\), 편향은 \(0\) 으로 초기화합니다):
class MLP(d2l.Classifier):
"""An MLP with one hidden layer, built from framework layers."""
def __init__(self, num_outputs, num_hiddens, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(nn.Flatten(), nn.LazyLinear(num_hiddens),
nn.ReLU(), nn.LazyLinear(num_outputs))
def weight_init(self, module):
# The Trainer calls this once the lazy layers know their shapes
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, std=0.01)
nn.init.zeros_(module.bias)class MLP(d2l.Classifier):
"""An MLP with one hidden layer, built from framework layers."""
def __init__(self, num_outputs, num_hiddens, lr):
super().__init__()
self.save_hyperparameters()
normal = tf.keras.initializers.RandomNormal
self.net = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(num_hiddens, activation='relu',
kernel_initializer=normal(stddev=0.01)),
tf.keras.layers.Dense(num_outputs,
kernel_initializer=normal(stddev=0.01))])class MLP(d2l.Classifier):
"""An MLP with one hidden layer, built from framework layers."""
def __init__(self, num_outputs, num_hiddens, lr, num_inputs=784,
rngs=None):
super().__init__()
self.save_hyperparameters(ignore=['rngs'])
rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
normal = nnx.initializers.normal(0.01)
self.net = nnx.Sequential(
nnx.Linear(num_inputs, num_hiddens, kernel_init=normal,
rngs=rngs),
nnx.relu,
nnx.Linear(num_hiddens, num_outputs, kernel_init=normal,
rngs=rngs))
def forward(self, X):
return self.net(X.reshape((X.shape[0], -1))) # Flatten each imageclass MLP(d2l.Classifier):
"""An MLP with one hidden layer, built from framework layers."""
def __init__(self, num_outputs, num_hiddens, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential()
self.net.add(nn.Dense(num_hiddens, activation='relu'),
nn.Dense(num_outputs))
self.net.initialize(init.Normal(sigma=0.01))4.2.3 소프트맥스 회귀와의 비교
4.2.3.1 정확도
동일한 설정에서 간결한 MLP 와 d2l.SoftmaxRegression 을 모두 \(30\) 에포크 동안 훈련하면서, 에포크당 평균 실제 소요 시간(wall-clock time)은 seconds 에, 검증 정확도 궤적은 curves 에 기록해 보겠습니다:
curves, seconds = {'MLP from scratch': trainer.history['val_acc']}, {}
trainer.board.display = False
models = {'concise MLP': MLP(num_outputs=10, num_hiddens=256, lr=0.1),
'softmax regression': d2l.SoftmaxRegression(num_outputs=10, lr=0.1)}
for name, net in models.items():
start = time.perf_counter()
trainer.fit(net, data)
seconds[name] = (time.perf_counter() - start) / trainer.max_epochs
curves[name] = trainer.history['val_acc']curves 에 담긴 세 모델의 1~30에포크 검증 정확도 궤적을 함께 그리면 처음부터 구현한 MLP와 간결한 MLP를 선형 소프트맥스 베이스라인과 직접 비교할 수 있습니다:
d2l.plot(list(range(1, trainer.max_epochs + 1)), list(curves.values()),
'epoch', 'validation accuracy', legend=list(curves))단일 에포크의 검증 변동을 완화하기 위해 마지막 다섯 에포크(acc[-5:])의 평균 검증 정확도를 MLPScratch 의 훈련 데이터셋 정확도와 함께 출력합니다:
print('validation accuracy averaged over the last 5 epochs')
for name, acc in curves.items(): # A single epoch can land a few points low
print(f' {name}: {sum(acc[-5:]) / 5:.3f}')
train_acc = trainer.evaluate(model, data, train=True)['acc']
print(f'training accuracy of the MLP from scratch: {train_acc:.3f}')validation accuracy averaged over the last 5 epochs
MLP from scratch: 0.876
concise MLP: 0.867
softmax regression: 0.840
training accuracy of the MLP from scratch: 0.903
validation accuracy averaged over the last 5 epochs
MLP from scratch: 0.870
concise MLP: 0.872
softmax regression: 0.840
training accuracy of the MLP from scratch: 0.898
validation accuracy averaged over the last 5 epochs
MLP from scratch: 0.869
concise MLP: 0.871
softmax regression: 0.834
training accuracy of the MLP from scratch: 0.884
validation accuracy averaged over the last 5 epochs
MLP from scratch: 0.867
concise MLP: 0.871
softmax regression: 0.841
training accuracy of the MLP from scratch: 0.896
학습 곡선에서 두 가지 유익한 패턴을 확인할 수 있습니다:
std=0.01로 인한 느린 초기 워밍업: 1에포크에서는 두 MLP 모두 오히려 소프트맥스 회귀보다 뒤처집니다. \(\mathbf{W}^{(1)}\) 과 \(\mathbf{W}^{(2)}\) 모두 원소가 \(0.01\) 수준에서 출발하기 때문에, \(\mathbf{W}^{(2)}\) 가 커지기 전까지는 은닉 활성화값 \(\mathbf{H}\) 와 \(\mathbf{W}^{(1)}\) 으로 역전파되는 그레이디언트가 \(0.01\) 배로 억제되기 때문입니다. 이 병목은 4.4절 에서 He 초기화로 해결합니다.- 분류 오류의 5분의 1 감소: 26~30에포크 무렵 소프트맥스 회귀는 검증 정확도 약 \(84\%\) (오류율 \(16\%\))에서 정체되는 반면, 두 MLP는 검증 정확도 \(\sim 87\%\) (오류율 \(\sim 13\%\), 훈련 정확도 \(87\)–\(90\%\))에 도달하여 소프트맥스 회귀가 범하던 오류의 약 \(20\%\) 를 없앱니다.
그렇다면 어떤 오류가 여전히 남아 있을까요? 3.2절 에서 보았듯이 상의 네 종류(티셔츠, 풀오버, 코트, 셔츠)는 생김새가 서로 비슷해 가장 유력한 오분류 후보입니다. 방금 훈련한 두 모델 각각에 대해 전체 검증 오류 수와 그중 상의끼리 혼동한 오류 수를 세어 보겠습니다:
tops = [0, 2, 4, 6] # T-shirt/top, pullover, coat, shirt
for name, net in models.items():
errors = among_tops = 0
for batch in data.val_dataloader():
X, y = trainer.prepare_batch(batch)
pred, y = d2l.numpy(net(X)).argmax(axis=1), d2l.numpy(y)
errors += (pred != y).sum()
among_tops += ((pred != y) & np.isin(y, tops) & np.isin(pred, tops)).sum()
print(f'{name}: {errors} errors, {among_tops} of them between two tops')concise MLP: 1303 errors, 772 of them between two tops
softmax regression: 1602 errors, 959 of them between two tops
concise MLP: 1286 errors, 732 of them between two tops
softmax regression: 1604 errors, 947 of them between two tops
concise MLP: 1369 errors, 864 of them between two tops
softmax regression: 1752 errors, 1061 of them between two tops
concise MLP: 1302 errors, 799 of them between two tops
softmax regression: 1599 errors, 944 of them between two tops
두 모델 모두 전체 오류의 절반 이상이 상의 두 가지를 서로 혼동한 경우입니다. MLP는 소프트맥스 회귀보다 이러한 오류를 줄였지만, 상의 구분은 여전히 Fashion-MNIST에서 가장 어려운 부분으로 남습니다.
4.2.3.2 학습된 특성
3.3절 에서 소프트맥스 회귀의 가중치 행렬 \(\mathbf{W}\) 의 10개 열은 의류 전체의 모양을 본뜬 템플릿 역할을 해야 했습니다. 반면 MLP의 은닉 유닛 256개가 무엇을 학습했는지 살펴보기 위해, 훈련된 가중치 행렬 \(\mathbf{W}^{(1)}\) 과 \(\mathbf{W}^{(2)}\) 를 NumPy 배열로 추출합니다:
W1, W2 = d2l.numpy(model.W1), d2l.numpy(model.W2)W1, W2 = d2l.numpy(model.W1[...]), d2l.numpy(model.W2[...])W1, W2 = d2l.numpy(model.W1.data()), d2l.numpy(model.W2.data())유클리드 가중치 노름이 가장 큰 상위 10개 은닉 유닛을 \(28 \times 28\) 이미지로 시각화하고, 각 유닛이 가장 큰 양의 출력 가중치를 보내는 의류 클래스를 제목으로 표시합니다:
이 이미지들은 더 이상 전체 의류 템플릿처럼 보이지 않습니다. 노름이 큰 각 은닉 유닛은 이미지의 일부 영역에 양의 가중치(빨간색)를, 인접한 영역에 음의 가중치(파란색)를 부여하므로, 어깨선을 따라서나 몸통 옆선을 따라 한 영역은 밝고 바로 옆 영역은 어두운 대비(contrast)에 반응합니다. 다만 대부분의 패턴이 여전히 의류 상당 부분에 걸쳐 퍼져 있으므로 이를 작은 에지 검출기로 해석해서는 안 됩니다. 출력층은 이러한 대비 패턴 \(256\) 개를 조합해 열 개의 클래스 점수를 만듭니다.
4.2.3.3 매개변수, 연산량 및 실행 시간
| 모델 | 매개변수 수 | 이미지당 곱셈-덧셈 수 | 검증 정확도(26~30에포크) |
|---|---|---|---|
| 소프트맥스 회귀 | \(7{,}850\) | \(7{,}840\) | \(\sim 84\%\) |
| MLP (\(h = 256\) ReLU 유닛) | \(203{,}530\) | \(203{,}264\) | \(\sim 87\%\) |
MLP가 이미지당 소프트맥스 회귀보다 26배나 많은 곱셈-덧셈 연산을 수행하는데도 실제 에포크당 소요 시간은 얼마나 차이 나는지 비교해 보겠습니다:
for name, s in seconds.items():
print(f'{name}: {s:.1f} s per epoch')concise MLP: 1.3 s per epoch
softmax regression: 1.3 s per epoch
concise MLP: 0.7 s per epoch
softmax regression: 0.6 s per epoch
concise MLP: 0.8 s per epoch
softmax regression: 0.7 s per epoch
concise MLP: 0.8 s per epoch
softmax regression: 0.7 s per epoch
현대 하드웨어(특히 GPU)에서는 두 모델의 에포크당 실제 소요 시간이 거의 같습니다. 너비 \(h = 256\) 수준에서는 데이터 로딩과 Python 반복 또는 커널 실행 오버헤드가 전체 실행 시간을 지배하므로, 밀집 행렬 산술량이 26배 늘어나더라도 실제 소요 시간에는 거의 추가 비용이 발생하지 않습니다 (3 에서는 행렬 연산이 마침내 데이터 로딩 오버헤드를 추월하는 너비를 실험으로 확인합니다).
4.2.4 요약
훈련을 시작하기 전에 작은 배치로 순전파를 한 번 실행해 보면 중간 텐서와 출력 텐서의 형상을 검증하고, 초기 교차 엔트로피 손실이 \(\log q \approx 2.30\) 부근에 놓이는지 확인하며, ReLU 은닉 유닛의 약 절반이 활성화되는지 점검할 수 있습니다. Fashion-MNIST에서 256-유닛 ReLU 은닉층 하나를 삽입하면 에포크당 GPU 실제 소요 시간은 거의 그대로 유지하면서 검증 정확도가 \(\sim 84\%\) 에서 \(\sim 87\%\) 로 올라가 오류율이 약 5분의 1 줄어듭니다. 이때 은닉 유닛들은 흐릿한 전체 의류 템플릿을 만드는 대신 인접 영역에 반대 부호의 가중치를 부여하는 대비 패턴을 학습하고, 출력층에서 이를 조합해 예측을 수행합니다.
4.2.5 연습 문제
- [code] 활성화 함수 없는 은닉층.
MLPScratch에서relu를 항등 함수로 바꾸고 이 절과 동일한 방식으로 모델을 훈련하십시오.- 30에포크 후의 검증 정확도를 MLP 및 소프트맥스 회귀와 비교하십시오.
- 훈련이 끝난 뒤 \(\mathbf{W} = \mathbf{W}^{(1)}\mathbf{W}^{(2)}\) 와 \(\mathbf{b} = \mathbf{W}^{(2)\top}\mathbf{b}^{(1)} + \mathbf{b}^{(2)}\) 를 계산하고, 미니배치에서 \(\mathbf{X}\mathbf{W} + \mathbf{b}\) 가 모델의 로짓을 정확히 재현하는지 확인하십시오.
- 1 에서는 이러한 신경망이 가중치 행렬의 랭크가 최대 은닉층 너비 이하인 아핀 사상들만 정확히 계산함을 보였습니다. 여기서 이 제약이 아무런 손실도 일으키지 않는 이유를 설명하고, Fashion-MNIST에서 모델의 표현력을 실제로 축소시키게 되는 은닉층 너비의 기준값을 제시하십시오.
- [code] 단일 은닉 유닛.
MLPScratch에서num_hiddens=1로 설정하여 은닉층이 가중치 \(\mathbf{w}^{(1)} \in \mathbb{R}^{784 \times 1}\) 와 편향 \(b^{(1)} \in \mathbb{R}\) 를 갖는 단일 ReLU 유닛만 포함하도록 합시다. 그러면 각 입력 \(\mathbf{x} \in \mathbb{R}^{1 \times 784}\) 는 스칼라 \(t = \operatorname{ReLU}(\mathbf{x}\mathbf{w}^{(1)} + b^{(1)}) \geq 0\) 으로 축약되고, 로짓은 \(\mathbf{w}^{(2)} \in \mathbb{R}^{1 \times 10}\) 과 \(\mathbf{b}^{(2)} \in \mathbb{R}^{10}\) 에 대해 \(\mathbf{o} = t\, \mathbf{w}^{(2)} + \mathbf{b}^{(2)}\) 가 됩니다.- 각 클래스가 \(t\) 의 최대 한 구간에서만 예측되며, \(t\) 축을 따른 이 구간들의 순서가 \(\mathbf{w}^{(2)}\) 의 원소들에 의해 고정됨을 보이십시오. 모델이 각 클래스에 할당하는 입력 공간 영역의 형태를 기술하고, 이것이 Fashion-MNIST의 열 개 클래스를 분리하는 데 어떤 함의를 갖는지 설명하십시오.
- 어떤 업데이트 이후 모든 훈련 표본에 대해 \(\mathbf{x}\mathbf{w}^{(1)} + b^{(1)} < 0\) 이 되었다고 가정합시다. 그 시점부터 0이 아닌 그레이디언트를 받는 매개변수는 무엇이며 신경망은 무엇을 예측합니까? 이 절의 256개 은닉 유닛 중 하나에 똑같은 일이 벌어졌을 때는 왜 피해가 거의 없습니까?
- 이 모델을 다섯 번 훈련하고, 각 실행마다 검증 정확도와
model.hidden으로 구한 검증 표본 중 \(t > 0\) 인 비율을 기록하십시오. 이 비율이 0인 실행이 있다면 (b)의 답과 비교하십시오.
- [code] 은닉층 너비. 이 절과 동일한 설정(학습률 0.1, 30에포크)으로 은닉층 너비 \(h \in \{16, 64, 256, 1024, 4096\}\) 에 대해
MLP를 훈련하고 최종 검증 정확도와 에포크당 소요 시간을 기록하십시오.- 로그 축 위에 \(h\) 에 따른 두 값을 모두 그리십시오. 어느 너비부터 정확도 향상 폭이 에포크 간 변동 폭 이하로 줄어듭니까?
- 곱셈-덧셈 연산량은 \(h\) 에 비례해 증가합니다. 모델 없이 미니배치를 읽기만 하는 훈련 데이터 1회 순회 시간을 측정하고, 이를 이용해 시간 곡선에서 \(h\) 에 따라 증가하지 않는 구간을 설명하십시오. 사용 중인 하드웨어에서는 어느 너비부터 산술 연산이 전체 시간을 지배합니까?
- 너비 64와 1024에서 학습률 \(\{0.03, 0.1, 0.3\}\) 으로 훈련을 반복하십시오. 최적의 학습률은 너비에 따라 달라집니까?