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.
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
# guess each test message, print the wrong ones, count the right ones
print("accuracy", round(correct / len(test), 2))
راهنما و جواب این چالش · برگشت به درس جلسهی 24: پروژه: تشخیص هرز
بیشتر بخوان: list comprehension در پایتون: از حلقه for تا یک خط کد