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/C4 - Convolutional Neural Networks/Week 1/cnn_utils.py
Views: 4802
import math1import numpy as np2import h5py3import matplotlib.pyplot as plt4import tensorflow as tf5from tensorflow.python.framework import ops678def load_dataset():9train_dataset = h5py.File('datasets/train_signs.h5', "r")10# your train set features11train_set_x_orig = np.array(train_dataset["train_set_x"][:])12train_set_y_orig = np.array(13train_dataset["train_set_y"][:]) # your train set labels1415test_dataset = h5py.File('datasets/test_signs.h5', "r")16# your test set features17test_set_x_orig = np.array(test_dataset["test_set_x"][:])18test_set_y_orig = np.array(19test_dataset["test_set_y"][:]) # your test set labels2021classes = np.array(test_dataset["list_classes"][:]) # the list of classes2223train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))24test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))2526return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes272829def random_mini_batches(X, Y, mini_batch_size=64, seed=0):30"""31Creates a list of random minibatches from (X, Y)3233Arguments:34X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)35Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)36mini_batch_size - size of the mini-batches, integer37seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.3839Returns:40mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)41"""4243m = X.shape[0] # number of training examples44mini_batches = []45np.random.seed(seed)4647# Step 1: Shuffle (X, Y)48permutation = list(np.random.permutation(m))49shuffled_X = X[permutation, :, :, :]50shuffled_Y = Y[permutation, :]5152# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.53# number of mini batches of size mini_batch_size in your partitionning54num_complete_minibatches = math.floor(m / mini_batch_size)55for k in range(0, num_complete_minibatches):56mini_batch_X = shuffled_X[k * mini_batch_size: k *57mini_batch_size + mini_batch_size, :, :, :]58mini_batch_Y = shuffled_Y[k * mini_batch_size: k *59mini_batch_size + mini_batch_size, :]60mini_batch = (mini_batch_X, mini_batch_Y)61mini_batches.append(mini_batch)6263# Handling the end case (last mini-batch < mini_batch_size)64if m % mini_batch_size != 0:65mini_batch_X = shuffled_X[num_complete_minibatches *66mini_batch_size: m, :, :, :]67mini_batch_Y = shuffled_Y[num_complete_minibatches *68mini_batch_size: m, :]69mini_batch = (mini_batch_X, mini_batch_Y)70mini_batches.append(mini_batch)7172return mini_batches737475def convert_to_one_hot(Y, C):76Y = np.eye(C)[Y.reshape(-1)].T77return Y787980def forward_propagation_for_predict(X, parameters):81"""82Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX8384Arguments:85X -- input dataset placeholder, of shape (input size, number of examples)86parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"87the shapes are given in initialize_parameters8889Returns:90Z3 -- the output of the last LINEAR unit91"""9293# Retrieve the parameters from the dictionary "parameters"94W1 = parameters['W1']95b1 = parameters['b1']96W2 = parameters['W2']97b2 = parameters['b2']98W3 = parameters['W3']99b3 = parameters['b3']100# Numpy Equivalents:101# Z1 = np.dot(W1, X) + b1102Z1 = tf.add(tf.matmul(W1, X), b1)103A1 = tf.nn.relu(Z1) # A1 = relu(Z1)104# Z2 = np.dot(W2, a1) + b2105Z2 = tf.add(tf.matmul(W2, A1), b2)106A2 = tf.nn.relu(Z2) # A2 = relu(Z2)107# Z3 = np.dot(W3,Z2) + b3108Z3 = tf.add(tf.matmul(W3, A2), b3)109110return Z3111112113def predict(X, parameters):114115W1 = tf.convert_to_tensor(parameters["W1"])116b1 = tf.convert_to_tensor(parameters["b1"])117W2 = tf.convert_to_tensor(parameters["W2"])118b2 = tf.convert_to_tensor(parameters["b2"])119W3 = tf.convert_to_tensor(parameters["W3"])120b3 = tf.convert_to_tensor(parameters["b3"])121122params = {"W1": W1,123"b1": b1,124"W2": W2,125"b2": b2,126"W3": W3,127"b3": b3}128129x = tf.placeholder("float", [12288, 1])130131z3 = forward_propagation_for_predict(x, params)132p = tf.argmax(z3)133134sess = tf.Session()135prediction = sess.run(p, feed_dict={x: X})136137return prediction138139140