Show Sidebar Hide Sidebar

Non-Linear SVM in Scikit-learn

Perform binary classification using non-linear SVC with RBF kernel. The target to predict is a XOR of the inputs.

The color map illustrates the decision function learned by the SVC.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version

In [1]:
import sklearn
sklearn.__version__
Out[1]:
'0.18.1'

Imports

In [2]:
print(__doc__)

import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np
from sklearn import svm
import matplotlib.pyplot as plt
Automatically created module for IPython interactive environment

Calculations

In [3]:
x_ = np.linspace(-3, 3, 500)
y_ = np.linspace(-3, 3, 500)
xx, yy = np.meshgrid(x_, y_)
np.random.seed(0)
X = np.random.randn(300, 2)
Y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)

# fit the model
clf = svm.NuSVC()
clf.fit(X, Y)

# plot the decision function for each datapoint on the grid
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

Plot Results

In [4]:
def matplotlib_to_plotly(cmap, pl_entries):
    h = 1.0/(pl_entries-1)
    pl_colorscale = []
    
    for k in range(pl_entries):
        C = map(np.uint8, np.array(cmap(k*h)[:3])*255)
        pl_colorscale.append([k*h, 'rgb'+str((C[0], C[1], C[2]))])
        
    return pl_colorscale

cmap = matplotlib_to_plotly(plt.cm.PuOr_r, 4)
cmap1 = matplotlib_to_plotly(plt.cm.Paired, 4)
In [5]:
p1 = go.Heatmap(x=x_, y=y_, z=Z, 
                colorscale=cmap,
                showscale=False)

p2 = go.Contour(x=x_, y=y_, z=Z, 
                contours=dict(coloring='lines',
                              start=-1,
                              end=1,
                              size=2),
                line=dict(width=2),
                colorscale=cmap, showscale=False
                )

p3 = go.Scatter(x=X[:, 0], y=X[:, 1], 
                mode='markers',
                marker=dict(color=X[:, 0],
                            colorscale=cmap1,
                            line=dict(color='black', width=1)))
layout = go.Layout(xaxis=dict(ticks='', showticklabels=False,
                              zeroline=False),
                   yaxis=dict(ticks='', showticklabels=False,
                              zeroline=False),
                   hovermode='closest')
fig = go.Figure(data = [p1, p2, p3], layout=layout)
py.iplot(fig)
Out[5]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.