![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Programming](https://towardsdatascience.com/category/programming/)
# Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch
Can a language model invent unique fantasy character names? Let's build it from scratch
[Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)
September 22, 202311 min read
![Source: pixabay.com](../images/000.jpeg)
Source: [pixabay.com](https://pixabay.com/illustrations/book-old-surreal-fantasy-pages-863418/)
To truly grasp the intricacies of [**Language Models**](https://en.wikipedia.org/wiki/Language_model#:~:text=A%20language%20model%20is%20a,feedforward%20neural%20networks%20and%20transformers.) (LM) and become familiar with their underlying principles, there is no other way than rolling up our sleeves and starting to write code. In this article, I present the creation of a [**Recurrent Neural Network**](https://en.wikipedia.org/wiki/Recurrent_neural_network) (RNN) built entirely from scratch, without the aid of any deep learning library.
Tensorflow, Keras, Pytorch make building deep and complex neural networks effortless. Undoubtedly, this is a great advantage for Machine Learning practitioners, however, this approach has the massive downside of leaving the functioning of those networks unclear as they happen "under the hood".
This is why today we will perform the inspiring exercise of building a Language Model using only the [Numpy Python](https://numpy.org/) library!
Learn this step by step with the interactive [Computer Science](https://roadmap.sh/computer-science) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.
## Understanding Recurrent Neural Networks and Language Models
Standard fully connected neural networks are not suited for [Natural Language Processing](https://en.wikipedia.org/wiki/Natural_language_processing) (NLP) tasks like text generation. The main reasons are:
  * For NLP tasks, input and outputs may take different forms and dimensions.
  * Standard neural networks don't simultaneously use features learned at different steps of the network.


The main breakthrough in AI application within the NLP field is undeniably represented by Recurrent Neural Networks (RNN).
RNNs are a class of artificial neural networks particularly well suited for NLP tasks and text generation. The reason for their efficacy lies in their ability of capturing sequential dependencies in data. Human language deeply relies on considering the context and linking the first words in a sentence to the last ones. Consider these sentences:
  1. _He said, "Teddy Roosevelt was the US President."_
  2. _He said, "Teddy bears are on sale!"_


The word "_Teddy_ " has a completely different meaning in the two sentences. We humans easily understand that by considering the context and the words written in the opposite part of the sentence. Surprisingly enough, **RNNs can do the same**!
### RNN Architecture
The architecture of RNNs is fairly straightforward. They are made of sequential cells, each one of them takes as input a word _x_ (or a single character), outputs a word/character _y_ , and passes an activation _a_ to the next cell.
![RNN flowchart. Image by the author.](../images/001.png)
RNN flowchart. Image by the author.
What happens inside a RNN cell is more interesting. The steps are the following:
  1. The activation of the previous cell is multiplied by some weights _W _aa_
  2. The input _x_ is multiplied by some weights _W _ax_
  3. The results of the previous steps are summed together and with a bias _b _a_
  4. An activation function like the hyperbolic tangent is applied to compute the activation which is passed to the next cell
  5. The activation is multiplied by some weights _W _ya_ and summed with a bias _b _y_
  6. Finally, a softmax function is applied to the resulting vector and the output _y _hat_ is returned


![RNN cell flowchart. Image by the author.](../images/002.png)
RNN cell flowchart. Image by the author.
To summarize, the formulas for the activation and output are as follows:
![](../images/body-3e5ec5f71fd305b75977.png)
![](../images/body-649b98898e981d7292b7.png)
I'm unable to provide a comprehensive theoretical introduction of RNNs and LMs here. For that, I refer you to the resources listed at the end of this article.
Let's dive now into the actual Python code. The most important parts of the code will be explained in detail in this article. In order to keep the article concise, some intuitive parts are omitted. The entire commented code can be accessed in my [GitHub repository](https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN):
> [**articles/names-generator-RNN at main · andreoniriccardo/articles**](https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN)
## Data Preparation
Our goal is to teach a Language Model to invent novel fantasy character names. For this reason, the first thing we need to provide our Language Model is a database of actual fantasy names. The LM will be trained and will take inspiration from that.
Thanks to this [Wikipedia page](https://en.wikipedia.org/wiki/List_of_Middle-earth_characters), we can easily access a list of all the characters mentioned in the _[Lord Of The Ring](https://en.wikipedia.org/wiki/The_Lord_of_the_Rings) _or_[The Hobbit](https://en.wikipedia.org/wiki/The_Hobbit)_ books. Using the [BeautifulSoup](https://pypi.org/project/beautifulsoup4/)and [Regex](https://docs.python.org/3/library/re.html) libraries, the following lines of code will collect the data:
python

```
from bs4 import BeautifulSoup
import requests
import re

url = "https://en.wikipedia.org/wiki/List_of_Middle-earth_characters"
# Get the contents of the webpage in text format
data  = requests.get(url).text

soup = BeautifulSoup(data,"html.parser")

# Parse the HTML code to isolate rows containing character names
names = soup.find_all('li')

# Apply a second filter to isolate actual names
names_2 = []
for i in names:
    if """<li><a href="/wiki/""" in str(i):
        names_2.append(str(i))

# Retrieve final character names applying cleaning conditions
lotr_names = []
for i in names_2:
    candidate_name = re.findall(r'"(.*?)"', i)[1]
    conditions = 'Category:' not in candidate_name and 'Middle-earth ' not in candidate_name and 'Tolkien' not in candidate_name and 'Lord of the Rings' not in candidate_name and 'The Hobbit' not in candidate_name
    if conditions:
        lotr_names.append(candidate_name.replace(' (Middle-earth)',''))

```

For the explanation of the Regex functions, I leave you with this comprehensive [guide](https://pub.towardsai.net/regex-for-the-modern-data-scientists-37bd528d343a).
At this point, our dataset will look like this:
![](../images/body-dcae09b9793e33989b3c.png)
I aim to simplify our vocabulary by replacing unwanted characters such as ä, é, î.
python

```
replace_dict = {'a':['â','ä','á'],
                'e':['ê','ë','é'],
                'i':['î','í'],
                'o':['ô','ö','ó'],
                'u':['ú','û',],
                ' ':['-']
}
for new_char in replace_dict.keys():
    for old_char in replace_dict[new_char]:
        lotr_names = lotr_names.replace(old_char, new_char)
```

Finally, our vocabulary consists in 27 characters:
_['x', 'j', 'f', 't', 'c', 'b', 'o', 'l', 'y', 'w', 'i', 'e', 'g', 'm', 'k', 'd', 'v', 'n', 'u', 'a', 'z', 'r', 'n', 's', ' ', 'p', 'h']_
Note that the special character _'n'_ serves as an End of Name token, indicating when the generated name should terminate.
The dataset is ready and we can now focus on modeling the Recurrent Neural Network.
## Building the Language Model
In this section, I present the Python implementation of the Language Model. The whole code can be divided into 2 sections:
  1. Forward Propagation
  2. Backprop


In the following sections, I will present the code that actually trains the model and how to generate fantasy character names.
### Forward Propagation
As illustrated above, a RNN is a network composed of multiple cells. It is advantageous to model a single RNN cell in Python and then integrate its output through multiple cells.
The code that models a single RNN cell is the following:
python

```
def RNN_forward_prop_step(parameters, a_prev, x):
    W_aa = parameters['W_aa']
    W_ax = parameters['W_ax']
    W_ya = parameters['W_ya']
    b_y = parameters['b_y']
    b = parameters['b']

    # Compute hidden state
    a_next = np.tanh(np.dot(W_ax, x) + np.dot(W_aa, a_prev) + b)

    # Compute log probabilities for next character
    p_t = softmax(np.dot(W_ya, a_next) + b_y)

    return a_next, p_t
```

As you can see, it is not complex at all. We simply take as input the model's parameters and multiply them by the cell's input and previous activation function. Finally, we apply the softmax function to return a vector of probabilities for what the output character should be.
The next step is to iterate through several RNN cells. This is exactly what the `RNN_roward_prop()` function does.
python

```
def RNN_forward_prop(X, Y, a0, parameters, vocab_size):

    x = {}
    a = {}
    y_hat = {}
    a[-1] = np.copy(a0)
    loss= 0

    # Iterate for the T timesteps
    for t in range(len(X)):

        # One-hot representation of the t-th character
        x[t] = np.zeros((vocab_size, 1))
        if X[t] != None:
            x[t][X[t]] = 1

        # Run one timestep of forward prop
        a[t], y_hat[t] = RNN_forward_prop_step(parameters, a[t-1], x[t])

        # Update loss function
        loss -= np.log(y_hat[t][Y[t],0])

    cache = (y_hat, a, x)

    return loss, cache
```

It calls the previous `RNN_roward_pro_step()` function _T_ times, where _T_ is the number of characters of the input word. At the end, a loss function and the output is returned.
### Backprop
Backprop, short for backward propagation, is the process of adjusting the network's weights to get closer and closer to the desired output, i.e. reducing the model loss function. This is done by applying gradient descent.
Detailing the formulas of gradient descent or other viable optimization algorithms is out of [this article](https://towardsdatascience.com/choose-the-right-optimization-algorithm-for-your-neural-network-cb86c15d7328)'s scope. I will leave instead with **this article** , which deals exactly with the selection of the right Optimization Algorithm for your Deep Networks.
> [**Choose the Right Optimization Algorithm for your Neural Network**](https://towardsdatascience.com/choose-the-right-optimization-algorithm-for-your-neural-network-cb86c15d7328)
The strategy I used to model the backprop flow is the same as the one for the forward propagation: code the backprop of a single RNN cell and iterate it multiple times.
python

```
def RNN_back_prop_step(d_y, grads, parameters, x, a, a_prev):

    grads['dW_ya'] += np.dot(d_y, a.T)
    grads['db_y'] += d_y
    da = np.dot(parameters['W_ya'].T, d_y) + grads['da_next']
    da_raw = (1 - a * a) * da
    grads['db'] += da_raw
    grads['dW_ax'] += np.dot(daraw, x.T)
    grads['dW_aa'] += np.dot(daraw, a_prev.T)
    grads['da_next'] = np.dot(parameters['W_aa'].T, daraw)
    return grads
```

The above function takes as input the output of the forward propagation and the previous gradients and it computes the updated gradients.
The ideration of the `RNN_back_prop_function()` function is performed with these lines of code:
python

```
def RNN_back_prop(X, Y, parameters, cache):
    # Initialize gradients as an empty dictionary
    grads = {}

    # Retrieve from cache and parameters
    (y_hat, a, x) = cache
    W_aa = parameters['W_aa']
    W_ax = parameters['W_ax']
    W_ya = parameters['W_ya']
    b_y = parameters['b_y']
    b = parameters['b']

    # Initialize gradients
    grads['dW_ax'], grads['dW_aa'], grads['dW_ya'] = np.zeros_like(W_ax), np.zeros_like(W_aa), np.zeros_like(W_ya)
    grads['db'], grads['db_y'] = np.zeros_like(b), np.zeros_like(b_y)
    grads['da_next'] = np.zeros_like(a[0])

    # Backpropagate through timesteps
    for t in reversed(range(len(X))):
        dy = np.copy(y_hat[t])
        dy[Y[t]] -= 1
        grads = RNN_back_prop_step(dy, grads, parameters, x[t], a[t], a[t-1])

    return grads, a
```

## Training the Language Model
At this point, all the model's components are set and ready to be executed. I wrote the following code to put together the functions we saw above.
python

```
def RNN_optimization(X, Y, a_prev, parameters, alpha, vocab_size):

    # 1. Forward propagation
    loss_now, cache = RNN_forward_prop(X, Y, a_prev, parameters, vocab_size)

    # 2. Backward propagation
    grads, a = RNN_back_prop(X, Y, parameters, cache)

    # 3. Clip gradients
    grads = clip_grads(grads, 10)

    # 4. Update parameters
    parameters = update_parameters(parameters, grads, alpha)

    return loss_now, parameters, a[len(X)-1]
```

The actual magic happens in the following code snipped. This is the main part of the whole algorithm and once this function is called, the Language Model will be trained.
python

```
def train_model(data, n_a=50, max_iter = 100000):
    # Get the list of characters
    chars = list(set(data))
    # Get the dictionary size (number of characters)
    vocab_size = len(chars)

    # Get encoding and decoding dictionaries
    chars_to_encoding = encode_chars(chars)
    encoding_to_chars = decode_chars(chars)

    # Get dataset as a list of names and strip, then shuffle the dataset
    data = data.split('n')
    data = [x.strip() for x in data]   
    np.random.shuffle(data) 

    # Define n_x, n_y parameters
    n_x, n_y = vocab_size, vocab_size

    # Initialize the hidden state
    # a_prev = initialize_hidden_state(n_a)
    a_prev = np.zeros((n_a, 1))

    # Initialize the parameters
    parameters = initialize_parameters(n_a, n_x, n_y)
    # for k in parameters.keys():
    #     print('{}: tipo {}, Datatype {}'.format(k, type(parameters[k]), parameters[k].dtype))
    # Get current loss function value
    loss_now = get_initial_loss(vocab_size, len(data))

    # Perform max_iter iteration to train the model's parameters
    for iter in range(max_iter):
        # print(iter)
        # Get the index of the name to pick
        name_idx = iter % len(data)
        example = data[name_idx]

        # Convert encoded and decoded example into a list
        example_chars = [char for char in example]
        example_encoded = [chars_to_encoding[char] for char in example]

        # Create training input X. The value None is used to consider the first input character
        # as a vector of zeros
        X = [None] + example_encoded

        # Create the label vector Y by appending the 'n' encoding to the end of the vector
        Y = example_encoded + [chars_to_encoding['n']]

        # Perform one step of the optimization cycle:
        # 1. Forward propagation
        # 2. Backward propagation
        # 3. Gradient clipping
        # 4. Parameters update

        loss_tmp, parameters, a_prev = RNN_optimization(X, Y, a_prev, parameters, alpha=0.01, vocab_size=vocab_size)
        # for k in parameters.keys():
        #     print('{}: tipo {}, Datatype {}'.format(k, type(parameters[k]), parameters[k].dtype))
        loss_now = smooth(loss_now, loss_tmp)

    return parameters
```

The result is a model able to mimics the creative process of Tolkien and effortlessly produce unique character names.
## Generating Fantasy Character Names
To sample novel character names from our trained Language Model, I developed two functions.
The `sample()` function takes as input the network's parameters and the vocabulary mapping the characters to numbers. The idea is to apply the forward propagation steps multiple times until either the _'n'_ special character is return, or we reach an upper bound for the number of generated characters (in this case set to 50).
Finally, it returns a list of indices that encode the generated fantasy character name.
python

```
def sample(parameters, chars_to_encoding):
    W_aa = parameters['W_aa']
    W_ax = parameters['W_ax']
    W_ya = parameters['W_ya']
    b_y = parameters['b_y']
    b = parameters['b']
    vocab_size = b_y.shape[0]
    n_a = W_aa.shape[1]

    x = np.zeros((vocab_size,))
    a_prev = np.zeros((n_a,))

    indices = []
    idx = -1 

    counter = 0
    newline_character = chars_to_encoding['n']

    while (idx != newline_character and counter != 50):
        a = np.tanh(np.dot(W_ax,x)+np.dot(W_aa,a_prev)+np.ravel(b))
        z = np.dot(W_ya,a) + np.ravel(b_y)
        y = softmax(z)

        idx = np.random.choice(list(chars_to_encoding.values()), p=np.ravel(y))
        indices.append(idx)    

        x = np.zeros((vocab_size,))
        x[idx] = 1

        a_prev = a

        counter +=1
        if (counter == 50):
            indices.append(chars_to_encoding['n'])
    return indices
```

To print the generated fantasy names in a human-readable form, we need to call the `get_sample()` function, which takes as input the list of indices previously generated and the decoding dictionary mapping indices to characters.
python

```
def get_sample(sample_ix, encoding_to_chars):
    txt = ''.join(encoding_to_chars[ix] for ix in sample_ix)
    txt = txt[0].upper() + txt[1:]
    return txt
```

With everything in place, you can now appreciate some original fantasy character names, as shown below:
![Image by the author.](../images/003.png)
Image by the author.
## Evaluating Model Performance
During the first phases of the training process, the model is still unable to effectively mimic Tolkien's style. If we sample random names at this stage we obtain pure gibberish such as:
  * "Orvnnvfufufiiubx" at iteration 2000 and loss 27.96
  * "Aotvux" at iteration 4000 and loss 26.43


We can clearly see how these names don't meet the iconic Middle Earth patterns and sounds. However, by letting the model learn the dataset features for a longer period of time, we start to obtain progressively more plausible generated names:
  * "Furun I" at iteration 14000 and loss 21.53
  * "Flutto Balger" at iteration 16000 and loss 21.11


Finally, the trained model seems to be able to emulate the characters' name style.
The improvement I described qualitatively can be also quantitatively visualized as follows.
By plotting the loss function through the iterations, we can clearly see how the [optimization algorithm](https://towardsdatascience.com/choose-the-right-optimization-algorithm-for-your-neural-network-cb86c15d7328) progressively tunes the weights and biases in the right direction.
![Image by the author.](../images/004.png)
Image by the author.
The oscillating behavior of the loss function is motivated by the fact that we are using a single training example in each iteration step to train the model. Using a larger batch would result in a smoother loss curve.
## Conclusion
In conclusion, building a Language Model for fantasy name generation has brought us several insights.
We discovered how RNNs and LMs are capable of appreciating sequential dependencies in the data, making them essential elements for NLP and all the tasks that involve text.
Moreover, I cannot enphasize more the importance of an hands-on approach to gain experience in any Data Science related subject. Studying the theory is fundamental, but provides you only half of what you need.
Finally, I want to stretch again the flexibility of the tool we just created. I recommend training it with a different set of names. Try using Disney character names or typical pet names as the input dataset and share what you generate with me!
* * *
If you liked this story, consider following me to be notified of my upcoming projects and articles!
Here are some of my past projects:
> [**Ensemble Learning with Scikit-Learn: A Friendly Introduction**](https://towardsdatascience.com/ensemble-learning-with-scikit-learn-a-friendly-introduction-5dd64650de6c)
> [**Euro Trip Optimization: Genetic Algorithms and Google Maps API Solve the Traveling Salesman Problem**](https://towardsdatascience.com/euro-trip-optimization-genetic-algorithms-and-google-maps-python-api-solve-the-traveling-salesman-4ad8e1548207)
> [**The Birth of Data Science: History's First Hypothesis Test & Python Insights**](https://towardsdatascience.com/the-birth-of-data-science-historys-first-hypothesis-test-python-insights-4745dccaf6d)
## Resources
  * [GitHub Repository](https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN)
  * [LOTR character names](https://www.behindthename.com/namesakes/list/tolkien/alpha)
  * [Deep Learning Course](https://www.coursera.org/specializations/deep-learning)
  * [Recurrent Neural Network](https://en.wikipedia.org/wiki/Recurrent_neural_network)
  * [BeautifulSoup](https://pypi.org/project/beautifulsoup4/)


## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-34347b17fbf8612c4a0c.jpeg)
Written By
## [Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)
[See all from Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)
[Fantasy](https://towardsdatascience.com/tag/fantasy/)[Hands On Tutorials](https://towardsdatascience.com/tag/hands-on-tutorials/)[Language Model](https://towardsdatascience.com/tag/language-model/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Programming](https://towardsdatascience.com/tag/programming/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fuse-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa%2F&title=Use%20Deep%20Learning%20to%20Generate%20Fantasy%20Names%3A%20Build%20a%20Language%20Model%20from%20Scratch)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fuse-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa%2F&title=Use%20Deep%20Learning%20to%20Generate%20Fantasy%20Names%3A%20Build%20a%20Language%20Model%20from%20Scratch)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fuse-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa%2F&text=Use%20Deep%20Learning%20to%20Generate%20Fantasy%20Names%3A%20Build%20a%20Language%20Model%20from%20Scratch)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/005.jpeg)](https://towardsdatascience.com/feature-engineering-examples-binning-numerical-features-7627149093d/)
## [Feature Engineering Examples: Binning Numerical Features](https://towardsdatascience.com/feature-engineering-examples-binning-numerical-features-7627149093d/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
How to use NumPy or Pandas to quickly bin numerical features
[Max Steele (they/them)](https://towardsdatascience.com/author/maxsteele731/)
April 5, 20215 min read
  * [![](../images/006.png)](https://towardsdatascience.com/all-you-need-to-know-to-build-your-first-llm-app-eb982c78ffac/)
## [All You Need to Know to Build Your First LLM App](https://towardsdatascience.com/all-you-need-to-know-to-build-your-first-llm-app-eb982c78ffac/)
[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)
A step-by-step tutorial to document loaders, embeddings, vector stores and prompt templates
[Dominik Polzer](https://towardsdatascience.com/author/dmnkplzr/)
June 22, 202327 min read
  * [![](../images/007.jpeg)](https://towardsdatascience.com/paper-explained-dino-emerging-properties-in-self-supervised-vision-transformers-f9386df266f1/)
## [Paper explained: DINO - Emerging Properties in Self-Supervised Vision Transformers](https://towardsdatascience.com/paper-explained-dino-emerging-properties-in-self-supervised-vision-transformers-f9386df266f1/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
In this story, I would love to give you a a good idea of how the DINO paper works and what makes it great. I've tried to keep the article...
[Leon Sick](https://towardsdatascience.com/author/leon.sick/)
December 1, 20216 min read
  * [![](../images/008.jpg)](https://towardsdatascience.com/sentiment-analysis-on-amazon-food-reviews-from-eda-to-deployment-f985c417b0c/)
## [Sentiment Analysis On Amazon Food Reviews: From EDA To Deployment](https://towardsdatascience.com/sentiment-analysis-on-amazon-food-reviews-from-eda-to-deployment-f985c417b0c/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Amazon.com, Inc., is an American multinational technology company based in Seattle, Washington. Amazon focuses on e-commerce, cloud...
[Arun Mohan](https://towardsdatascience.com/author/arunm8489/)
September 6, 202010 min read
  * [![](../images/009.jpeg)](https://towardsdatascience.com/a-conceptual-explanation-of-convolutional-neural-networks-cnns-ccd2e62f213b/)
## [A Conceptual Explanation of Convolutional Neural Networks (CNN's)](https://towardsdatascience.com/a-conceptual-explanation-of-convolutional-neural-networks-cnns-ccd2e62f213b/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
A gentle introduction into the inner workings of a popular algorithm used for computer vision purposes
[Vishnu Nair](https://towardsdatascience.com/author/vishnu-nair/)
June 7, 20216 min read
  * [![](../images/010.jpg)](https://towardsdatascience.com/linear-regression-algorithm-under-the-hood-math-for-non-mathematicians-c228d244e3f3/)
## [Linear Regression Algorithm -Under The Hood Math For Non-Mathematicians](https://towardsdatascience.com/linear-regression-algorithm-under-the-hood-math-for-non-mathematicians-c228d244e3f3/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
It is one of the oldest algorithms in the field of mathematics and statistics borrowed in machine learning.
[Kaushik Choudhury](https://towardsdatascience.com/author/kaushikthoughts/)
August 24, 20206 min read
  * [![](../images/011.jpeg)](https://towardsdatascience.com/the-remarkable-world-of-recommender-systems-bff4b9cbe6a7/)
## [The Remarkable world of Recommender Systems](https://towardsdatascience.com/the-remarkable-world-of-recommender-systems-bff4b9cbe6a7/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
An overview of the Recommendation systems and how they provide an effective form of targeted marketing.
[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)
May 9, 201910 min read
  * [![](../images/012.jpg)](https://towardsdatascience.com/getting-started-with-great-expectations-a-guide-to-data-validation-in-python-95a8ffc2b747/)
## [Getting Started with Great Expectations: A Guide to Data Validation in Python](https://towardsdatascience.com/getting-started-with-great-expectations-a-guide-to-data-validation-in-python-95a8ffc2b747/)
[Programming](https://towardsdatascience.com/category/programming/)
Learn how to prevent data quality issues with a few lines of code in Python
[Eugenia Anello](https://towardsdatascience.com/author/eugenia-anello/)
July 12, 20235 min read
  * [![](../images/body-63beb50f664a055ed739.jpg)](https://towardsdatascience.com/latest-picks-modern-recommender-systems-a8c09fea7db0/)
## [Latest picks: Modern Recommender Systems](https://towardsdatascience.com/latest-picks-modern-recommender-systems-a8c09fea7db0/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Your daily dose of data science
[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)
January 26, 20211 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
####  Recommended Articles 
Close
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ "How Relevance Models Foreshadowed Transformers for NLP")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ "Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ "The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs")
  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ "Does Your Company Have a Data Strategy?")


