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

جواب «A Neuron Learns the Camera» چالش 6 از جلسه‌ی 31

سؤال

جلسه‌ی قبل وزن‌های [1, -1] را خودمان دادیم؛ حالا نورون خودش یاد بگیرد! data برای هر عکس نمونه (top, bottom, 1 یا 0) دارد (1 یعنی دست بالا). وزن‌ها از صفر شروع می‌شوند. حلقه‌ی آموزش را با قانون پرسپترون بنویس (حداکثر ۲۰ دور، با break وقتی دوری بی‌اشتباه بود) و هر دور rounds را یکی زیاد کن. بعد برنامه روی عکس‌های امید می‌آزماید. خروجی:
rounds: 2
omid right: 8 of 8

راهنما

مثل سؤال «Train Until Perfect»: for rnd in range(20):، rounds += 1، mistakes = 0، for top, bottom, target in data: با حدس، خطا و قانون، و آخر if mistakes == 0: break. یادت باشد t را -= کنی.

یک جواب درست

import cam

def features(photo):
    top = 0
    bottom = 0
    for row in photo[:8]:
        top += sum(row)
    for row in photo[8:]:
        bottom += sum(row)
    return top // 128, bottom // 128

data = []
for label, photo in cam.samples():
    top, bottom = features(photo)
    data.append((top, bottom, 1 if label == "up" else 0))

w1, w2, t = 0.0, 0.0, 0.0
rate = 0.1
rounds = 0
for rnd in range(20):
    rounds += 1
    mistakes = 0
    for top, bottom, target in data:
        out = 1 if w1 * top + w2 * bottom >= t else 0
        error = target - out
        if error != 0:
            mistakes += 1
            w1 += rate * error * top
            w2 += rate * error * bottom
            t -= rate * error
    if mistakes == 0:
        break

right = 0
for label, photo in cam.samples(who="omid", start=4):
    top, bottom = features(photo)
    guess = "up" if w1 * top + w2 * bottom >= t else "down"
    if guess == label:
        right += 1
print("rounds:", rounds)
print("omid right:", right, "of 8")

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