-
Notifications
You must be signed in to change notification settings - Fork 0
/
mlutils1.py
72 lines (66 loc) · 2.59 KB
/
mlutils1.py
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
import numpy as np
import matplotlib.pyplot as plt
def plot_2d_clf_problem(X, y, h=None):
'''
Plots a two-dimensional labeled dataset (X,y) and, if function h(x) is given,
the decision surfaces.
'''
assert X.shape[1] == 2, "Dataset is not two-dimensional"
if h!=None :
# Create a mesh to plot in
r = 0.02 # mesh resolution
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, r),
np.arange(y_min, y_max, r))
XX=np.c_[xx.ravel(), yy.ravel()]
try:
Z_test = h(XX)
if Z_test.shape == ():
# h returns a scalar when applied to a matrix; map explicitly
Z = np.array(map(h,XX))
else :
Z = Z_test
except ValueError:
# can't apply to a matrix; map explicitly
Z = np.array(map(h,XX))
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Pastel1)
# Plot the dataset
plt.scatter(X[:,0],X[:,1], c=y, cmap=plt.cm.Paired, marker='o', s=50)
#plt.show()
def plot_2d_svc_problem(X, y, svc=None):
'''
Plots a two-dimensional labeled dataset (X,y) and, if SVC object is given,
the decision surfaces (with margin as well).
'''
assert X.shape[1] == 2, "Dataset is not two-dimensional"
if svc!=None :
# Create a mesh to plot in
r = 0.03 # mesh resolution
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, r),
np.arange(y_min, y_max, r))
XX=np.c_[xx.ravel(), yy.ravel()]
Z = np.array([svc_predict(svc, x) for x in XX])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Pastel1)
# Plot the dataset
plt.scatter(X[:,0],X[:,1], c=y, cmap=plt.cm.Paired, marker='o', s=50)
#plt.show()
def svc_predict(svc, x) :
h = svc.decision_function([x])
if h >= -1 and h <= 1:
return 0.5
else:
return max(-1, min(1, h))
def plot_error_surface(err,(c1,c2),(g1,g2)) :
plt.xticks(range(0,g2-g1+1,5),range(g1,g2,5)); plt.xlabel("gamma")
plt.yticks(range(0,c2-c1+1,5),range(c1,c2,5)); plt.ylabel("C")
p = plt.contour(err);
plt.imshow(1-err, interpolation='bilinear', origin='lower',cmap=plt.cm.gray)
plt.clabel(p, inline=1, fontsize=10)
#plt.show()