Skip to content

Instantly share code, notes, and snippets.

@matmoody
Created May 19, 2016 20:32
Show Gist options
  • Save matmoody/28b6830ff1a5ec09af0df7f408639b8a to your computer and use it in GitHub Desktop.
Save matmoody/28b6830ff1a5ec09af0df7f408639b8a to your computer and use it in GitHub Desktop.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import datasets
%matplotlib inline
iris = datasets.load_iris()
# Plot petal length & sepal width
plt.scatter(iris.data[:,1], iris.data[:, 2], c=iris.target)
plt.xlabel(iris.feature_names[1])
plt.ylabel(iris.feature_names[2])
# Simplify and only take two classes
plt.scatter(iris.data[0:100, 1], iris.data[0:100, 2], c=iris.target[0:100])
plt.xlabel(iris.feature_names[1])
plt.ylabel(iris.feature_names[2])
# Fit SVM
svc = svm.SVC(kernel='linear', C=1)
X = iris.data[:, 1:3]
y = iris.target[:]
svc.fit(X, y)
from matplotlib.colors import ListedColormap
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
# Plot the SVM
def plot_estimator(estimator, X, y):
estimator.fit(X, y)
x_min, x_max = X[:, 0].min() - .1, X[:, 0].max() + .1
y_min, y_max = X[:, 1].min() - .1, X[:, 1].max() + .1
xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
np.linspace(y_min, y_max, 100))
Z = estimator.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.axis('tight')
plt.axis('off')
plt.tight_layout()
plot_estimator(svc, X, y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment