第22章付録:深層学習のための数学
22.9.4. Training22.9.4 訓練
The problem now is that we do not know and . So we need to estimate their values given some training data first. This is training the model. Estimating is not too hard. Since we are only dealing with classes, we may count the number of occurrences for each of the digits and divide it by the total amount of data . For instance, if digit 8 occurs times and we have a total of images, the probability estimate is .
英語のヒント
今の問題は、とがわからないことである。そこで、まず何らかの訓練データが与えられたもとで、それらの値を推定する必要がある。これがモデルの訓練である。の推定はそれほど難しくない。扱うクラスは個だけなので、各数字の出現回数を数え、それをデータの総量で割ればよい。たとえば、数字8が回現れ、画像が全部で枚あるなら、確率の推定値はである。
X = torch.stack([mnist_train[i][0] for i in range(len(mnist_train))], dim=0)
Y = torch.tensor([mnist_train[i][1] for i in range(len(mnist_train))])
n_y = torch.zeros(10)
for y in range(10):
n_y[y] = (Y == y).sum()
P_y = n_y / n_y.sum()
P_ytensor([0.0987, 0.1124, 0.0993, 0.1022, 0.0974, 0.0904, 0.0986, 0.1044, 0.0975,
0.0992])Now on to slightly more difficult things . Since we picked black and white images, denotes the probability that pixel is switched on for class . Just like before we can go and count the number of times such that an event occurs and divide it by the total number of occurrences of , i.e., . But there is something slightly troubling: certain pixels may never be black (e.g., for well cropped images the corner pixels might always be white). A convenient way for statisticians to deal with this problem is to add pseudo counts to all occurrences. Hence, rather than we use and instead of we use (since there are two possible values pixel can take - it can either be black or white). This is also called Laplace Smoothing. It may seem ad-hoc, however it can be motivated from a Bayesian point-of-view by a Beta-binomial model.
英語のヒント
では、もう少し難しいに移ろう。白黒の画像を選んだので、は、クラスについて画素がオンになる確率を表す。前と同じように、ある事象が起きる回数を数え、それをの出現の総数、つまりで割ればよい。しかし、少し困ったことがある。ある画素は決して黒にならないかもしれないのである(たとえば、うまく切り抜かれた画像では、隅の画素はいつも白かもしれない)。この問題に対処する統計学者にとって便利な方法は、すべての出現に疑似カウントを加えることである。したがって、の代わりにを使い、の代わりにを使う(画素がとりうる値は黒か白の二つなので)。これはラプラス平滑化とも呼ばれる。その場しのぎに見えるかもしれないが、ベータ二項モデルによってベイズ的な観点から動機づけられる。
n_x = torch.zeros((10, 28, 28))
for y in range(10):
n_x[y] = torch.tensor(X.numpy()[Y.numpy() == y].sum(axis=0))
P_xy = (n_x + 1) / (n_y + 2).reshape(10, 1, 1)
d2l.show_images(P_xy, 2, 5);By visualizing these probabilities (for each pixel for each class) we could get some mean looking digits.
英語のヒント
これらの個の確率(各クラスの各画素についての確率)を視覚化すると、平均的な見た目の数字が得られる。
Now we can use (22.9.6) to predict a new image. Given , the following functions computes for every .
英語のヒント
これで、式(22.9.6)を使って新しい画像を予測できる。が与えられると、次の関数はすべてのについてを計算する。
def bayes_pred(x):
x = x.unsqueeze(0) # (28, 28) -> (1, 28, 28)
p_xy = P_xy * x + (1 - P_xy)*(1 - x)
p_xy = p_xy.reshape(10, -1).prod(dim=1) # p(x|y)
return p_xy * P_y
image, label = mnist_test[0]
bayes_pred(image)tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])This went horribly wrong! To find out why, let’s look at the per pixel probabilities. They are typically numbers between and . We are multiplying of them. At this point it is worth mentioning that we are calculating these numbers on a computer, hence with a fixed range for the exponent. What happens is that we experience numerical underflow, i.e., multiplying all the small numbers leads to something even smaller until it is rounded down to zero. We discussed this as a theoretical issue in Section 22.7, but we see the phenomena clearly here in practice.
英語のヒント
これはひどく失敗した。理由を突き止めるため、画素ごとの確率を見よう。それらはふつうからの間の数である。それを個掛け合わせている。ここで、これらの数をコンピュータで計算しているので、指数の範囲が固定されていることに触れておく価値がある。起きているのは数値的なアンダーフローである。つまり、小さな数をすべて掛け合わせるとさらに小さなものになり、ついには0に切り捨てられてしまう。22.7節ではこれを理論上の問題として論じたが、ここでは実際にこの現象がはっきり見える。
As discussed in that section, we fix this by use the fact that , i.e., we switch to summing logarithms. Even if both and are small numbers, the logarithm values should be in a proper range.
英語のヒント
その節で論じたように、という事実を使って、つまり対数の和に切り替えることで、これを直す。とがどちらも小さな数でも、対数の値は適切な範囲に収まるはずである。
a = 0.1
print('underflow:', a**784)
print('logarithm is normal:', 784*math.log(a))underflow: 0.0
logarithm is normal: -1805.2267129073316Since the logarithm is an increasing function, we can rewrite (22.9.6) as
英語のヒント
対数は増加関数なので、式(22.9.6)は次のように書き直せる。
(22.9.7)
We can implement the following stable version:
英語のヒント
次の安定な版を実装できる。
log_P_xy = torch.log(P_xy)
log_P_xy_neg = torch.log(1 - P_xy)
log_P_y = torch.log(P_y)
def bayes_pred_stable(x):
x = x.unsqueeze(0) # (28, 28) -> (1, 28, 28)
p_xy = log_P_xy * x + log_P_xy_neg * (1 - x)
p_xy = p_xy.reshape(10, -1).sum(axis=1) # p(x|y)
return p_xy + log_P_y
py = bayes_pred_stable(image)
pytensor([-268.9725, -301.7044, -245.1951, -218.8738, -193.4570, -206.0909,
-292.5226, -114.6257, -220.3313, -163.1784])We may now check if the prediction is correct.
英語のヒント
これで、予測が正しいかを確かめられる。
py.argmax(dim=0) == labeltensor(True)If we now predict a few validation examples, we can see the Bayes classifier works pretty well.
英語のヒント
いくつかの検証用の例を予測すると、ベイズ分類器がかなりうまく働くことがわかる。
def predict(X):
return [bayes_pred_stable(x).argmax(dim=0).type(torch.int32).item()
for x in X]
X = torch.stack([mnist_test[i][0] for i in range(18)], dim=0)
y = torch.tensor([mnist_test[i][1] for i in range(18)])
preds = predict(X)
d2l.show_images(X, 2, 9, titles=[str(d) for d in preds]);Finally, let’s compute the overall accuracy of the classifier.
英語のヒント
最後に、分類器の全体の精度を計算しよう。
X = torch.stack([mnist_test[i][0] for i in range(len(mnist_test))], dim=0)
y = torch.tensor([mnist_test[i][1] for i in range(len(mnist_test))])
preds = torch.tensor(predict(X), dtype=torch.int32)
float((preds == y).sum()) / len(y) # Validation accuracy0.8427Modern deep networks achieve error rates of less than . The relatively poor performance is due to the incorrect statistical assumptions that we made in our model: we assumed that each and every pixel are independently generated, depending only on the label. This is clearly not how humans write digits, and this wrong assumption led to the downfall of our overly naive (Bayes) classifier.
英語のヒント
現代の深層ネットワークは未満の誤り率を達成する。比較的悪い性能は、モデルで置いた誤った統計的仮定のためである。各画素がラベルだけに依存して独立に生成されると仮定したのである。これは明らかに人間が数字を書くやり方ではなく、この誤った仮定が、あまりにナイーブな(ベイズ)分類器の失敗につながった。