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/C5 - Sequence Models/Week 1/Building a Recurrent Neural Network - Step by Step/utils.py
Views: 4819
1
import numpy as np
2
3
def softmax(x):
4
e_x = np.exp(x - np.max(x))
5
return e_x / e_x.sum(axis=0)
6
7
def smooth(loss, cur_loss):
8
return loss * 0.999 + cur_loss * 0.001
9
10
def print_sample(sample_ix, ix_to_char):
11
txt = ''.join(ix_to_char[ix] for ix in sample_ix)
12
print ('----\n %s \n----' % (txt, ))
13
14
def get_initial_loss(vocab_size, seq_length):
15
return -np.log(1.0/vocab_size)*seq_length
16
17
def softmax(x):
18
e_x = np.exp(x - np.max(x))
19
return e_x / e_x.sum(axis=0)
20
21
def initialize_parameters(n_a, n_x, n_y):
22
"""
23
Initialize parameters with small random values
24
25
Returns:
26
parameters -- python dictionary containing:
27
Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
28
Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
29
Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
30
b -- Bias, numpy array of shape (n_a, 1)
31
by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
32
"""
33
np.random.seed(1)
34
Wax = np.random.randn(n_a, n_x)*0.01 # input to hidden
35
Waa = np.random.randn(n_a, n_a)*0.01 # hidden to hidden
36
Wya = np.random.randn(n_y, n_a)*0.01 # hidden to output
37
b = np.zeros((n_a, 1)) # hidden bias
38
by = np.zeros((n_y, 1)) # output bias
39
40
parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "b": b,"by": by}
41
42
return parameters
43
44
def rnn_step_forward(parameters, a_prev, x):
45
46
Waa, Wax, Wya, by, b = parameters['Waa'], parameters['Wax'], parameters['Wya'], parameters['by'], parameters['b']
47
a_next = np.tanh(np.dot(Wax, x) + np.dot(Waa, a_prev) + b) # hidden state
48
p_t = softmax(np.dot(Wya, a_next) + by) # unnormalized log probabilities for next chars # probabilities for next chars
49
50
return a_next, p_t
51
52
def rnn_step_backward(dy, gradients, parameters, x, a, a_prev):
53
54
gradients['dWya'] += np.dot(dy, a.T)
55
gradients['dby'] += dy
56
da = np.dot(parameters['Wya'].T, dy) + gradients['da_next'] # backprop into h
57
daraw = (1 - a * a) * da # backprop through tanh nonlinearity
58
gradients['db'] += daraw
59
gradients['dWax'] += np.dot(daraw, x.T)
60
gradients['dWaa'] += np.dot(daraw, a_prev.T)
61
gradients['da_next'] = np.dot(parameters['Waa'].T, daraw)
62
return gradients
63
64
def update_parameters(parameters, gradients, lr):
65
66
parameters['Wax'] += -lr * gradients['dWax']
67
parameters['Waa'] += -lr * gradients['dWaa']
68
parameters['Wya'] += -lr * gradients['dWya']
69
parameters['b'] += -lr * gradients['db']
70
parameters['by'] += -lr * gradients['dby']
71
return parameters
72
73
def rnn_forward(X, Y, a0, parameters, vocab_size = 71):
74
75
# Initialize x, a and y_hat as empty dictionaries
76
x, a, y_hat = {}, {}, {}
77
78
a[-1] = np.copy(a0)
79
80
# initialize your loss to 0
81
loss = 0
82
83
for t in range(len(X)):
84
85
# Set x[t] to be the one-hot vector representation of the t'th character in X.
86
x[t] = np.zeros((vocab_size,1))
87
x[t][X[t]] = 1
88
89
# Run one step forward of the RNN
90
a[t], y_hat[t] = rnn_step_forward(parameters, a[t-1], x[t])
91
92
# Update the loss by substracting the cross-entropy term of this time-step from it.
93
loss -= np.log(y_hat[t][Y[t],0])
94
95
cache = (y_hat, a, x)
96
97
return loss, cache
98
99
def rnn_backward(X, Y, parameters, cache):
100
# Initialize gradients as an empty dictionary
101
gradients = {}
102
103
# Retrieve from cache and parameters
104
(y_hat, a, x) = cache
105
Waa, Wax, Wya, by, b = parameters['Waa'], parameters['Wax'], parameters['Wya'], parameters['by'], parameters['b']
106
107
# each one should be initialized to zeros of the same dimension as its corresponding parameter
108
gradients['dWax'], gradients['dWaa'], gradients['dWya'] = np.zeros_like(Wax), np.zeros_like(Waa), np.zeros_like(Wya)
109
gradients['db'], gradients['dby'] = np.zeros_like(b), np.zeros_like(by)
110
gradients['da_next'] = np.zeros_like(a[0])
111
112
### START CODE HERE ###
113
# Backpropagate through time
114
for t in reversed(range(len(X))):
115
dy = np.copy(y_hat[t])
116
dy[Y[t]] -= 1
117
gradients = rnn_step_backward(dy, gradients, parameters, x[t], a[t], a[t-1])
118
### END CODE HERE ###
119
120
return gradients, a
121