بتل کد Battle Codeدارد باز می‌شود…

جواب «Patience» چالش 5 از جلسه‌ی 49

سؤال

تابع train_with_patience(hidden, patience, max_epochs) را بنویس: دوره به دوره آموزش بده، کپی بهترین شبکه را (با اعتبارسنجی) نگه دار و وقتی بهترین دوره patience دوره قدیمی شد، بایست. best_net, best_epoch و دوره‌ای که در آن ایستادی را برگردان. خروجی: patience 3: stopped at epoch 14, best epoch 11, validation 89% و patience 5: stopped at epoch 16, best epoch 11, validation 89%.

راهنما

در هر دوره یا رکورد زده می‌شود، یا اگر epoch - best_epoch >= patience شد، همان‌جا return کن.

یک جواب درست

import random
import numpy as np

SHAPES = '''
.###. ..#.. .###. ####. #..#. ##### .###. ##### .###. .###.
#...# .##.. #...# ....# #..#. #.... #.... ....# #...# #...#
#...# ..#.. ..##. .###. ##### ####. ####. ...#. .###. .####
#...# ..#.. .#... ....# ...#. ....# #...# ..#.. #...# ....#
.###. .###. ##### ####. ...#. ####. .###. ..#.. .###. .###.
'''


def make_digits(copies, noise, seed):
    random.seed(seed)
    rows = SHAPES.strip().splitlines()
    X, y = [], []
    for c in range(copies):
        for d in range(10):
            pixels = [1.0 if ch == "#" else 0.0 for ch in "".join(r.split()[d] for r in rows)]
            for i in random.sample(range(25), noise):
                pixels[i] = 1.0 - pixels[i]
            X.append(pixels)
            y.append(d)
    return np.array(X), np.array(y)


X, y = make_digits(20, 4, 1)      # train: 200 digits, 4 flipped pixels each
Xv, yv = make_digits(10, 4, 3)    # validation: 100 digits for our choices
Xt, yt = make_digits(10, 4, 2)    # test: 100 digits, used once at the very end



def softmax(z):
    e = np.exp(z - z.max(axis=1, keepdims=True))
    return e / e.sum(axis=1, keepdims=True)


def rand_matrix(rows, cols):
    return np.array([[random.uniform(-0.5, 0.5) for c in range(cols)] for r in range(rows)])


def new_net(hidden):
    random.seed(0)
    return {"W1": rand_matrix(25, hidden), "b1": np.zeros(hidden),
            "W2": rand_matrix(hidden, 10), "b2": np.zeros(10)}


def forward(net, x):
    h = np.maximum(0, x @ net["W1"] + net["b1"])
    return h, softmax(h @ net["W2"] + net["b2"])


def accuracy(net, Xs, ys):
    h, p = forward(net, Xs)
    return round(float((p.argmax(axis=1) == ys).mean()) * 100)


def train_epoch(net, Xs, ys, lr=0.5, batch=20):
    order = list(range(len(Xs)))
    random.shuffle(order)
    for start in range(0, len(order), batch):
        idx = order[start:start + batch]
        xb, yb = Xs[idx], ys[idx]
        h, p = forward(net, xb)
        dz2 = (p - np.eye(10)[yb]) / len(xb)
        dh = dz2 @ net["W2"].T * (h > 0)
        net["W2"] -= lr * (h.T @ dz2)
        net["b2"] -= lr * dz2.sum(axis=0)
        net["W1"] -= lr * (xb.T @ dh)
        net["b1"] -= lr * dh.sum(axis=0)


def train_with_patience(hidden, patience, max_epochs):
    net = new_net(hidden)
    best_val, best_epoch, best_net = -1, 0, None
    for epoch in range(1, max_epochs + 1):
        train_epoch(net, X, y)
        v = accuracy(net, Xv, yv)
        if v > best_val:
            best_val, best_epoch = v, epoch
            best_net = {name: a.copy() for name, a in net.items()}
        elif epoch - best_epoch >= patience:
            return best_net, best_epoch, epoch
    return best_net, best_epoch, max_epochs



for patience in [3, 5]:
    best_net, best_epoch, stopped = train_with_patience(32, patience, 30)
    print(f"patience {patience}: stopped at epoch {stopped}, best epoch {best_epoch}, validation {accuracy(best_net, Xv, yv)}%")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن