2010-10-27 16:46:18 +08:00
|
|
|
"""
|
2010-12-01 23:59:52 +08:00
|
|
|
=========================================
|
|
|
|
|
SGD: Maximum margin separating hyperplane
|
|
|
|
|
=========================================
|
2010-10-27 16:46:18 +08:00
|
|
|
|
|
|
|
|
Plot the maximum margin separating hyperplane within a two-class
|
|
|
|
|
separable dataset using a linear Support Vector Machines classifier
|
|
|
|
|
trained using SGD.
|
|
|
|
|
"""
|
2013-02-01 22:04:03 +08:00
|
|
|
print(__doc__)
|
2010-10-27 16:46:18 +08:00
|
|
|
|
|
|
|
|
import numpy as np
|
2014-05-15 04:31:03 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn.linear_model import SGDClassifier
|
2012-03-19 03:53:00 +08:00
|
|
|
from sklearn.datasets.samples_generator import make_blobs
|
2010-10-27 16:46:18 +08:00
|
|
|
|
2012-03-19 03:53:00 +08:00
|
|
|
# we create 50 separable points
|
|
|
|
|
X, Y = make_blobs(n_samples=50, centers=2, random_state=0, cluster_std=0.60)
|
2010-10-27 16:46:18 +08:00
|
|
|
|
|
|
|
|
# fit the model
|
2019-01-17 18:41:13 +08:00
|
|
|
clf = SGDClassifier(loss="hinge", alpha=0.01, max_iter=200,
|
|
|
|
|
fit_intercept=True, tol=1e-3)
|
2010-10-27 16:46:18 +08:00
|
|
|
clf.fit(X, Y)
|
|
|
|
|
|
|
|
|
|
# plot the line, the points, and the nearest vectors to the plane
|
2012-03-19 03:53:00 +08:00
|
|
|
xx = np.linspace(-1, 5, 10)
|
|
|
|
|
yy = np.linspace(-1, 5, 10)
|
|
|
|
|
|
2010-10-27 16:46:18 +08:00
|
|
|
X1, X2 = np.meshgrid(xx, yy)
|
|
|
|
|
Z = np.empty(X1.shape)
|
2011-12-24 02:12:26 +08:00
|
|
|
for (i, j), val in np.ndenumerate(X1):
|
2010-10-27 16:46:18 +08:00
|
|
|
x1 = val
|
2011-12-24 02:12:26 +08:00
|
|
|
x2 = X2[i, j]
|
2015-11-05 06:11:25 +08:00
|
|
|
p = clf.decision_function([[x1, x2]])
|
2011-12-24 02:12:26 +08:00
|
|
|
Z[i, j] = p[0]
|
2010-10-27 16:46:18 +08:00
|
|
|
levels = [-1.0, 0.0, 1.0]
|
2011-12-24 02:12:26 +08:00
|
|
|
linestyles = ['dashed', 'solid', 'dashed']
|
2010-10-27 16:46:18 +08:00
|
|
|
colors = 'k'
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)
|
2017-06-07 19:23:12 +08:00
|
|
|
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired,
|
|
|
|
|
edgecolor='black', s=20)
|
2010-10-27 16:46:18 +08:00
|
|
|
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.axis('tight')
|
|
|
|
|
plt.show()
|