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