🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Naive Bayes

Naive Bayes sorts rows by counting. It learns how often each value shows up in each group, then multiplies the chances.

Count the words

Nine of twenty spam messages hold the word free. Only one holds the word hello.

words = {'free': 9, 'win': 8, 'hello': 1, 'lunch': 1}
total_spam = 20
print(round(words['free'] / total_spam, 3))
print(round(words['hello'] / total_spam, 3))

Multiply the chances

Two word chances multiply to give the chance of both words together.

p_free = 0.45
p_win = 0.4
print(round(p_free * p_win, 4))

GaussianNB in three lines

GaussianNB fits the Breast Cancer data and scores 0.958 on the test set.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = GaussianNB()
model.fit(X_train, y_train)
print(round(model.score(X_test, y_test), 4))

Example

import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
model = GaussianNB()
model.fit(X_train, y_train)
print("Train accuracy:", round(model.score(X_train, y_train), 4))
print("Test accuracy:", round(model.score(X_test, y_test), 4))
print("First predictions:", model.predict(X_test[:5]))
print("First actual labels:", y_test[:5])
print("First probabilities:", np.round(model.predict_proba(X_test[:3]), 3))
words = {"free": 9, "win": 8, "hello": 1, "lunch": 1}
total_spam = 20
total_ham = 20
print("P(free | spam):", round(words["free"] / total_spam, 3))
print("P(hello | spam):", round(words["hello"] / total_spam, 3))

Key points

  • Naive Bayes: a model that sorts by multiplying the chances of each feature
  • GaussianNB: the sklearn version for numbers that form a bell shape
  • Use GaussianNB from sklearn.naive_bayes to build the model
  • Each group gets its own average and spread for every feature
  • A new row is scored against each group, and the best group wins
  • Naive: the model pretends the features do not affect each other
  • The counting idea also works on words, which a later section of the course uses for text

In this example, GaussianNB learns the average and spread of each measurement for the benign group and the malignant group. It scores 0.9366 on the training tumours and 0.958 on the test tumours. The first five test rows are all called correctly. The model gives the first test tumour a malignant chance of 1.0, so it is sure. The word counts show the same idea on text: a message with free and win looks like spam because those words are common in spam.

Note

The word counts in this lesson are a small hand example. The closing program runs GaussianNB on the Breast Cancer numbers.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

How does Naive Bayes decide the group of a new row?