Show Sidebar Hide Sidebar

SGD Maximum Margin Separating Hyperplane in Scikit-learn

Plot the maximum margin separating hyperplane within a two-class separable dataset using a linear Support Vector Machines classifier trained using SGD.

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

This tutorial imports SGDClassifier and make_blobs.

In [2]:
import plotly.plotly as py
import plotly.graph_objs as go

import numpy as np
from sklearn.linear_model import SGDClassifier
from sklearn.datasets.samples_generator import make_blobs

Calculations

In [3]:
# we create 50 separable points
X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)

# fit the model
clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=200, fit_intercept=True)
clf.fit(X, Y)

# plot the line, the points, and the nearest vectors to the plane
xx = np.linspace(-1, 5, 10)
yy = np.linspace(-1, 5, 10)

X1, X2 = np.meshgrid(xx, yy)
Z = np.empty(X1.shape)
for (i, j), val in np.ndenumerate(X1):
    x1 = val
    x2 = X2[i, j]
    p = clf.decision_function([[x1, x2]])
    Z[i, j] = p[0]

Plot Results

In [4]:
levels = [-1.0, 0.0, 1.0]
linestyles = ['dashed', 'solid', 'dashed']
cmap = [[0, 'black'],[1, 'white']]

trace = go.Contour(x=xx, y=yy, z=Z, 
                   colorscale=cmap,
                   showscale=False,
                   ncontours=4,
                   contours=dict(coloring='lines',
                                 start=-1,
                                 size=1,
                                 end=2
                                ),
                  )

trace1 = go.Scatter(x=X[:, 0], y=X[:, 1],
                    mode='markers',
                    marker=dict(color=X[:, 0],
                                colorscale='Viridis',
                                showscale=False,
                                line=dict(color='black', width=1))
                   )
data = [trace, trace1]
layout = go.Layout(xaxis=dict(zeroline=False, showgrid=False),
                   yaxis=dict(zeroline=False, showgrid=False),
                   hovermode='closest')
fig = go.Figure(data=data, layout=layout)
In [5]:
py.iplot(fig)
Out[5]:
Still need help?
Contact Us

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