Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
greyhatguy007
GitHub Repository: greyhatguy007/Machine-Learning-Specialization-Coursera
Path: blob/main/C2 - Advanced Learning Algorithms/week2/optional-labs/lab_utils_multiclass_TF.py
3586 views
1
import matplotlib.pyplot as plt
2
import numpy as np
3
import matplotlib as mpl
4
import warnings
5
from matplotlib import cm
6
from matplotlib.patches import FancyArrowPatch
7
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
8
import matplotlib.colors as colors
9
from lab_utils_common import dlc
10
from matplotlib import cm
11
12
13
14
dlc = dict(dlblue = '#0096ff', dlorange = '#FF9300', dldarkred='#C00000', dlmagenta='#FF40FF', dlpurple='#7030A0', dldarkblue = '#0D5BDC')
15
dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0'; dldarkblue = '#0D5BDC'
16
dlcolors = [dlblue, dlorange, dldarkred, dlmagenta, dlpurple]
17
plt.style.use('./deeplearning.mplstyle')
18
19
dkcolors = plt.cm.Paired((1,3,7,9,5,11))
20
ltcolors = plt.cm.Paired((0,2,6,8,4,10))
21
dkcolors_map = mpl.colors.ListedColormap(dkcolors)
22
ltcolors_map = mpl.colors.ListedColormap(ltcolors)
23
24
#Plot a multi-class categorical decision boundary
25
# This version handles a non-vector prediction (adds a for-loop over points)
26
def plot_cat_decision_boundary_mc(ax, X, predict , class_labels=None, legend=False, vector=True):
27
28
# create a mesh to points to plot
29
x_min, x_max = X[:, 0].min()- 0.5, X[:, 0].max()+0.5
30
y_min, y_max = X[:, 1].min()- 0.5, X[:, 1].max()+0.5
31
h = max(x_max-x_min, y_max-y_min)/100
32
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
33
np.arange(y_min, y_max, h))
34
points = np.c_[xx.ravel(), yy.ravel()]
35
#print("points", points.shape)
36
#print("xx.shape", xx.shape)
37
38
#make predictions for each point in mesh
39
if vector:
40
Z = predict(points)
41
else:
42
Z = np.zeros((len(points),))
43
for i in range(len(points)):
44
Z[i] = predict(points[i].reshape(1,2))
45
Z = Z.reshape(xx.shape)
46
47
#contour plot highlights boundaries between values - classes in this case
48
ax.contour(xx, yy, Z, linewidths=1)
49
#ax.axis('tight')
50
51
52
def plt_mc_data(ax, X, y, classes, class_labels=None, map=plt.cm.Paired,
53
legend=False, size=50, m='o', equal_xy = False):
54
""" Plot multiclass data. Note, if equal_xy is True, setting ylim on the plot may not work """
55
for i in range(classes):
56
idx = np.where(y == i)
57
col = len(idx[0])*[i]
58
label = class_labels[i] if class_labels else "c{}".format(i)
59
# this didn't work on coursera but did in local version
60
#ax.scatter(X[idx, 0], X[idx, 1], marker=m,
61
# c=col, vmin=0, vmax=map.N, cmap=map,
62
# s=size, label=label)
63
ax.scatter(X[idx, 0], X[idx, 1], marker=m,
64
color=map(col), vmin=0, vmax=map.N,
65
s=size, label=label)
66
if legend: ax.legend()
67
if equal_xy: ax.axis("equal")
68
69
def plt_mc(X_train,y_train,classes, centers, std):
70
css = np.unique(y_train)
71
fig,ax = plt.subplots(1,1,figsize=(3,3))
72
fig.canvas.toolbar_visible = False
73
fig.canvas.header_visible = False
74
fig.canvas.footer_visible = False
75
plt_mc_data(ax, X_train,y_train,classes, map=dkcolors_map, legend=True, size=50, equal_xy = False)
76
ax.set_title("Multiclass Data")
77
ax.set_xlabel("x0")
78
ax.set_ylabel("x1")
79
#for c in css:
80
# circ = plt.Circle(centers[c], 2*std, color=dkcolors_map(c), clip_on=False, fill=False, lw=0.5)
81
# ax.add_patch(circ)
82
plt.show()
83
84
def plt_cat_mc(X_train, y_train, model, classes):
85
#make a model for plotting routines to call
86
model_predict = lambda Xl: np.argmax(model.predict(Xl),axis=1)
87
88
fig,ax = plt.subplots(1,1, figsize=(3,3))
89
fig.canvas.toolbar_visible = False
90
fig.canvas.header_visible = False
91
fig.canvas.footer_visible = False
92
93
#add the original data to the decison boundary
94
plt_mc_data(ax, X_train,y_train, classes, map=dkcolors_map, legend=True)
95
#plot the decison boundary.
96
plot_cat_decision_boundary_mc(ax, X_train, model_predict, vector=True)
97
ax.set_title("model decision boundary")
98
99
plt.xlabel(r'$x_0$');
100
plt.ylabel(r"$x_1$");
101
plt.show()
102
103
104
def plt_prob_z(ax,fwb, x0_rng=(-8,8), x1_rng=(-5,4)):
105
""" plots a decision boundary but include shading to indicate the probability
106
and adds a conouter to show where z=0
107
"""
108
#setup useful ranges and common linspaces
109
x0_space = np.linspace(x0_rng[0], x0_rng[1], 40)
110
x1_space = np.linspace(x1_rng[0], x1_rng[1], 40)
111
112
# get probability for x0,x1 ranges
113
tmp_x0,tmp_x1 = np.meshgrid(x0_space,x1_space)
114
z = np.zeros_like(tmp_x0)
115
c = np.zeros_like(tmp_x0)
116
for i in range(tmp_x0.shape[0]):
117
for j in range(tmp_x1.shape[1]):
118
x = np.array([[tmp_x0[i,j],tmp_x1[i,j]]])
119
z[i,j] = fwb(x)
120
c[i,j] = 0. if z[i,j] == 0 else 1.
121
with warnings.catch_warnings(): # suppress no contour warning
122
warnings.simplefilter("ignore")
123
#ax.contour(tmp_x0, tmp_x1, c, colors='b', linewidths=1)
124
ax.contour(tmp_x0, tmp_x1, c, linewidths=1)
125
126
cmap = plt.get_cmap('Blues')
127
new_cmap = truncate_colormap(cmap, 0.0, 0.7)
128
129
pcm = ax.pcolormesh(tmp_x0, tmp_x1, z,
130
norm=cm.colors.Normalize(vmin=np.amin(z), vmax=np.amax(z)),
131
cmap=new_cmap, shading='nearest', alpha = 0.9)
132
ax.figure.colorbar(pcm, ax=ax)
133
134
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
135
""" truncates color map """
136
new_cmap = colors.LinearSegmentedColormap.from_list(
137
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
138
cmap(np.linspace(minval, maxval, n)))
139
return new_cmap
140
141
142
def plt_layer_relu(X, Y, W1, b1, classes):
143
nunits = (W1.shape[1])
144
Y = Y.reshape(-1,)
145
fig,ax = plt.subplots(1,W1.shape[1], figsize=(7,2.5))
146
fig.canvas.toolbar_visible = False
147
fig.canvas.header_visible = False
148
fig.canvas.footer_visible = False
149
150
for i in range(nunits):
151
layerf= lambda x : np.maximum(0,(np.dot(x,W1[:,i]) + b1[i]))
152
plt_prob_z(ax[i], layerf)
153
plt_mc_data(ax[i], X, Y, classes, map=dkcolors_map,legend=True, size=50, m='o')
154
ax[i].set_title(f"Layer 1 Unit {i}")
155
ax[i].set_ylabel(r"$x_1$",size=10)
156
ax[i].set_xlabel(r"$x_0$",size=10)
157
fig.tight_layout()
158
plt.show()
159
160
161
def plt_output_layer_linear(X, Y, W, b, classes, x0_rng=None, x1_rng=None):
162
nunits = (W.shape[1])
163
Y = Y.reshape(-1,)
164
fig,ax = plt.subplots(2,int(nunits/2), figsize=(7,5))
165
fig.canvas.toolbar_visible = False
166
fig.canvas.header_visible = False
167
fig.canvas.footer_visible = False
168
for i,axi in enumerate(ax.flat):
169
layerf = lambda x : np.dot(x,W[:,i]) + b[i]
170
plt_prob_z(axi, layerf, x0_rng=x0_rng, x1_rng=x1_rng)
171
plt_mc_data(axi, X, Y, classes, map=dkcolors_map,legend=True, size=50, m='o')
172
axi.set_ylabel(r"$a^{[1]}_1$",size=9)
173
axi.set_xlabel(r"$a^{[1]}_0$",size=9)
174
axi.set_xlim(x0_rng)
175
axi.set_ylim(x1_rng)
176
axi.set_title(f"Linear Output Unit {i}")
177
fig.tight_layout()
178
plt.show()
179