The Naive Bayes classifier — built from a CSV, explained one probability at a time. Pick the weather, watch Bayes' theorem decide whether to play tennis, then run it on a test set and read the accuracy.
The classic play_tennis.csv — 14 days of weather and whether a game was played. Teal = Yes, rose = No. This is what the classifier learns from.
| # | Outlook | Temperature | Humidity | Wind | Play? |
|---|
Pick the weather for tomorrow. The classifier shows its full working — the priors, each feature's likelihood for both classes, the multiplied scores, and the final normalized decision. Everything updates live.
The real task: run the trained classifier on a few test days whose true answers we already know, then count how many it got right. Press the button to classify them one by one.
| Outlook | Temp | Humidity | Wind | Actual | Predicted | ✓/✗ |
|---|
Two clear explainers from StatQuest with Josh Starmer. The first covers Naive Bayes for categorical data (like our weather CSV); the second handles continuous numbers.
Videos are embedded from YouTube and belong to their creators. If a frame is blank, your network may block YouTube — search the titles on youtube.com.
Two ways to implement it: the quick scikit-learn version, and a from-scratch version that mirrors the live demo above.
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import CategoricalNB
from sklearn.metrics import accuracy_score, confusion_matrix
df = pd.read_csv("play_tennis.csv")
# encode every text column to numbers
enc = {c: LabelEncoder() for c in df.columns}
for c in df.columns:
df[c] = enc[c].fit_transform(df[c])
X = df[["Outlook","Temp","Humidity","Wind"]]
y = df["Play"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=1)
model = CategoricalNB() # Naive Bayes for categorical data
model.fit(X_tr, y_tr)
pred = model.predict(X_te)
print("Accuracy:", accuracy_score(y_te, pred))
print("Confusion matrix:\n", confusion_matrix(y_te, pred))
import pandas as pd
df = pd.read_csv("play_tennis.csv")
target, n = "Play", len(df)
def predict(query):
best, best_p = None, -1
for c in df[target].unique():
sub = df[df[target] == c]
p = len(sub) / n # prior
for feat, val in query.items():
k = df[feat].nunique() # Laplace smoothing
p *= (len(sub[sub[feat]==val]) + 1) / (len(sub) + k)
if p > best_p: best, best_p = c, p
return best
q = {"Outlook":"Sunny","Temp":"Cool",
"Humidity":"High","Wind":"Strong"}
print("Prediction:", predict(q)) # -> No
The Naive Bayes classifier was implemented from a CSV file. Prior and conditional probabilities were estimated with Laplace smoothing, unseen samples were classified, and the accuracy was computed on a test set along with a confusion matrix, demonstrating CO3.