プリンキピア

第22章付録:深層学習のための数学

22.9.4. Training22.9.4 訓練

The problem now is that we do not know Pxy and Py. So we need to estimate their values given some training data first. This is training the model. Estimating Py is not too hard. Since we are only dealing with 10 classes, we may count the number of occurrences ny for each of the digits and divide it by the total amount of data n. For instance, if digit 8 occurs n8=5,800 times and we have a total of n=60,000 images, the probability estimate is p(y=8)=0.0967.
英語のヒント
今の問題は、PxyとPyがわからないことである。そこで、まず何らかの訓練データが与えられたもとで、それらの値を推定する必要がある。これがモデルの訓練である。Pyの推定はそれほど難しくない。扱うクラスは10個だけなので、各数字の出現回数nyを数え、それをデータの総量nで割ればよい。たとえば、数字8がn8=5,800回現れ、画像が全部でn=60,000枚あるなら、確率の推定値はp(y=8)=0.0967である。
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_y
tensor([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 Pxy. Since we picked black and white images, p(xi∣y) denotes the probability that pixel i is switched on for class y. Just like before we can go and count the number of times niy such that an event occurs and divide it by the total number of occurrences of y, i.e., ny. 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 niy we use niy+1 and instead of ny we use ny+2 (since there are two possible values pixel i 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.
英語のヒント
では、もう少し難しいPxyに移ろう。白黒の画像を選んだので、p(xi∣y)は、クラスyについて画素iがオンになる確率を表す。前と同じように、ある事象が起きる回数niyを数え、それをyの出現の総数、つまりnyで割ればよい。しかし、少し困ったことがある。ある画素は決して黒にならないかもしれないのである(たとえば、うまく切り抜かれた画像では、隅の画素はいつも白かもしれない)。この問題に対処する統計学者にとって便利な方法は、すべての出現に疑似カウントを加えることである。したがって、niyの代わりにniy+1を使い、nyの代わりにny+2を使う(画素iがとりうる値は黒か白の二つなので)。これはラプラス平滑化とも呼ばれる。その場しのぎに見えるかもしれないが、ベータ二項モデルによってベイズ的な観点から動機づけられる。
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 10×28×28 probabilities (for each pixel for each class) we could get some mean looking digits.
英語のヒント
これらの10×28×28個の確率(各クラスの各画素についての確率)を視覚化すると、平均的な見た目の数字が得られる。
Now we can use (22.9.6) to predict a new image. Given 𝐱, the following functions computes p(𝐱∣y)p(y) for every y.
英語のヒント
これで、式(22.9.6)を使って新しい画像を予測できる。𝐱が与えられると、次の関数はすべてのyについてp(𝐱∣y)p(y)を計算する。
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 0.001 and 1. We are multiplying 784 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.001から1の間の数である。それを784個掛け合わせている。ここで、これらの数をコンピュータで計算しているので、指数の範囲が固定されていることに触れておく価値がある。起きているのは数値的なアンダーフローである。つまり、小さな数をすべて掛け合わせるとさらに小さなものになり、ついには0に切り捨てられてしまう。22.7節ではこれを理論上の問題として論じたが、ここでは実際にこの現象がはっきり見える。
As discussed in that section, we fix this by use the fact that log⁡ab=log⁡a+log⁡b, i.e., we switch to summing logarithms. Even if both a and b are small numbers, the logarithm values should be in a proper range.
英語のヒント
その節で論じたように、log⁡ab=log⁡a+log⁡bという事実を使って、つまり対数の和に切り替えることで、これを直す。aとbがどちらも小さな数でも、対数の値は適切な範囲に収まるはずである。
a = 0.1
print('underflow:', a**784)
print('logarithm is normal:', 784*math.log(a))
underflow: 0.0
logarithm is normal: -1805.2267129073316
Since the logarithm is an increasing function, we can rewrite (22.9.6) as
英語のヒント
対数は増加関数なので、式(22.9.6)は次のように書き直せる。
yˆ=argmaxy log⁡Py[y]+∑i=1d[tilog⁡Pxy[xi,y]+(1−ti)log⁡(1−Pxy[xi,y])].(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)
py
tensor([-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) == label
tensor(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 accuracy
0.8427
Modern deep networks achieve error rates of less than 0.01. 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.
英語のヒント
現代の深層ネットワークは0.01未満の誤り率を達成する。比較的悪い性能は、モデルで置いた誤った統計的仮定のためである。各画素がラベルだけに依存して独立に生成されると仮定したのである。これは明らかに人間が数字を書くやり方ではなく、この誤った仮定が、あまりにナイーブな(ベイズ)分類器の失敗につながった。