Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 29

Training Gaussian Naive Bayes with scikit-learn

Recommended resources

Introduction

Hello! In our previous lesson, we established the theoretical foundation of the Naive Bayes classifier. We learned that its "naive" conditional independence assumption is a powerful simplification that makes an otherwise computationally impossible problem practical. We summarized the algorithm's logic as:

Today, we'll put this theory into practice. We will focus on a specific type of Naive Bayes classifier called Gaussian Naive Bayes, which is designed for continuous data. You will learn how to train this model from start to finish using scikit-learn on a real-world dataset, solidifying your understanding of how this elegant and efficient algorithm works in code.


From Counts to Curves: Gaussian Naive Bayes

In our last discussion, we used text classification as an example, where features are discrete (e.g., word counts). But what if our features are continuous, like temperature, age, or sensor readings? We can't simply count their occurrences.

This is where Gaussian Naive Bayes comes in. It handles continuous features by making an additional assumption:

For each class, the distribution of each continuous feature is assumed to be Gaussian (i.e., a normal distribution or "bell curve").

Under this assumption, "training" the model doesn't involve counting frequencies. Instead, the algorithm calculates the mean () and variance () of each feature for each class from the training data. When a new data point comes in, the model uses the Gaussian probability density function to calculate the likelihood for each feature.

The image below illustrates this perfectly. For the feature 'PSA level', the model learns two separate Gaussian distributions: one for the 'Healthy' class and one for the 'Cancer' class, each with its own mean and standard deviation.

Gaussian Naive Bayes with PSA Levels
This shows how Gaussian Naive Bayes models a continuous feature ('PSA' level) for two different classes ('Healthy' and 'Cancer'). It fits a separate normal distribution to the data for each class.

With this intuition in mind, let's see how to implement it.


Training a Classifier with Scikit-learn

We will now walk through the process of training a GaussianNB classifier on the classic Titanic dataset. The goal is to predict survival based on features like passenger class, sex, and age.

The following video provides a clear, practical demonstration of the entire workflow. Since you're already familiar with libraries like Pandas and Scikit-learn, focus on how the specific GaussianNB model is integrated into the familiar machine learning pipeline.

Step 1: Data Preparation

First, the data must be loaded and prepared for the model. This involves dropping irrelevant columns, converting categorical text data into numerical format (one-hot encoding), and handling any missing values.

Machine Learning Tutorial Python - 14: Naive Bayes Classifier Algorithm Part 1

This first segment from codebasics demonstrates the essential data preprocessing steps required before training the model.

Watch from 04:21 to 08:49. Pay attention to how pd.get_dummies is used to handle the 'sex' column and how missing 'age' values are filled with the mean.

Step 2: Model Training

Once the data is clean and numeric, the next steps are to split it into training and testing sets, import the GaussianNB model, and train it. The beauty of scikit-learn is how consistent this process is across different algorithms.

Machine Learning Tutorial Python - 14: Naive Bayes Classifier Algorithm Part 1

This segment covers the core of our learning outcome: splitting the data and training the Gaussian Naive Bayes model.

Watch from 08:49 to 11:17. The most important lines are where GaussianNB is imported, instantiated, and trained with the .fit() method. Notice how simple this is.

The key lines of code for training are remarkably concise:




# 1. Import the model
from sklearn.naive_bayes import GaussianNB




# 2. Instantiate the model
model = GaussianNB()




# 3. Train the model on the training data
model.fit(X_train, y_train)

All the underlying work of calculating the means and variances for each feature and class happens automatically within the .fit() method.

Step 3: Evaluation and Prediction

With a trained model, we can now evaluate its performance on the unseen test data and use it to make predictions.

Machine Learning Tutorial Python - 14: Naive Bayes Classifier Algorithm Part 1

Finally, let's see how to use the trained model to get an accuracy score and predict outcomes.

Watch from 11:12 to 13:20. Note the difference between .predict(), which gives the final class prediction (0 or 1), and .predict_proba(), which gives the underlying probabilities for each class.

Using .predict_proba() is a great way to see the model's "confidence" in its prediction, which ties directly back to the posterior probabilities we discussed in the previous lesson.


A Complete Example for Reference

To bring everything together, here is a complete, self-contained example of training a GaussianNB classifier on a synthetic dataset. You can use this as a quick reference for the entire process.

Naive Bayes Classifier Tutorial: with Python Scikit-learn

This tutorial from DataCamp provides a clean, end-to-end code example for training a Gaussian Naive Bayes classifier. It reinforces the steps you just saw in the video.

Read through the code in the section 'Naive Bayes Classifier with a synthetic dataset'. It covers data generation, train-test split, model building, and evaluation all in one place.

This example is a great template for applying GaussianNB to any classification problem with continuous features.


Conclusion

Congratulations! You have successfully bridged the gap from theory to practice. In this lesson, we focused on applying the Naive Bayes algorithm to a dataset with continuous features.

Key Takeaways:

  • Gaussian Naive Bayes is the version of the algorithm used for continuous features (e.g., age, measurements).
  • It operates by assuming that features for each class follow a Gaussian (normal) distribution.
  • "Training" involves calculating the mean and variance of each feature for each class.
  • Implementing Gaussian Naive Bayes in scikit-learn is a straightforward process: import GaussianNB, instantiate it, and use the .fit() and .predict() methods.

Preview of the Next Lesson

We've now explored our first probabilistic classifier. Next, we will pivot to an entirely different and highly intuitive family of models: tree-based methods. In the upcoming lesson, you will learn how a single Decision Tree makes predictions by learning a series of simple, hierarchical rules from the data.