Programming

Dummy Classifier Explained: A Visual Guide with Code Examples for Beginners

Setting the Bar in Machine Learning with Simple Baseline Models

Samy Baladram
August 14, 20247 min read

CLASSIFICATION ALGORITHM

Dummy Classifier, Explained: A Visual Guide with Code Examples for Beginners

Setting the bar in machine learning with simple baseline models

⛳️ More CLASSIFICATION ALGORITHM, explained: ▶ [Dummy Classifier](https://towardsdatascience.com/dummy-classifier-explained-a-visual-guide-with-code-examples-for-beginners-009ff95fc86e) · [K Nearest Neighbor Classifier](https://towardsdatascience.com/k-nearest-neighbor-classifier-explained-a-visual-guide-with-code-examples-for-beginners-a3d85cad00e1) · [Bernoulli Naive Bayes](https://towardsdatascience.com/bernoulli-naive-bayes-explained-a-visual-guide-with-code-examples-for-beginners-aec39771ddd6) · [Gaussian Naive Bayes](https://towardsdatascience.com/gaussian-naive-bayes-explained-a-visual-guide-with-code-examples-for-beginners-04949cef383c) · [Decision Tree Classifier](https://towardsdatascience.com/decision-tree-classifier-explained-a-visual-guide-with-code-examples-for-beginners-7c863f06a71e) · [Logistic Regression](https://towardsdatascience.com/logistic-regression-explained-a-visual-guide-with-code-examples-for-beginners-81baf5871505) · [Support Vector Classifier](https://towardsdatascience.com/support-vector-classifier-explained-a-visual-guide-with-mini-2d-dataset-62e831e7b9e9) · [Multilayer Perceptron](https://towardsdatascience.com/multilayer-perceptron-explained-a-visual-guide-with-mini-2d-dataset-0ae8100c5d1c)

Have you ever wondered how data scientists measure the performance of their machine learning models? Enter the dummy classifier - a simple yet powerful tool in the world of data science. Think of it as the baseline player in a game, setting the minimum standard that other, more sophisticated models need to beat.

All visuals: Author-created using Canva Pro. Optimized for mobile; may appear oversized on desktop.
All visuals: Author-created using Canva Pro. Optimized for mobile; may appear oversized on desktop.

Definition

A dummy classifier is a simple machine learning model that makes predictions using basic rules, without actually learning from the input data. It serves as a baseline for comparing the performance of more complex models. The dummy classifier helps us understand if our sophisticated models are actually learning useful patterns or just guessing.

Dummy Classifier is one of the basic key algorithms in machine learning.
Dummy Classifier is one of the basic key algorithms in machine learning.

📊 Dataset & Libraries

Throughout this article, we'll use this simple artificial golf dataset (inspired by [1]) as an example. This dataset predicts whether a person will play golf based on weather conditions. It includes features like outlook, temperature, humidity, and wind, with the target variable being whether to play golf or not.

Columns: 'Outlook', 'Temperature', 'Humidity', 'Wind' and 'Play' (target feature)
Columns: 'Outlook', 'Temperature', 'Humidity', 'Wind' and 'Play' (target feature)
python
# Import librariesfrom sklearn.model_selection import train_test_splitimport pandas as pd# Make a datasetdataset_dict = {    'Outlook': ['sunny', 'sunny', 'overcast', 'rain', 'rain', 'rain', 'overcast', 'sunny', 'sunny', 'rain', 'sunny', 'overcast', 'overcast', 'rain', 'sunny', 'overcast', 'rain', 'sunny', 'sunny', 'rain', 'overcast', 'rain', 'sunny', 'overcast', 'sunny', 'overcast', 'rain', 'overcast'],    'Temperature': [85.0, 80.0, 83.0, 70.0, 68.0, 65.0, 64.0, 72.0, 69.0, 75.0, 75.0, 72.0, 81.0, 71.0, 81.0, 74.0, 76.0, 78.0, 82.0, 67.0, 85.0, 73.0, 88.0, 77.0, 79.0, 80.0, 66.0, 84.0],    'Humidity': [85.0, 90.0, 78.0, 96.0, 80.0, 70.0, 65.0, 95.0, 70.0, 80.0, 70.0, 90.0, 75.0, 80.0, 88.0, 92.0, 85.0, 75.0, 92.0, 90.0, 85.0, 88.0, 65.0, 70.0, 60.0, 95.0, 70.0, 78.0],    'Wind': [False, True, False, False, False, True, True, False, False, False, True, True, False, True, True, False, False, True, False, True, True, False, True, False, False, True, False, False],    'Play': ['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'No', 'No', 'Yes', 'Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'No', 'Yes']}df = pd.DataFrame(dataset_dict)# One-hot Encode 'Outlook' Columndf = pd.get_dummies(df, columns=['Outlook'],  prefix='', prefix_sep='', dtype=int)# Convert 'Windy' (bool) and 'Play' (binary) Columns to 0 and 1df['Wind'] = df['Wind'].astype(int)df['Play'] = (df['Play'] == 'Yes').astype(int)# Set feature matrix X and target vector yX, y = df.drop(columns='Play'), df['Play']# Split the data into training and testing setsX_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.5, shuffle=False)

Main Mechanism

The dummy classifier operates on simple strategies to make predictions. These strategies don't involve any actual learning from the data. Instead, they use basic rules like:

  1. Always predicting the most frequent class

  2. Randomly predicting a class based on the training set's class distribution

  3. Always predicting a specific class

For our golf dataset, a dummy classifier might always predict "Yes" for playing golf if that's the most common outcome in the training data.
For our golf dataset, a dummy classifier might always predict "Yes" for playing golf if that's the most common outcome in the training data.

Training Steps

The "training" process for a dummy classifier is quite simple and doesn't involve the usual learning algorithms. Here's a general outline:

1. Select Strategy

Choose one of the following strategies:

  • Stratified: Makes random guesses based on the original class distribution.

  • Most Frequent: Always picks the most common class.

  • Uniform: Randomly picks any class.

Depends on the strategy, Dummy Classifier makes different prediction.
Depends on the strategy, Dummy Classifier makes different prediction.
python
from sklearn.dummy import DummyClassifier# Choose a strategy for your DummyClassifier (e.g., 'most_frequent', 'stratified', etc.)strategy = 'most_frequent'

2. Collect Training Labels

Collect the class labels from the training dataset to determine the strategy parameters.

The algorithm is simply getting information of the "Most Frequent" class in the training dataset - in this case "Yes".
The algorithm is simply getting information of the "Most Frequent" class in the training dataset - in this case "Yes".
python
# Initialize the DummyClassifierdummy_clf = DummyClassifier(strategy=strategy)# "Train" the DummyClassifier (although no real training happens)dummy_clf.fit(X_train, y_train)

3. Apply Strategy to Test Data

Use the chosen strategy to generate a list of predicted labels for your test data.

If we choose the "most frequent" strategy and find that "Yes" (play golf) appears more often in our training data, the dummy classifier will simply remember to always predict "Yes".
If we choose the "most frequent" strategy and find that "Yes" (play golf) appears more often in our training data, the dummy classifier will simply remember to always predict "Yes".
python
# Use the DummyClassifier to make predictionsy_pred = dummy_clf.predict(X_test)print("Label     :",list(y_test))print("Prediction:",list(y_pred))

Evaluate the Model

Dummy classifier gives 64% accuracy as the baseline for future models.
Dummy classifier gives 64% accuracy as the baseline for future models.
python
# Evaluate the DummyClassifier's accuracyfrom sklearn.metrics import accuracy_scoreaccuracy = accuracy_score(y_test, y_pred)print(f"Dummy Classifier Accuracy: {accuracy.round(4)*100}%")

Key Parameters

While dummy classifiers are simple, they do have a few important parameters:

  1. Strategy: This determines how the classifier makes predictions. Common options include:

  2. 'most_frequent': Always predicts the most common class in the training set. 'stratified': Generates predictions based on the training set's class distribution. 'uniform': Generates predictions uniformly at random. 'constant': Always predicts a specified class.

For our golf dataset, we might choose the 'most_frequent' strategy, which doesn't require additional parameters.
For our golf dataset, we might choose the 'most_frequent' strategy, which doesn't require additional parameters.

Pros and Cons

Like any tool in machine learning, dummy classifiers have their strengths and limitations.

Pros:

  1. Simplicity: Easy to understand and implement.

  2. Baseline Performance: Provides a minimum performance benchmark for other models.

  3. Overfitting Check: Helps identify when complex models are overfitting by comparing their performance to the dummy classifier.

  4. Quick to Train and Predict: Requires minimal computational resources.

Cons:

  1. Limited Predictive Power: By design, it doesn't learn from the data, so its predictions are often inaccurate.

  2. No Feature Importance: It doesn't provide insights into which features are most important for predictions.

  3. Not Suitable for Complex Problems: In real-world scenarios with intricate patterns, dummy classifiers are too simplistic to be useful on their own.

Final Remarks

Understanding dummy classifiers is crucial for any data scientist or machine learning enthusiast. They serve as a reality check, helping us ensure that our more complex models are actually learning useful patterns from the data. As you continue your journey in machine learning, always remember to compare your models against these simple baselines - you might be surprised by what you learn!

🌟 Dummy Classifier Code Summarized

python
# Import necessary librariesimport pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import accuracy_scorefrom sklearn.dummy import DummyClassifier# Make datasetdataset_dict = {    'Outlook': ['sunny', 'sunny', 'overcast', 'rain', 'rain', 'rain', 'overcast', 'sunny', 'sunny', 'rain', 'sunny', 'overcast', 'overcast', 'rain', 'sunny', 'overcast', 'rain', 'sunny', 'sunny', 'rain', 'overcast', 'rain', 'sunny', 'overcast', 'sunny', 'overcast', 'rain', 'overcast'],    'Temperature': [85.0, 80.0, 83.0, 70.0, 68.0, 65.0, 64.0, 72.0, 69.0, 75.0, 75.0, 72.0, 81.0, 71.0, 81.0, 74.0, 76.0, 78.0, 82.0, 67.0, 85.0, 73.0, 88.0, 77.0, 79.0, 80.0, 66.0, 84.0],    'Humidity': [85.0, 90.0, 78.0, 96.0, 80.0, 70.0, 65.0, 95.0, 70.0, 80.0, 70.0, 90.0, 75.0, 80.0, 88.0, 92.0, 85.0, 75.0, 92.0, 90.0, 85.0, 88.0, 65.0, 70.0, 60.0, 95.0, 70.0, 78.0],    'Wind': [False, True, False, False, False, True, True, False, False, False, True, True, False, True, True, False, False, True, False, True, True, False, True, False, False, True, False, False],    'Play': ['No', 'No', 'Yes', 'Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'No', 'No', 'Yes', 'Yes', 'No', 'No', 'No', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'Yes', 'No', 'Yes']}df = pd.DataFrame(dataset_dict)# Perform one-hot encoding on 'Outlook' columndf = pd.get_dummies(df, columns=['Outlook'], prefix='', prefix_sep='', dtype=int)# Convert 'Wind' and 'Play' columns to binary indicatorsdf['Wind'] = df['Wind'].astype(int)df['Play'] = (df['Play'] == 'Yes').astype(int)# Split data into features (X) and target (y), then into training and test setsX, y = df.drop(columns='Play'), df['Play']X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.5, shuffle=False)# Initialize and train the dummy classifier modeldummy_clf = DummyClassifier(strategy='most_frequent')dummy_clf.fit(X_train, y_train)# Make predictions on the test datay_pred = dummy_clf.predict(X_test)# Calculate and print the model's accuracy on the test dataprint(f"Accuracy: {accuracy_score(y_test, y_pred)*100:.4f}%")

Further Reading

For a detailed explanation of the DummyClassifier and its implementation in scikit-learn, readers can refer to the official documentation [2], which provides comprehensive information on its usage and parameters.

Technical Environment

This article uses Python 3.7 and scikit-learn 1.5. While the concepts discussed are generally applicable, specific code implementations may vary slightly with different versions.

About the Illustrations

Unless otherwise noted, all images are created by the author, incorporating licensed design elements from Canva Pro.

For a concise visual summary of Dummy Classifier, check out the companion Instagram post.
For a concise visual summary of Dummy Classifier, check out the companion Instagram post.

Reference

[1] T. M. Mitchell, Machine Learning (1997), McGraw-Hill Science/Engineering/Math, pp. 59

[2] F. Pedregosa et al., Scikit-learn: Machine Learning in Python, Journal of Machine Learning Research, vol. 12, pp. 2825–2830, 2011. [Online]. Available: https://scikit-learn.org/stable/modules/generated/sklearn.dummy.DummyClassifier.html

Classification Algorithms

Related Articles