Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
greyhatguy007
GitHub Repository: greyhatguy007/Machine-Learning-Specialization-Coursera
Path: blob/main/C2 - Advanced Learning Algorithms/week1/optional-labs/lab_coffee_utils.py
3586 views
1
import numpy as np
2
import matplotlib.pyplot as plt
3
plt.style.use('./deeplearning.mplstyle')
4
import tensorflow as tf
5
from tensorflow.keras.activations import sigmoid
6
from matplotlib import cm
7
import matplotlib.colors as colors
8
from lab_utils_common import dlc
9
10
def load_coffee_data():
11
""" Creates a coffee roasting data set.
12
roasting duration: 12-15 minutes is best
13
temperature range: 175-260C is best
14
"""
15
rng = np.random.default_rng(2)
16
X = rng.random(400).reshape(-1,2)
17
X[:,1] = X[:,1] * 4 + 11.5 # 12-15 min is best
18
X[:,0] = X[:,0] * (285-150) + 150 # 350-500 F (175-260 C) is best
19
Y = np.zeros(len(X))
20
21
i=0
22
for t,d in X:
23
y = -3/(260-175)*t + 21
24
if (t > 175 and t < 260 and d > 12 and d < 15 and d<=y ):
25
Y[i] = 1
26
else:
27
Y[i] = 0
28
i += 1
29
30
return (X, Y.reshape(-1,1))
31
32
def plt_roast(X,Y):
33
Y = Y.reshape(-1,)
34
colormap = np.array(['r', 'b'])
35
fig, ax = plt.subplots(1,1,)
36
ax.scatter(X[Y==1,0],X[Y==1,1], s=70, marker='x', c='red', label="Good Roast" )
37
ax.scatter(X[Y==0,0],X[Y==0,1], s=100, marker='o', facecolors='none',
38
edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")
39
tr = np.linspace(175,260,50)
40
ax.plot(tr, (-3/85) * tr + 21, color=dlc["dlpurple"],linewidth=1)
41
ax.axhline(y=12,color=dlc["dlpurple"],linewidth=1)
42
ax.axvline(x=175,color=dlc["dlpurple"],linewidth=1)
43
ax.set_title(f"Coffee Roasting", size=16)
44
ax.set_xlabel("Temperature \n(Celsius)",size=12)
45
ax.set_ylabel("Duration \n(minutes)",size=12)
46
ax.legend(loc='upper right')
47
plt.show()
48
49
def plt_prob(ax,fwb):
50
""" plots a decision boundary but include shading to indicate the probability """
51
#setup useful ranges and common linspaces
52
x0_space = np.linspace(150, 285 , 40)
53
x1_space = np.linspace(11.5, 15.5 , 40)
54
55
# get probability for x0,x1 ranges
56
tmp_x0,tmp_x1 = np.meshgrid(x0_space,x1_space)
57
z = np.zeros_like(tmp_x0)
58
for i in range(tmp_x0.shape[0]):
59
for j in range(tmp_x1.shape[1]):
60
x = np.array([[tmp_x0[i,j],tmp_x1[i,j]]])
61
z[i,j] = fwb(x)
62
63
64
cmap = plt.get_cmap('Blues')
65
new_cmap = truncate_colormap(cmap, 0.0, 0.5)
66
pcm = ax.pcolormesh(tmp_x0, tmp_x1, z,
67
norm=cm.colors.Normalize(vmin=0, vmax=1),
68
cmap=new_cmap, shading='nearest', alpha = 0.9)
69
ax.figure.colorbar(pcm, ax=ax)
70
71
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
72
""" truncates color map """
73
new_cmap = colors.LinearSegmentedColormap.from_list(
74
'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
75
cmap(np.linspace(minval, maxval, n)))
76
return new_cmap
77
78
def plt_layer(X,Y,W1,b1,norm_l):
79
Y = Y.reshape(-1,)
80
fig,ax = plt.subplots(1,W1.shape[1], figsize=(16,4))
81
for i in range(W1.shape[1]):
82
layerf= lambda x : sigmoid(np.dot(norm_l(x),W1[:,i]) + b1[i])
83
plt_prob(ax[i], layerf)
84
ax[i].scatter(X[Y==1,0],X[Y==1,1], s=70, marker='x', c='red', label="Good Roast" )
85
ax[i].scatter(X[Y==0,0],X[Y==0,1], s=100, marker='o', facecolors='none',
86
edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")
87
tr = np.linspace(175,260,50)
88
ax[i].plot(tr, (-3/85) * tr + 21, color=dlc["dlpurple"],linewidth=2)
89
ax[i].axhline(y= 12, color=dlc["dlpurple"], linewidth=2)
90
ax[i].axvline(x=175, color=dlc["dlpurple"], linewidth=2)
91
ax[i].set_title(f"Layer 1, unit {i}")
92
ax[i].set_xlabel("Temperature \n(Celsius)",size=12)
93
ax[0].set_ylabel("Duration \n(minutes)",size=12)
94
plt.show()
95
96
def plt_network(X,Y,netf):
97
fig, ax = plt.subplots(1,2,figsize=(16,4))
98
Y = Y.reshape(-1,)
99
plt_prob(ax[0], netf)
100
ax[0].scatter(X[Y==1,0],X[Y==1,1], s=70, marker='x', c='red', label="Good Roast" )
101
ax[0].scatter(X[Y==0,0],X[Y==0,1], s=100, marker='o', facecolors='none',
102
edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")
103
ax[0].plot(X[:,0], (-3/85) * X[:,0] + 21, color=dlc["dlpurple"],linewidth=1)
104
ax[0].axhline(y= 12, color=dlc["dlpurple"], linewidth=1)
105
ax[0].axvline(x=175, color=dlc["dlpurple"], linewidth=1)
106
ax[0].set_xlabel("Temperature \n(Celsius)",size=12)
107
ax[0].set_ylabel("Duration \n(minutes)",size=12)
108
ax[0].legend(loc='upper right')
109
ax[0].set_title(f"network probability")
110
111
ax[1].plot(X[:,0], (-3/85) * X[:,0] + 21, color=dlc["dlpurple"],linewidth=1)
112
ax[1].axhline(y= 12, color=dlc["dlpurple"], linewidth=1)
113
ax[1].axvline(x=175, color=dlc["dlpurple"], linewidth=1)
114
fwb = netf(X)
115
yhat = (fwb > 0.5).astype(int)
116
ax[1].scatter(X[yhat[:,0]==1,0],X[yhat[:,0]==1,1], s=70, marker='x', c='orange', label="Predicted Good Roast" )
117
ax[1].scatter(X[yhat[:,0]==0,0],X[yhat[:,0]==0,1], s=100, marker='o', facecolors='none',
118
edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")
119
ax[1].set_title(f"network decision")
120
ax[1].set_xlabel("Temperature \n(Celsius)",size=12)
121
ax[1].set_ylabel("Duration \n(minutes)",size=12)
122
ax[1].legend(loc='upper right')
123
124
125
def plt_output_unit(W,b):
126
""" plots a single unit function with 3 inputs """
127
steps = 10
128
fig = plt.figure()
129
ax = fig.add_subplot(projection='3d')
130
x_ = np.linspace(0., 1., steps)
131
y_ = np.linspace(0., 1., steps)
132
z_ = np.linspace(0., 1., steps)
133
x, y, z = np.meshgrid(x_, y_, z_, indexing='ij')
134
d = np.zeros((steps,steps,steps))
135
cmap = plt.get_cmap('Blues')
136
for i in range(steps):
137
for j in range(steps):
138
for k in range(steps):
139
v = np.array([x[i,j,k],y[i,j,k],z[i,j,k]])
140
d[i,j,k] = tf.keras.activations.sigmoid(np.dot(v,W[:,0])+b).numpy()
141
pcm = ax.scatter(x, y, z, c=d, cmap=cmap, alpha = 1 )
142
ax.set_xlabel("unit 0");
143
ax.set_ylabel("unit 1");
144
ax.set_zlabel("unit 2");
145
ax.view_init(30, -120)
146
ax.figure.colorbar(pcm, ax=ax)
147
ax.set_title(f"Layer 2, output unit")
148
149
plt.show()
150