Path: blob/main/C2 - Advanced Learning Algorithms/week1/optional-labs/lab_neurons_utils.py
3584 views
import numpy as np1import matplotlib.pyplot as plt2plt.style.use('./deeplearning.mplstyle')3from matplotlib import cm4import matplotlib.colors as colors5from lab_utils_common import dlc67def plt_prob_1d(ax,fwb):8""" plots a decision boundary but include shading to indicate the probability """9#setup useful ranges and common linspaces10x_space = np.linspace(0, 5 , 50)11y_space = np.linspace(0, 1 , 50)1213# get probability for x range, extend to y14z = np.zeros((len(x_space),len(y_space)))15for i in range(len(x_space)):16x = np.array([[x_space[i]]])17z[:,i] = fwb(x)1819cmap = plt.get_cmap('Blues')20new_cmap = truncate_colormap(cmap, 0.0, 0.5)21pcm = ax.pcolormesh(x_space, y_space, z,22norm=cm.colors.Normalize(vmin=0, vmax=1),23cmap=new_cmap, shading='nearest', alpha = 0.9)24ax.figure.colorbar(pcm, ax=ax)2526def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):27""" truncates color map """28new_cmap = colors.LinearSegmentedColormap.from_list(29'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),30cmap(np.linspace(minval, maxval, n)))31return new_cmap323334def sigmoidnp(z):35"""36Compute the sigmoid of z3738Parameters39----------40z : array_like41A scalar or numpy array of any size.4243Returns44-------45g : array_like46sigmoid(z)47"""48z = np.clip( z, -500, 500 ) # protect against overflow49g = 1.0/(1.0+np.exp(-z))5051return g5253def plt_linear(X_train, Y_train, prediction_tf, prediction_np):54fig, ax = plt.subplots(1,2, figsize=(16,4))55ax[0].scatter(X_train, Y_train, marker='x', c='r', label="Data Points")56ax[0].plot(X_train, prediction_tf, c=dlc['dlblue'], label="model output")57ax[0].text(1.6,350,r"y=$200 x + 100$", fontsize='xx-large', color=dlc['dlmagenta'])58ax[0].legend(fontsize='xx-large')59ax[0].set_ylabel('Price (in 1000s of dollars)', fontsize='xx-large')60ax[0].set_xlabel('Size (1000 sqft)', fontsize='xx-large')61ax[0].set_title("Tensorflow prediction",fontsize='xx-large')6263ax[1].scatter(X_train, Y_train, marker='x', c='r', label="Data Points")64ax[1].plot(X_train, prediction_np, c=dlc['dlblue'], label="model output")65ax[1].text(1.6,350,r"y=$200 x + 100$", fontsize='xx-large', color=dlc['dlmagenta'])66ax[1].legend(fontsize='xx-large')67ax[1].set_ylabel('Price (in 1000s of dollars)', fontsize='xx-large')68ax[1].set_xlabel('Size (1000 sqft)', fontsize='xx-large')69ax[1].set_title("Numpy prediction",fontsize='xx-large')70plt.show()717273def plt_logistic(X_train, Y_train, model, set_w, set_b, pos, neg):74fig,ax = plt.subplots(1,2,figsize=(16,4))7576layerf= lambda x : model.predict(x)77plt_prob_1d(ax[0], layerf)7879ax[0].scatter(X_train[pos], Y_train[pos], marker='x', s=80, c = 'red', label="y=1")80ax[0].scatter(X_train[neg], Y_train[neg], marker='o', s=100, label="y=0", facecolors='none',81edgecolors=dlc["dlblue"],lw=3)8283ax[0].set_ylim(-0.08,1.1)84ax[0].set_xlim(-0.5,5.5)85ax[0].set_ylabel('y', fontsize=16)86ax[0].set_xlabel('x', fontsize=16)87ax[0].set_title('Tensorflow Model', fontsize=20)88ax[0].legend(fontsize=16)8990layerf= lambda x : sigmoidnp(np.dot(set_w,x.reshape(1,1)) + set_b)91plt_prob_1d(ax[1], layerf)9293ax[1].scatter(X_train[pos], Y_train[pos], marker='x', s=80, c = 'red', label="y=1")94ax[1].scatter(X_train[neg], Y_train[neg], marker='o', s=100, label="y=0", facecolors='none',95edgecolors=dlc["dlblue"],lw=3)9697ax[1].set_ylim(-0.08,1.1)98ax[1].set_xlim(-0.5,5.5)99ax[1].set_ylabel('y', fontsize=16)100ax[1].set_xlabel('x', fontsize=16)101ax[1].set_title('Numpy Model', fontsize=20)102ax[1].legend(fontsize=16)103plt.show()104105106