Show Sidebar Hide Sidebar

# Non-Linear SVM in Scikit-learn

Note: this page is part of the documentation for version 3 of Plotly.py, which is not the most recent version.
See our Version 4 Migration Guide for information about how to upgrade.

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 :
import sklearn
sklearn.__version__

Out:
'0.18.1'

### Imports¶

In :
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 :
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 :
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, C, C))])

return pl_colorscale

cmap = matplotlib_to_plotly(plt.cm.PuOr_r, 4)
cmap1 = matplotlib_to_plotly(plt.cm.Paired, 4)

In :
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: 