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/Convolutional Neural Networks/week1/cnn_utils.py
Views: 13372
import math1import numpy as np2import h5py3import matplotlib.pyplot as plt4import tensorflow as tf5from tensorflow.python.framework import ops67def load_dataset():8train_dataset = h5py.File('datasets/train_signs.h5', "r")9train_set_x_orig = np.array(train_dataset["train_set_x"][:]) # your train set features10train_set_y_orig = np.array(train_dataset["train_set_y"][:]) # your train set labels1112test_dataset = h5py.File('datasets/test_signs.h5', "r")13test_set_x_orig = np.array(test_dataset["test_set_x"][:]) # your test set features14test_set_y_orig = np.array(test_dataset["test_set_y"][:]) # your test set labels1516classes = np.array(test_dataset["list_classes"][:]) # the list of classes1718train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))19test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))2021return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes222324def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):25"""26Creates a list of random minibatches from (X, Y)2728Arguments:29X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)30Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)31mini_batch_size - size of the mini-batches, integer32seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.3334Returns:35mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)36"""3738m = X.shape[0] # number of training examples39mini_batches = []40np.random.seed(seed)4142# Step 1: Shuffle (X, Y)43permutation = list(np.random.permutation(m))44shuffled_X = X[permutation,:,:,:]45shuffled_Y = Y[permutation,:]4647# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.48num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning49for k in range(0, num_complete_minibatches):50mini_batch_X = shuffled_X[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:,:,:]51mini_batch_Y = shuffled_Y[k * mini_batch_size : k * mini_batch_size + mini_batch_size,:]52mini_batch = (mini_batch_X, mini_batch_Y)53mini_batches.append(mini_batch)5455# Handling the end case (last mini-batch < mini_batch_size)56if m % mini_batch_size != 0:57mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size : m,:,:,:]58mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size : m,:]59mini_batch = (mini_batch_X, mini_batch_Y)60mini_batches.append(mini_batch)6162return mini_batches636465def convert_to_one_hot(Y, C):66Y = np.eye(C)[Y.reshape(-1)].T67return Y686970def forward_propagation_for_predict(X, parameters):71"""72Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX7374Arguments:75X -- input dataset placeholder, of shape (input size, number of examples)76parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"77the shapes are given in initialize_parameters7879Returns:80Z3 -- the output of the last LINEAR unit81"""8283# Retrieve the parameters from the dictionary "parameters"84W1 = parameters['W1']85b1 = parameters['b1']86W2 = parameters['W2']87b2 = parameters['b2']88W3 = parameters['W3']89b3 = parameters['b3']90# Numpy Equivalents:91Z1 = tf.add(tf.matmul(W1, X), b1) # Z1 = np.dot(W1, X) + b192A1 = tf.nn.relu(Z1) # A1 = relu(Z1)93Z2 = tf.add(tf.matmul(W2, A1), b2) # Z2 = np.dot(W2, a1) + b294A2 = tf.nn.relu(Z2) # A2 = relu(Z2)95Z3 = tf.add(tf.matmul(W3, A2), b3) # Z3 = np.dot(W3,Z2) + b39697return Z39899def predict(X, parameters):100101W1 = tf.convert_to_tensor(parameters["W1"])102b1 = tf.convert_to_tensor(parameters["b1"])103W2 = tf.convert_to_tensor(parameters["W2"])104b2 = tf.convert_to_tensor(parameters["b2"])105W3 = tf.convert_to_tensor(parameters["W3"])106b3 = tf.convert_to_tensor(parameters["b3"])107108params = {"W1": W1,109"b1": b1,110"W2": W2,111"b2": b2,112"W3": W3,113"b3": b3}114115x = tf.placeholder("float", [12288, 1])116117z3 = forward_propagation_for_predict(x, params)118p = tf.argmax(z3)119120sess = tf.Session()121prediction = sess.run(p, feed_dict = {x: X})122123return prediction124125#def predict(X, parameters):126#127# W1 = tf.convert_to_tensor(parameters["W1"])128# b1 = tf.convert_to_tensor(parameters["b1"])129# W2 = tf.convert_to_tensor(parameters["W2"])130# b2 = tf.convert_to_tensor(parameters["b2"])131## W3 = tf.convert_to_tensor(parameters["W3"])132## b3 = tf.convert_to_tensor(parameters["b3"])133#134## params = {"W1": W1,135## "b1": b1,136## "W2": W2,137## "b2": b2,138## "W3": W3,139## "b3": b3}140#141# params = {"W1": W1,142# "b1": b1,143# "W2": W2,144# "b2": b2}145#146# x = tf.placeholder("float", [12288, 1])147#148# z3 = forward_propagation(x, params)149# p = tf.argmax(z3)150#151# with tf.Session() as sess:152# prediction = sess.run(p, feed_dict = {x: X})153#154# return prediction155156