Path: blob/main/C2 - Advanced Learning Algorithms/week1/optional-labs/lab_coffee_utils.py
3586 views
import numpy as np1import matplotlib.pyplot as plt2plt.style.use('./deeplearning.mplstyle')3import tensorflow as tf4from tensorflow.keras.activations import sigmoid5from matplotlib import cm6import matplotlib.colors as colors7from lab_utils_common import dlc89def load_coffee_data():10""" Creates a coffee roasting data set.11roasting duration: 12-15 minutes is best12temperature range: 175-260C is best13"""14rng = np.random.default_rng(2)15X = rng.random(400).reshape(-1,2)16X[:,1] = X[:,1] * 4 + 11.5 # 12-15 min is best17X[:,0] = X[:,0] * (285-150) + 150 # 350-500 F (175-260 C) is best18Y = np.zeros(len(X))1920i=021for t,d in X:22y = -3/(260-175)*t + 2123if (t > 175 and t < 260 and d > 12 and d < 15 and d<=y ):24Y[i] = 125else:26Y[i] = 027i += 12829return (X, Y.reshape(-1,1))3031def plt_roast(X,Y):32Y = Y.reshape(-1,)33colormap = np.array(['r', 'b'])34fig, ax = plt.subplots(1,1,)35ax.scatter(X[Y==1,0],X[Y==1,1], s=70, marker='x', c='red', label="Good Roast" )36ax.scatter(X[Y==0,0],X[Y==0,1], s=100, marker='o', facecolors='none',37edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")38tr = np.linspace(175,260,50)39ax.plot(tr, (-3/85) * tr + 21, color=dlc["dlpurple"],linewidth=1)40ax.axhline(y=12,color=dlc["dlpurple"],linewidth=1)41ax.axvline(x=175,color=dlc["dlpurple"],linewidth=1)42ax.set_title(f"Coffee Roasting", size=16)43ax.set_xlabel("Temperature \n(Celsius)",size=12)44ax.set_ylabel("Duration \n(minutes)",size=12)45ax.legend(loc='upper right')46plt.show()4748def plt_prob(ax,fwb):49""" plots a decision boundary but include shading to indicate the probability """50#setup useful ranges and common linspaces51x0_space = np.linspace(150, 285 , 40)52x1_space = np.linspace(11.5, 15.5 , 40)5354# get probability for x0,x1 ranges55tmp_x0,tmp_x1 = np.meshgrid(x0_space,x1_space)56z = np.zeros_like(tmp_x0)57for i in range(tmp_x0.shape[0]):58for j in range(tmp_x1.shape[1]):59x = np.array([[tmp_x0[i,j],tmp_x1[i,j]]])60z[i,j] = fwb(x)616263cmap = plt.get_cmap('Blues')64new_cmap = truncate_colormap(cmap, 0.0, 0.5)65pcm = ax.pcolormesh(tmp_x0, tmp_x1, z,66norm=cm.colors.Normalize(vmin=0, vmax=1),67cmap=new_cmap, shading='nearest', alpha = 0.9)68ax.figure.colorbar(pcm, ax=ax)6970def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):71""" truncates color map """72new_cmap = colors.LinearSegmentedColormap.from_list(73'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),74cmap(np.linspace(minval, maxval, n)))75return new_cmap7677def plt_layer(X,Y,W1,b1,norm_l):78Y = Y.reshape(-1,)79fig,ax = plt.subplots(1,W1.shape[1], figsize=(16,4))80for i in range(W1.shape[1]):81layerf= lambda x : sigmoid(np.dot(norm_l(x),W1[:,i]) + b1[i])82plt_prob(ax[i], layerf)83ax[i].scatter(X[Y==1,0],X[Y==1,1], s=70, marker='x', c='red', label="Good Roast" )84ax[i].scatter(X[Y==0,0],X[Y==0,1], s=100, marker='o', facecolors='none',85edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")86tr = np.linspace(175,260,50)87ax[i].plot(tr, (-3/85) * tr + 21, color=dlc["dlpurple"],linewidth=2)88ax[i].axhline(y= 12, color=dlc["dlpurple"], linewidth=2)89ax[i].axvline(x=175, color=dlc["dlpurple"], linewidth=2)90ax[i].set_title(f"Layer 1, unit {i}")91ax[i].set_xlabel("Temperature \n(Celsius)",size=12)92ax[0].set_ylabel("Duration \n(minutes)",size=12)93plt.show()9495def plt_network(X,Y,netf):96fig, ax = plt.subplots(1,2,figsize=(16,4))97Y = Y.reshape(-1,)98plt_prob(ax[0], netf)99ax[0].scatter(X[Y==1,0],X[Y==1,1], s=70, marker='x', c='red', label="Good Roast" )100ax[0].scatter(X[Y==0,0],X[Y==0,1], s=100, marker='o', facecolors='none',101edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")102ax[0].plot(X[:,0], (-3/85) * X[:,0] + 21, color=dlc["dlpurple"],linewidth=1)103ax[0].axhline(y= 12, color=dlc["dlpurple"], linewidth=1)104ax[0].axvline(x=175, color=dlc["dlpurple"], linewidth=1)105ax[0].set_xlabel("Temperature \n(Celsius)",size=12)106ax[0].set_ylabel("Duration \n(minutes)",size=12)107ax[0].legend(loc='upper right')108ax[0].set_title(f"network probability")109110ax[1].plot(X[:,0], (-3/85) * X[:,0] + 21, color=dlc["dlpurple"],linewidth=1)111ax[1].axhline(y= 12, color=dlc["dlpurple"], linewidth=1)112ax[1].axvline(x=175, color=dlc["dlpurple"], linewidth=1)113fwb = netf(X)114yhat = (fwb > 0.5).astype(int)115ax[1].scatter(X[yhat[:,0]==1,0],X[yhat[:,0]==1,1], s=70, marker='x', c='orange', label="Predicted Good Roast" )116ax[1].scatter(X[yhat[:,0]==0,0],X[yhat[:,0]==0,1], s=100, marker='o', facecolors='none',117edgecolors=dlc["dldarkblue"],linewidth=1, label="Bad Roast")118ax[1].set_title(f"network decision")119ax[1].set_xlabel("Temperature \n(Celsius)",size=12)120ax[1].set_ylabel("Duration \n(minutes)",size=12)121ax[1].legend(loc='upper right')122123124def plt_output_unit(W,b):125""" plots a single unit function with 3 inputs """126steps = 10127fig = plt.figure()128ax = fig.add_subplot(projection='3d')129x_ = np.linspace(0., 1., steps)130y_ = np.linspace(0., 1., steps)131z_ = np.linspace(0., 1., steps)132x, y, z = np.meshgrid(x_, y_, z_, indexing='ij')133d = np.zeros((steps,steps,steps))134cmap = plt.get_cmap('Blues')135for i in range(steps):136for j in range(steps):137for k in range(steps):138v = np.array([x[i,j,k],y[i,j,k],z[i,j,k]])139d[i,j,k] = tf.keras.activations.sigmoid(np.dot(v,W[:,0])+b).numpy()140pcm = ax.scatter(x, y, z, c=d, cmap=cmap, alpha = 1 )141ax.set_xlabel("unit 0");142ax.set_ylabel("unit 1");143ax.set_zlabel("unit 2");144ax.view_init(30, -120)145ax.figure.colorbar(pcm, ax=ax)146ax.set_title(f"Layer 2, output unit")147148plt.show()149150