{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Riccardo Andreoni",
  "title_listed": "Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch",
  "keywords": "",
  "domain": "文本处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/use-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa/",
  "publish_date": "2023-09-22",
  "corpus_stage": "",
  "notes": "",
  "id": "d76e8540089f",
  "collected_at": "2026-10-02T03:28:07",
  "title": "Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Programming](https://towardsdatascience.com/category/programming/)\n# Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch\nCan a language model invent unique fantasy character names? Let's build it from scratch\n[Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\nSeptember 22, 202311 min read\n![Source: pixabay.com](../images/000.jpeg)\nSource: [pixabay.com](https://pixabay.com/illustrations/book-old-surreal-fantasy-pages-863418/)\nTo 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.\nTensorflow, 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\".\nThis is why today we will perform the inspiring exercise of building a Language Model using only the [Numpy Python](https://numpy.org/) library!\nLearn this step by step with the interactive [Computer Science](https://roadmap.sh/computer-science) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n## Understanding Recurrent Neural Networks and Language Models\nStandard 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:\n  * For NLP tasks, input and outputs may take different forms and dimensions.\n  * Standard neural networks don't simultaneously use features learned at different steps of the network.\n\n\nThe main breakthrough in AI application within the NLP field is undeniably represented by Recurrent Neural Networks (RNN).\nRNNs 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:\n  1. _He said, \"Teddy Roosevelt was the US President.\"_\n  2. _He said, \"Teddy bears are on sale!\"_\n\n\nThe 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**!\n### RNN Architecture\nThe 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.\n![RNN flowchart. Image by the author.](../images/001.png)\nRNN flowchart. Image by the author.\nWhat happens inside a RNN cell is more interesting. The steps are the following:\n  1. The activation of the previous cell is multiplied by some weights _W _aa_\n  2. The input _x_ is multiplied by some weights _W _ax_\n  3. The results of the previous steps are summed together and with a bias _b _a_\n  4. An activation function like the hyperbolic tangent is applied to compute the activation which is passed to the next cell\n  5. The activation is multiplied by some weights _W _ya_ and summed with a bias _b _y_\n  6. Finally, a softmax function is applied to the resulting vector and the output _y _hat_ is returned\n\n\n![RNN cell flowchart. Image by the author.](../images/002.png)\nRNN cell flowchart. Image by the author.\nTo summarize, the formulas for the activation and output are as follows:\n![](../images/body-3e5ec5f71fd305b75977.png)\n![](../images/body-649b98898e981d7292b7.png)\nI'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.\nLet'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):\n> [**articles/names-generator-RNN at main · andreoniriccardo/articles**](https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN)\n## Data Preparation\nOur 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.\nThanks 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:\npython\n\n```\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\n\nurl = \"https://en.wikipedia.org/wiki/List_of_Middle-earth_characters\"\n# Get the contents of the webpage in text format\ndata  = requests.get(url).text\n\nsoup = BeautifulSoup(data,\"html.parser\")\n\n# Parse the HTML code to isolate rows containing character names\nnames = soup.find_all('li')\n\n# Apply a second filter to isolate actual names\nnames_2 = []\nfor i in names:\n    if \"\"\"<li><a href=\"/wiki/\"\"\" in str(i):\n        names_2.append(str(i))\n\n# Retrieve final character names applying cleaning conditions\nlotr_names = []\nfor i in names_2:\n    candidate_name = re.findall(r'\"(.*?)\"', i)[1]\n    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\n    if conditions:\n        lotr_names.append(candidate_name.replace(' (Middle-earth)',''))\n\n```\n\nFor the explanation of the Regex functions, I leave you with this comprehensive [guide](https://pub.towardsai.net/regex-for-the-modern-data-scientists-37bd528d343a).\nAt this point, our dataset will look like this:\n![](../images/body-dcae09b9793e33989b3c.png)\nI aim to simplify our vocabulary by replacing unwanted characters such as ä, é, î.\npython\n\n```\nreplace_dict = {'a':['â','ä','á'],\n                'e':['ê','ë','é'],\n                'i':['î','í'],\n                'o':['ô','ö','ó'],\n                'u':['ú','û',],\n                ' ':['-']\n}\nfor new_char in replace_dict.keys():\n    for old_char in replace_dict[new_char]:\n        lotr_names = lotr_names.replace(old_char, new_char)\n```\n\nFinally, our vocabulary consists in 27 characters:\n_['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']_\nNote that the special character _'n'_ serves as an End of Name token, indicating when the generated name should terminate.\nThe dataset is ready and we can now focus on modeling the Recurrent Neural Network.\n## Building the Language Model\nIn this section, I present the Python implementation of the Language Model. The whole code can be divided into 2 sections:\n  1. Forward Propagation\n  2. Backprop\n\n\nIn the following sections, I will present the code that actually trains the model and how to generate fantasy character names.\n### Forward Propagation\nAs 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.\nThe code that models a single RNN cell is the following:\npython\n\n```\ndef RNN_forward_prop_step(parameters, a_prev, x):\n    W_aa = parameters['W_aa']\n    W_ax = parameters['W_ax']\n    W_ya = parameters['W_ya']\n    b_y = parameters['b_y']\n    b = parameters['b']\n\n    # Compute hidden state\n    a_next = np.tanh(np.dot(W_ax, x) + np.dot(W_aa, a_prev) + b)\n\n    # Compute log probabilities for next character\n    p_t = softmax(np.dot(W_ya, a_next) + b_y)\n\n    return a_next, p_t\n```\n\nAs 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.\nThe next step is to iterate through several RNN cells. This is exactly what the `RNN_roward_prop()` function does.\npython\n\n```\ndef RNN_forward_prop(X, Y, a0, parameters, vocab_size):\n\n    x = {}\n    a = {}\n    y_hat = {}\n    a[-1] = np.copy(a0)\n    loss= 0\n\n    # Iterate for the T timesteps\n    for t in range(len(X)):\n\n        # One-hot representation of the t-th character\n        x[t] = np.zeros((vocab_size, 1))\n        if X[t] != None:\n            x[t][X[t]] = 1\n\n        # Run one timestep of forward prop\n        a[t], y_hat[t] = RNN_forward_prop_step(parameters, a[t-1], x[t])\n\n        # Update loss function\n        loss -= np.log(y_hat[t][Y[t],0])\n\n    cache = (y_hat, a, x)\n\n    return loss, cache\n```\n\nIt 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.\n### Backprop\nBackprop, 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.\nDetailing 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.\n> [**Choose the Right Optimization Algorithm for your Neural Network**](https://towardsdatascience.com/choose-the-right-optimization-algorithm-for-your-neural-network-cb86c15d7328)\nThe 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.\npython\n\n```\ndef RNN_back_prop_step(d_y, grads, parameters, x, a, a_prev):\n\n    grads['dW_ya'] += np.dot(d_y, a.T)\n    grads['db_y'] += d_y\n    da = np.dot(parameters['W_ya'].T, d_y) + grads['da_next']\n    da_raw = (1 - a * a) * da\n    grads['db'] += da_raw\n    grads['dW_ax'] += np.dot(daraw, x.T)\n    grads['dW_aa'] += np.dot(daraw, a_prev.T)\n    grads['da_next'] = np.dot(parameters['W_aa'].T, daraw)\n    return grads\n```\n\nThe above function takes as input the output of the forward propagation and the previous gradients and it computes the updated gradients.\nThe ideration of the `RNN_back_prop_function()` function is performed with these lines of code:\npython\n\n```\ndef RNN_back_prop(X, Y, parameters, cache):\n    # Initialize gradients as an empty dictionary\n    grads = {}\n\n    # Retrieve from cache and parameters\n    (y_hat, a, x) = cache\n    W_aa = parameters['W_aa']\n    W_ax = parameters['W_ax']\n    W_ya = parameters['W_ya']\n    b_y = parameters['b_y']\n    b = parameters['b']\n\n    # Initialize gradients\n    grads['dW_ax'], grads['dW_aa'], grads['dW_ya'] = np.zeros_like(W_ax), np.zeros_like(W_aa), np.zeros_like(W_ya)\n    grads['db'], grads['db_y'] = np.zeros_like(b), np.zeros_like(b_y)\n    grads['da_next'] = np.zeros_like(a[0])\n\n    # Backpropagate through timesteps\n    for t in reversed(range(len(X))):\n        dy = np.copy(y_hat[t])\n        dy[Y[t]] -= 1\n        grads = RNN_back_prop_step(dy, grads, parameters, x[t], a[t], a[t-1])\n\n    return grads, a\n```\n\n## Training the Language Model\nAt 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.\npython\n\n```\ndef RNN_optimization(X, Y, a_prev, parameters, alpha, vocab_size):\n\n    # 1. Forward propagation\n    loss_now, cache = RNN_forward_prop(X, Y, a_prev, parameters, vocab_size)\n\n    # 2. Backward propagation\n    grads, a = RNN_back_prop(X, Y, parameters, cache)\n\n    # 3. Clip gradients\n    grads = clip_grads(grads, 10)\n\n    # 4. Update parameters\n    parameters = update_parameters(parameters, grads, alpha)\n\n    return loss_now, parameters, a[len(X)-1]\n```\n\nThe 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.\npython\n\n```\ndef train_model(data, n_a=50, max_iter = 100000):\n    # Get the list of characters\n    chars = list(set(data))\n    # Get the dictionary size (number of characters)\n    vocab_size = len(chars)\n\n    # Get encoding and decoding dictionaries\n    chars_to_encoding = encode_chars(chars)\n    encoding_to_chars = decode_chars(chars)\n\n    # Get dataset as a list of names and strip, then shuffle the dataset\n    data = data.split('n')\n    data = [x.strip() for x in data]   \n    np.random.shuffle(data) \n\n    # Define n_x, n_y parameters\n    n_x, n_y = vocab_size, vocab_size\n\n    # Initialize the hidden state\n    # a_prev = initialize_hidden_state(n_a)\n    a_prev = np.zeros((n_a, 1))\n\n    # Initialize the parameters\n    parameters = initialize_parameters(n_a, n_x, n_y)\n    # for k in parameters.keys():\n    #     print('{}: tipo {}, Datatype {}'.format(k, type(parameters[k]), parameters[k].dtype))\n    # Get current loss function value\n    loss_now = get_initial_loss(vocab_size, len(data))\n\n    # Perform max_iter iteration to train the model's parameters\n    for iter in range(max_iter):\n        # print(iter)\n        # Get the index of the name to pick\n        name_idx = iter % len(data)\n        example = data[name_idx]\n\n        # Convert encoded and decoded example into a list\n        example_chars = [char for char in example]\n        example_encoded = [chars_to_encoding[char] for char in example]\n\n        # Create training input X. The value None is used to consider the first input character\n        # as a vector of zeros\n        X = [None] + example_encoded\n\n        # Create the label vector Y by appending the 'n' encoding to the end of the vector\n        Y = example_encoded + [chars_to_encoding['n']]\n\n        # Perform one step of the optimization cycle:\n        # 1. Forward propagation\n        # 2. Backward propagation\n        # 3. Gradient clipping\n        # 4. Parameters update\n\n        loss_tmp, parameters, a_prev = RNN_optimization(X, Y, a_prev, parameters, alpha=0.01, vocab_size=vocab_size)\n        # for k in parameters.keys():\n        #     print('{}: tipo {}, Datatype {}'.format(k, type(parameters[k]), parameters[k].dtype))\n        loss_now = smooth(loss_now, loss_tmp)\n\n    return parameters\n```\n\nThe result is a model able to mimics the creative process of Tolkien and effortlessly produce unique character names.\n## Generating Fantasy Character Names\nTo sample novel character names from our trained Language Model, I developed two functions.\nThe `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).\nFinally, it returns a list of indices that encode the generated fantasy character name.\npython\n\n```\ndef sample(parameters, chars_to_encoding):\n    W_aa = parameters['W_aa']\n    W_ax = parameters['W_ax']\n    W_ya = parameters['W_ya']\n    b_y = parameters['b_y']\n    b = parameters['b']\n    vocab_size = b_y.shape[0]\n    n_a = W_aa.shape[1]\n\n    x = np.zeros((vocab_size,))\n    a_prev = np.zeros((n_a,))\n\n    indices = []\n    idx = -1 \n\n    counter = 0\n    newline_character = chars_to_encoding['n']\n\n    while (idx != newline_character and counter != 50):\n        a = np.tanh(np.dot(W_ax,x)+np.dot(W_aa,a_prev)+np.ravel(b))\n        z = np.dot(W_ya,a) + np.ravel(b_y)\n        y = softmax(z)\n\n        idx = np.random.choice(list(chars_to_encoding.values()), p=np.ravel(y))\n        indices.append(idx)    \n\n        x = np.zeros((vocab_size,))\n        x[idx] = 1\n\n        a_prev = a\n\n        counter +=1\n        if (counter == 50):\n            indices.append(chars_to_encoding['n'])\n    return indices\n```\n\nTo 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.\npython\n\n```\ndef get_sample(sample_ix, encoding_to_chars):\n    txt = ''.join(encoding_to_chars[ix] for ix in sample_ix)\n    txt = txt[0].upper() + txt[1:]\n    return txt\n```\n\nWith everything in place, you can now appreciate some original fantasy character names, as shown below:\n![Image by the author.](../images/003.png)\nImage by the author.\n## Evaluating Model Performance\nDuring 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:\n  * \"Orvnnvfufufiiubx\" at iteration 2000 and loss 27.96\n  * \"Aotvux\" at iteration 4000 and loss 26.43\n\n\nWe 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:\n  * \"Furun I\" at iteration 14000 and loss 21.53\n  * \"Flutto Balger\" at iteration 16000 and loss 21.11\n\n\nFinally, the trained model seems to be able to emulate the characters' name style.\nThe improvement I described qualitatively can be also quantitatively visualized as follows.\nBy 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.\n![Image by the author.](../images/004.png)\nImage by the author.\nThe 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.\n## Conclusion\nIn conclusion, building a Language Model for fantasy name generation has brought us several insights.\nWe 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.\nMoreover, 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.\nFinally, 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!\n* * *\nIf you liked this story, consider following me to be notified of my upcoming projects and articles!\nHere are some of my past projects:\n> [**Ensemble Learning with Scikit-Learn: A Friendly Introduction**](https://towardsdatascience.com/ensemble-learning-with-scikit-learn-a-friendly-introduction-5dd64650de6c)\n> [**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)\n> [**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)\n## Resources\n  * [GitHub Repository](https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN)\n  * [LOTR character names](https://www.behindthename.com/namesakes/list/tolkien/alpha)\n  * [Deep Learning Course](https://www.coursera.org/specializations/deep-learning)\n  * [Recurrent Neural Network](https://en.wikipedia.org/wiki/Recurrent_neural_network)\n  * [BeautifulSoup](https://pypi.org/project/beautifulsoup4/)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-34347b17fbf8612c4a0c.jpeg)\nWritten By\n## [Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[See all from Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](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)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/005.jpeg)](https://towardsdatascience.com/feature-engineering-examples-binning-numerical-features-7627149093d/)\n## [Feature Engineering Examples: Binning Numerical Features](https://towardsdatascience.com/feature-engineering-examples-binning-numerical-features-7627149093d/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to use NumPy or Pandas to quickly bin numerical features\n[Max Steele (they/them)](https://towardsdatascience.com/author/maxsteele731/)\nApril 5, 20215 min read\n  * [![](../images/006.png)](https://towardsdatascience.com/all-you-need-to-know-to-build-your-first-llm-app-eb982c78ffac/)\n## [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/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nA step-by-step tutorial to document loaders, embeddings, vector stores and prompt templates\n[Dominik Polzer](https://towardsdatascience.com/author/dmnkplzr/)\nJune 22, 202327 min read\n  * [![](../images/007.jpeg)](https://towardsdatascience.com/paper-explained-dino-emerging-properties-in-self-supervised-vision-transformers-f9386df266f1/)\n## [Paper explained: DINO - Emerging Properties in Self-Supervised Vision Transformers](https://towardsdatascience.com/paper-explained-dino-emerging-properties-in-self-supervised-vision-transformers-f9386df266f1/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIn 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...\n[Leon Sick](https://towardsdatascience.com/author/leon.sick/)\nDecember 1, 20216 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/sentiment-analysis-on-amazon-food-reviews-from-eda-to-deployment-f985c417b0c/)\n## [Sentiment Analysis On Amazon Food Reviews: From EDA To Deployment](https://towardsdatascience.com/sentiment-analysis-on-amazon-food-reviews-from-eda-to-deployment-f985c417b0c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAmazon.com, Inc., is an American multinational technology company based in Seattle, Washington. Amazon focuses on e-commerce, cloud...\n[Arun Mohan](https://towardsdatascience.com/author/arunm8489/)\nSeptember 6, 202010 min read\n  * [![](../images/009.jpeg)](https://towardsdatascience.com/a-conceptual-explanation-of-convolutional-neural-networks-cnns-ccd2e62f213b/)\n## [A Conceptual Explanation of Convolutional Neural Networks (CNN's)](https://towardsdatascience.com/a-conceptual-explanation-of-convolutional-neural-networks-cnns-ccd2e62f213b/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA gentle introduction into the inner workings of a popular algorithm used for computer vision purposes\n[Vishnu Nair](https://towardsdatascience.com/author/vishnu-nair/)\nJune 7, 20216 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/linear-regression-algorithm-under-the-hood-math-for-non-mathematicians-c228d244e3f3/)\n## [Linear Regression Algorithm -Under The Hood Math For Non-Mathematicians](https://towardsdatascience.com/linear-regression-algorithm-under-the-hood-math-for-non-mathematicians-c228d244e3f3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIt is one of the oldest algorithms in the field of mathematics and statistics borrowed in machine learning.\n[Kaushik Choudhury](https://towardsdatascience.com/author/kaushikthoughts/)\nAugust 24, 20206 min read\n  * [![](../images/011.jpeg)](https://towardsdatascience.com/the-remarkable-world-of-recommender-systems-bff4b9cbe6a7/)\n## [The Remarkable world of Recommender Systems](https://towardsdatascience.com/the-remarkable-world-of-recommender-systems-bff4b9cbe6a7/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAn overview of the Recommendation systems and how they provide an effective form of targeted marketing.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nMay 9, 201910 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/getting-started-with-great-expectations-a-guide-to-data-validation-in-python-95a8ffc2b747/)\n## [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/)\n[Programming](https://towardsdatascience.com/category/programming/)\nLearn how to prevent data quality issues with a few lines of code in Python\n[Eugenia Anello](https://towardsdatascience.com/author/eugenia-anello/)\nJuly 12, 20235 min read\n  * [![](../images/body-63beb50f664a055ed739.jpg)](https://towardsdatascience.com/latest-picks-modern-recommender-systems-a8c09fea7db0/)\n## [Latest picks: Modern Recommender Systems](https://towardsdatascience.com/latest-picks-modern-recommender-systems-a8c09fea7db0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nYour daily dose of data science\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nJanuary 26, 20211 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n\n\n",
  "metadata": {
    "title": "Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch | Towards Data Science",
    "description": "Can a language model invent unique fantasy character names? Let's build it from scratch",
    "keywords": null,
    "author": "Riccardo Andreoni",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch",
    "og:description": "Can a language model invent unique fantasy character names? Let's build it from scratch",
    "og:url": "https://towardsdatascience.com/use-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/1w6gOUBuJQhANiVkQYfZPnw.jpeg",
    "og:image:width": "2048",
    "og:image:height": "1280",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Riccardo Andreoni",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "11 min read",
    "article:published_time": "2023-09-22T16:27:10.000Z",
    "article:modified_time": "2023-09-22T16:27:10.000Z",
    "article:author": "https://towardsdatascience.com/author/riccardo.andreoni/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_000.txt",
      "chars": 949
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_001.txt",
      "chars": 337
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_002.txt",
      "chars": 407
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_003.txt",
      "chars": 583
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_004.txt",
      "chars": 408
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_005.txt",
      "chars": 804
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_006.txt",
      "chars": 453
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_007.txt",
      "chars": 2226
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_008.txt",
      "chars": 897
    },
    {
      "language": "txt",
      "file": "attachments/d76e8540089f/code/block_009.txt",
      "chars": 157
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:43Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:43Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:43Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:50:43Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/riccardo.andreoni/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/choose-the-right-optimization-algorithm-for-your-neural-network-cb86c15d7328"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/ensemble-learning-with-scikit-learn-a-friendly-introduction-5dd64650de6c"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/euro-trip-optimization-genetic-algorithms-and-google-maps-python-api-solve-the-traveling-salesman-4ad8e1548207"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/the-birth-of-data-science-historys-first-hypothesis-test-python-insights-4745dccaf6d"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/fantasy/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/hands-on-tutorials/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/language-model/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/feature-engineering-examples-binning-numerical-features-7627149093d/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/maxsteele731/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://pixabay.com/illustrations/book-old-surreal-fantasy-pages-863418/"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Language_model"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Recurrent_neural_network"
    },
    {
      "type": "external",
      "href": "https://numpy.org/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/computer-science"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Natural_language_processing"
    },
    {
      "type": "external",
      "href": "https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/List_of_Middle-earth_characters"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/The_Lord_of_the_Rings"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/The_Hobbit"
    },
    {
      "type": "external",
      "href": "https://pypi.org/project/beautifulsoup4/"
    },
    {
      "type": "external",
      "href": "https://docs.python.org/3/library/re.html"
    },
    {
      "type": "external",
      "href": "https://pub.towardsai.net/regex-for-the-modern-data-scientists-37bd528d343a"
    },
    {
      "type": "external",
      "href": "https://www.behindthename.com/namesakes/list/tolkien/alpha"
    },
    {
      "type": "external",
      "href": "https://www.coursera.org/specializations/deep-learning"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Use+Deep+Learning+to+Generate+Fantasy+Names%3A+Build+a+Language+Model+from+Scratch&u=https%3A%2F%2Ftowardsdatascience.com%2Fuse-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa%2F"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:27:46Z",
  "source_url": "https://towardsdatascience.com/use-deep-learning-to-generate-fantasy-character-names-build-a-language-model-from-scratch-792b13629efa/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe 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.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe 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\nNecessaryAlways Active\nNecessary 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.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress 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.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis 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.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo 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. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes 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.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe 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.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical 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.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot 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).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot 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.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle 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.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance 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.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement 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.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter 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.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube 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.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[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/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Programming](https://towardsdatascience.com/category/programming/)\n# Use Deep Learning to Generate Fantasy Names: Build a Language Model from Scratch\nCan a language model invent unique fantasy character names? Let's build it from scratch\n[Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\nSeptember 22, 202311 min read\n![Source: pixabay.com](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/1w6gOUBuJQhANiVkQYfZPnw.jpeg)\nSource: [pixabay.com](https://pixabay.com/illustrations/book-old-surreal-fantasy-pages-863418/)\nTo 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.\nTensorflow, 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\".\nThis is why today we will perform the inspiring exercise of building a Language Model using only the [Numpy Python](https://numpy.org/) library!\nLearn this step by step with the interactive [Computer Science](https://roadmap.sh/computer-science) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n## Understanding Recurrent Neural Networks and Language Models\nStandard 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:\n  * For NLP tasks, input and outputs may take different forms and dimensions.\n  * Standard neural networks don't simultaneously use features learned at different steps of the network.\n\n\nThe main breakthrough in AI application within the NLP field is undeniably represented by Recurrent Neural Networks (RNN).\nRNNs 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:\n  1. _He said, \"Teddy Roosevelt was the US President.\"_\n  2. _He said, \"Teddy bears are on sale!\"_\n\n\nThe 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**!\n### RNN Architecture\nThe 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.\n![RNN flowchart. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/1J8Kad_0FljJMyOLD-ozPOg.png)\nRNN flowchart. Image by the author.\nWhat happens inside a RNN cell is more interesting. The steps are the following:\n  1. The activation of the previous cell is multiplied by some weights _W _aa_\n  2. The input _x_ is multiplied by some weights _W _ax_\n  3. The results of the previous steps are summed together and with a bias _b _a_\n  4. An activation function like the hyperbolic tangent is applied to compute the activation which is passed to the next cell\n  5. The activation is multiplied by some weights _W _ya_ and summed with a bias _b _y_\n  6. Finally, a softmax function is applied to the resulting vector and the output _y _hat_ is returned\n\n\n![RNN cell flowchart. Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/1ER9-wam3bBvxdF_F_LaGdA.png)\nRNN cell flowchart. Image by the author.\nTo summarize, the formulas for the activation and output are as follows:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/18EE4VeMdY4Tb7pxaqaOJ_Q.png)\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/14QJGOYOB5HgXZgT2DZb8cA.png)\nI'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.\nLet'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):\n> [**articles/names-generator-RNN at main · andreoniriccardo/articles**](https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN)\n## Data Preparation\nOur 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.\nThanks 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:\npython\n\n```\nfrom bs4 import BeautifulSoup\nimport requests\nimport re\n\nurl = \"https://en.wikipedia.org/wiki/List_of_Middle-earth_characters\"\n# Get the contents of the webpage in text format\ndata  = requests.get(url).text\n\nsoup = BeautifulSoup(data,\"html.parser\")\n\n# Parse the HTML code to isolate rows containing character names\nnames = soup.find_all('li')\n\n# Apply a second filter to isolate actual names\nnames_2 = []\nfor i in names:\n    if \"\"\"<li><a href=\"/wiki/\"\"\" in str(i):\n        names_2.append(str(i))\n\n# Retrieve final character names applying cleaning conditions\nlotr_names = []\nfor i in names_2:\n    candidate_name = re.findall(r'\"(.*?)\"', i)[1]\n    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\n    if conditions:\n        lotr_names.append(candidate_name.replace(' (Middle-earth)',''))\n\n```\n\nFor the explanation of the Regex functions, I leave you with this comprehensive [guide](https://pub.towardsai.net/regex-for-the-modern-data-scientists-37bd528d343a).\nAt this point, our dataset will look like this:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/1oqWgsS3hEKYHqYOXQO0xfw.png)\nI aim to simplify our vocabulary by replacing unwanted characters such as ä, é, î.\npython\n\n```\nreplace_dict = {'a':['â','ä','á'],\n                'e':['ê','ë','é'],\n                'i':['î','í'],\n                'o':['ô','ö','ó'],\n                'u':['ú','û',],\n                ' ':['-']\n}\nfor new_char in replace_dict.keys():\n    for old_char in replace_dict[new_char]:\n        lotr_names = lotr_names.replace(old_char, new_char)\n```\n\nFinally, our vocabulary consists in 27 characters:\n_['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']_\nNote that the special character _'n'_ serves as an End of Name token, indicating when the generated name should terminate.\nThe dataset is ready and we can now focus on modeling the Recurrent Neural Network.\n## Building the Language Model\nIn this section, I present the Python implementation of the Language Model. The whole code can be divided into 2 sections:\n  1. Forward Propagation\n  2. Backprop\n\n\nIn the following sections, I will present the code that actually trains the model and how to generate fantasy character names.\n### Forward Propagation\nAs 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.\nThe code that models a single RNN cell is the following:\npython\n\n```\ndef RNN_forward_prop_step(parameters, a_prev, x):\n    W_aa = parameters['W_aa']\n    W_ax = parameters['W_ax']\n    W_ya = parameters['W_ya']\n    b_y = parameters['b_y']\n    b = parameters['b']\n\n    # Compute hidden state\n    a_next = np.tanh(np.dot(W_ax, x) + np.dot(W_aa, a_prev) + b)\n\n    # Compute log probabilities for next character\n    p_t = softmax(np.dot(W_ya, a_next) + b_y)\n\n    return a_next, p_t\n```\n\nAs 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.\nThe next step is to iterate through several RNN cells. This is exactly what the `RNN_roward_prop()` function does.\npython\n\n```\ndef RNN_forward_prop(X, Y, a0, parameters, vocab_size):\n\n    x = {}\n    a = {}\n    y_hat = {}\n    a[-1] = np.copy(a0)\n    loss= 0\n\n    # Iterate for the T timesteps\n    for t in range(len(X)):\n\n        # One-hot representation of the t-th character\n        x[t] = np.zeros((vocab_size, 1))\n        if X[t] != None:\n            x[t][X[t]] = 1\n\n        # Run one timestep of forward prop\n        a[t], y_hat[t] = RNN_forward_prop_step(parameters, a[t-1], x[t])\n\n        # Update loss function\n        loss -= np.log(y_hat[t][Y[t],0])\n\n    cache = (y_hat, a, x)\n\n    return loss, cache\n```\n\nIt 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.\n### Backprop\nBackprop, 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.\nDetailing 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.\n> [**Choose the Right Optimization Algorithm for your Neural Network**](https://towardsdatascience.com/choose-the-right-optimization-algorithm-for-your-neural-network-cb86c15d7328)\nThe 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.\npython\n\n```\ndef RNN_back_prop_step(d_y, grads, parameters, x, a, a_prev):\n\n    grads['dW_ya'] += np.dot(d_y, a.T)\n    grads['db_y'] += d_y\n    da = np.dot(parameters['W_ya'].T, d_y) + grads['da_next']\n    da_raw = (1 - a * a) * da\n    grads['db'] += da_raw\n    grads['dW_ax'] += np.dot(daraw, x.T)\n    grads['dW_aa'] += np.dot(daraw, a_prev.T)\n    grads['da_next'] = np.dot(parameters['W_aa'].T, daraw)\n    return grads\n```\n\nThe above function takes as input the output of the forward propagation and the previous gradients and it computes the updated gradients.\nThe ideration of the `RNN_back_prop_function()` function is performed with these lines of code:\npython\n\n```\ndef RNN_back_prop(X, Y, parameters, cache):\n    # Initialize gradients as an empty dictionary\n    grads = {}\n\n    # Retrieve from cache and parameters\n    (y_hat, a, x) = cache\n    W_aa = parameters['W_aa']\n    W_ax = parameters['W_ax']\n    W_ya = parameters['W_ya']\n    b_y = parameters['b_y']\n    b = parameters['b']\n\n    # Initialize gradients\n    grads['dW_ax'], grads['dW_aa'], grads['dW_ya'] = np.zeros_like(W_ax), np.zeros_like(W_aa), np.zeros_like(W_ya)\n    grads['db'], grads['db_y'] = np.zeros_like(b), np.zeros_like(b_y)\n    grads['da_next'] = np.zeros_like(a[0])\n\n    # Backpropagate through timesteps\n    for t in reversed(range(len(X))):\n        dy = np.copy(y_hat[t])\n        dy[Y[t]] -= 1\n        grads = RNN_back_prop_step(dy, grads, parameters, x[t], a[t], a[t-1])\n\n    return grads, a\n```\n\n## Training the Language Model\nAt 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.\npython\n\n```\ndef RNN_optimization(X, Y, a_prev, parameters, alpha, vocab_size):\n\n    # 1. Forward propagation\n    loss_now, cache = RNN_forward_prop(X, Y, a_prev, parameters, vocab_size)\n\n    # 2. Backward propagation\n    grads, a = RNN_back_prop(X, Y, parameters, cache)\n\n    # 3. Clip gradients\n    grads = clip_grads(grads, 10)\n\n    # 4. Update parameters\n    parameters = update_parameters(parameters, grads, alpha)\n\n    return loss_now, parameters, a[len(X)-1]\n```\n\nThe 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.\npython\n\n```\ndef train_model(data, n_a=50, max_iter = 100000):\n    # Get the list of characters\n    chars = list(set(data))\n    # Get the dictionary size (number of characters)\n    vocab_size = len(chars)\n\n    # Get encoding and decoding dictionaries\n    chars_to_encoding = encode_chars(chars)\n    encoding_to_chars = decode_chars(chars)\n\n    # Get dataset as a list of names and strip, then shuffle the dataset\n    data = data.split('n')\n    data = [x.strip() for x in data]   \n    np.random.shuffle(data) \n\n    # Define n_x, n_y parameters\n    n_x, n_y = vocab_size, vocab_size\n\n    # Initialize the hidden state\n    # a_prev = initialize_hidden_state(n_a)\n    a_prev = np.zeros((n_a, 1))\n\n    # Initialize the parameters\n    parameters = initialize_parameters(n_a, n_x, n_y)\n    # for k in parameters.keys():\n    #     print('{}: tipo {}, Datatype {}'.format(k, type(parameters[k]), parameters[k].dtype))\n    # Get current loss function value\n    loss_now = get_initial_loss(vocab_size, len(data))\n\n    # Perform max_iter iteration to train the model's parameters\n    for iter in range(max_iter):\n        # print(iter)\n        # Get the index of the name to pick\n        name_idx = iter % len(data)\n        example = data[name_idx]\n\n        # Convert encoded and decoded example into a list\n        example_chars = [char for char in example]\n        example_encoded = [chars_to_encoding[char] for char in example]\n\n        # Create training input X. The value None is used to consider the first input character\n        # as a vector of zeros\n        X = [None] + example_encoded\n\n        # Create the label vector Y by appending the 'n' encoding to the end of the vector\n        Y = example_encoded + [chars_to_encoding['n']]\n\n        # Perform one step of the optimization cycle:\n        # 1. Forward propagation\n        # 2. Backward propagation\n        # 3. Gradient clipping\n        # 4. Parameters update\n\n        loss_tmp, parameters, a_prev = RNN_optimization(X, Y, a_prev, parameters, alpha=0.01, vocab_size=vocab_size)\n        # for k in parameters.keys():\n        #     print('{}: tipo {}, Datatype {}'.format(k, type(parameters[k]), parameters[k].dtype))\n        loss_now = smooth(loss_now, loss_tmp)\n\n    return parameters\n```\n\nThe result is a model able to mimics the creative process of Tolkien and effortlessly produce unique character names.\n## Generating Fantasy Character Names\nTo sample novel character names from our trained Language Model, I developed two functions.\nThe `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).\nFinally, it returns a list of indices that encode the generated fantasy character name.\npython\n\n```\ndef sample(parameters, chars_to_encoding):\n    W_aa = parameters['W_aa']\n    W_ax = parameters['W_ax']\n    W_ya = parameters['W_ya']\n    b_y = parameters['b_y']\n    b = parameters['b']\n    vocab_size = b_y.shape[0]\n    n_a = W_aa.shape[1]\n\n    x = np.zeros((vocab_size,))\n    a_prev = np.zeros((n_a,))\n\n    indices = []\n    idx = -1 \n\n    counter = 0\n    newline_character = chars_to_encoding['n']\n\n    while (idx != newline_character and counter != 50):\n        a = np.tanh(np.dot(W_ax,x)+np.dot(W_aa,a_prev)+np.ravel(b))\n        z = np.dot(W_ya,a) + np.ravel(b_y)\n        y = softmax(z)\n\n        idx = np.random.choice(list(chars_to_encoding.values()), p=np.ravel(y))\n        indices.append(idx)    \n\n        x = np.zeros((vocab_size,))\n        x[idx] = 1\n\n        a_prev = a\n\n        counter +=1\n        if (counter == 50):\n            indices.append(chars_to_encoding['n'])\n    return indices\n```\n\nTo 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.\npython\n\n```\ndef get_sample(sample_ix, encoding_to_chars):\n    txt = ''.join(encoding_to_chars[ix] for ix in sample_ix)\n    txt = txt[0].upper() + txt[1:]\n    return txt\n```\n\nWith everything in place, you can now appreciate some original fantasy character names, as shown below:\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/1GAzc_cVm4RSPuNq1dGIzJA.png)\nImage by the author.\n## Evaluating Model Performance\nDuring 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:\n  * \"Orvnnvfufufiiubx\" at iteration 2000 and loss 27.96\n  * \"Aotvux\" at iteration 4000 and loss 26.43\n\n\nWe 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:\n  * \"Furun I\" at iteration 14000 and loss 21.53\n  * \"Flutto Balger\" at iteration 16000 and loss 21.11\n\n\nFinally, the trained model seems to be able to emulate the characters' name style.\nThe improvement I described qualitatively can be also quantitatively visualized as follows.\nBy 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.\n![Image by the author.](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/09/15dyQ9f1p5DREBHU-NSgcWQ.png)\nImage by the author.\nThe 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.\n## Conclusion\nIn conclusion, building a Language Model for fantasy name generation has brought us several insights.\nWe 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.\nMoreover, 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.\nFinally, 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!\n* * *\nIf you liked this story, consider following me to be notified of my upcoming projects and articles!\nHere are some of my past projects:\n> [**Ensemble Learning with Scikit-Learn: A Friendly Introduction**](https://towardsdatascience.com/ensemble-learning-with-scikit-learn-a-friendly-introduction-5dd64650de6c)\n> [**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)\n> [**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)\n## Resources\n  * [GitHub Repository](https://github.com/andreoniriccardo/articles/tree/main/names-generator-RNN)\n  * [LOTR character names](https://www.behindthename.com/namesakes/list/tolkien/alpha)\n  * [Deep Learning Course](https://www.coursera.org/specializations/deep-learning)\n  * [Recurrent Neural Network](https://en.wikipedia.org/wiki/Recurrent_neural_network)\n  * [BeautifulSoup](https://pypi.org/project/beautifulsoup4/)\n\n\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657095428_xaezyc.jpeg)\nWritten By\n## [Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[See all from Riccardo Andreoni](https://towardsdatascience.com/author/riccardo.andreoni/)\n[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/)\nShare This Article\n  * [](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)\n  * [](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)\n  * [](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)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/1l-c-U6x2MATxgXIbvzKE9A.jpeg)](https://towardsdatascience.com/feature-engineering-examples-binning-numerical-features-7627149093d/)\n## [Feature Engineering Examples: Binning Numerical Features](https://towardsdatascience.com/feature-engineering-examples-binning-numerical-features-7627149093d/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nHow to use NumPy or Pandas to quickly bin numerical features\n[Max Steele (they/them)](https://towardsdatascience.com/author/maxsteele731/)\nApril 5, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/1njagJOgiT-VTJjQ18bugcw.png)](https://towardsdatascience.com/all-you-need-to-know-to-build-your-first-llm-app-eb982c78ffac/)\n## [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/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nA step-by-step tutorial to document loaders, embeddings, vector stores and prompt templates\n[Dominik Polzer](https://towardsdatascience.com/author/dmnkplzr/)\nJune 22, 202327 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/12/1jJpVxkZesxDSV-NCgNrOsA.jpeg)](https://towardsdatascience.com/paper-explained-dino-emerging-properties-in-self-supervised-vision-transformers-f9386df266f1/)\n## [Paper explained: DINO - Emerging Properties in Self-Supervised Vision Transformers](https://towardsdatascience.com/paper-explained-dino-emerging-properties-in-self-supervised-vision-transformers-f9386df266f1/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIn 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...\n[Leon Sick](https://towardsdatascience.com/author/leon.sick/)\nDecember 1, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/09/0nPIXgF4S51sk_Vyy-scaled.jpg)](https://towardsdatascience.com/sentiment-analysis-on-amazon-food-reviews-from-eda-to-deployment-f985c417b0c/)\n## [Sentiment Analysis On Amazon Food Reviews: From EDA To Deployment](https://towardsdatascience.com/sentiment-analysis-on-amazon-food-reviews-from-eda-to-deployment-f985c417b0c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nAmazon.com, Inc., is an American multinational technology company based in Seattle, Washington. Amazon focuses on e-commerce, cloud...\n[Arun Mohan](https://towardsdatascience.com/author/arunm8489/)\nSeptember 6, 202010 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/06/12RdfimeWaFU2lsGSgWVViw-scaled.jpeg)](https://towardsdatascience.com/a-conceptual-explanation-of-convolutional-neural-networks-cnns-ccd2e62f213b/)\n## [A Conceptual Explanation of Convolutional Neural Networks (CNN's)](https://towardsdatascience.com/a-conceptual-explanation-of-convolutional-neural-networks-cnns-ccd2e62f213b/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA gentle introduction into the inner workings of a popular algorithm used for computer vision purposes\n[Vishnu Nair](https://towardsdatascience.com/author/vishnu-nair/)\nJune 7, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/08/0Xz8RO7a8Y5z2O-hf-scaled.jpg)](https://towardsdatascience.com/linear-regression-algorithm-under-the-hood-math-for-non-mathematicians-c228d244e3f3/)\n## [Linear Regression Algorithm -Under The Hood Math For Non-Mathematicians](https://towardsdatascience.com/linear-regression-algorithm-under-the-hood-math-for-non-mathematicians-c228d244e3f3/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nIt is one of the oldest algorithms in the field of mathematics and statistics borrowed in machine learning.\n[Kaushik Choudhury](https://towardsdatascience.com/author/kaushikthoughts/)\nAugust 24, 20206 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2019/05/1zbDABl5-RaISCsXvsbPkbQ-scaled.jpeg)](https://towardsdatascience.com/the-remarkable-world-of-recommender-systems-bff4b9cbe6a7/)\n## [The Remarkable world of Recommender Systems](https://towardsdatascience.com/the-remarkable-world-of-recommender-systems-bff4b9cbe6a7/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nAn overview of the Recommendation systems and how they provide an effective form of targeted marketing.\n[Parul Pandey](https://towardsdatascience.com/author/pandeyparul/)\nMay 9, 201910 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/07/0ffLDTeNxDeEOlpSu.jpg)](https://towardsdatascience.com/getting-started-with-great-expectations-a-guide-to-data-validation-in-python-95a8ffc2b747/)\n## [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/)\n[Programming](https://towardsdatascience.com/category/programming/)\nLearn how to prevent data quality issues with a few lines of code in Python\n[Eugenia Anello](https://towardsdatascience.com/author/eugenia-anello/)\nJuly 12, 20235 min read\n  * [![](https://towardsdatascience.com/images/fallback-image.jpg)](https://towardsdatascience.com/latest-picks-modern-recommender-systems-a8c09fea7db0/)\n## [Latest picks: Modern Recommender Systems](https://towardsdatascience.com/latest-picks-modern-recommender-systems-a8c09fea7db0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nYour daily dose of data science\n[TDS Editors](https://towardsdatascience.com/author/towardsdatascience/)\nJanuary 26, 20211 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe 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/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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\")\n  * [ ![](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?\")\n\n\n",
  "body_base_path": "attachments/d76e8540089f/pages/",
  "body_markdown_path": "attachments/d76e8540089f/pages/archived-body.md",
  "local_html": "attachments/d76e8540089f/pages/archived-body.html",
  "body_source": "prior_capture"
}