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/C2 - Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/Week 3/tf_utils.py
Views: 4804
import h5py1import numpy as np2import tensorflow as tf3import math45def load_dataset():6train_dataset = h5py.File('datasets/train_signs.h5', "r")7train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features8train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels910test_dataset = h5py.File('datasets/test_signs.h5', "r")11test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features12test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels1314classes = np.array(test_dataset["list_classes"][:]) # the list of classes1516train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))17test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))1819return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes202122def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):23"""24Creates a list of random minibatches from (X, Y)2526Arguments:27X -- input data, of shape (input size, number of examples)28Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)29mini_batch_size - size of the mini-batches, integer30seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.3132Returns:33mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)34"""3536m = X.shape[1] # number of training examples37mini_batches = []38np.random.seed(seed)3940# Step 1: Shuffle (X, Y)41permutation = list(np.random.permutation(m))42shuffled_X = X[:, permutation]43shuffled_Y = Y[:, permutation].reshape((Y.shape[0],m))4445# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.46num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning47for k in range(0, num_complete_minibatches):48mini_batch_X = shuffled_X[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size]49mini_batch_Y = shuffled_Y[:, k * mini_batch_size : k * mini_batch_size + mini_batch_size]50mini_batch = (mini_batch_X, mini_batch_Y)51mini_batches.append(mini_batch)5253# Handling the end case (last mini-batch < mini_batch_size)54if m % mini_batch_size != 0:55mini_batch_X = shuffled_X[:, num_complete_minibatches * mini_batch_size : m]56mini_batch_Y = shuffled_Y[:, num_complete_minibatches * mini_batch_size : m]57mini_batch = (mini_batch_X, mini_batch_Y)58mini_batches.append(mini_batch)5960return mini_batches6162def convert_to_one_hot(Y, C):63Y = np.eye(C)[Y.reshape(-1)].T64return Y656667def predict(X, parameters):6869W1 = tf.convert_to_tensor(parameters["W1"])70b1 = tf.convert_to_tensor(parameters["b1"])71W2 = tf.convert_to_tensor(parameters["W2"])72b2 = tf.convert_to_tensor(parameters["b2"])73W3 = tf.convert_to_tensor(parameters["W3"])74b3 = tf.convert_to_tensor(parameters["b3"])7576params = {"W1": W1,77"b1": b1,78"W2": W2,79"b2": b2,80"W3": W3,81"b3": b3}8283x = tf.placeholder("float", [12288, 1])8485z3 = forward_propagation_for_predict(x, params)86p = tf.argmax(z3)8788sess = tf.Session()89prediction = sess.run(p, feed_dict = {x: X})9091return prediction9293def forward_propagation_for_predict(X, parameters):94"""95Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX9697Arguments:98X -- input dataset placeholder, of shape (input size, number of examples)99parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"100the shapes are given in initialize_parameters101102Returns:103Z3 -- the output of the last LINEAR unit104"""105106# Retrieve the parameters from the dictionary "parameters"107W1 = parameters['W1']108b1 = parameters['b1']109W2 = parameters['W2']110b2 = parameters['b2']111W3 = parameters['W3']112b3 = parameters['b3']113# Numpy Equivalents:114Z1 = tf.add(tf.matmul(W1, X), b1) # Z1 = np.dot(W1, X) + b1115A1 = tf.nn.relu(Z1) # A1 = relu(Z1)116Z2 = tf.add(tf.matmul(W2, A1), b2) # Z2 = np.dot(W2, a1) + b2117A2 = tf.nn.relu(Z2) # A2 = relu(Z2)118Z3 = tf.add(tf.matmul(W3, A2), b3) # Z3 = np.dot(W3,Z2) + b3119120return Z3121122123