-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbai21_Kernel_SVM_NearlyLinearSeparate.py
More file actions
80 lines (68 loc) · 2.09 KB
/
bai21_Kernel_SVM_NearlyLinearSeparate.py
File metadata and controls
80 lines (68 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding: utf-8 -*-
"""
Created on Fri May 1 17:16:37 2020
@author: phamk
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
from matplotlib.backends.backend_pdf import PdfPages
# XOR dataset and targets
X = np.c_[(-1, -3),
(0, -2),
(1, -2),
(2, 1),
(3, 0),
(1.5, 1.4),
#---
(1, 3),
(0.5, -1),
(-1, 2),
(-2, -1.5),
(-2, 0),
(-1.5, -1.2)].T
N = 6
Y = [0] * N + [1] * N
# figure number
# means = [[2, 2], [4, 2]]
# cov = [[.7, 0], [0, .7]]
# N = 20
# X0 = np.random.multivariate_normal(means[0], cov, N) # each row is a data point
# X1 = np.random.multivariate_normal(means[1], cov, N)
# X = np.vstack((X0, X1))
# Y = [0]*N + [1]*N
fignum = 1
# fit the model
for kernel in ('sigmoid', 'poly', 'rbf'):
clf = svm.SVC(kernel=kernel, gamma=1, coef0 = 1)
clf.fit(X, Y)
with PdfPages(kernel + '3.pdf') as pdf:
# plot the line, the points, and the nearest vectors to the plane
fig, ax = plt.subplots()
plt.figure(fignum, figsize=(4, 3))
plt.clf()
plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
facecolors='None')
plt.plot(X[:N, 0], X[:N, 1], 'bs', markersize = 8)
plt.plot(X[N:, 0], X[N:, 1], 'ro', markersize = 8)
plt.axis('tight')
x_min = -5
x_max = 5
y_min = -5
y_max = 5
XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.decision_function(np.c_[XX.ravel(), YY.ravel()])
# Put the result into a color plot
Z = Z.reshape(XX.shape)
plt.figure(fignum, figsize=(4, 3))
CS = plt.contourf(XX, YY, np.sign(Z), 200, cmap='jet', alpha = .2)
plt.contour(XX, YY, Z, colors=['k', 'k', 'k'], linestyles=['--', '-', '--'],
levels=[-.5, 0, .5])
plt.title(kernel, fontsize = 15)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
fignum = fignum + 1
pdf.savefig()
plt.show()