Advertisement
ERENARD63

Dinosaur name generator RNN and LSTM

May 24th, 2018
705
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 26.88 KB | None | 0 0
  1.  
  2. # coding: utf-8
  3.  
  4. # # Character level language model - Dinosaurus land
  5. #
  6. # Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new breeds of dinosaurs and bringing them to life on earth, and your job is to give names to these dinosaurs. If a dinosaur does not like its name, it might go beserk, so choose wisely!
  7. #
  8. #
  9. #
  10. # Luckily you have learned some deep learning and you will use it to save the day. Your assistant has collected a list of all the dinosaur names they could find, and compiled them into this [dataset](dinos.txt). (Feel free to take a look by clicking the previous link.) To create new dinosaur names, you will build a character level language model to generate new names. Your algorithm will learn the different name patterns, and randomly generate new names. Hopefully this algorithm will keep you and your team safe from the dinosaurs' wrath!
  11. #
  12. # By completing this assignment you will learn:
  13. #
  14. # - How to store text data for processing using an RNN
  15. # - How to synthesize data, by sampling predictions at each time step and passing it to the next RNN-cell unit
  16. # - How to build a character-level text generation recurrent neural network
  17. # - Why clipping the gradients is important
  18. #
  19. # We will begin by loading in some functions that we have provided for you in `rnn_utils`. Specifically, you have access to functions such as `rnn_forward` and `rnn_backward` which are equivalent to those you've implemented in the previous assignment.
  20.  
  21. # In[4]:
  22.  
  23. import numpy as np
  24. from utils import *
  25. import random
  26.  
  27.  
  28. # ## 1 - Problem Statement
  29. #
  30. # ### 1.1 - Dataset and Preprocessing
  31. #
  32. # Run the following cell to read the dataset of dinosaur names, create a list of unique characters (such as a-z), and compute the dataset and vocabulary size.
  33.  
  34. # In[5]:
  35.  
  36. data = open('dinos.txt', 'r').read()
  37. data= data.lower()
  38. chars = list(set(data))
  39. data_size, vocab_size = len(data), len(chars)
  40. print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size))
  41.  
  42.  
  43. # The characters are a-z (26 characters) plus the "\n" (or newline character), which in this assignment plays a role similar to the `<EOS>` (or "End of sentence") token we had discussed in lecture, only here it indicates the end of the dinosaur name rather than the end of a sentence. In the cell below, we create a python dictionary (i.e., a hash table) to map each character to an index from 0-26. We also create a second python dictionary that maps each index back to the corresponding character character. This will help you figure out what index corresponds to what character in the probability distribution output of the softmax layer. Below, `char_to_ix` and `ix_to_char` are the python dictionaries.
  44.  
  45. # In[6]:
  46.  
  47. char_to_ix = { ch:i for i,ch in enumerate(sorted(chars)) }
  48. ix_to_char = { i:ch for i,ch in enumerate(sorted(chars)) }
  49. print(ix_to_char)
  50.  
  51.  
  52. # ### 1.2 - Overview of the model
  53. #
  54. # Your model will have the following structure:
  55. #
  56. # - Initialize parameters
  57. # - Run the optimization loop
  58. #     - Forward propagation to compute the loss function
  59. #     - Backward propagation to compute the gradients with respect to the loss function
  60. #     - Clip the gradients to avoid exploding gradients
  61. #     - Using the gradients, update your parameter with the gradient descent update rule.
  62. # - Return the learned parameters
  63. #
  64. # At each time-step, the RNN tries to predict what is the next character given the previous characters. The dataset $X = (x^{\langle 1 \rangle}, x^{\langle 2 \rangle}, ..., x^{\langle T_x \rangle})$ is a list of characters in the training set, while $Y = (y^{\langle 1 \rangle}, y^{\langle 2 \rangle}, ..., y^{\langle T_x \rangle})$ is such that at every time-step $t$, we have $y^{\langle t \rangle} = x^{\langle t+1 \rangle}$.
  65.  
  66. # ## 2 - Building blocks of the model
  67. #
  68. # In this part, you will build two important blocks of the overall model:
  69. # - Gradient clipping: to avoid exploding gradients
  70. # - Sampling: a technique used to generate characters
  71. #
  72. # You will then apply these two functions to build the model.
  73.  
  74. # ### 2.1 - Clipping the gradients in the optimization loop
  75. #
  76. # In this section you will implement the `clip` function that you will call inside of your optimization loop. Recall that your overall loop structure usually consists of a forward pass, a cost computation, a backward pass, and a parameter update. Before updating the parameters, you will perform gradient clipping when needed to make sure that your gradients are not "exploding," meaning taking on overly large values.
  77. #
  78. # In the exercise below, you will implement a function `clip` that takes in a dictionary of gradients and returns a clipped version of gradients if needed. There are different ways to clip gradients; we will use a simple element-wise clipping procedure, in which every element of the gradient vector is clipped to lie between some range [-N, N]. More generally, you will provide a `maxValue` (say 10). In this example, if any component of the gradient vector is greater than 10, it would be set to 10; and if any component of the gradient vector is less than -10, it would be set to -10. If it is between -10 and 10, it is left alone.
  79. #
  80. # **Exercise**: Implement the function below to return the clipped gradients of your dictionary `gradients`. Your function takes in a maximum threshold and returns the clipped versions of your gradients. You can check out this [hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.clip.html) for examples of how to clip in numpy. You will need to use the argument `out = ...`.
  81.  
  82. # In[7]:
  83.  
  84. ### GRADED FUNCTION: clip
  85.  
  86. def clip(gradients, maxValue):
  87.     '''
  88.    Clips the gradients' values between minimum and maximum.
  89.    
  90.    Arguments:
  91.    gradients -- a dictionary containing the gradients "dWaa", "dWax", "dWya", "db", "dby"
  92.    maxValue -- everything above this number is set to this number, and everything less than -maxValue is set to -maxValue
  93.    
  94.    Returns:
  95.    gradients -- a dictionary with the clipped gradients.
  96.    '''
  97.    
  98.     dWaa, dWax, dWya, db, dby = gradients['dWaa'], gradients['dWax'], gradients['dWya'], gradients['db'], gradients['dby']
  99.    
  100.     ### START CODE HERE ###
  101.     # clip to mitigate exploding gradients, loop over [dWax, dWaa, dWya, db, dby]. (≈2 lines)
  102.     for gradient in [dWax, dWaa, dWya, db, dby]:
  103.         np.clip(gradient,-maxValue,maxValue,gradient)
  104.     ### END CODE HERE ###
  105.    
  106.     gradients = {"dWaa": dWaa, "dWax": dWax, "dWya": dWya, "db": db, "dby": dby}
  107.    
  108.     return gradients
  109.  
  110.  
  111. # In[8]:
  112.  
  113. np.random.seed(3)
  114. dWax = np.random.randn(5,3)*10
  115. dWaa = np.random.randn(5,5)*10
  116. dWya = np.random.randn(2,5)*10
  117. db = np.random.randn(5,1)*10
  118. dby = np.random.randn(2,1)*10
  119. gradients = {"dWax": dWax, "dWaa": dWaa, "dWya": dWya, "db": db, "dby": dby}
  120. gradients = clip(gradients, 10)
  121. print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
  122. print("gradients[\"dWax\"][3][1] =", gradients["dWax"][3][1])
  123. print("gradients[\"dWya\"][1][2] =", gradients["dWya"][1][2])
  124. print("gradients[\"db\"][4] =", gradients["db"][4])
  125. print("gradients[\"dby\"][1] =", gradients["dby"][1])
  126.  
  127.  
  128.  
  129. # ### 2.2 - Sampling
  130. #
  131. # Now assume that your model is trained. You would like to generate new text (characters). The process of generation is explained in the picture below:
  132. #
  133. # <img src="images/dinos3.png" style="width:500;height:300px;">
  134. # <caption><center> **Figure 3**: In this picture, we assume the model is already trained. We pass in $x^{\langle 1\rangle} = \vec{0}$ at the first time step, and have the network then sample one character at a time. </center></caption>
  135. #
  136. # **Exercise**: Implement the `sample` function below to sample characters. You need to carry out 4 steps:
  137. #
  138. # - **Step 1**: Pass the network the first "dummy" input $x^{\langle 1 \rangle} = \vec{0}$ (the vector of zeros). This is the default input before we've generated any characters. We also set $a^{\langle 0 \rangle} = \vec{0}$
  139. #
  140. # - **Step 2**: Run one step of forward propagation to get $a^{\langle 1 \rangle}$ and $\hat{y}^{\langle 1 \rangle}$. Here are the equations:
  141. #
  142. # $$ a^{\langle t+1 \rangle} = \tanh(W_{ax}  x^{\langle t \rangle } + W_{aa} a^{\langle t \rangle } + b)\tag{1}$$
  143. #
  144. # $$ z^{\langle t + 1 \rangle } = W_{ya}  a^{\langle t + 1 \rangle } + b_y \tag{2}$$
  145. #
  146. # $$ \hat{y}^{\langle t+1 \rangle } = softmax(z^{\langle t + 1 \rangle })\tag{3}$$
  147. #
  148. # Note that $\hat{y}^{\langle t+1 \rangle }$ is a (softmax) probability vector (its entries are between 0 and 1 and sum to 1). $\hat{y}^{\langle t+1 \rangle}_i$ represents the probability that the character indexed by "i" is the next character.  We have provided a `softmax()` function that you can use.
  149. #
  150. # - **Step 3**: Carry out sampling: Pick the next character's index according to the probability distribution specified by $\hat{y}^{\langle t+1 \rangle }$. This means that if $\hat{y}^{\langle t+1 \rangle }_i = 0.16$, you will pick the index "i" with 16% probability. To implement it, you can use [`np.random.choice`](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.random.choice.html).
  151. #
  152. # Here is an example of how to use `np.random.choice()`:
  153. # ```python
  154. # np.random.seed(0)
  155. # p = np.array([0.1, 0.0, 0.7, 0.2])
  156. # index = np.random.choice([0, 1, 2, 3], p = p.ravel())
  157. # ```
  158. # This means that you will pick the `index` according to the distribution:
  159. # $P(index = 0) = 0.1, P(index = 1) = 0.0, P(index = 2) = 0.7, P(index = 3) = 0.2$.
  160. #
  161. # - **Step 4**: The last step to implement in `sample()` is to overwrite the variable `x`, which currently stores $x^{\langle t \rangle }$, with the value of $x^{\langle t + 1 \rangle }$. You will represent $x^{\langle t + 1 \rangle }$ by creating a one-hot vector corresponding to the character you've chosen as your prediction. You will then forward propagate $x^{\langle t + 1 \rangle }$ in Step 1 and keep repeating the process until you get a "\n" character, indicating you've reached the end of the dinosaur name.
  162.  
  163. # In[11]:
  164.  
  165. # GRADED FUNCTION: sample
  166.  
  167. def sample(parameters, char_to_ix, seed):
  168.     """
  169.    Sample a sequence of characters according to a sequence of probability distributions output of the RNN
  170.  
  171.    Arguments:
  172.    parameters -- python dictionary containing the parameters Waa, Wax, Wya, by, and b.
  173.    char_to_ix -- python dictionary mapping each character to an index.
  174.    seed -- used for grading purposes. Do not worry about it.
  175.  
  176.    Returns:
  177.    indices -- a list of length n containing the indices of the sampled characters.
  178.    """
  179.    
  180.     # Retrieve parameters and relevant shapes from "parameters" dictionary
  181.     Waa, Wax, Wya, by, b = parameters['Waa'], parameters['Wax'], parameters['Wya'], parameters['by'], parameters['b']
  182.     vocab_size = by.shape[0]
  183.     n_a = Waa.shape[1]
  184.    
  185.     ### START CODE HERE ###
  186.     # Step 1: Create the one-hot vector x for the first character (initializing the sequence generation). (≈1 line)
  187.     x = np.zeros((vocab_size,1))
  188.     # Step 1': Initialize a_prev as zeros (≈1 line)
  189.     a_prev = np.zeros((n_a,1))
  190.    
  191.     # Create an empty list of indices, this is the list which will contain the list of indices of the characters to generate (≈1 line)
  192.     indices = []
  193.    
  194.     # Idx is a flag to detect a newline character, we initialize it to -1
  195.     idx = -1
  196.    
  197.     # Loop over time-steps t. At each time-step, sample a character from a probability distribution and append
  198.     # its index to "indices". We'll stop if we reach 50 characters (which should be very unlikely with a well
  199.     # trained model), which helps debugging and prevents entering an infinite loop.
  200.     counter = 0
  201.     newline_character = char_to_ix['\n']
  202.    
  203.     while (idx != newline_character and counter != 50):
  204.        
  205.         # Step 2: Forward propagate x using the equations (1), (2) and (3)
  206.         a = np.tanh(np.dot(Wax,x)+np.dot(Waa,a_prev)+b)
  207.         z = np.dot(Wya,a)+by
  208.         y = softmax(z)
  209.        
  210.         # for grading purposes
  211.         np.random.seed(counter+seed)
  212.        
  213.         # Step 3: Sample the index of a character within the vocabulary from the probability distribution y
  214.         idx = np.random.choice(range(vocab_size), p = y.ravel())
  215.  
  216.         # Append the index to "indices"
  217.         indices.append(idx)
  218.        
  219.         # Step 4: Overwrite the input character as the one corresponding to the sampled index.
  220.         x = np.zeros((vocab_size,1))
  221.         x[idx] = 1
  222.        
  223.         # Update "a_prev" to be "a"
  224.         a_prev = a
  225.        
  226.         # for grading purposes
  227.         seed += 1
  228.         counter +=1
  229.        
  230.     ### END CODE HERE ###
  231.  
  232.     if (counter == 50):
  233.         indices.append(char_to_ix['\n'])
  234.    
  235.     return indices
  236.  
  237.  
  238. # In[12]:
  239.  
  240. np.random.seed(2)
  241. _, n_a = 20, 100
  242. Wax, Waa, Wya = np.random.randn(n_a, vocab_size), np.random.randn(n_a, n_a), np.random.randn(vocab_size, n_a)
  243. b, by = np.random.randn(n_a, 1), np.random.randn(vocab_size, 1)
  244. parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "b": b, "by": by}
  245.  
  246.  
  247. indices = sample(parameters, char_to_ix, 0)
  248. print("Sampling:")
  249. print("list of sampled indices:", indices)
  250. print("list of sampled characters:", [ix_to_char[i] for i in indices])
  251.  
  252.  
  253.  
  254.  
  255. # ## 3 - Building the language model
  256. #
  257. # It is time to build the character-level language model for text generation.
  258. #
  259. #
  260. # ### 3.1 - Gradient descent
  261. #
  262. # In this section you will implement a function performing one step of stochastic gradient descent (with clipped gradients). You will go through the training examples one at a time, so the optimization algorithm will be stochastic gradient descent. As a reminder, here are the steps of a common optimization loop for an RNN:
  263. #
  264. # - Forward propagate through the RNN to compute the loss
  265. # - Backward propagate through time to compute the gradients of the loss with respect to the parameters
  266. # - Clip the gradients if necessary
  267. # - Update your parameters using gradient descent
  268. #
  269. # **Exercise**: Implement this optimization process (one step of stochastic gradient descent).
  270. #
  271. # We provide you with the following functions:
  272. #
  273. # ```python
  274. # def rnn_forward(X, Y, a_prev, parameters):
  275. #     """ Performs the forward propagation through the RNN and computes the cross-entropy loss.
  276. #     It returns the loss' value as well as a "cache" storing values to be used in the backpropagation."""
  277. #     ....
  278. #     return loss, cache
  279. #    
  280. # def rnn_backward(X, Y, parameters, cache):
  281. #     """ Performs the backward propagation through time to compute the gradients of the loss with respect
  282. #     to the parameters. It returns also all the hidden states."""
  283. #     ...
  284. #     return gradients, a
  285. #
  286. # def update_parameters(parameters, gradients, learning_rate):
  287. #     """ Updates parameters using the Gradient Descent Update Rule."""
  288. #     ...
  289. #     return parameters
  290. # ```
  291.  
  292. # In[17]:
  293.  
  294. # GRADED FUNCTION: optimize
  295.  
  296. def optimize(X, Y, a_prev, parameters, learning_rate = 0.01):
  297.     """
  298.    Execute one step of the optimization to train the model.
  299.    
  300.    Arguments:
  301.    X -- list of integers, where each integer is a number that maps to a character in the vocabulary.
  302.    Y -- list of integers, exactly the same as X but shifted one index to the left.
  303.    a_prev -- previous hidden state.
  304.    parameters -- python dictionary containing:
  305.                        Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x)
  306.                        Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a)
  307.                        Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a)
  308.                        b --  Bias, numpy array of shape (n_a, 1)
  309.                        by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1)
  310.    learning_rate -- learning rate for the model.
  311.    
  312.    Returns:
  313.    loss -- value of the loss function (cross-entropy)
  314.    gradients -- python dictionary containing:
  315.                        dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x)
  316.                        dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a)
  317.                        dWya -- Gradients of hidden-to-output weights, of shape (n_y, n_a)
  318.                        db -- Gradients of bias vector, of shape (n_a, 1)
  319.                        dby -- Gradients of output bias vector, of shape (n_y, 1)
  320.    a[len(X)-1] -- the last hidden state, of shape (n_a, 1)
  321.    """
  322.    
  323.     ### START CODE HERE ###
  324.    
  325.     # Forward propagate through time (≈1 line)
  326.     loss, cache = rnn_forward(X, Y, a_prev, parameters)
  327.    
  328.     # Backpropagate through time (≈1 line)
  329.     gradients, a = rnn_backward(X, Y, parameters, cache)
  330.    
  331.     # Clip your gradients between -5 (min) and 5 (max) (≈1 line)
  332.     gradients = clip(gradients,5)
  333.    
  334.     # Update parameters (≈1 line)
  335.     parameters = update_parameters(parameters, gradients, learning_rate)
  336.    
  337.     ### END CODE HERE ###
  338.    
  339.     return loss, gradients, a[len(X)-1]
  340.  
  341.  
  342. # In[18]:
  343.  
  344. np.random.seed(1)
  345. vocab_size, n_a = 27, 100
  346. a_prev = np.random.randn(n_a, 1)
  347. Wax, Waa, Wya = np.random.randn(n_a, vocab_size), np.random.randn(n_a, n_a), np.random.randn(vocab_size, n_a)
  348. b, by = np.random.randn(n_a, 1), np.random.randn(vocab_size, 1)
  349. parameters = {"Wax": Wax, "Waa": Waa, "Wya": Wya, "b": b, "by": by}
  350. X = [12,3,5,11,22,3]
  351. Y = [4,14,11,22,25, 26]
  352.  
  353. loss, gradients, a_last = optimize(X, Y, a_prev, parameters, learning_rate = 0.01)
  354. print("Loss =", loss)
  355. print("gradients[\"dWaa\"][1][2] =", gradients["dWaa"][1][2])
  356. print("np.argmax(gradients[\"dWax\"]) =", np.argmax(gradients["dWax"]))
  357. print("gradients[\"dWya\"][1][2] =", gradients["dWya"][1][2])
  358. print("gradients[\"db\"][4] =", gradients["db"][4])
  359. print("gradients[\"dby\"][1] =", gradients["dby"][1])
  360. print("a_last[4] =", a_last[4])
  361.  
  362.  
  363. #
  364.  
  365. # ### 3.2 - Training the model
  366.  
  367. # Given the dataset of dinosaur names, we use each line of the dataset (one name) as one training example. Every 100 steps of stochastic gradient descent, you will sample 10 randomly chosen names to see how the algorithm is doing. Remember to shuffle the dataset, so that stochastic gradient descent visits the examples in random order.
  368. #
  369. # **Exercise**: Follow the instructions and implement `model()`. When `examples[index]` contains one dinosaur name (string), to create an example (X, Y), you can use this:
  370. # ```python
  371. #         index = j % len(examples)
  372. #         X = [None] + [char_to_ix[ch] for ch in examples[index]]
  373. #         Y = X[1:] + [char_to_ix["\n"]]
  374. # ```
  375. # Note that we use: `index= j % len(examples)`, where `j = 1....num_iterations`, to make sure that `examples[index]` is always a valid statement (`index` is smaller than `len(examples)`).
  376. # The first entry of `X` being `None` will be interpreted by `rnn_forward()` as setting $x^{\langle 0 \rangle} = \vec{0}$. Further, this ensures that `Y` is equal to `X` but shifted one step to the left, and with an additional "\n" appended to signify the end of the dinosaur name.
  377.  
  378. # In[22]:
  379.  
  380. # GRADED FUNCTION: model
  381.  
  382. def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27):
  383.     """
  384.    Trains the model and generates dinosaur names.
  385.    
  386.    Arguments:
  387.    data -- text corpus
  388.    ix_to_char -- dictionary that maps the index to a character
  389.    char_to_ix -- dictionary that maps a character to an index
  390.    num_iterations -- number of iterations to train the model for
  391.    n_a -- number of units of the RNN cell
  392.    dino_names -- number of dinosaur names you want to sample at each iteration.
  393.    vocab_size -- number of unique characters found in the text, size of the vocabulary
  394.    
  395.    Returns:
  396.    parameters -- learned parameters
  397.    """
  398.    
  399.     # Retrieve n_x and n_y from vocab_size
  400.     n_x, n_y = vocab_size, vocab_size
  401.    
  402.     # Initialize parameters
  403.     parameters = initialize_parameters(n_a, n_x, n_y)
  404.    
  405.     # Initialize loss (this is required because we want to smooth our loss, don't worry about it)
  406.     loss = get_initial_loss(vocab_size, dino_names)
  407.    
  408.     # Build list of all dinosaur names (training examples).
  409.     with open("dinos.txt") as f:
  410.         examples = f.readlines()
  411.     examples = [x.lower().strip() for x in examples]
  412.    
  413.     # Shuffle list of all dinosaur names
  414.     np.random.seed(0)
  415.     np.random.shuffle(examples)
  416.    
  417.     # Initialize the hidden state of your LSTM
  418.     a_prev = np.zeros((n_a, 1))
  419.    
  420.     # Optimization loop
  421.     for j in range(num_iterations):
  422.        
  423.         ### START CODE HERE ###
  424.        
  425.         # Use the hint above to define one training example (X,Y) (≈ 2 lines)
  426.         index = j % len(examples)
  427.         X = [None] + [char_to_ix[ch] for ch in examples[index]]
  428.         Y = X[1:] + [char_to_ix["\n"]]
  429.        
  430.         # Perform one optimization step: Forward-prop -> Backward-prop -> Clip -> Update parameters
  431.         # Choose a learning rate of 0.01
  432.         curr_loss, gradients, a_prev = optimize(X,Y,a_prev,parameters,learning_rate=0.01)
  433.        
  434.         ### END CODE HERE ###
  435.        
  436.         # Use a latency trick to keep the loss smooth. It happens here to accelerate the training.
  437.         loss = smooth(loss, curr_loss)
  438.  
  439.         # Every 2000 Iteration, generate "n" characters thanks to sample() to check if the model is learning properly
  440.         if j % 2000 == 0:
  441.            
  442.             print('Iteration: %d, Loss: %f' % (j, loss) + '\n')
  443.            
  444.             # The number of dinosaur names to print
  445.             seed = 0
  446.             for name in range(dino_names):
  447.                
  448.                 # Sample indices and print them
  449.                 sampled_indices = sample(parameters, char_to_ix, seed)
  450.                 print_sample(sampled_indices, ix_to_char)
  451.                
  452.                 seed += 1  # To get the same result for grading purposed, increment the seed by one.
  453.      
  454.             print('\n')
  455.        
  456.     return parameters
  457.  
  458.  
  459. # Run the following cell, you should observe your model outputting random-looking characters at the first iteration. After a few thousand iterations, your model should learn to generate reasonable-looking names.
  460.  
  461. # In[23]:
  462.  
  463. parameters = model(data, ix_to_char, char_to_ix)
  464.  
  465.  
  466. # ## Conclusion
  467. #
  468. # You can see that your algorithm has started to generate plausible dinosaur names towards the end of the training. At first, it was generating random characters, but towards the end you could see dinosaur names with cool endings. Feel free to run the algorithm even longer and play with hyperparameters to see if you can get even better results. Our implemetation generated some really cool names like `maconucon`, `marloralus` and `macingsersaurus`. Your model hopefully also learned that dinosaur names tend to end in `saurus`, `don`, `aura`, `tor`, etc.
  469. #
  470. # If your model generates some non-cool names, don't blame the model entirely--not all actual dinosaur names sound cool. (For example, `dromaeosauroides` is an actual dinosaur name and is in the training set.) But this model should give you a set of candidates from which you can pick the coolest!
  471. #
  472. # This assignment had used a relatively small dataset, so that you could train an RNN quickly on a CPU. Training a model of the english language requires a much bigger dataset, and usually needs much more computation, and could run for many hours on GPUs. We ran our dinosaur name for quite some time, and so far our favoriate name is the great, undefeatable, and fierce: Mangosaurus!
  473. #
  474. # <img src="images/mangosaurus.jpeg" style="width:250;height:300px;">
  475.  
  476. # ## 4 - Writing like Shakespeare
  477. #
  478. # The rest of this notebook is optional and is not graded, but we hope you'll do it anyway since it's quite fun and informative.
  479. #
  480. # A similar (but more complicated) task is to generate Shakespeare poems. Instead of learning from a dataset of Dinosaur names you can use a collection of Shakespearian poems. Using LSTM cells, you can learn longer term dependencies that span many characters in the text--e.g., where a character appearing somewhere a sequence can influence what should be a different character much much later in ths sequence. These long term dependencies were less important with dinosaur names, since the names were quite short.
  481. #
  482. #
  483. # <img src="images/shakespeare.jpg" style="width:500;height:400px;">
  484. # <caption><center> Let's become poets! </center></caption>
  485. #
  486. # We have implemented a Shakespeare poem generator with Keras. Run the following cell to load the required packages and models. This may take a few minutes.
  487.  
  488. # In[24]:
  489.  
  490. from __future__ import print_function
  491. from keras.callbacks import LambdaCallback
  492. from keras.models import Model, load_model, Sequential
  493. from keras.layers import Dense, Activation, Dropout, Input, Masking
  494. from keras.layers import LSTM
  495. from keras.utils.data_utils import get_file
  496. from keras.preprocessing.sequence import pad_sequences
  497. from shakespeare_utils import *
  498. import sys
  499. import io
  500.  
  501.  
  502. # To save you some time, we have already trained a model for ~1000 epochs on a collection of Shakespearian poems called [*"The Sonnets"*](shakespeare.txt).
  503.  
  504. # Let's train the model for one more epoch. When it finishes training for an epoch---this will also take a few minutes---you can run `generate_output`, which will prompt asking you for an input (`<`40 characters). The poem will start with your sentence, and our RNN-Shakespeare will complete the rest of the poem for you! For example, try "Forsooth this maketh no sense " (don't enter the quotation marks). Depending on whether you include the space at the end, your results might also differ--try it both ways, and try other inputs as well.
  505. #
  506.  
  507. # In[25]:
  508.  
  509. print_callback = LambdaCallback(on_epoch_end=on_epoch_end)
  510.  
  511. model.fit(x, y, batch_size=128, epochs=1, callbacks=[print_callback])
  512.  
  513.  
  514. # In[ ]:
  515.  
  516. # Run this cell to try with different inputs without having to re-train the model
  517. generate_output()
  518.  
  519.  
  520. # The RNN-Shakespeare model is very similar to the one you have built for dinosaur names. The only major differences are:
  521. # - LSTMs instead of the basic RNN to capture longer-range dependencies
  522. # - The model is a deeper, stacked LSTM model (2 layer)
  523. # - Using Keras instead of python to simplify the code
  524. #
  525. # If you want to learn more, you can also check out the Keras Team's text generation implementation on GitHub: https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py.
  526. #
  527. # Congratulations on finishing this notebook!
  528.  
  529. # **References**:
  530. # - This exercise took inspiration from Andrej Karpathy's implementation: https://gist.github.com/karpathy/d4dee566867f8291f086. To learn more about text generation, also check out Karpathy's [blog post](http://karpathy.github.io/2015/05/21/rnn-effectiveness/).
  531. # - For the Shakespearian poem generator, our implementation was based on the implementation of an LSTM text generator by the Keras team: https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py
  532.  
  533. # In[ ]:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement