جواب «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.
راهنما
for msg in new_messages: guess = knn(features(msg), X, y, 3); print(msg, "->", 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]
new_messages = ["click to win free now", "are we playing football today", "free free free!!!"]
for msg in new_messages:
guess = knn(features(msg), X, y, 3)
print(msg, "->", guess)
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن