The following code demonstrates how to visualize decision boundaries of a Perceptron classifier using a synthetic dataset. It trains a Perceptron classifier (a simple linear classifier) on a synthetic 2D dataset and plot the decision regions using a custom function.
#
# Helper Function to Plot Decision Regions
#
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap # for assigning custom colors
from sklearn.linear_model import Perceptron # classifier
from sklearn.datasets import make_classification # data generator
# This function visualizes decision boundaries and data points
def plot_decision_regions(X, y, classifier, resolution=0.02):
# set up marker types and colors to represent different classes
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
# define a color map with as many unique colors as there are classes in y
cmap = ListedColormap(colors[:len(np.unique(y))])
#
# plot the decision surface (background prediction)
#
# determine the bounds of the plot area with padding.
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
# create a grid of points spanning the plot area.
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
# predict the class for each point in the grid
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
# reshape predictions to match the shape of the meshgrid for plotting
Z = Z.reshape(xx1.shape)
# draw filled contours to represent decision regions
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
#
# plot the actual data points
#
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
alpha=0.8, c=[cmap(idx)],
marker=markers[idx], label=f"Class {cl}")
#
# Train a Perceptron on Synthetic Data
#
# create a binary classification dataset with:
# 30 samples, 2 features (for 2D plotting)
# 2 informative features, no redundant features
# balanced classes with ~30% weight each
# random_state=300 ensures reproducibility
X, y = make_classification(n_samples=30, n_features=2, n_informative=2, n_redundant=0,
n_clusters_per_class=1, weights=[0.5, 0.5], random_state=300)
# visualize the data points before training
plt.scatter(X[:, 0], X[:, 1], s=50)
plt.title('Raw Data')
plt.show()
# initialize the Perceptron classifier
pct = Perceptron(max_iter=100, eta0=0.002, fit_intercept=True, random_state=300)
# train it using .fit(X, y)
pct.fit(X, y)
#
# plot decision boundary
#
plot_decision_regions(X, y, classifier=pct)
plt.title('Perceptron Decision Regions')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.legend()
plt.show()