Step 2: Weights and Forward Pass چالش 2 از جلسهی 47، آسان
قدم ۲: وزنها و forward اضافه شدهاند اما لایهی پنهان هنوز ReLU ندارد. همان یک خط را درست کن تا منفیها صفر شوند. بعد از خروجی قدم ۱، این سه خط باید بیاید: (3, 10)، [0.33 0.02 0.11 0.01 0.03 0.03 0.27 0.13 0.04 0.05] و 1.0 (احتمالهای تصویر اول قبل از آموزش و جمعشان).
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, 2, 1) # 200 training digits
Xt, yt = make_digits(10, 2, 2) # 100 test digits
def show(pixels):
for r in range(5):
row = pixels[r * 5:r * 5 + 5]
print("".join("#" if p > 0.5 else "." for p in row))
print(X.shape, Xt.shape)
print("label:", int(y[3]))
show(X[3])
random.seed(0)
def rand_matrix(rows, cols):
return np.array([[random.uniform(-0.5, 0.5) for c in range(cols)] for r in range(rows)])
net = {"W1": rand_matrix(25, 16), "b1": np.zeros(16),
"W2": rand_matrix(16, 10), "b2": np.zeros(10)}
def softmax(z):
e = np.exp(z - z.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
def forward(x):
h = x @ net["W1"] + net["b1"] # add ReLU here
p = softmax(h @ net["W2"] + net["b2"])
return h, p
h, p = forward(X[:3])
print(p.shape)
print(np.round(p[0], 2))
print(round(float(p[0].sum()), 3))
راهنما و جواب این چالش · برگشت به درس جلسهی 47: پروژه: شناسای کامل رقم · چالش بعدی: Step 3: The Accuracy Function
بیشتر بخوان: list comprehension در پایتون: از حلقه for تا یک خط کد