انتقل للمحتوى
Robo EgyptRobo Egypt
تقدّمك في الجزء0 من 30
الدرس 10.2 · الكود والأرقام⏱ 12 دقيقة
الفصل 10: أول روبوت بيتعلم: يقلّد المدرّس

تجربة: 15,000 مثال

طالبين: واحد من غير ذاكرة، وواحد بالذاكرة.

  • من غير ذاكرة: دقة 95.8%، ولفّ المضمار بالعكس.
  • بالذاكرة: 99.8%، و 1.57 لفة زي المدرّس.
  • الدقة على البيانات مش هي النجاح في المهمة.

الشرح بالتفصيل

import math, numpy as np
# نفس مضمار الفصل 5. «المدرّس» = الـ state machine. «الطالب» = شبكة عصبية صغيرة بتتعلم تقلّده
S, LINE_W = 0.6, 0.02
PTS = np.array([[(t, -S), (S, t), (-t, S), (-S, -t)][k] for k in range(4) for t in np.linspace(-S, S, 120, endpoint=False)])
on_line = lambda x, y: np.min(np.hypot(PTS[:, 0] - x, PTS[:, 1] - y)) < LINE_W / 2
ACTIONS = [(1.0, 1.0), (0.2, 1.0), (1.0, 0.2), (-0.6, 0.6), (0.6, -0.6)]   # قدّام، شمال، يمين، لف شمال، لف يمين

def teacher(L, C, R, last):
    if L and not R: return 1
    if R and not L: return 2
    if C: return 0
    return 3 if last > 0 else 4

def features(L, C, R, last, memory):
    f = [L, C, R]
    return np.array(f + ([last > 0, last < 0] if memory else []), dtype=float)

def drive(policy, speed=0.4, T=20.0, dt=0.004, record=None, rng=None):
    x, y, th, last, progress = 0.0, -S, 0.0, 0, 0.0
    prev = math.atan2(y, x)
    for i in range(int(T / dt)):
        sx, sy = x + 0.04 * math.cos(th), y + 0.04 * math.sin(th)
        nx, ny = -math.sin(th), math.cos(th)
        L, C, R = on_line(sx + .015 * nx, sy + .015 * ny), on_line(sx, sy), on_line(sx - .015 * nx, sy - .015 * ny)
        a = policy(L, C, R, last)
        if record is not None: record.append((L, C, R, last, teacher(L, C, R, last)))
        if rng is not None and rng.random() < 0.1: a = rng.integers(5)      # «غلطات» أثناء جمع البيانات، عشان المدرّس يورّي إزاي يصلّح
        if a == 1: last = +1
        if a == 2: last = -1
        vl, vr = ACTIONS[a][0] * speed, ACTIONS[a][1] * speed
        v, w = (vl + vr) / 2, (vr - vl) / 0.10
        th += w * dt; x += v * math.cos(th) * dt; y += v * math.sin(th) * dt
        ang = math.atan2(y, x); progress += (ang - prev + math.pi) % (2 * math.pi) - math.pi; prev = ang
    return progress / (2 * math.pi)

# 1) اجمع بيانات: المدرّس بيسوق، ونسجّل (اللي شافه، اللي عمله)
rng = np.random.default_rng(0)
data = []
for seed in range(3):
    drive(teacher, record=data, rng=np.random.default_rng(seed))
print(f"collected {len(data):,} (sensors → action) examples from the teacher")

# 2) درّب شبكة صغيرة: input → 16 neuron → 5 actions
def train(memory, epochs=300, lr=0.5):
    X = np.array([features(L, C, R, last, memory) for L, C, R, last, _ in data])
    Y = np.eye(5)[[a for *_, a in data]]
    W1 = rng.normal(0, 0.5, (X.shape[1], 16)); b1 = np.zeros(16)
    W2 = rng.normal(0, 0.5, (16, 5)); b2 = np.zeros(5)
    for _ in range(epochs):
        H = np.tanh(X @ W1 + b1); Z = H @ W2 + b2
        P = np.exp(Z - Z.max(1, keepdims=True)); P /= P.sum(1, keepdims=True)
        G = (P - Y) / len(X)                                      # gradient بتاع الـ cross-entropy
        gW2, gb2 = H.T @ G, G.sum(0); GH = G @ W2.T * (1 - H ** 2)
        gW1, gb1 = X.T @ GH, GH.sum(0)
        W1 -= lr * gW1; b1 -= lr * gb1; W2 -= lr * gW2; b2 -= lr * gb2
    acc = (P.argmax(1) == Y.argmax(1)).mean()
    return (W1, b1, W2, b2), acc

# 3) سيب الطالب يسوق لوحده
for memory in (False, True):
    params, acc = train(memory)
    W1, b1, W2, b2 = params
    student = lambda L, C, R, last: int(np.argmax(np.tanh(features(L, C, R, last, memory) @ W1 + b1) @ W2 + b2))
    laps = drive(student)
    print(f"student {'WITH memory   ' if memory else 'without memory'}: imitation accuracy {acc:.1%}   laps in 20 s: {laps:.2f}")
    if memory: np.savez("student.npz", W1=W1, b1=b1, W2=W2, b2=b2)
print(f"teacher (state machine)              : laps in 20 s: {drive(teacher):.2f}")
النتيجة المتوقعة (من الكتاب):
collected 15,000 (sensors → action) examples from the teacher
student without memory: imitation accuracy 95.8%   laps in 20 s: -1.27
student WITH memory   : imitation accuracy 99.8%   laps in 20 s: 1.57
teacher (state machine)              : laps in 20 s: 1.56

3 دروس من 3 أرقام. (1) الطالب من غير ذاكرة شايف الـ 3 حساسات بس. لما الخط يختفي، مش عارف يلف يمين ولا شمال، فبيخمّن. دقته على البيانات 95.8% (رقم يبان ممتاز)، بس لما ساق لوحده لفّ المضمار بالعكس (−1.27 لفة: لف حوالين نفسه عند زاوية وكمّل في الاتجاه الغلط). الدقة على البيانات مش هي النجاح في المهمة. الـ 4.2% الغلط كانوا بالظبط اللحظات الحرجة. (2) الطالب بالذاكرة (نفس الشبكة + آخر ناحية شاف فيها الخط، زي الفصل 5): 99.8%، وسواقته زي المدرّس بالظبط (1.57 مقابل 1.56 لفة). (3) الـ 10% غلطات العشوائية وقت التسجيل مهمة: من غيرها، البيانات مش هيبقى فيها مواقف «الروبوت خرج عن الخط»، وده درس ALVINN.

ملاحظةدي محاكاة بـ Python: دوس «▶ شغّل هنا» وشوف الأرقام بنفسك.
خلصت الدرس؟ علّم عليه عشان تقدّمك يتحسب.