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

جواب «Step 4: Test Accuracy Report» چالش 4 از جلسه‌ی 24

سؤال

قدم آخر: پیام‌های آزمون با برچسب واقعی داده شده‌اند. برای هر کدام با k=3 حدس بزن؛ اگر اشتباه بود خطی چاپ کن: wrong: <پیام> (guessed <حدس>). در پایان accuracy 0.8 را چاپ کن (نسبت درست‌ها، گرد با دو رقم). خروجی باید دو خط باشد: wrong: win the free game now (guessed spam) و accuracy 0.8.

راهنما

for text, label in test: guess = knn(features(text), X, y, 3)؛ if guess == label: correct += 1 و در غیر این صورت print(f"wrong: {text} (guessed {guess})").

یک جواب درست

import math

SPAM_WORDS = ["free", "win", "now", "click", "prize"]


def features(text):
    words = text.lower().split()
    spam_count = 0
    for w in words:
        if w.strip("!") in SPAM_WORDS:
            spam_count += 1
    return [spam_count, len(words), text.count("!")]


def distance(a, b):
    return math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(len(a))))


def knn(point, X, y, k):
    pairs = sorted((distance(point, X[i]), y[i]) for i in range(len(X)))
    votes = {}
    for d, label in pairs[:k]:
        votes[label] = votes.get(label, 0) + 1
    return max(votes, key=votes.get)


messages = [
    ("Win a FREE prize now!", "spam"),
    ("free money win now click", "spam"),
    ("you won click now!!", "spam"),
    ("hi are you coming to class", "ham"),
    ("see you at football practice", "ham"),
    ("mum says dinner is ready", "ham"),
]
X = [features(t) for t, l in messages]
y = [l for t, l in messages]

test = [
    ("click now win a prize", "spam"),
    ("free prize click!!", "spam"),
    ("can you bring my book tomorrow", "ham"),
    ("win the free game now", "ham"),
    ("we have a maths test on monday", "ham"),
]
correct = 0
for text, label in test:
    guess = knn(features(text), X, y, 3)
    if guess == label:
        correct += 1
    else:
        print(f"wrong: {text} (guessed {guess})")
print("accuracy", round(correct / len(test), 2))

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