Skip to content

Instantly share code, notes, and snippets.

@rasbt
Created September 13, 2016 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rasbt/6fb65bba38b70e28e60a9842b988cc67 to your computer and use it in GitHub Desktop.
Save rasbt/6fb65bba38b70e28e60a9842b988cc67 to your computer and use it in GitHub Desktop.
plot_decision_region bug
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
def plot_decision_regions(X, y, classifier, resolution=0.1):
# setup marker generator and color map
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))+1])
# plot the decision surface
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
# plot class samples
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
alpha=0.8, c=colors[idx],
marker=markers[idx], label=cl)
# Loading some example data
iris = datasets.load_iris()
X = iris.data[:, [0,2]]
y = iris.target
y = np.concatenate((y, np.ones(50)+2))
y = y.astype(int)
X = np.concatenate((X, X[:50]*2))
lr = LogisticRegression(solver='newton-cg', multi_class='multinomial')
lr.fit(X, y)
plot_decision_regions(X, y, classifier=lr)
iris = datasets.load_iris()
X = iris.data[:, [0,2]]
y = iris.target
y = np.concatenate((y, np.ones(50)+2, np.ones(50)+3))
y = y.astype(int)
X = np.concatenate((X, X[:50]*2, X[:50]*3))
lr = LogisticRegression(solver='newton-cg', multi_class='multinomial')
lr.fit(X, y)
plot_decision_regions(X, y, classifier=lr)
@rasbt
Copy link
Author

rasbt commented Sep 13, 2016

This function works just fine with 2, 3, and 4 class labels (plot_decision_region_bug_1.py):
unknown

Somehow, I can't figure out why this function fails when 5 class labels are present as in plot_decision_region_bug_2.py:
unknown-1

Probably, I am overlooking something and would really, really appreciate any help or pointer!

@rasbt
Copy link
Author

rasbt commented Sep 13, 2016

As Jake Vanderplas suggested, a continuous colormap seems to do the job, i.e., replacing the custom cmap by 'viridis' in plt.contourf(xx1, xx2, Z, alpha=0.4, cmap='viridis') produces the following image:

unknown

This leaves the question whether this is a bug in matplotlib's ListedColormap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment