Advertisement
ERENARD63

Building your Recurrent Neural Network - Step by Step

May 24th, 2018
798
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 45.42 KB | None | 0 0
  1.  
  2. # coding: utf-8
  3.  
  4. # # Building your Recurrent Neural Network - Step by Step
  5. #
  6. # Welcome to Course 5's first assignment! In this assignment, you will implement your first Recurrent Neural Network in numpy.
  7. #
  8. # Recurrent Neural Networks (RNN) are very effective for Natural Language Processing and other sequence tasks because they have "memory". They can read inputs $x^{\langle t \rangle}$ (such as words) one at a time, and remember some information/context through the hidden layer activations that get passed from one time-step to the next. This allows a uni-directional RNN to take information from the past to process later inputs. A bidirection RNN can take context from both the past and the future.
  9. #
  10. # **Notation**:
  11. # - Superscript $[l]$ denotes an object associated with the $l^{th}$ layer.
  12. #     - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters.
  13. #
  14. # - Superscript $(i)$ denotes an object associated with the $i^{th}$ example.
  15. #     - Example: $x^{(i)}$ is the $i^{th}$ training example input.
  16. #
  17. # - Superscript $\langle t \rangle$ denotes an object at the $t^{th}$ time-step.
  18. #     - Example: $x^{\langle t \rangle}$ is the input x at the $t^{th}$ time-step. $x^{(i)\langle t \rangle}$ is the input at the $t^{th}$ timestep of example $i$.
  19. #    
  20. # - Lowerscript $i$ denotes the $i^{th}$ entry of a vector.
  21. #     - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$.
  22. #
  23. # We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started!
  24.  
  25. # Let's first import all the packages that you will need during this assignment.
  26.  
  27. # In[1]:
  28.  
  29. import numpy as np
  30. from rnn_utils import *
  31.  
  32.  
  33. # ## 1 - Forward propagation for the basic Recurrent Neural Network
  34. #
  35. # Later this week, you will generate music using an RNN. The basic RNN that you will implement has the structure below. In this example, $T_x = T_y$.
  36.  
  37. #**Figure 1**: Basic RNN model </center></caption>
  38.  
  39. # Here's how you can implement an RNN:
  40. #
  41. # **Steps**:
  42. # 1. Implement the calculations needed for one time-step of the RNN.
  43. # 2. Implement a loop over $T_x$ time-steps in order to process all the inputs, one at a time.
  44. #
  45. # Let's go!
  46. #
  47. # ## 1.1 - RNN cell
  48. #
  49. # A Recurrent neural network can be seen as the repetition of a single cell. You are first going to implement the computations for a single time-step. The following figure describes the operations for a single time-step of an RNN cell.
  50. #
  51. # **Exercise**: Implement the RNN-cell described in Figure (2).
  52. #
  53. # **Instructions**:
  54. # 1. Compute the hidden state with tanh activation: $a^{\langle t \rangle} = \tanh(W_{aa} a^{\langle t-1 \rangle} + W_{ax} x^{\langle t \rangle} + b_a)$.
  55. # 2. Using your new hidden state $a^{\langle t \rangle}$, compute the prediction $\hat{y}^{\langle t \rangle} = softmax(W_{ya} a^{\langle t \rangle} + b_y)$. We provided you a function: `softmax`.
  56. # 3. Store $(a^{\langle t \rangle}, a^{\langle t-1 \rangle}, x^{\langle t \rangle}, parameters)$ in cache
  57. # 4. Return $a^{\langle t \rangle}$ , $y^{\langle t \rangle}$ and cache
  58. #
  59. # We will vectorize over $m$ examples. Thus, $x^{\langle t \rangle}$ will have dimension $(n_x,m)$, and $a^{\langle t \rangle}$ will have dimension $(n_a,m)$.
  60.  
  61. # In[2]:
  62.  
  63. # GRADED FUNCTION: rnn_cell_forward
  64.  
  65. def rnn_cell_forward(xt, a_prev, parameters):
  66.     """
  67.    Implements a single forward step of the RNN-cell as described in Figure (2)
  68.  
  69.    Arguments:
  70.    xt -- your input data at timestep "t", numpy array of shape (n_x, m).
  71.    a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
  72.    parameters -- python dictionary containing:
  73.                        Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
  74.                        Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
  75.                        Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
  76.                        ba --  Bias, numpy array of shape (n_a, 1)
  77.                        by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
  78.    Returns:
  79.    a_next -- next hidden state, of shape (n_a, m)
  80.    yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
  81.    cache -- tuple of values needed for the backward pass, contains (a_next, a_prev, xt, parameters)
  82.    """
  83.    
  84.     # Retrieve parameters from "parameters"
  85.     Wax = parameters["Wax"]
  86.     Waa = parameters["Waa"]
  87.     Wya = parameters["Wya"]
  88.     ba = parameters["ba"]
  89.     by = parameters["by"]
  90.    
  91.     ### START CODE HERE ### (≈2 lines)
  92.     # compute next activation state using the formula given above
  93.     #print("a_prev",np.shape(a_prev))
  94.     #print("xt",np.shape(xt))
  95.     a_next = np.tanh(np.dot(Waa,a_prev)+np.dot(Wax,xt)+ba)
  96.     #np.multiply(Waa,a_prev)+
  97.     # compute output of the current cell using the formula given above
  98.     yt_pred = softmax(np.dot(Wya,a_next)+by)  
  99.     ### END CODE HERE ###
  100.    
  101.     # store values you need for backward propagation in cache
  102.     cache = (a_next, a_prev, xt, parameters)
  103.    
  104.     return a_next, yt_pred, cache
  105.  
  106.  
  107. # In[3]:
  108.  
  109. np.random.seed(1)
  110. xt = np.random.randn(3,10)
  111. a_prev = np.random.randn(5,10)
  112. Waa = np.random.randn(5,5)
  113. Wax = np.random.randn(5,3)
  114. Wya = np.random.randn(2,5)
  115. ba = np.random.randn(5,1)
  116. by = np.random.randn(2,1)
  117. parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
  118.  
  119. a_next, yt_pred, cache = rnn_cell_forward(xt, a_prev, parameters)
  120. print("a_next[4] = ", a_next[4])
  121. print("a_next.shape = ", a_next.shape)
  122. print("yt_pred[1] =", yt_pred[1])
  123. print("yt_pred.shape = ", yt_pred.shape)
  124.  
  125.  
  126.  
  127. # ## 1.2 - RNN forward pass
  128. #
  129. # You can see an RNN as the repetition of the cell you've just built. If your input sequence of data is carried over 10 time steps, then you will copy the RNN cell 10 times. Each cell takes as input the hidden state from the previous cell ($a^{\langle t-1 \rangle}$) and the current time-step's input data ($x^{\langle t \rangle}$). It outputs a hidden state ($a^{\langle t \rangle}$) and a prediction ($y^{\langle t \rangle}$) for this time-step.
  130. #
  131. #
  132. #
  133. # **Exercise**: Code the forward propagation of the RNN described in Figure (3).
  134. #
  135. # **Instructions**:
  136. # 1. Create a vector of zeros ($a$) that will store all the hidden states computed by the RNN.
  137. # 2. Initialize the "next" hidden state as $a_0$ (initial hidden state).
  138. # 3. Start looping over each time step, your incremental index is $t$ :
  139. #     - Update the "next" hidden state and the cache by running `rnn_cell_forward`
  140. #     - Store the "next" hidden state in $a$ ($t^{th}$ position)
  141. #     - Store the prediction in y
  142. #     - Add the cache to the list of caches
  143. # 4. Return $a$, $y$ and caches
  144.  
  145. # In[4]:
  146.  
  147. # GRADED FUNCTION: rnn_forward
  148.  
  149. def rnn_forward(x, a0, parameters):
  150.     """
  151.    Implement the forward propagation of the recurrent neural network described in Figure (3).
  152.  
  153.    Arguments:
  154.    x -- Input data for every time-step, of shape (n_x, m, T_x).
  155.    a0 -- Initial hidden state, of shape (n_a, m)
  156.    parameters -- python dictionary containing:
  157.                        Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
  158.                        Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
  159.                        Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
  160.                        ba --  Bias numpy array of shape (n_a, 1)
  161.                        by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
  162.  
  163.    Returns:
  164.    a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
  165.    y_pred -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
  166.    caches -- tuple of values needed for the backward pass, contains (list of caches, x)
  167.    """
  168.    
  169.     # Initialize "caches" which will contain the list of all caches
  170.     caches = [a0,x]
  171.    
  172.     # Retrieve dimensions from shapes of x and parameters["Wya"]
  173.     n_x, m, T_x = x.shape
  174.     n_y, n_a = parameters["Wya"].shape
  175.    
  176.     ### START CODE HERE ###
  177.    
  178.     # initialize "a" and "y" with zeros (≈2 lines)
  179.     a = np.zeros((n_a, m,T_x))
  180.     y_pred = np.zeros((n_y, m, T_x))
  181.    
  182.     # Initialize a_next (≈1 line)
  183.     a_next = a0
  184.    
  185.     # loop over all time-steps
  186.    
  187.     for t in range(T_x):
  188.         # Update next hidden state, compute the prediction, get the cache (≈1 line)
  189.         #print("x", np.shape(x))
  190.         #print("a_next",a_next)
  191.         a_next, yt_pred, cache = rnn_cell_forward(x[:,:,t], a_next, parameters)
  192.         # Save the value of the new "next" hidden state in a (≈1 line)
  193.        
  194.         a[:,:,t] = a_next
  195.         # Save the value of the prediction in y (≈1 line)
  196.         y_pred[:,:,t] = yt_pred
  197.         # Append "cache" to "caches" (≈1 line)
  198.         caches=(caches,cache)
  199.        
  200.     ### END CODE HERE ###
  201.    
  202.     # store values needed for backward propagation in cache
  203.     caches = (caches, x)
  204.    
  205.     return a, y_pred, caches
  206.  
  207.  
  208. # In[5]:
  209.  
  210. np.random.seed(1)
  211. x = np.random.randn(3,10,4)
  212. a0 = np.random.randn(5,10)
  213. Waa = np.random.randn(5,5)
  214. Wax = np.random.randn(5,3)
  215. Wya = np.random.randn(2,5)
  216. ba = np.random.randn(5,1)
  217. by = np.random.randn(2,1)
  218. parameters = {"Waa": Waa, "Wax": Wax, "Wya": Wya, "ba": ba, "by": by}
  219.  
  220. a, y_pred, caches = rnn_forward(x, a0, parameters)
  221. print("a[4][1] = ", a[4][1])
  222. print("a.shape = ", a.shape)
  223. print("y_pred[1][3] =", y_pred[1][3])
  224. print("y_pred.shape = ", y_pred.shape)
  225. print("caches[1][1][3] =", caches[1][1][3])
  226. print("len(caches) = ", len(caches))
  227.  
  228.  
  229. # Congratulations! You've successfully built the forward propagation of a recurrent neural network from scratch. This will work well enough for some applications, but it suffers from vanishing gradient problems. So it works best when each output $y^{\langle t \rangle}$ can be estimated using mainly "local" context (meaning information from inputs $x^{\langle t' \rangle}$ where $t'$ is not too far from $t$).
  230. #
  231. # In the next part, you will build a more complex LSTM model, which is better at addressing vanishing gradients. The LSTM will be better able to remember a piece of information and keep it saved for many timesteps.
  232.  
  233. # ## 2 - Long Short-Term Memory (LSTM) network
  234. #
  235. # This following figure shows the operations of an LSTM-cell.
  236. #
  237. # Similar to the RNN example above, you will start by implementing the LSTM cell for a single time-step. Then you can iteratively call it from inside a for-loop to have it process an input with $T_x$ time-steps.
  238. #
  239. # ### About the gates
  240. #
  241. # #### - Forget gate
  242. #
  243. # For the sake of this illustration, lets assume we are reading words in a piece of text, and want use an LSTM to keep track of grammatical structures, such as whether the subject is singular or plural. If the subject changes from a singular word to a plural word, we need to find a way to get rid of our previously stored memory value of the singular/plural state. In an LSTM, the forget gate lets us do this:
  244. #
  245. # $$\Gamma_f^{\langle t \rangle} = \sigma(W_f[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_f)\tag{1} $$
  246. #
  247. # Here, $W_f$ are weights that govern the forget gate's behavior. We concatenate $[a^{\langle t-1 \rangle}, x^{\langle t \rangle}]$ and multiply by $W_f$. The equation above results in a vector $\Gamma_f^{\langle t \rangle}$ with values between 0 and 1. This forget gate vector will be multiplied element-wise by the previous cell state $c^{\langle t-1 \rangle}$. So if one of the values of $\Gamma_f^{\langle t \rangle}$ is 0 (or close to 0) then it means that the LSTM should remove that piece of information (e.g. the singular subject) in the corresponding component of $c^{\langle t-1 \rangle}$. If one of the values is 1, then it will keep the information.
  248. #
  249. # #### - Update gate
  250. #
  251. # Once we forget that the subject being discussed is singular, we need to find a way to update it to reflect that the new subject is now plural. Here is the formulat for the update gate:
  252. #
  253. # $$\Gamma_u^{\langle t \rangle} = \sigma(W_u[a^{\langle t-1 \rangle}, x^{\{t\}}] + b_u)\tag{2} $$
  254. #
  255. # Similar to the forget gate, here $\Gamma_u^{\langle t \rangle}$ is again a vector of values between 0 and 1. This will be multiplied element-wise with $\tilde{c}^{\langle t \rangle}$, in order to compute $c^{\langle t \rangle}$.
  256. #
  257. # #### - Updating the cell
  258. #
  259. # To update the new subject we need to create a new vector of numbers that we can add to our previous cell state. The equation we use is:
  260. #
  261. # $$ \tilde{c}^{\langle t \rangle} = \tanh(W_c[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_c)\tag{3} $$
  262. #
  263. # Finally, the new cell state is:
  264. #
  265. # $$ c^{\langle t \rangle} = \Gamma_f^{\langle t \rangle}* c^{\langle t-1 \rangle} + \Gamma_u^{\langle t \rangle} *\tilde{c}^{\langle t \rangle} \tag{4} $$
  266. #
  267. #
  268. # #### - Output gate
  269. #
  270. # To decide which outputs we will use, we will use the following two formulas:
  271. #
  272. # $$ \Gamma_o^{\langle t \rangle}=  \sigma(W_o[a^{\langle t-1 \rangle}, x^{\langle t \rangle}] + b_o)\tag{5}$$
  273. # $$ a^{\langle t \rangle} = \Gamma_o^{\langle t \rangle}* \tanh(c^{\langle t \rangle})\tag{6} $$
  274. #
  275. # Where in equation 5 you decide what to output using a sigmoid function and in equation 6 you multiply that by the $\tanh$ of the previous state.
  276.  
  277. # ### 2.1 - LSTM cell
  278. #
  279. # **Exercise**: Implement the LSTM cell described in the Figure (3).
  280. #
  281. # **Instructions**:
  282. # 1. Concatenate $a^{\langle t-1 \rangle}$ and $x^{\langle t \rangle}$ in a single matrix: $concat = \begin{bmatrix} a^{\langle t-1 \rangle} \\ x^{\langle t \rangle} \end{bmatrix}$
  283. # 2. Compute all the formulas 1-6. You can use `sigmoid()` (provided) and `np.tanh()`.
  284. # 3. Compute the prediction $y^{\langle t \rangle}$. You can use `softmax()` (provided).
  285.  
  286. # In[6]:
  287.  
  288. # GRADED FUNCTION: lstm_cell_forward
  289.  
  290. def lstm_cell_forward(xt, a_prev, c_prev, parameters):
  291.     """
  292.    Implement a single forward step of the LSTM-cell as described in Figure (4)
  293.  
  294.    Arguments:
  295.    xt -- your input data at timestep "t", numpy array of shape (n_x, m).
  296.    a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m)
  297.    c_prev -- Memory state at timestep "t-1", numpy array of shape (n_a, m)
  298.    parameters -- python dictionary containing:
  299.                        Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
  300.                        bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
  301.                        Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
  302.                        bi -- Bias of the update gate, numpy array of shape (n_a, 1)
  303.                        Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
  304.                        bc --  Bias of the first "tanh", numpy array of shape (n_a, 1)
  305.                        Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
  306.                        bo --  Bias of the output gate, numpy array of shape (n_a, 1)
  307.                        Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
  308.                        by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
  309.                        
  310.    Returns:
  311.    a_next -- next hidden state, of shape (n_a, m)
  312.    c_next -- next memory state, of shape (n_a, m)
  313.    yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m)
  314.    cache -- tuple of values needed for the backward pass, contains (a_next, c_next, a_prev, c_prev, xt, parameters)
  315.    
  316.    Note: ft/it/ot stand for the forget/update/output gates, cct stands for the candidate value (c tilde),
  317.          c stands for the memory value
  318.    """
  319.  
  320.     # Retrieve parameters from "parameters"
  321.     Wf = parameters["Wf"]
  322.     bf = parameters["bf"]
  323.     Wi = parameters["Wi"]
  324.     bi = parameters["bi"]
  325.     Wc = parameters["Wc"]
  326.     bc = parameters["bc"]
  327.     Wo = parameters["Wo"]
  328.     bo = parameters["bo"]
  329.     Wy = parameters["Wy"]
  330.     by = parameters["by"]
  331.    
  332.     # Retrieve dimensions from shapes of xt and Wy
  333.     n_x, m = xt.shape
  334.     n_y, n_a = Wy.shape
  335.  
  336.     ### START CODE HERE ###
  337.     # Concatenate a_prev and xt (≈3 lines)
  338.     concat = np.zeros((n_x+n_a,m))
  339.     concat[: n_a, :] = a_prev
  340.     concat[n_a :, :] = xt
  341.  
  342.     # Compute values for ft, it, cct, c_next, ot, a_next using the formulas given figure (4) (≈6 lines)
  343.     ft = sigmoid(np.dot(Wf,concat)+bf)
  344.     it = sigmoid(np.dot(Wi,concat)+bi)
  345.     cct = np.tanh(np.dot(Wc,concat)+bc)
  346.     c_next = ft*c_prev+it*cct
  347.     ot = sigmoid(np.dot(Wo,concat)+bo)
  348.     a_next = ot*np.tanh(c_next)
  349.    
  350.     # Compute prediction of the LSTM cell (≈1 line)
  351.     yt_pred = softmax(np.dot(Wy,a_next)+by)
  352.     ### END CODE HERE ###
  353.  
  354.     # store values needed for backward propagation in cache
  355.     cache = (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters)
  356.  
  357.     return a_next, c_next, yt_pred, cache
  358.  
  359.  
  360. # In[7]:
  361.  
  362. np.random.seed(1)
  363. xt = np.random.randn(3,10)
  364. a_prev = np.random.randn(5,10)
  365. c_prev = np.random.randn(5,10)
  366. Wf = np.random.randn(5, 5+3)
  367. bf = np.random.randn(5,1)
  368. Wi = np.random.randn(5, 5+3)
  369. bi = np.random.randn(5,1)
  370. Wo = np.random.randn(5, 5+3)
  371. bo = np.random.randn(5,1)
  372. Wc = np.random.randn(5, 5+3)
  373. bc = np.random.randn(5,1)
  374. Wy = np.random.randn(2,5)
  375. by = np.random.randn(2,1)
  376.  
  377. parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
  378.  
  379. a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
  380. print("a_next[4] = ", a_next[4])
  381. print("a_next.shape = ", c_next.shape)
  382. print("c_next[2] = ", c_next[2])
  383. print("c_next.shape = ", c_next.shape)
  384. print("yt[1] =", yt[1])
  385. print("yt.shape = ", yt.shape)
  386. print("cache[1][3] =", cache[1][3])
  387. print("len(cache) = ", len(cache))
  388.  
  389.  
  390.  
  391. # ### 2.2 - Forward pass for LSTM
  392. #
  393. # Now that you have implemented one step of an LSTM, you can now iterate this over this using a for-loop to process a sequence of $T_x$ inputs.
  394. #
  395. # **Exercise:** Implement `lstm_forward()` to run an LSTM over $T_x$ time-steps.
  396. #
  397. # **Note**: $c^{\langle 0 \rangle}$ is initialized with zeros.
  398.  
  399. # In[8]:
  400.  
  401. # GRADED FUNCTION: lstm_forward
  402.  
  403. def lstm_forward(x, a0, parameters):
  404.     """
  405.    Implement the forward propagation of the recurrent neural network using an LSTM-cell described in Figure (3).
  406.  
  407.    Arguments:
  408.    x -- Input data for every time-step, of shape (n_x, m, T_x).
  409.    a0 -- Initial hidden state, of shape (n_a, m)
  410.    parameters -- python dictionary containing:
  411.                        Wf -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
  412.                        bf -- Bias of the forget gate, numpy array of shape (n_a, 1)
  413.                        Wi -- Weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
  414.                        bi -- Bias of the update gate, numpy array of shape (n_a, 1)
  415.                        Wc -- Weight matrix of the first "tanh", numpy array of shape (n_a, n_a + n_x)
  416.                        bc -- Bias of the first "tanh", numpy array of shape (n_a, 1)
  417.                        Wo -- Weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
  418.                        bo -- Bias of the output gate, numpy array of shape (n_a, 1)
  419.                        Wy -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
  420.                        by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
  421.                        
  422.    Returns:
  423.    a -- Hidden states for every time-step, numpy array of shape (n_a, m, T_x)
  424.    y -- Predictions for every time-step, numpy array of shape (n_y, m, T_x)
  425.    caches -- tuple of values needed for the backward pass, contains (list of all the caches, x)
  426.    """
  427.  
  428.     # Initialize "caches", which will track the list of all the caches
  429.     caches = []
  430.    
  431.     ### START CODE HERE ###
  432.     # Retrieve dimensions from shapes of x and parameters['Wy'] (≈2 lines)
  433.     n_x, m, T_x = x.shape
  434.     n_y, n_a = parameters["Wy"].shape
  435.    
  436.     # initialize "a", "c" and "y" with zeros (≈3 lines)
  437.     a = np.zeros((n_a,m,T_x))
  438.     c = np.zeros((n_a,m,T_x))
  439.     y = np.zeros((n_y,m,T_x))
  440.    
  441.     # Initialize a_next and c_next (≈2 lines)
  442.     a_next = a0
  443.     c_next = np.zeros((n_a,m))
  444.    
  445.     # loop over all time-steps
  446.     for t in range(T_x):
  447.         # Update next hidden state, next memory state, compute the prediction, get the cache (≈1 line)
  448.         a_next, c_next, yt, cache = lstm_cell_forward(x[:,:,t], a_next, c_next, parameters)
  449.         # Save the value of the new "next" hidden state in a (≈1 line)
  450.         a[:,:,t] = a_next
  451.         # Save the value of the prediction in y (≈1 line)
  452.         y[:,:,t] = yt
  453.         # Save the value of the next cell state (≈1 line)
  454.         c[:,:,t]  = c_next
  455.         # Append the cache into caches (≈1 line)
  456.         caches.append(cache)
  457.        
  458.     ### END CODE HERE ###
  459.    
  460.     # store values needed for backward propagation in cache
  461.     caches = (caches, x)
  462.  
  463.     return a, y, c, caches
  464.  
  465.  
  466. # In[9]:
  467.  
  468. np.random.seed(1)
  469. x = np.random.randn(3,10,7)
  470. a0 = np.random.randn(5,10)
  471. Wf = np.random.randn(5, 5+3)
  472. bf = np.random.randn(5,1)
  473. Wi = np.random.randn(5, 5+3)
  474. bi = np.random.randn(5,1)
  475. Wo = np.random.randn(5, 5+3)
  476. bo = np.random.randn(5,1)
  477. Wc = np.random.randn(5, 5+3)
  478. bc = np.random.randn(5,1)
  479. Wy = np.random.randn(2,5)
  480. by = np.random.randn(2,1)
  481.  
  482. parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
  483.  
  484. a, y, c, caches = lstm_forward(x, a0, parameters)
  485. print("a[4][3][6] = ", a[4][3][6])
  486. print("a.shape = ", a.shape)
  487. print("y[1][4][3] =", y[1][4][3])
  488. print("y.shape = ", y.shape)
  489. print("caches[1][1[1]] =", caches[1][1][1])
  490. print("c[1][2][1]", c[1][2][1])
  491. print("len(caches) = ", len(caches))
  492.  
  493.  
  494.  
  495. # Congratulations! You have now implemented the forward passes for the basic RNN and the LSTM. When using a deep learning framework, implementing the forward pass is sufficient to build systems that achieve great performance.
  496. #
  497. # The rest of this notebook is optional, and will not be graded.
  498.  
  499. # ## 3 - Backpropagation in recurrent neural networks (OPTIONAL / UNGRADED)
  500. #
  501. # In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers do not need to bother with the details of the backward pass. If however you are an expert in calculus and want to see the details of backprop in RNNs, you can work through this optional portion of the notebook.
  502. #
  503. # When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in recurrent neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are quite complicated and we did not derive them in lecture. However, we will briefly present them below.
  504.  
  505. # ### 3.1 - Basic RNN  backward pass
  506. #
  507. # We will start by computing the backward pass for the basic RNN-cell.
  508. #
  509. # #### Deriving the one step backward functions:
  510. #
  511. # To compute the `rnn_cell_backward` you need to compute the following equations. It is a good exercise to derive them by hand.
  512. #
  513. # The derivative of $\tanh$ is $1-\tanh(x)^2$. You can find the complete proof [here](https://www.wyzant.com/resources/lessons/math/calculus/derivative_proofs/tanx). Note that: $ \text{sech}(x)^2 = 1 - \tanh(x)^2$
  514. #
  515. # Similarly for $\frac{ \partial a^{\langle t \rangle} } {\partial W_{ax}}, \frac{ \partial a^{\langle t \rangle} } {\partial W_{aa}},  \frac{ \partial a^{\langle t \rangle} } {\partial b}$, the derivative of  $\tanh(u)$ is $(1-\tanh(u)^2)du$.
  516. #
  517. # The final two equations also follow same rule and are derived using the $\tanh$ derivative. Note that the arrangement is done in a way to get the same dimensions to match.
  518.  
  519. # In[14]:
  520.  
  521. def rnn_cell_backward(da_next, cache):
  522.     """
  523.    Implements the backward pass for the RNN-cell (single time-step).
  524.  
  525.    Arguments:
  526.    da_next -- Gradient of loss with respect to next hidden state
  527.    cache -- python dictionary containing useful values (output of rnn_cell_forward())
  528.  
  529.    Returns:
  530.    gradients -- python dictionary containing:
  531.                        dx -- Gradients of input data, of shape (n_x, m)
  532.                        da_prev -- Gradients of previous hidden state, of shape (n_a, m)
  533.                        dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x)
  534.                        dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a)
  535.                        dba -- Gradients of bias vector, of shape (n_a, 1)
  536.    """
  537.    
  538.     # Retrieve values from cache
  539.     (a_next, a_prev, xt, parameters) = cache
  540.    
  541.     # Retrieve values from parameters
  542.     Wax = parameters["Wax"]
  543.     Waa = parameters["Waa"]
  544.     Wya = parameters["Wya"]
  545.     ba = parameters["ba"]
  546.     by = parameters["by"]
  547.  
  548.     ### START CODE HERE ###
  549.     # compute the gradient of tanh with respect to a_next (≈1 line)
  550.     dtanh = (1-a_next*a_next)*da_next
  551.  
  552.     # compute the gradient of the loss with respect to Wax (≈2 lines)
  553.     dxt = np.dot(Wax.T,dtanh)
  554.     dWax = np.dot(dtanh,xt.T)
  555.  
  556.     # compute the gradient with respect to Waa (≈2 lines)
  557.     da_prev = np.dot(Waa.T,dtanh)
  558.     dWaa = np.dot(dtanh,a_prev.T)
  559.  
  560.     # compute the gradient with respect to b (≈1 line)
  561.     dba = np.sum(dtanh,keepdims=True,axis=-1)
  562.  
  563.     ### END CODE HERE ###
  564.    
  565.     # Store the gradients in a python dictionary
  566.     gradients = {"dxt": dxt, "da_prev": da_prev, "dWax": dWax, "dWaa": dWaa, "dba": dba}
  567.    
  568.     return gradients
  569.  
  570.  
  571. # In[15]:
  572.  
  573. np.random.seed(1)
  574. xt = np.random.randn(3,10)
  575. a_prev = np.random.randn(5,10)
  576. Wax = np.random.randn(5,3)
  577. Waa = np.random.randn(5,5)
  578. Wya = np.random.randn(2,5)
  579. b = np.random.randn(5,1)
  580. by = np.random.randn(2,1)
  581. parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
  582.  
  583. a_next, yt, cache = rnn_cell_forward(xt, a_prev, parameters)
  584.  
  585. da_next = np.random.randn(5,10)
  586. gradients = rnn_cell_backward(da_next, cache)
  587. print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
  588. print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
  589. print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
  590. print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
  591. print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
  592. print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
  593. print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
  594. print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
  595. print("gradients[\"dba\"][4] =", gradients["dba"][4])
  596. print("gradients[\"dba\"].shape =", gradients["dba"].shape)
  597.  
  598.  
  599.  
  600. # #### Backward pass through the RNN
  601. #
  602. # Computing the gradients of the cost with respect to $a^{\langle t \rangle}$ at every time-step $t$ is useful because it is what helps the gradient backpropagate to the previous RNN-cell. To do so, you need to iterate through all the time steps starting at the end, and at each step, you increment the overall $db_a$, $dW_{aa}$, $dW_{ax}$ and you store $dx$.
  603. #
  604. # **Instructions**:
  605. #
  606. # Implement the `rnn_backward` function. Initialize the return variables with zeros first and then loop through all the time steps while calling the `rnn_cell_backward` at each time timestep, update the other variables accordingly.
  607.  
  608. # In[20]:
  609.  
  610. def rnn_backward(da, caches):
  611.     """
  612.    Implement the backward pass for a RNN over an entire sequence of input data.
  613.  
  614.    Arguments:
  615.    da -- Upstream gradients of all hidden states, of shape (n_a, m, T_x)
  616.    caches -- tuple containing information from the forward pass (rnn_forward)
  617.    
  618.    Returns:
  619.    gradients -- python dictionary containing:
  620.                        dx -- Gradient w.r.t. the input data, numpy-array of shape (n_x, m, T_x)
  621.                        da0 -- Gradient w.r.t the initial hidden state, numpy-array of shape (n_a, m)
  622.                        dWax -- Gradient w.r.t the input's weight matrix, numpy-array of shape (n_a, n_x)
  623.                        dWaa -- Gradient w.r.t the hidden state's weight matrix, numpy-arrayof shape (n_a, n_a)
  624.                        dba -- Gradient w.r.t the bias, of shape (n_a, 1)
  625.    """
  626.        
  627.     ### START CODE HERE ###
  628.    
  629.     # Retrieve values from the first cache (t=1) of caches (≈2 lines)
  630.    
  631.     (cache, x)= caches
  632.     (a1, a0, x1, parameters) = caches[0]
  633.    
  634.     # Retrieve dimensions from da's and x1's shapes (≈2 lines)
  635.     n_a, m, T_x = da.shape
  636.     n_x, m = x1.shape
  637.    
  638.     # initialize the gradients with the right sizes (≈6 lines)
  639.     dx = np.zeros((n_x,m,T-x))
  640.     dWax = np.zeros((n_a,n_x))
  641.     dWaa = np.zeros((n_a,n_a))
  642.     dba = np.zeros((n_a,1))
  643.     da0 = np.zeros((n_a,m))
  644.     da_prevt = np.zeros((n_a,m))
  645.    
  646.     # Loop through all the time steps
  647.     for t in reversed(range(T_x)):
  648.         # Compute gradients at time step t. Choose wisely the "da_next" and the "cache" to use in the backward propagation step. (≈1 line)
  649.         gradients = rnn_cell_backward(da[:,:,t]+da_prevt,caches[t])
  650.         # Retrieve derivatives from gradients (≈ 1 line)
  651.         dxt, da_prevt, dWaxt, dWaat, dbat = gradients["dxt"], gradients["da_prev"], gradients["dWax"], gradients["dWaa"], gradients["dba"]
  652.         # Increment global derivatives w.r.t parameters by adding their derivative at time-step t (≈4 lines)
  653.         dx[:, :, t] = dxt
  654.         dWax += dWax
  655.         dWaa += dWaa
  656.         dba += dbat
  657.        
  658.     # Set da0 to the gradient of a which has been backpropagated through all time-steps (≈1 line)
  659.     da0 = da_prevt
  660.     ### END CODE HERE ###
  661.  
  662.     # Store the gradients in a python dictionary
  663.     gradients = {"dx": dx, "da0": da0, "dWax": dWax, "dWaa": dWaa,"dba": dba}
  664.    
  665.     return gradients
  666.  
  667.  
  668. # In[21]:
  669.  
  670. np.random.seed(1)
  671. x = np.random.randn(3,10,4)
  672. a0 = np.random.randn(5,10)
  673. Wax = np.random.randn(5,3)
  674. Waa = np.random.randn(5,5)
  675. Wya = np.random.randn(2,5)
  676. ba = np.random.randn(5,1)
  677. by = np.random.randn(2,1)
  678. parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "ba": ba, "by": by}
  679. a, y, caches = rnn_forward(x, a0, parameters)
  680. da = np.random.randn(5, 10, 4)
  681. gradients = rnn_backward(da, caches)
  682.  
  683. print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
  684. print("gradients[\"dx\"].shape =", gradients["dx"].shape)
  685. print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
  686. print("gradients[\"da0\"].shape =", gradients["da0"].shape)
  687. print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
  688. print("gradients[\"dWax\"].shape =", gradients["dWax"].shape)
  689. print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
  690. print("gradients[\"dWaa\"].shape =", gradients["dWaa"].shape)
  691. print("gradients[\"dba\"][4] =", gradients["dba"][4])
  692. print("gradients[\"dba\"].shape =", gradients["dba"].shape)
  693.  
  694.  
  695.  
  696. # ## 3.2 - LSTM backward pass
  697.  
  698. # ### 3.2.1 One Step backward
  699. #
  700. # The LSTM backward pass is slighltly more complicated than the forward one. We have provided you with all the equations for the LSTM backward pass below. (If you enjoy calculus exercises feel free to try deriving these from scratch yourself.)
  701. #
  702. # ### 3.2.2 gate derivatives
  703. #
  704. # $$d \Gamma_o^{\langle t \rangle} = da_{next}*\tanh(c_{next}) * \Gamma_o^{\langle t \rangle}*(1-\Gamma_o^{\langle t \rangle})\tag{7}$$
  705. #
  706. # $$d\tilde c^{\langle t \rangle} = dc_{next}*\Gamma_u^{\langle t \rangle}+ \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * i_t * da_{next} * \tilde c^{\langle t \rangle} * (1-\tanh(\tilde c)^2) \tag{8}$$
  707. #
  708. # $$d\Gamma_u^{\langle t \rangle} = dc_{next}*\tilde c^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * \tilde c^{\langle t \rangle} * da_{next}*\Gamma_u^{\langle t \rangle}*(1-\Gamma_u^{\langle t \rangle})\tag{9}$$
  709. #
  710. # $$d\Gamma_f^{\langle t \rangle} = dc_{next}*\tilde c_{prev} + \Gamma_o^{\langle t \rangle} (1-\tanh(c_{next})^2) * c_{prev} * da_{next}*\Gamma_f^{\langle t \rangle}*(1-\Gamma_f^{\langle t \rangle})\tag{10}$$
  711. #
  712. # ### 3.2.3 parameter derivatives
  713. #
  714. # $$ dW_f = d\Gamma_f^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{11} $$
  715. # $$ dW_u = d\Gamma_u^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{12} $$
  716. # $$ dW_c = d\tilde c^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{13} $$
  717. # $$ dW_o = d\Gamma_o^{\langle t \rangle} * \begin{pmatrix} a_{prev} \\ x_t\end{pmatrix}^T \tag{14}$$
  718. #
  719. # To calculate $db_f, db_u, db_c, db_o$ you just need to sum across the horizontal (axis= 1) axis on $d\Gamma_f^{\langle t \rangle}, d\Gamma_u^{\langle t \rangle}, d\tilde c^{\langle t \rangle}, d\Gamma_o^{\langle t \rangle}$ respectively. Note that you should have the `keep_dims = True` option.
  720. #
  721. # Finally, you will compute the derivative with respect to the previous hidden state, previous memory state, and input.
  722. #
  723. # $$ da_{prev} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c^{\langle t \rangle} + W_o^T * d\Gamma_o^{\langle t \rangle} \tag{15}$$
  724. # Here, the weights for equations 13 are the first n_a, (i.e. $W_f = W_f[:n_a,:]$ etc...)
  725. #
  726. # $$ dc_{prev} = dc_{next}\Gamma_f^{\langle t \rangle} + \Gamma_o^{\langle t \rangle} * (1- \tanh(c_{next})^2)*\Gamma_f^{\langle t \rangle}*da_{next} \tag{16}$$
  727. # $$ dx^{\langle t \rangle} = W_f^T*d\Gamma_f^{\langle t \rangle} + W_u^T * d\Gamma_u^{\langle t \rangle}+ W_c^T * d\tilde c_t + W_o^T * d\Gamma_o^{\langle t \rangle}\tag{17} $$
  728. # where the weights for equation 15 are from n_a to the end, (i.e. $W_f = W_f[n_a:,:]$ etc...)
  729. #
  730. # **Exercise:** Implement `lstm_cell_backward` by implementing equations $7-17$ below. Good luck! :)
  731.  
  732. # In[22]:
  733.  
  734. def lstm_cell_backward(da_next, dc_next, cache):
  735.     """
  736.    Implement the backward pass for the LSTM-cell (single time-step).
  737.  
  738.    Arguments:
  739.    da_next -- Gradients of next hidden state, of shape (n_a, m)
  740.    dc_next -- Gradients of next cell state, of shape (n_a, m)
  741.    cache -- cache storing information from the forward pass
  742.  
  743.    Returns:
  744.    gradients -- python dictionary containing:
  745.                        dxt -- Gradient of input data at time-step t, of shape (n_x, m)
  746.                        da_prev -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
  747.                        dc_prev -- Gradient w.r.t. the previous memory state, of shape (n_a, m, T_x)
  748.                        dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
  749.                        dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
  750.                        dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
  751.                        dWo -- Gradient w.r.t. the weight matrix of the output gate, numpy array of shape (n_a, n_a + n_x)
  752.                        dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
  753.                        dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
  754.                        dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
  755.                        dbo -- Gradient w.r.t. biases of the output gate, of shape (n_a, 1)
  756.    """
  757.  
  758.     # Retrieve information from "cache"
  759.     (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) = cache
  760.    
  761.     ### START CODE HERE ###
  762.     # Retrieve dimensions from xt's and a_next's shape (≈2 lines)
  763.     n_x, m =xt.shape
  764.     n_a, m = a_next.shape
  765.    
  766.     # Compute gates related derivatives, you can find their values can be found by looking carefully at equations (7) to (10) (≈4 lines)
  767.     dot = da_next*np.tanh(c_next)*ot*(1-ot)
  768.     dcct = (dc_next*it+ot*(1-np.square(np.tanh(c_next)))*it*da_next)*(1-np.square(cct))
  769.     dit = (dc_next*cct+ot*(1-np.square(np.tanh(c_next)))*cct*da_next)*it*(1-it)
  770.     dft = (dc_next*c_prev+ot*(1-np.square(np.tanh(c_next)))*c_prev*da_next)*ft*(1-ft)
  771.    
  772.     # Code equations (7) to (10) (≈4 lines)
  773.     dit = None
  774.     dft = None
  775.     dot = None
  776.     dcct = None
  777.  
  778.     # Compute parameters related derivatives. Use equations (11)-(14) (≈8 lines)
  779.     dWf = np.dot(dft,np.concatenate((a_prev,xt), axis=0).T)
  780.     dWi = np.dot(dit,np.concatenate((a_prev,xt), axis=0).T)
  781.     dWc = np.dcct(dft,np.concatenate((a_prev,xt), axis=0).T)
  782.     dWo = np.dot(dot,np.concatenate((a_prev,xt), axis=0).T)
  783.     dbf = np.sum(dft, axis=1,keepdims=True)
  784.     dbi = np.sum(dcct, axis=1,keepdims=True)
  785.     dbc = np.sum(dft, axis=1,keepdims=True)
  786.     dbo = np.sum(dot, axis=1,keepdims=True)
  787.  
  788.     # Compute derivatives w.r.t previous hidden state, previous memory state and input. Use equations (15)-(17). (≈3 lines)
  789.     da_prev = np.dot(parameters["Wf"][:,:n_a].T,dft)+np.dot(parameters["Wi"][:,:n_a].T,dit)+np.dot(parameters["Wc"][:,:n_a].T,dcct)+np.dot(parameters["Wo"][:,:n_a].T,dot)
  790.     dc_prev = dc_next*ft+ot*(1-np.square(np.tanh(c_next)))*ft*da_next
  791.     dxt = np.dot(parameters["Wf"][:,:n_a].T,dft)+np.dot(parameters["Wi"][:,:n_a].T,dit)+np.dot(parameters["Wc"][:,:n_a].T,dcct)+np.dot(parameters["Wo"][:,:n_a].T,dot)
  792.     ### END CODE HERE ###
  793.    
  794.     # Save gradients in dictionary
  795.     gradients = {"dxt": dxt, "da_prev": da_prev, "dc_prev": dc_prev, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
  796.                 "dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
  797.  
  798.     return gradients
  799.  
  800.  
  801. # In[24]:
  802.  
  803. np.random.seed(1)
  804. xt = np.random.randn(3,10)
  805. a_prev = np.random.randn(5,10)
  806. c_prev = np.random.randn(5,10)
  807. Wf = np.random.randn(5, 5+3)
  808. bf = np.random.randn(5,1)
  809. Wi = np.random.randn(5, 5+3)
  810. bi = np.random.randn(5,1)
  811. Wo = np.random.randn(5, 5+3)
  812. bo = np.random.randn(5,1)
  813. Wc = np.random.randn(5, 5+3)
  814. bc = np.random.randn(5,1)
  815. Wy = np.random.randn(2,5)
  816. by = np.random.randn(2,1)
  817.  
  818. parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
  819.  
  820. a_next, c_next, yt, cache = lstm_cell_forward(xt, a_prev, c_prev, parameters)
  821.  
  822. da_next = np.random.randn(5,10)
  823. dc_next = np.random.randn(5,10)
  824. gradients = lstm_cell_backward(da_next, dc_next, cache)
  825. print("gradients[\"dxt\"][1][2] =", gradients["dxt"][1][2])
  826. print("gradients[\"dxt\"].shape =", gradients["dxt"].shape)
  827. print("gradients[\"da_prev\"][2][3] =", gradients["da_prev"][2][3])
  828. print("gradients[\"da_prev\"].shape =", gradients["da_prev"].shape)
  829. print("gradients[\"dc_prev\"][2][3] =", gradients["dc_prev"][2][3])
  830. print("gradients[\"dc_prev\"].shape =", gradients["dc_prev"].shape)
  831. print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
  832. print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
  833. print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
  834. print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
  835. print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
  836. print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
  837. print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
  838. print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
  839. print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
  840. print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
  841. print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
  842. print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
  843. print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
  844. print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
  845. print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
  846. print("gradients[\"dbo\"].shape =", gradients["dbo"].shape)
  847.  
  848.  
  849.  
  850. # ### 3.3 Backward pass through the LSTM RNN
  851. #
  852. # This part is very similar to the `rnn_backward` function you implemented above. You will first create variables of the same dimension as your return variables. You will then iterate over all the time steps starting from the end and call the one step function you implemented for LSTM at each iteration. You will then update the parameters by summing them individually. Finally return a dictionary with the new gradients.
  853. #
  854. # **Instructions**: Implement the `lstm_backward` function. Create a for loop starting from $T_x$ and going backward. For each step call `lstm_cell_backward` and update the your old gradients by adding the new gradients to them. Note that `dxt` is not updated but is stored.
  855.  
  856. # In[27]:
  857.  
  858. def lstm_backward(da, caches):
  859.    
  860.     """
  861.    Implement the backward pass for the RNN with LSTM-cell (over a whole sequence).
  862.  
  863.    Arguments:
  864.    da -- Gradients w.r.t the hidden states, numpy-array of shape (n_a, m, T_x)
  865.    dc -- Gradients w.r.t the memory states, numpy-array of shape (n_a, m, T_x)
  866.    caches -- cache storing information from the forward pass (lstm_forward)
  867.  
  868.    Returns:
  869.    gradients -- python dictionary containing:
  870.                        dx -- Gradient of inputs, of shape (n_x, m, T_x)
  871.                        da0 -- Gradient w.r.t. the previous hidden state, numpy array of shape (n_a, m)
  872.                        dWf -- Gradient w.r.t. the weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x)
  873.                        dWi -- Gradient w.r.t. the weight matrix of the update gate, numpy array of shape (n_a, n_a + n_x)
  874.                        dWc -- Gradient w.r.t. the weight matrix of the memory gate, numpy array of shape (n_a, n_a + n_x)
  875.                        dWo -- Gradient w.r.t. the weight matrix of the save gate, numpy array of shape (n_a, n_a + n_x)
  876.                        dbf -- Gradient w.r.t. biases of the forget gate, of shape (n_a, 1)
  877.                        dbi -- Gradient w.r.t. biases of the update gate, of shape (n_a, 1)
  878.                        dbc -- Gradient w.r.t. biases of the memory gate, of shape (n_a, 1)
  879.                        dbo -- Gradient w.r.t. biases of the save gate, of shape (n_a, 1)
  880.    """
  881.  
  882.     # Retrieve values from the first cache (t=1) of caches.
  883.     (caches, x) = caches
  884.     (a1, c1, a0, c0, f1, i1, cc1, o1, x1, parameters) = caches[0]
  885.    
  886.     ### START CODE HERE ###
  887.     # Retrieve dimensions from da's and x1's shapes (≈2 lines)
  888.     n_a, m, T_x = da.shape  
  889.     n_x, m = x1.shape  
  890.    
  891.     # initialize the gradients with the right sizes (≈12 lines)
  892.     dx = np.zeros((n_x, m, T_x))  
  893.     da0 = np.zeros((n_a, m))  
  894.     da_prevt = np.zeros((n_a, m))  
  895.     dc_prevt = np.zeros((n_a, m))  
  896.     dWf = np.zeros((n_a, n_a + n_x))  
  897.     dWi = np.zeros((n_a, n_a + n_x))  
  898.     dWc = np.zeros((n_a, n_a + n_x))  
  899.     dWo = np.zeros((n_a, n_a + n_x))  
  900.     dbf = np.zeros((n_a, 1))  
  901.     dbi = np.zeros((n_a, 1))  
  902.     dbc = np.zeros((n_a, 1))  
  903.     dbo = np.zeros((n_a, 1))  
  904.    
  905.    
  906.     # loop back over the whole sequence
  907.     for t in reversed(range(T_x)):
  908.         # Compute all gradients using lstm_cell_backward
  909.         gradients = lstm_cell_backward(da[:,:,t]+da_prevt,dc_prevt,caches[t])  
  910.         # Store or add the gradient to the parameters' previous step's gradient
  911.         dx[:, :, t] = gradients['dxt']  
  912.         dWf = dWf+gradients['dWf']  
  913.         dWi = dWi+gradients['dWi']  
  914.         dWc = dWc+gradients['dWc']  
  915.         dWo = dWo+gradients['dWo']  
  916.         dbf = dbf+gradients['dbf']  
  917.         dbi = dbi+gradients['dbi']  
  918.         dbc = dbc+gradients['dbc']  
  919.         dbo = dbo+gradients['dbo']  
  920.        
  921.        
  922.     # Set the first activation's gradient to the backpropagated gradient da_prev.
  923.     da0 = gradients['da_prev']  
  924.    
  925.     ### END CODE HERE ###
  926.  
  927.     # Store the gradients in a python dictionary
  928.     gradients = {"dx": dx, "da0": da0, "dWf": dWf,"dbf": dbf, "dWi": dWi,"dbi": dbi,
  929.                 "dWc": dWc,"dbc": dbc, "dWo": dWo,"dbo": dbo}
  930.    
  931.     return gradients
  932.  
  933.  
  934. # In[28]:
  935.  
  936. np.random.seed(1)
  937. x = np.random.randn(3,10,7)
  938. a0 = np.random.randn(5,10)
  939. Wf = np.random.randn(5, 5+3)
  940. bf = np.random.randn(5,1)
  941. Wi = np.random.randn(5, 5+3)
  942. bi = np.random.randn(5,1)
  943. Wo = np.random.randn(5, 5+3)
  944. bo = np.random.randn(5,1)
  945. Wc = np.random.randn(5, 5+3)
  946. bc = np.random.randn(5,1)
  947.  
  948. parameters = {"Wf": Wf, "Wi": Wi, "Wo": Wo, "Wc": Wc, "Wy": Wy, "bf": bf, "bi": bi, "bo": bo, "bc": bc, "by": by}
  949.  
  950. a, y, c, caches = lstm_forward(x, a0, parameters)
  951.  
  952. da = np.random.randn(5, 10, 4)
  953. gradients = lstm_backward(da, caches)
  954.  
  955. print("gradients[\"dx\"][1][2] =", gradients["dx"][1][2])
  956. print("gradients[\"dx\"].shape =", gradients["dx"].shape)
  957. print("gradients[\"da0\"][2][3] =", gradients["da0"][2][3])
  958. print("gradients[\"da0\"].shape =", gradients["da0"].shape)
  959. print("gradients[\"dWf\"][3][1] =", gradients["dWf"][3][1])
  960. print("gradients[\"dWf\"].shape =", gradients["dWf"].shape)
  961. print("gradients[\"dWi\"][1][2] =", gradients["dWi"][1][2])
  962. print("gradients[\"dWi\"].shape =", gradients["dWi"].shape)
  963. print("gradients[\"dWc\"][3][1] =", gradients["dWc"][3][1])
  964. print("gradients[\"dWc\"].shape =", gradients["dWc"].shape)
  965. print("gradients[\"dWo\"][1][2] =", gradients["dWo"][1][2])
  966. print("gradients[\"dWo\"].shape =", gradients["dWo"].shape)
  967. print("gradients[\"dbf\"][4] =", gradients["dbf"][4])
  968. print("gradients[\"dbf\"].shape =", gradients["dbf"].shape)
  969. print("gradients[\"dbi\"][4] =", gradients["dbi"][4])
  970. print("gradients[\"dbi\"].shape =", gradients["dbi"].shape)
  971. print("gradients[\"dbc\"][4] =", gradients["dbc"][4])
  972. print("gradients[\"dbc\"].shape =", gradients["dbc"].shape)
  973. print("gradients[\"dbo\"][4] =", gradients["dbo"][4])
  974. print("gradients[\"dbo\"].shape =", gradients["dbo"].shape)
  975.  
  976.  
  977.  
  978. # ### Congratulations !
  979. #
  980. # Congratulations on completing this assignment. You now understand how recurrent neural networks work!
  981. #
  982. # Lets go on to the next exercise, where you'll use an RNN to build a character-level language model.
  983. #
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement