CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
y33-j3T

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: y33-j3T/Coursera-Deep-Learning
Path: blob/master/Improving Deep Neural Networks Hyperparameter tuning, Regularization and Optimization/week5/Gradient Checking/gc_utils.py
Views: 13377
1
import numpy as np
2
3
def sigmoid(x):
4
"""
5
Compute the sigmoid of x
6
7
Arguments:
8
x -- A scalar or numpy array of any size.
9
10
Return:
11
s -- sigmoid(x)
12
"""
13
s = 1/(1+np.exp(-x))
14
return s
15
16
def relu(x):
17
"""
18
Compute the relu of x
19
20
Arguments:
21
x -- A scalar or numpy array of any size.
22
23
Return:
24
s -- relu(x)
25
"""
26
s = np.maximum(0,x)
27
28
return s
29
30
def dictionary_to_vector(parameters):
31
"""
32
Roll all our parameters dictionary into a single vector satisfying our specific required shape.
33
"""
34
keys = []
35
count = 0
36
for key in ["W1", "b1", "W2", "b2", "W3", "b3"]:
37
38
# flatten parameter
39
new_vector = np.reshape(parameters[key], (-1,1))
40
keys = keys + [key]*new_vector.shape[0]
41
42
if count == 0:
43
theta = new_vector
44
else:
45
theta = np.concatenate((theta, new_vector), axis=0)
46
count = count + 1
47
48
return theta, keys
49
50
def vector_to_dictionary(theta):
51
"""
52
Unroll all our parameters dictionary from a single vector satisfying our specific required shape.
53
"""
54
parameters = {}
55
parameters["W1"] = theta[:20].reshape((5,4))
56
parameters["b1"] = theta[20:25].reshape((5,1))
57
parameters["W2"] = theta[25:40].reshape((3,5))
58
parameters["b2"] = theta[40:43].reshape((3,1))
59
parameters["W3"] = theta[43:46].reshape((1,3))
60
parameters["b3"] = theta[46:47].reshape((1,1))
61
62
return parameters
63
64
def gradients_to_vector(gradients):
65
"""
66
Roll all our gradients dictionary into a single vector satisfying our specific required shape.
67
"""
68
69
count = 0
70
for key in ["dW1", "db1", "dW2", "db2", "dW3", "db3"]:
71
# flatten parameter
72
new_vector = np.reshape(gradients[key], (-1,1))
73
74
if count == 0:
75
theta = new_vector
76
else:
77
theta = np.concatenate((theta, new_vector), axis=0)
78
count = count + 1
79
80
return theta
81