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

Step 3: Classify New Messages چالش 3 از جلسه‌ی 24، متوسط

قدم سوم: با knn آماده (k=3)، برای هر پیام در new_messages حدس بزن و چاپ کن: پیام، یک -> و حدس. خروجی سه خط: click to win free now -> spam، are we playing football today -> ham، free free free!!! -> spam.

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]

new_messages = ["click to win free now", "are we playing football today", "free free free!!!"]
# guess each new message with knn(features(msg), X, y, 3) and print "msg -> guess"

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 24: پروژه: تشخیص هرز · چالش بعدی: Step 4: Test Accuracy Report

بیشتر بخوان: list comprehension در پایتون: از حلقه for تا یک خط کد