Build a tiny naive-Bayes spam/ham classifier (Laplace-smoothed) and classify "cheap meds now". Print the predicted class and its normalized posterior.
Build a tiny naive-Bayes spam/ham classifier (Laplace-smoothed) and classify "cheap meds now". Print the predicted class and its normalized posterior.
Answer
train = [ ("buy cheap meds now", "spam"), ("cheap meds cheap deal", "spam"), ("limited offer buy now", "spam"), ("meeting at noon today", "ham"), ("lunch with the team now", "ham"), ("project notes for the meeting now", "ham"), ] classes = ["spam", "ham"] vocab = set(w for text, _ in train for w in text.split()) V = len(vocab) class_docs = {c: 0 for c in classes} word_counts = {c: {} for c in classes} total_words = {c: 0 for c in classes} for text, label in train: class_docs[label] += 1 for w in text.split(): word_counts[label][w] = word_counts[label].get(w, 0) + 1 total_words[label] += 1 N = len(train) def likelihood(word, c): # Laplace-smoothed P(word | class) return (word_counts[c].get(word, 0) + 1) / (total_words[c] + V) def classify(text): scores = {} for c in classes: p = class_docs[c] / N # prior P(class) for w in text.split(): p *= likelihood(w, c) # naive: product of likelihoods scores[c] = p z = sum(scores.values()) # normalize to a posterior posterior = {c: scores[c] / z for c in classes} best = max(classes, key=lambda c: posterior[c]) return best, posterior[best] msg = "cheap meds now" label, p = classify(msg) print(f"predict('{msg}') -> {label} (p={p:.2f})")