CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
amanchadha

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: amanchadha/coursera-deep-learning-specialization
Path: blob/master/C4 - Convolutional Neural Networks/Week 1/cnn_utils.py
Views: 4802
1
import math
2
import numpy as np
3
import h5py
4
import matplotlib.pyplot as plt
5
import tensorflow as tf
6
from tensorflow.python.framework import ops
7
8
9
def load_dataset():
10
train_dataset = h5py.File('datasets/train_signs.h5', "r")
11
# your train set features
12
train_set_x_orig = np.array(train_dataset["train_set_x"][:])
13
train_set_y_orig = np.array(
14
train_dataset["train_set_y"][:]) # your train set labels
15
16
test_dataset = h5py.File('datasets/test_signs.h5', "r")
17
# your test set features
18
test_set_x_orig = np.array(test_dataset["test_set_x"][:])
19
test_set_y_orig = np.array(
20
test_dataset["test_set_y"][:]) # your test set labels
21
22
classes = np.array(test_dataset["list_classes"][:]) # the list of classes
23
24
train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))
25
test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))
26
27
return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes
28
29
30
def random_mini_batches(X, Y, mini_batch_size=64, seed=0):
31
"""
32
Creates a list of random minibatches from (X, Y)
33
34
Arguments:
35
X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)
36
Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples) (m, n_y)
37
mini_batch_size - size of the mini-batches, integer
38
seed -- this is only for the purpose of grading, so that you're "random minibatches are the same as ours.
39
40
Returns:
41
mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)
42
"""
43
44
m = X.shape[0] # number of training examples
45
mini_batches = []
46
np.random.seed(seed)
47
48
# Step 1: Shuffle (X, Y)
49
permutation = list(np.random.permutation(m))
50
shuffled_X = X[permutation, :, :, :]
51
shuffled_Y = Y[permutation, :]
52
53
# Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.
54
# number of mini batches of size mini_batch_size in your partitionning
55
num_complete_minibatches = math.floor(m / mini_batch_size)
56
for k in range(0, num_complete_minibatches):
57
mini_batch_X = shuffled_X[k * mini_batch_size: k *
58
mini_batch_size + mini_batch_size, :, :, :]
59
mini_batch_Y = shuffled_Y[k * mini_batch_size: k *
60
mini_batch_size + mini_batch_size, :]
61
mini_batch = (mini_batch_X, mini_batch_Y)
62
mini_batches.append(mini_batch)
63
64
# Handling the end case (last mini-batch < mini_batch_size)
65
if m % mini_batch_size != 0:
66
mini_batch_X = shuffled_X[num_complete_minibatches *
67
mini_batch_size: m, :, :, :]
68
mini_batch_Y = shuffled_Y[num_complete_minibatches *
69
mini_batch_size: m, :]
70
mini_batch = (mini_batch_X, mini_batch_Y)
71
mini_batches.append(mini_batch)
72
73
return mini_batches
74
75
76
def convert_to_one_hot(Y, C):
77
Y = np.eye(C)[Y.reshape(-1)].T
78
return Y
79
80
81
def forward_propagation_for_predict(X, parameters):
82
"""
83
Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX
84
85
Arguments:
86
X -- input dataset placeholder, of shape (input size, number of examples)
87
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3"
88
the shapes are given in initialize_parameters
89
90
Returns:
91
Z3 -- the output of the last LINEAR unit
92
"""
93
94
# Retrieve the parameters from the dictionary "parameters"
95
W1 = parameters['W1']
96
b1 = parameters['b1']
97
W2 = parameters['W2']
98
b2 = parameters['b2']
99
W3 = parameters['W3']
100
b3 = parameters['b3']
101
# Numpy Equivalents:
102
# Z1 = np.dot(W1, X) + b1
103
Z1 = tf.add(tf.matmul(W1, X), b1)
104
A1 = tf.nn.relu(Z1) # A1 = relu(Z1)
105
# Z2 = np.dot(W2, a1) + b2
106
Z2 = tf.add(tf.matmul(W2, A1), b2)
107
A2 = tf.nn.relu(Z2) # A2 = relu(Z2)
108
# Z3 = np.dot(W3,Z2) + b3
109
Z3 = tf.add(tf.matmul(W3, A2), b3)
110
111
return Z3
112
113
114
def predict(X, parameters):
115
116
W1 = tf.convert_to_tensor(parameters["W1"])
117
b1 = tf.convert_to_tensor(parameters["b1"])
118
W2 = tf.convert_to_tensor(parameters["W2"])
119
b2 = tf.convert_to_tensor(parameters["b2"])
120
W3 = tf.convert_to_tensor(parameters["W3"])
121
b3 = tf.convert_to_tensor(parameters["b3"])
122
123
params = {"W1": W1,
124
"b1": b1,
125
"W2": W2,
126
"b2": b2,
127
"W3": W3,
128
"b3": b3}
129
130
x = tf.placeholder("float", [12288, 1])
131
132
z3 = forward_propagation_for_predict(x, params)
133
p = tf.argmax(z3)
134
135
sess = tf.Session()
136
prediction = sess.run(p, feed_dict={x: X})
137
138
return prediction
139
140