Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
import numpy as np
2
import matplotlib.pyplot as plt
3
from sklearn.linear_model import SGDClassifier
4
from sklearn.datasets.samples_generator import make_blobs
5
6
def plot_sgd_separator():
7
# we create 50 separable points
8
X, Y = make_blobs(n_samples=50, centers=2,
9
random_state=0, cluster_std=0.60)
10
11
# fit the model
12
clf = SGDClassifier(loss="hinge", alpha=0.01,
13
n_iter=200, fit_intercept=True)
14
clf.fit(X, Y)
15
16
# plot the line, the points, and the nearest vectors to the plane
17
xx = np.linspace(-1, 5, 10)
18
yy = np.linspace(-1, 5, 10)
19
20
X1, X2 = np.meshgrid(xx, yy)
21
Z = np.empty(X1.shape)
22
for (i, j), val in np.ndenumerate(X1):
23
x1 = val
24
x2 = X2[i, j]
25
p = clf.decision_function([x1, x2])
26
Z[i, j] = p[0]
27
levels = [-1.0, 0.0, 1.0]
28
linestyles = ['dashed', 'solid', 'dashed']
29
colors = 'k'
30
31
ax = plt.axes()
32
ax.contour(X1, X2, Z, levels, colors=colors, linestyles=linestyles)
33
ax.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
34
35
ax.axis('tight')
36
37
38
if __name__ == '__main__':
39
plot_sgd_separator()
40
plt.show()
41
42