Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week5/Initialization/init_utils.py
Views: 13376
import numpy as np1import matplotlib.pyplot as plt2import h5py3import sklearn4import sklearn.datasets56def sigmoid(x):7"""8Compute the sigmoid of x910Arguments:11x -- A scalar or numpy array of any size.1213Return:14s -- sigmoid(x)15"""16s = 1/(1+np.exp(-x))17return s1819def relu(x):20"""21Compute the relu of x2223Arguments:24x -- A scalar or numpy array of any size.2526Return:27s -- relu(x)28"""29s = np.maximum(0,x)3031return s3233def forward_propagation(X, parameters):34"""35Implements the forward propagation (and computes the loss) presented in Figure 2.3637Arguments:38X -- input dataset, of shape (input size, number of examples)39Y -- true "label" vector (containing 0 if cat, 1 if non-cat)40parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":41W1 -- weight matrix of shape ()42b1 -- bias vector of shape ()43W2 -- weight matrix of shape ()44b2 -- bias vector of shape ()45W3 -- weight matrix of shape ()46b3 -- bias vector of shape ()4748Returns:49loss -- the loss function (vanilla logistic loss)50"""5152# retrieve parameters53W1 = parameters["W1"]54b1 = parameters["b1"]55W2 = parameters["W2"]56b2 = parameters["b2"]57W3 = parameters["W3"]58b3 = parameters["b3"]5960# LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID61z1 = np.dot(W1, X) + b162a1 = relu(z1)63z2 = np.dot(W2, a1) + b264a2 = relu(z2)65z3 = np.dot(W3, a2) + b366a3 = sigmoid(z3)6768cache = (z1, a1, W1, b1, z2, a2, W2, b2, z3, a3, W3, b3)6970return a3, cache7172def backward_propagation(X, Y, cache):73"""74Implement the backward propagation presented in figure 2.7576Arguments:77X -- input dataset, of shape (input size, number of examples)78Y -- true "label" vector (containing 0 if cat, 1 if non-cat)79cache -- cache output from forward_propagation()8081Returns:82gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables83"""84m = X.shape[1]85(z1, a1, W1, b1, z2, a2, W2, b2, z3, a3, W3, b3) = cache8687dz3 = 1./m * (a3 - Y)88dW3 = np.dot(dz3, a2.T)89db3 = np.sum(dz3, axis=1, keepdims = True)9091da2 = np.dot(W3.T, dz3)92dz2 = np.multiply(da2, np.int64(a2 > 0))93dW2 = np.dot(dz2, a1.T)94db2 = np.sum(dz2, axis=1, keepdims = True)9596da1 = np.dot(W2.T, dz2)97dz1 = np.multiply(da1, np.int64(a1 > 0))98dW1 = np.dot(dz1, X.T)99db1 = np.sum(dz1, axis=1, keepdims = True)100101gradients = {"dz3": dz3, "dW3": dW3, "db3": db3,102"da2": da2, "dz2": dz2, "dW2": dW2, "db2": db2,103"da1": da1, "dz1": dz1, "dW1": dW1, "db1": db1}104105return gradients106107def update_parameters(parameters, grads, learning_rate):108"""109Update parameters using gradient descent110111Arguments:112parameters -- python dictionary containing your parameters113grads -- python dictionary containing your gradients, output of n_model_backward114115Returns:116parameters -- python dictionary containing your updated parameters117parameters['W' + str(i)] = ...118parameters['b' + str(i)] = ...119"""120121L = len(parameters) // 2 # number of layers in the neural networks122123# Update rule for each parameter124for k in range(L):125parameters["W" + str(k+1)] = parameters["W" + str(k+1)] - learning_rate * grads["dW" + str(k+1)]126parameters["b" + str(k+1)] = parameters["b" + str(k+1)] - learning_rate * grads["db" + str(k+1)]127128return parameters129130def compute_loss(a3, Y):131132"""133Implement the loss function134135Arguments:136a3 -- post-activation, output of forward propagation137Y -- "true" labels vector, same shape as a3138139Returns:140loss - value of the loss function141"""142143m = Y.shape[1]144logprobs = np.multiply(-np.log(a3),Y) + np.multiply(-np.log(1 - a3), 1 - Y)145loss = 1./m * np.nansum(logprobs)146147return loss148149def load_cat_dataset():150train_dataset = h5py.File('datasets/train_catvnoncat.h5', "r")151train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features152train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels153154test_dataset = h5py.File('datasets/test_catvnoncat.h5', "r")155test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features156test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels157158classes = np.array(test_dataset["list_classes"][:]) # the list of classes159160train_set_y = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))161test_set_y = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))162163train_set_x_orig = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T164test_set_x_orig = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T165166train_set_x = train_set_x_orig/255167test_set_x = test_set_x_orig/255168169return train_set_x, train_set_y, test_set_x, test_set_y, classes170171172def predict(X, y, parameters):173"""174This function is used to predict the results of a n-layer neural network.175176Arguments:177X -- data set of examples you would like to label178parameters -- parameters of the trained model179180Returns:181p -- predictions for the given dataset X182"""183184m = X.shape[1]185p = np.zeros((1,m), dtype = np.int)186187# Forward propagation188a3, caches = forward_propagation(X, parameters)189190# convert probas to 0/1 predictions191for i in range(0, a3.shape[1]):192if a3[0,i] > 0.5:193p[0,i] = 1194else:195p[0,i] = 0196197# print results198print("Accuracy: " + str(np.mean((p[0,:] == y[0,:]))))199200return p201202def plot_decision_boundary(model, X, y):203# Set min and max values and give it some padding204x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1205y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1206h = 0.01207# Generate a grid of points with distance h between them208xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))209# Predict the function value for the whole grid210Z = model(np.c_[xx.ravel(), yy.ravel()])211Z = Z.reshape(xx.shape)212# Plot the contour and training examples213plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)214plt.ylabel('x2')215plt.xlabel('x1')216plt.scatter(X[0, :], X[1, :], c=y, cmap=plt.cm.Spectral)217plt.show()218219def predict_dec(parameters, X):220"""221Used for plotting decision boundary.222223Arguments:224parameters -- python dictionary containing your parameters225X -- input data of size (m, K)226227Returns228predictions -- vector of predictions of our model (red: 0 / blue: 1)229"""230231# Predict using forward propagation and a classification threshold of 0.5232a3, cache = forward_propagation(X, parameters)233predictions = (a3>0.5)234return predictions235236def load_dataset():237np.random.seed(1)238train_X, train_Y = sklearn.datasets.make_circles(n_samples=300, noise=.05)239np.random.seed(2)240test_X, test_Y = sklearn.datasets.make_circles(n_samples=100, noise=.05)241# Visualize the data242plt.scatter(train_X[:, 0], train_X[:, 1], c=train_Y, s=40, cmap=plt.cm.Spectral);243train_X = train_X.T244train_Y = train_Y.reshape((1, train_Y.shape[0]))245test_X = test_X.T246test_Y = test_Y.reshape((1, test_Y.shape[0]))247return train_X, train_Y, test_X, test_Y248249