Path: blob/main/C2 - Advanced Learning Algorithms/week2/optional-labs/lab_utils_multiclass_TF.py
3586 views
import matplotlib.pyplot as plt1import numpy as np2import matplotlib as mpl3import warnings4from matplotlib import cm5from matplotlib.patches import FancyArrowPatch6from matplotlib.colors import ListedColormap, LinearSegmentedColormap7import matplotlib.colors as colors8from lab_utils_common import dlc9from matplotlib import cm10111213dlc = dict(dlblue = '#0096ff', dlorange = '#FF9300', dldarkred='#C00000', dlmagenta='#FF40FF', dlpurple='#7030A0', dldarkblue = '#0D5BDC')14dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0'; dldarkblue = '#0D5BDC'15dlcolors = [dlblue, dlorange, dldarkred, dlmagenta, dlpurple]16plt.style.use('./deeplearning.mplstyle')1718dkcolors = plt.cm.Paired((1,3,7,9,5,11))19ltcolors = plt.cm.Paired((0,2,6,8,4,10))20dkcolors_map = mpl.colors.ListedColormap(dkcolors)21ltcolors_map = mpl.colors.ListedColormap(ltcolors)2223#Plot a multi-class categorical decision boundary24# This version handles a non-vector prediction (adds a for-loop over points)25def plot_cat_decision_boundary_mc(ax, X, predict , class_labels=None, legend=False, vector=True):2627# create a mesh to points to plot28x_min, x_max = X[:, 0].min()- 0.5, X[:, 0].max()+0.529y_min, y_max = X[:, 1].min()- 0.5, X[:, 1].max()+0.530h = max(x_max-x_min, y_max-y_min)/10031xx, yy = np.meshgrid(np.arange(x_min, x_max, h),32np.arange(y_min, y_max, h))33points = np.c_[xx.ravel(), yy.ravel()]34#print("points", points.shape)35#print("xx.shape", xx.shape)3637#make predictions for each point in mesh38if vector:39Z = predict(points)40else:41Z = np.zeros((len(points),))42for i in range(len(points)):43Z[i] = predict(points[i].reshape(1,2))44Z = Z.reshape(xx.shape)4546#contour plot highlights boundaries between values - classes in this case47ax.contour(xx, yy, Z, linewidths=1)48#ax.axis('tight')495051def plt_mc_data(ax, X, y, classes, class_labels=None, map=plt.cm.Paired,52legend=False, size=50, m='o', equal_xy = False):53""" Plot multiclass data. Note, if equal_xy is True, setting ylim on the plot may not work """54for i in range(classes):55idx = np.where(y == i)56col = len(idx[0])*[i]57label = class_labels[i] if class_labels else "c{}".format(i)58# this didn't work on coursera but did in local version59#ax.scatter(X[idx, 0], X[idx, 1], marker=m,60# c=col, vmin=0, vmax=map.N, cmap=map,61# s=size, label=label)62ax.scatter(X[idx, 0], X[idx, 1], marker=m,63color=map(col), vmin=0, vmax=map.N,64s=size, label=label)65if legend: ax.legend()66if equal_xy: ax.axis("equal")6768def plt_mc(X_train,y_train,classes, centers, std):69css = np.unique(y_train)70fig,ax = plt.subplots(1,1,figsize=(3,3))71fig.canvas.toolbar_visible = False72fig.canvas.header_visible = False73fig.canvas.footer_visible = False74plt_mc_data(ax, X_train,y_train,classes, map=dkcolors_map, legend=True, size=50, equal_xy = False)75ax.set_title("Multiclass Data")76ax.set_xlabel("x0")77ax.set_ylabel("x1")78#for c in css:79# circ = plt.Circle(centers[c], 2*std, color=dkcolors_map(c), clip_on=False, fill=False, lw=0.5)80# ax.add_patch(circ)81plt.show()8283def plt_cat_mc(X_train, y_train, model, classes):84#make a model for plotting routines to call85model_predict = lambda Xl: np.argmax(model.predict(Xl),axis=1)8687fig,ax = plt.subplots(1,1, figsize=(3,3))88fig.canvas.toolbar_visible = False89fig.canvas.header_visible = False90fig.canvas.footer_visible = False9192#add the original data to the decison boundary93plt_mc_data(ax, X_train,y_train, classes, map=dkcolors_map, legend=True)94#plot the decison boundary.95plot_cat_decision_boundary_mc(ax, X_train, model_predict, vector=True)96ax.set_title("model decision boundary")9798plt.xlabel(r'$x_0$');99plt.ylabel(r"$x_1$");100plt.show()101102103def plt_prob_z(ax,fwb, x0_rng=(-8,8), x1_rng=(-5,4)):104""" plots a decision boundary but include shading to indicate the probability105and adds a conouter to show where z=0106"""107#setup useful ranges and common linspaces108x0_space = np.linspace(x0_rng[0], x0_rng[1], 40)109x1_space = np.linspace(x1_rng[0], x1_rng[1], 40)110111# get probability for x0,x1 ranges112tmp_x0,tmp_x1 = np.meshgrid(x0_space,x1_space)113z = np.zeros_like(tmp_x0)114c = np.zeros_like(tmp_x0)115for i in range(tmp_x0.shape[0]):116for j in range(tmp_x1.shape[1]):117x = np.array([[tmp_x0[i,j],tmp_x1[i,j]]])118z[i,j] = fwb(x)119c[i,j] = 0. if z[i,j] == 0 else 1.120with warnings.catch_warnings(): # suppress no contour warning121warnings.simplefilter("ignore")122#ax.contour(tmp_x0, tmp_x1, c, colors='b', linewidths=1)123ax.contour(tmp_x0, tmp_x1, c, linewidths=1)124125cmap = plt.get_cmap('Blues')126new_cmap = truncate_colormap(cmap, 0.0, 0.7)127128pcm = ax.pcolormesh(tmp_x0, tmp_x1, z,129norm=cm.colors.Normalize(vmin=np.amin(z), vmax=np.amax(z)),130cmap=new_cmap, shading='nearest', alpha = 0.9)131ax.figure.colorbar(pcm, ax=ax)132133def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):134""" truncates color map """135new_cmap = colors.LinearSegmentedColormap.from_list(136'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),137cmap(np.linspace(minval, maxval, n)))138return new_cmap139140141def plt_layer_relu(X, Y, W1, b1, classes):142nunits = (W1.shape[1])143Y = Y.reshape(-1,)144fig,ax = plt.subplots(1,W1.shape[1], figsize=(7,2.5))145fig.canvas.toolbar_visible = False146fig.canvas.header_visible = False147fig.canvas.footer_visible = False148149for i in range(nunits):150layerf= lambda x : np.maximum(0,(np.dot(x,W1[:,i]) + b1[i]))151plt_prob_z(ax[i], layerf)152plt_mc_data(ax[i], X, Y, classes, map=dkcolors_map,legend=True, size=50, m='o')153ax[i].set_title(f"Layer 1 Unit {i}")154ax[i].set_ylabel(r"$x_1$",size=10)155ax[i].set_xlabel(r"$x_0$",size=10)156fig.tight_layout()157plt.show()158159160def plt_output_layer_linear(X, Y, W, b, classes, x0_rng=None, x1_rng=None):161nunits = (W.shape[1])162Y = Y.reshape(-1,)163fig,ax = plt.subplots(2,int(nunits/2), figsize=(7,5))164fig.canvas.toolbar_visible = False165fig.canvas.header_visible = False166fig.canvas.footer_visible = False167for i,axi in enumerate(ax.flat):168layerf = lambda x : np.dot(x,W[:,i]) + b[i]169plt_prob_z(axi, layerf, x0_rng=x0_rng, x1_rng=x1_rng)170plt_mc_data(axi, X, Y, classes, map=dkcolors_map,legend=True, size=50, m='o')171axi.set_ylabel(r"$a^{[1]}_1$",size=9)172axi.set_xlabel(r"$a^{[1]}_0$",size=9)173axi.set_xlim(x0_rng)174axi.set_ylim(x1_rng)175axi.set_title(f"Linear Output Unit {i}")176fig.tight_layout()177plt.show()178179