Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
import matplotlib.pyplot as plt
2
from sklearn.svm import SVC
3
from .plot_2d_separator import plot_2d_separator
4
from .tools import make_handcrafted_dataset
5
from .plot_helpers import discrete_scatter
6
7
8
def plot_svm(log_C, log_gamma, ax=None):
9
X, y = make_handcrafted_dataset()
10
C = 10. ** log_C
11
gamma = 10. ** log_gamma
12
svm = SVC(kernel='rbf', C=C, gamma=gamma).fit(X, y)
13
if ax is None:
14
ax = plt.gca()
15
plot_2d_separator(svm, X, ax=ax, eps=.5)
16
# plot data
17
discrete_scatter(X[:, 0], X[:, 1], y, ax=ax)
18
# plot support vectors
19
sv = svm.support_vectors_
20
# class labels of support vectors are given by the sign of the dual coefficients
21
sv_labels = svm.dual_coef_.ravel() > 0
22
discrete_scatter(sv[:, 0], sv[:, 1], sv_labels, s=15, markeredgewidth=3, ax=ax)
23
ax.set_title("C = %.4f gamma = %.4f" % (C, gamma))
24
25
26
def plot_svm_interactive():
27
from IPython.html.widgets import interactive, FloatSlider
28
C_slider = FloatSlider(min=-3, max=3, step=.1, value=0, readout=False)
29
gamma_slider = FloatSlider(min=-2, max=2, step=.1, value=0, readout=False)
30
return interactive(plot_svm, log_C=C_slider, log_gamma=gamma_slider)
31
32