<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Quinn Lanners on Medium]]></title>
        <description><![CDATA[Stories by Quinn Lanners on Medium]]></description>
        <link>https://medium.com/@lannersq?source=rss-8a2f7df48b90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Brk5nEh8iz86Uf-730hMgA.png</url>
            <title>Stories by Quinn Lanners on Medium</title>
            <link>https://medium.com/@lannersq?source=rss-8a2f7df48b90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:04:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lannersq/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deploying a Scikit-Learn Model on AWS Using SKLearn Estimators, Local Jupyter Notebooks, and the…]]></title>
            <link>https://medium.com/data-science/deploying-a-scikit-learn-model-on-aws-using-sklearn-estimators-local-jupyter-notebooks-and-the-d94396589498?source=rss-8a2f7df48b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/d94396589498</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Quinn Lanners]]></dc:creator>
            <pubDate>Tue, 25 Feb 2020 04:20:07 GMT</pubDate>
            <atom:updated>2020-02-25T15:01:56.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a Scikit-Learn Model on AWS Using SKLearn Estimators, Local Jupyter Notebooks, and the Terminal</h3><h4>A step-by-step tutorial on how to deploy a scikit-learn model on AWS from a local device.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OykYM8Sn5dGcOMxAPu8BUw.png" /><figcaption>Logos retrieved from Wikipedia.com (scikit-learn) and aws.amazon.com.</figcaption></figure><p>Amazon Web Services (AWS) is currently the most in-demand cloud platform for Data Science and Machine Learning professionals. Given this, the first collection of blog posts in this Machine Learning Deployment series will outline how to deploy various models in a number of different ways on AWS.</p><p><strong>Other posts in this series:</strong></p><ul><li><a href="https://medium.com/@lannersq/why-you-should-know-how-to-deploy-your-models-in-the-cloud-41d1c85a8df0"><em>Intro</em></a></li></ul><p>The first AWS deployment we will cover will be the deployment of a simple Scikit-learn model done completely from one’s local computer using the AWS pre-build Scikit-learn Estimators.</p><p>Before we dig into the steps, it’s important to understand the basic concept of how AWS Sagemaker trains and deploys models. If you are unfamiliar with Docker, I recommend reading their overview docs <a href="https://docs.docker.com/engine/docker-overview/">here</a>. Without going into too much detail, AWS essentially uses Docker containers to store a model’s configuration, train the model, and eventually deploy the model. By encapsulating ML models within Docker containers, AWS is able to simultaneously provide a set of preconfigured Docker images for common ML frameworks, while also allowing for complete customization.</p><p>Luckily for us, in 2018, AWS added Scikit-learn to its list of supported frameworks. Thus, we can quickly deploy our model using a pre-configured Docker container. As you’ll see below, we will create a training script and execute it inside the container using the AWS Scikit-learn Estimators. So, without further ado, let’s get to it.</p><blockquote>You can find the code from this post in the repo I started for this blog series <a href="https://github.com/qlanners/ml_deploy/tree/master/aws/scikit-learn/sklearn_estimators_locally">here</a>.</blockquote><p><strong>Step 1: Account Setup</strong></p><p>Before we begin, we have to set up an AWS account. If you already have an AWS account, then you can skip to the next step. Otherwise, let’s get you signed up for AWS and their 175 (and continually growing) services. To start, navigate to <a href="https://portal.aws.amazon.com/billing/signup?nc2=h_ct&amp;src=header_signup&amp;redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start">this page to create your free AWS account</a> and get 12 months of free tier access (which will be plenty to complete the code in this post).</p><p><strong>Step 2: AWS CLI and Pip Packages</strong></p><p>Once you have registered for AWS, we also need to download the AWS command-line interface (CLI) so we can work on our AWS account from our local device. AWS does a good job of explaining how to <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">install</a>, <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html">configure</a>, and <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-using.html">use</a> their CLI.</p><p>We will also need to install a couple of python SDKs in order to access AWS in our python scripts. Specifically, we will need the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/index.html">Boto3</a> to handle data upload and <a href="https://github.com/aws/sagemaker-python-sdk">Sagemaker</a> to create our Scikit-learn estimators. Run the pip commands below to install them.</p><pre>pip install boto3<br>pip install sagemaker</pre><p><strong>Step 3: Data Set-Up</strong></p><p>In order to focus on the deployment of the model and avoid getting caught up in the weeds regarding data cleaning and model tuning, we are going to be training a simple logistic regression model on the Iris dataset. You can download the dataset <a href="https://archive.ics.uci.edu/ml/datasets/Iris">here</a> and save it to your local device.</p><p>We will use the code block below to strip a few samples from the dataset for testing out API calls once we have deployed the model, and save the data into two new files called <strong>train.csv</strong> and <strong>deploy_test.csv</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c64bb508127941efdee2d5e3a8112d2/href">https://medium.com/media/4c64bb508127941efdee2d5e3a8112d2/href</a></iframe><p><em>Note: We are disregarding ML train/test set guidelines. In practice, you should always be splitting your data into a train/test set. However, for this tutorial, we are just focusing on deploying the model and will check how the model predicts the few points we saved in </em><strong><em>deploy_test.csv</em></strong><em> by making an API call at the end.</em></p><p>In order for AWS Sagemaker to access this data when it comes time to train the model, we must upload the data to our AWS account by creating a new Simple Storage Service (S3) bucket and adding our training data to it. To do this, we will be using the boto3 SDK we installed above to create an S3 bucket in a specified region and then save our <strong>train.csv</strong> file inside a <strong>train/</strong> folder in that bucket. <a href="https://aws.amazon.com/s3/"><em>Click here for more information on S3</em></a><em>.</em></p><p><em>Note: In order for Sagemaker to access the data, the S3 bucket and Sagemaker session need to be in the same region. And given that Sagemaker is only available in certain regions, be sure to select a region for your S3 bucket from the regions listed </em><a href="https://docs.aws.amazon.com/general/latest/gr/sagemaker.html"><em>here</em></a><em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33ef369b12f0d6a12bde19ce0644e2d4/href">https://medium.com/media/33ef369b12f0d6a12bde19ce0644e2d4/href</a></iframe><p>To double-check that the above scripts worked correctly, you can navigate to the <a href="https://s3.console.aws.amazon.com/">AWS S3 Console</a>, login, and see if the bucket we created above is there. If it’s there, we are ready to move on to the meat of the work and create our model!</p><p><strong>Step 4: The Model Script</strong></p><p>In order to deploy a model to AWS using the Scikit-learn Sagemaker SDK, we first have to create a script that tells Sagemaker how to train and deploy our model. While much less work than creating our own Docker container to deploy our model, the SDK does require us to stick to rather strict guidelines.</p><p>First off, we will import all the packages we will need and create a couple of dictionaries to convert the target labels from text to numbers and vice versa.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2caa8ee9a2b8046fa8c9c087afd26acc/href">https://medium.com/media/2caa8ee9a2b8046fa8c9c087afd26acc/href</a></iframe><p>After these imports, we need to wrap the training steps within a __main__ function. We will also include a line to save the model at the end. The SKLearn Sagemaker SDK will run this __main__ function to train a model on the data we pushed to the S3 bucket above and then save the model so that it can be used later when we want to deploy it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46b524af6f13e9580120eafcbf234189/href">https://medium.com/media/46b524af6f13e9580120eafcbf234189/href</a></iframe><p>The __main__ function is the only required function. However, we have the ability to modify a number of additional functions that determine how the model will handle API calls once it is deployed. These optional functions are:</p><blockquote><strong><em>model_fn:</em> </strong><em>specifies from where and how to load the model that is being deployed.</em><br> <br><strong><em>input_fn:</em></strong><em> formats the request body sent to the deployed model into a format that can be fed into the model.<br> <br></em><strong><em>predict_fn:</em></strong><em> uses the deployed model loaded by model_fn and the data formatted by input_fn to make predictions.<br> <br></em><strong><em>output_fn:</em></strong><em> reformats the predictions made by predict_fn into the final format that is returned as the response to the API call.</em></blockquote><p>The Gist below shows these optional functions for our model. The comments above each function provide a bit more information on each. For even more information on these functions and their default behavior see <a href="https://sagemaker.readthedocs.io/en/stable/using_sklearn.html">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa07ab5ac44c5b93f1e0f7df22d2e245/href">https://medium.com/media/aa07ab5ac44c5b93f1e0f7df22d2e245/href</a></iframe><p><strong>Step 5: Create IAM Sagemaker Role</strong></p><p>Unfortunately, I lied a bit earlier when I said we were going to do ALL of this from our local computer. If you do not already have a Sagemaker IAM role, we are going to need to navigate to the AWS IAM Console and create a new role. Start by clicking <a href="https://console.aws.amazon.com/iam/home?#/roles$new?step=type">here</a> and logging in. You should see a screen like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vgYD4iLev9Pw8H2ni8nuLA.png" /><figcaption>AWS Select IAM Role Page</figcaption></figure><p>From here, select <strong>Sagemaker</strong> as the service and push <strong>Next</strong>.</p><p>Skip through the next two pages by selecting <strong>Next</strong>, until you see the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZboiggVz0w2ml_e0UU7RA.png" /><figcaption>AWS Create IAM Role Name Page</figcaption></figure><p>On this page, just create your own <strong>Role name*</strong> and (optional) <strong>Role description</strong> before pressing <strong>Create Role</strong>. Just be sure to remember what you named your role, as we will be needing it in the next step!</p><p><strong>Step 6: Deploy the Model</strong></p><p>With the hard work out of the way, let’s deploy your model. Luckily, with AWS SKLearn class, this only takes a few lines of code. Just make sure that the <strong><em>entry_point</em></strong> path points to the script we saved in step 4 and the <strong><em>role</em></strong> variable is the <strong>Role name*</strong> you created in step 5. In this snippet, we also specify instance_types for the model and the deployed endpoint. The instance_type specifies how much computing power we want AWS to allocate for our services. Obviously, the more power the more cost, so for this example we use small instances. Check <a href="https://aws.amazon.com/sagemaker/pricing/instance-types/">here</a> for a list of all the Sagemaker instance types available.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98af8df1ece5343d28606396576af041/href">https://medium.com/media/98af8df1ece5343d28606396576af041/href</a></iframe><p><em>Note: the SKLearn() constructor has a number of optional arguments you can add to configure the Scikit-learn framework_version, hyperparameters, etc. Click </em><a href="https://sagemaker.readthedocs.io/en/stable/using_sklearn.html#required-arguments"><em>here</em></a><em> for more info.</em></p><p><strong>Step 7: Test the Endpoint</strong></p><p>To test the endpoint, we will feed send a request with the data samples we saved to <strong>deploy_test.csv</strong> way back in step 3. In order to send a request to the deployed endpoint, we first need to get our test samples into a format that the model can parse (i.e. a format that can be interpreted by the <strong>input_fn</strong> function we defined in <strong>aws_sklearn_main.py</strong>). Since we configured our model to understand requests with multiple samples were each sample’s features are separated by a “,” and each individual sample is separated by a “|” we format our request_body into a format like below:</p><pre>&#39;147,6.5,3.0,5.2,2.0|148,6.2,3.4,5.4,2.3|149,5.9,3.0,5.1,1.8&#39;</pre><p>From here, we use boto3 to create a Sagemaker session which will allow us to interact with our deployed model. In order to call our Sagemaker endpoint, we use the <strong>invoke_endpoint</strong> function. For this function, we must specify an endpoint, a conent_type, and a body. There are also a number of optional arguments you can read more about <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sagemaker-runtime.html#SageMakerRuntime.Client.invoke_endpoint">here</a>. In our case, we will pass the endpoint that we printed out in the previous step, the content_type ‘text/csv’, and a string formatted to look like above. Finally, once we have run this method and received a response, we subscript into the body of our response and read what is returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bb3554ede7db3bbf48a9fee91e1b7be/href">https://medium.com/media/9bb3554ede7db3bbf48a9fee91e1b7be/href</a></iframe><p>If the expected response matches what was actually returned by the model, you have successfully trained and deployed a working Scikit-learn model on AWS!</p><p><strong>Step 8: Clean Up Resources</strong></p><p>In order to avoid any AWS charges, be sure to clean up your resources. You can quickly terminate your model’s endpoint by uncommenting the final line in Step 6 and running it.</p><pre>aws_sklearn_predictor.delete_endpoint()</pre><p>While this will delete the endpoint, to totally purge your AWS account of all of the resources you used in this tutorial complete the following.</p><ol><li>Open the <a href="https://console.aws.amazon.com/sagemaker/">Sagemaker Console</a></li><li>In the side-bar menu under <strong>Inferences,</strong> delete the resources created on the <em>Models</em>, <em>Endpoint</em>, and <em>Endpoint configurations</em> tabs.</li><li>Open the <a href="https://console.aws.amazon.com/s3/">S3 Console</a> and delete the bucket we created.</li><li>Open the <a href="https://console.aws.amazon.com/iam/">IAM Console</a> and delete the role we created.</li><li>Open the <a href="https://console.aws.amazon.com/cloudwatch/">Cloudwatch Console</a> and delete all of the /aws/sagemaker logs.</li></ol><p><strong>Review</strong></p><p>Overall, while the learning curve is a bit high, once you are able to navigate your way around the AWS services and understand the Sagemaker principals, AWS SKLearn Estimators become an incredible tool to quickly deploy Scikit-learn models.</p><p>Benefits:</p><ul><li>Very little configuration needed, but lots available</li><li>Plethora of documentation</li><li>Can deploy model with just a few lines of code</li></ul><p>Drawbacks</p><ul><li>The large initial learning curve</li><li>Several AWS services to understand and work with</li><li>Documentation can be difficult to find</li></ul><p><strong>Other Blog Posts in this Series:</strong></p><ul><li><a href="https://medium.com/@lannersq/why-you-should-know-how-to-deploy-your-models-in-the-cloud-41d1c85a8df0"><em>Intro</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d94396589498" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploying-a-scikit-learn-model-on-aws-using-sklearn-estimators-local-jupyter-notebooks-and-the-d94396589498">Deploying a Scikit-Learn Model on AWS Using SKLearn Estimators, Local Jupyter Notebooks, and the…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Know How to Deploy Your Models In The Cloud]]></title>
            <link>https://medium.com/data-science/why-you-should-know-how-to-deploy-your-models-in-the-cloud-41d1c85a8df0?source=rss-8a2f7df48b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/41d1c85a8df0</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Quinn Lanners]]></dc:creator>
            <pubDate>Tue, 25 Feb 2020 03:10:16 GMT</pubDate>
            <atom:updated>2020-02-25T15:02:14.603Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Indeed.com job postings to show why it is important for Data Scientists and Machine Learning Engineers to know how to deploy models and navigate cloud platforms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mb6giaHNdHVfWmo_bhlRSQ.jpeg" /><figcaption>From Pixabay.com</figcaption></figure><p>Growing skills in data science, specifically machine learning, is a long process. I’ve spent the past couple of years taking statistics and linear algebra classes, completing online courses in ML and Deep Learning, and building models in python. But after all this work, I realized that there was a very important skill that I was lacking… While I felt comfortable working with data and building a model, I had no experience actually deploying that model to production.</p><p>As the field of machine learning continues to grow and mature, companies are starting to demand more tangible results from their data science teams. And, in several cases, this has translated to companies demanding more software engineering skills from their data scientists, specifically in the area of continues integration and deployment of ML models. While these skills may initially seem out of reach, the majority of companies are using cloud technology to accomplish these tasks. And luckily enough for us, these cloud platforms are accessible by anyone with a device and internet connection.</p><p>To showcase the demand for these skills, I put together a script that scraped <a href="https://www.indeed.com/">Indeed.com</a> to see the frequency different terms showed up in job postings for any given search. Using this script, I searched for <strong>Data Scientist</strong> and <strong>Machine Learning</strong> jobs in ten of the largest “tech-hubs” of the United States (San Francisco, CA | New York, NY | Seattle, WA | Austin, TX | Boston, MA | Chicago, IL | Washington DC | San Jose, CA | Baltimore, MD | Arlington, VA). The job postings in all of these cities for each of these two searches were compiled and used to create the below graphics. These graphics showcase how often the terms <em>deploy </em>and<em> cloud</em> appeared in the job postings Indeed returned for each of these searches. Furthermore, I dug a bit deeper into the different cloud technologies to compare how often companies asked for candidates with skills in the three largest cloud platforms: Amazone Web Services (AWS), Google Cloud Platform (GCP), and Microsoft Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MA4NAOKVVikXdTcWHT_lOg.png" /><figcaption>Frequency of the keywords <strong>Deploy</strong> and <strong>Cloud</strong> in Data Scientist and Machine Learning job postings on Indeed.com.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2Cmv_Y_vIqM1Bs646q6Xg.png" /><figcaption>Frequency of Cloud Platforms in Data Scientist and Machine Learning job postings on Indeed.com.</figcaption></figure><p>The graphics above depict the need for skillsets in both deploying models and working in a cloud environment. While not a majority, a considerable percentage of job postings are seeking candidates with these abilities. And, given that data scientists have traditionally spent a majority of their time on the model building (versus the model implementation) side of the problem, growing these skills can differentiate yourself from other candidates. Furthermore, if you are looking for roles in machine learning specifically, deploying models and working in cloud environments are in even higher demand.</p><p>Finally, I dug a bit deeper into these job postings to compare the need for these skills at different experience levels. The graphics below show that as you work to move up to higher-level positions, most notably from entry to mid-level positions, deployment and cloud skills becoming more important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kWVri6ORtV3k2d-iSkzuqw.png" /><figcaption>Frequency deploy and cloud skills are listed on Indeed.com Data Scientist job postings for various experience levels.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRiLCThs4FhnqXgYxglv0g.png" /><figcaption>Frequency deploy and cloud skills are listed on Indeed.com Machine Learning job postings for various experience levels.</figcaption></figure><p>The graphs above speak to the career opportunities that you can realize by learning to deploy ML models and work effectively on cloud platforms. But even with all of these professional advantages aside, these skills are exciting to learn about and develop. Thus, I have decided to start a blog series on all of the different ways to deploy an ML model into production. In this series of blog posts, I will include a short follow-along activity for each deployment method, along with providing my feedback on the ease of use.</p><p>See below for a list of my current articles on the topic of ML deployment, and reach out with suggestions for any platforms/techniques that you’d like to see covered!</p><ul><li><a href="https://medium.com/@lannersq/deploying-a-scikit-learn-model-on-aws-using-sklearn-estimators-local-jupyter-notebooks-and-the-d94396589498">Deploying a scikit-learn model on AWS using SKLearn Estimators</a></li></ul><blockquote><em>Note: The data collected in this blog post was collected from Indeed.com on February 12, 2020.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41d1c85a8df0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-you-should-know-how-to-deploy-your-models-in-the-cloud-41d1c85a8df0">Why You Should Know How to Deploy Your Models In The Cloud</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing a Scikit-learn Linear Regression Algorithm]]></title>
            <link>https://medium.com/data-science/choosing-a-scikit-learn-linear-regression-algorithm-dd96b48105f5?source=rss-8a2f7df48b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd96b48105f5</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[flowchart]]></category>
            <dc:creator><![CDATA[Quinn Lanners]]></dc:creator>
            <pubDate>Mon, 15 Jul 2019 14:50:19 GMT</pubDate>
            <atom:updated>2019-07-15T15:53:33.014Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief overview of the various Scikit-learn linear regression algorithms, and what cases they are typically most effective for. Includes a summary table and flowchart to quickly decide on a model to fit your data.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*nFCwddEGNJeWvrbuRM765Q.jpeg" /></figure><p>The goal of any linear regression algorithm is to accurately predict an output value from a given set of input features. In python, there are a number of different libraries that can create models to perform this task; of which <a href="https://scikit-learn.org/stable/index.html">Scikit-learn</a> is the most popular and robust. Scikit-learn has hundreds of classes you can use to solve a variety of statistical problems. In the area of linear regression alone, there are several different algorithms to choose from. And while it is often best practice to implement and compare a number of different algorithms, it is often difficult to even know where to start.</p><p>That is why I decided to go through the linear regression algorithms in Scikit-learn and compile all of my findings in one location. This article includes both a table outlining each of the model types, along with a flowchart that you can use to help determine a starting point for your next regression task.</p><p>The information in the table and flowchart was derived largely from the <a href="https://scikit-learn.org/stable/supervised_learning.html#supervised-learning">Scikit-learn documentation</a>, StackOverflow answers, and some local testing of my own.</p><blockquote>You can open a pop-up window with all of a model’s information by navigating to the left-hand side of the model row and clicking on the icon that looks like the image below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/1*nB4UqiBDMjOeH4e0h4TtCQ.png" /></figure><blockquote>Explanations of each column field are in the table about_columns.csv below</blockquote><blockquote>It’s recommended to view the below table on a computer for full functionality.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrQ5rfksG64QobIy&amp;url=https%3A%2F%2Fairtable.com%2FshrQ5rfksG64QobIy&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c03125c1859e73907fb3ddb8e1b844/href">https://medium.com/media/12c03125c1859e73907fb3ddb8e1b844/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0e8a51fd9dfa4001fb842ff67111c34/href">https://medium.com/media/a0e8a51fd9dfa4001fb842ff67111c34/href</a></iframe><p>The following flowchart was derived from the information compiled in the above table. The flowchart idea was inspired by Scikit-learn’s <a href="https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html"><em>Choosing the Right Estimator</em></a>, but the one here goes much more in-depth on the various linear regression algorithms Scikit-learn offers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*_Wx0vKokbXd20HlbLKpj2A.jpeg" /></figure><p>While these resources can hopefully help you get started with Scikit-learn’s plethora of linear regression algorithms, they definitely do not replace the importance of testing and analyzing the effectiveness of several different models.</p><p>If you have any comments on how you use any of the algorithms above, please reach out and share! Also, be sure to let me know if you thought this article was helpful. If so, I’ll compile my notes on Scikit-learn’s classification and clustering algorithms into stories as well!</p><p>Sources:</p><ul><li><a href="https://scikit-learn.org/stable/index.html">scikit-learn</a></li><li><a href="https://www.codeastar.com/choose-machine-learning-models-python/">How to choose a machine learning model in Python? ⋆ Code A Star</a></li><li><a href="https://www.analyticsvidhya.com/blog/2017/06/a-comprehensive-guide-for-linear-ridge-and-lasso-regression/">Linear, Ridge and Lasso Regression comprehensive guide for beginners</a></li><li><a href="https://www.bonaccorso.eu/2017/10/06/ml-algorithms-addendum-passive-aggressive-algorithms/">ML Algorithms addendum: Passive Aggressive Algorithms - Giuseppe Bonaccorso</a></li><li><a href="http://saedsayad.com/decision_tree_reg.htm">Decision Tree Regression</a></li></ul><p>And Various StackOverflow responses</p><p>You can find a Jupyter Notebook of the skeleton I used to test the various Scikit-learn linear regression algorithm’s <a href="https://github.com/qlanners/scikit-learn_disect/blob/master/all_model_tester.ipynb">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd96b48105f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/choosing-a-scikit-learn-linear-regression-algorithm-dd96b48105f5">Choosing a Scikit-learn Linear Regression Algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Machine Translation]]></title>
            <link>https://medium.com/data-science/neural-machine-translation-15ecf6b0b?source=rss-8a2f7df48b90------2</link>
            <guid isPermaLink="false">https://medium.com/p/15ecf6b0b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-translation]]></category>
            <dc:creator><![CDATA[Quinn Lanners]]></dc:creator>
            <pubDate>Mon, 03 Jun 2019 22:52:04 GMT</pubDate>
            <atom:updated>2019-06-07T15:48:12.033Z</atom:updated>
            <content:encoded><![CDATA[<h4>A guide to Neural Machine Translation using an Encoder Decoder structure with attention. Includes a detailed tutorial using PyTorch in Google Colaboratory.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*H441VINdbjxItCdtgb-1Xw.jpeg" /><figcaption>Image from pixabay.com</figcaption></figure><p>Machine Translation (MT) is a subfield of computational linguistics that is focused on translating text from one language to another. With the power of deep learning, Neural Machine Translation (NMT) has arisen as the most powerful algorithm to perform this task. While Google Translate is the leading industry example of NMT, tech companies all over the globe are going <a href="https://slator.com/technology/corporates-going-all-in-on-neural-machine-translation-research/">all in on NMT</a>. This state-of-the-art algorithm is an application of deep learning in which massive datasets of translated sentences are used to train a model capable of translating between any two languages. With the vast amount of research in recent years, there are several variations of NMT currently being investigated and deployed in the industry. One of the older and more established versions of NMT is the Encoder Decoder structure. This architecture is composed of two recurrent neural networks (RNNs) used together in tandem to create a translation model. And when coupled with the power of <a href="https://arxiv.org/pdf/1508.04025.pdf">attention mechanisms</a>, this architecture can achieve impressive results.</p><p>This post is broken into two distinct parts. The first section consists of a brief explanation of NMT and the Encoder Decoder structure. Following this, the latter part of this article provides a tutorial which will allow the chance for you to create one of these structures yourself. This code tutorial is based largely on the <a href="https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html">PyTorch tutorial on NMT</a> with a number of enhancements. Most notably, this code tutorial can be run on a GPU to receive significantly better results.</p><p>Before we begin, it is assumed that if you are reading this article you have at least a general knowledge of <a href="https://skymind.ai/wiki/neural-network">neural networks and deep learning</a>; particularly the ideas of forward-propagation, loss functions and back-propagation, and the importance of <a href="https://towardsdatascience.com/train-validation-and-test-sets-72cb40cba9e7">train and test sets</a>.</p><p><em>If you are interested in jumping straight to the code, you can find the complete Jupyter notebook (or Python script) of the Google Colab tutorial outlined in this article on my </em><a href="https://github.com/qlanners/nmt_tutorial"><em>GitHub page for this project</em></a><em>.</em></p><h3>Brief Explanation of NMT and the Encoder Decoder Structure</h3><p>The ultimate goal of any NMT model is to take a sentence in one language as input and return that sentence translated into a different language as output. The figure below is a naive representation of a translation algorithm (such as Google Translate) tasked with translating from English to Spanish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWNEL7xMGraPLS6d6hCqyA.png" /><figcaption>Figure 1: Translation from English to Spanish of the English sentence “the cat likes to eat pizza”</figcaption></figure><p>Before diving into the Encoder Decoder structure that is oftentimes used as the algorithm in the above figure, we first must understand how we overcome a large hurdle in any machine translation task. Namely, we need a way to transform sentences into a data format that can be inputted into a machine learning model. In essence, we must somehow convert our textual data into a numeric form.</p><p>To do this in machine translation, each word is transformed into a One Hot Encoding vector which can then be inputted into the model. A One Hot Encoding vector is simply a vector with a 0 at every index except for a 1 at a single index corresponding to that particular word. In this way, each word has a distinct One Hot Encoding vector and thus we can represent every word in our dataset with a numerical representation.</p><p>The first step towards creating these vectors is to assign an index to each unique word in the input language, and then repeat this process for the output language. In assigning a unique index to each unique word, we will be creating what is referred to as a Vocabulary for each language. Ideally, the Vocabulary for each language would simply contain every unique word in that language. However, given that any single language can have hundreds of thousands of words, the vocabulary is often trimmed to the N most common words in the dataset we are working with (where N is chosen arbitrarily, but often ranges from 1,000–100,000 depending on the dataset size).</p><p>To understand how we can then use a Vocabulary to create One Hot Encoding vectors for every word in our dataset, consider a mini-Vocabulary containing just the words in Table 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*_Pp0bAv3nZPYHbPFlvO7Hg.png" /><figcaption>Table 1: Mini-vocabulary for the English language</figcaption></figure><p>Given this table, we have assigned a unique index 0–12 to every word in our mini-Vocabulary. The &lt;SOS&gt; and &lt;EOS&gt; tokens in the table are added to every Vocabulary and stand for START OF SENTENCE and END OF SENTENCE respectively. They are used by the NMT model to help identify these crucial points in sentences.</p><p>Now, let’s say we want to convert the words in the sentence “the blue whale ate the red fish” to their one hot encoding vectors. Using Table 1, we would do this as shown in Figure 2 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*nxHrAM5dwoqqFFldP0Wv6w.png" /><figcaption>Figure 2: One Hot Encoding vectors for the sentence “the blue whale ate the red fish”</figcaption></figure><p>As you can see above, each word becomes a vector of length 13 (which is the size of our vocabulary) and consists entirely of 0s except for a 1 at the index that was assigned to that word in Table 1.</p><p>By creating a vocabulary for both the input and output languages, we can perform this technique on every sentence in each language to completely transform any corpus of translated sentences into a format suitable for the task of machine translation.</p><p>Now, with an understanding of how we can represent textual data in a numeric way, let’s look at the magic behind this Encoder Decoder algorithm. At the most basic level, the Encoder portion of the model takes a sentence in the input language and creates a <em>thought vector</em> from this sentence. This <em>thought vector</em> stores the meaning of the sentence and is subsequently passed to a Decoder which outputs the translation of the sentence in the output language. This process is shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeD0mc9o9DQZ59-nO95sPw.png" /><figcaption>Figure 3: Encoder Decoder structure translating the English sentence “the cat likes to eat pizza” to the Spanish sentence “el gato le gusta comer pizza”</figcaption></figure><p>In the above architecture, the Encoder and the Decoder are both recurrent neural networks (RNN). In this particular tutorial, we will be using Long Short-Term Memory (LSTM) models, which are a type of RNN. However other RNN architectures, such as a GRU, are often used. At a basic level, RNNs are neural networks designed specifically to deal with temporal/textual data. This article will give a high-level overview of how RNNs work in the context of NMT, however, I would strongly recommend looking further into these concepts if you are not already familiar with them. For a more thorough explanation of RNNs and LSTMs see <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">here</a>, and for a deeper article on LSTMs in the context of language translation, in particular, see <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.248.4448&amp;rep=rep1&amp;type=pdf">here</a>.</p><p>In the case of the Encoder, each word in the input sentence is fed separately into the model in a number of consecutive time-steps. At each time-step, <em>t</em>, the model updates a hidden vector, <em>h</em>,<em> </em>using information from the word inputted to the model at that time-step<em>. </em>This hidden vector works to store information about the inputted sentence. In this way, since no words have yet been inputted to the Encoder at time-step <em>t=</em>0, the hidden state in the Encoder starts out as an empty vector at this time-step. We represent this hidden state with the blue box in Figure 4, where the subscript <em>t</em>=0 indicates the time-step and the superscript E corresponds to the fact that it’s a hidden state of the Encoder (rather than a D for the Decoder).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*GZCzxYAMHdiCLiTTHNBsSw.png" /><figcaption>Figure 4: Encoder hidden vector at t=0</figcaption></figure><p>At each time-step, this hidden vector takes in information from the inputted word at that time-step, while preserving the information it has already stored from previous time-steps. Thus, at the final time-step, the meaning of the whole input sentence is stored in the hidden vector. This hidden vector at the final time-step is the <em>thought vector</em> referred to above, which is then inputted into the Decoder. The process of encoding the English sentence “the cat likes to eat pizza” is represented in Figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd8j4KoKRSzRq0b1Vx0FAA.png" /><figcaption>Figure 5: Encoding of the sentence “the cat likes to eat pizza”</figcaption></figure><p>In the above figure, the blue arrows correspond to weight matrices, which we will work to enhance through training to achieve more accurate translations.</p><p>Also, notice how the final hidden state of the Encoder becomes the thought vector and is relabeled with superscript D at <em>t</em>=0. This is because this final hidden vector of the Encoder becomes the initial hidden vector of the Decoder. In this way, we are passing the encoded meaning of the sentence to the Decoder to be translated to a sentence in the output language. However, unlike the Encoder, we need the Decoder to output a translated sentence of variable length. Thus, we are going to have our Decoder output a prediction word at each time-step until we have outputted a complete sentence.</p><p>In order to start this translation, we are going to input a &lt;SOS&gt; tag as the input at the first time-step in the Decoder. Just as in the Encoder, the Decoder will use the &lt;SOS&gt; input at time-step <em>t</em>=1 to update its hidden state. However, rather than just proceeding to the next time-step, the Decoder will use an additional weight matrix to create a probability over all of the words in the output vocabulary. In this way, the word with the highest probability in the output vocabulary will become the first word in the predicted output sentence. This first step of the Decoder, translating from “the cat likes to eat pizza” to “el gato le gusta comer pizza” is shown in Figure 6. For the sake of simplicity, the output vocabulary is restricted to the words in the output sentence (but in practice would consist of the thousands of words in the entire output vocabulary).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*0kJbrSpwyzneRE1hHUHB6g.png" /><figcaption>Figure 6: First step of the Decoder</figcaption></figure><p>Now, given that the word “el” was given the highest probability, this word becomes the first word in our outputted prediction sentence. And we proceed by using “el” as the input in the next time-step as in Figure 7 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*fIOdNSYBADB4452cRXWcsA.png" /><figcaption>Figure 7: Second step of the Decoder</figcaption></figure><p>We proceed in this way through the duration of the sentence — that is until we run into an error such as that depicted below in Figure 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*cMo4JhbtDkm1Wy1EnqhEkg.png" /><figcaption>Figure 8: Translation error in Decoder</figcaption></figure><p>As you can see, the Decoder has predicted “pizza” to be the next word in the translated sentence, when it should actually be “comer”. When testing the model on the test set, we would do nothing to correct this error and would allow the Decoder to use this improper prediction as the input at the next time-step. However, during the training process, we are going to keep “pizza” as the predicted word at that point in the sentence, but force our Decoder to input the correct word “comer” as the input for the next time-step. This is a strategy referred to as <a href="https://machinelearningmastery.com/teacher-forcing-for-recurrent-neural-networks/">teacher-forcing</a> and helps speed up the training process. It is shown in the below figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*ignkCc7wFznUGDBKN-3ylg.png" /><figcaption>Figure 9: Teacher-forcing</figcaption></figure><p>Now, since the Decoder has to output prediction sentences of variable lengths, the Decoder will continue predicting words in this fashion until it predicts the next word in the sentence to be a &lt;EOS&gt; tag. Once this tag has been predicted, the decoding process is complete and we are left with a complete predicted translation of the input sentence. The entire process of decoding the thought vector for the input sentence “the cat likes to eat pizza” is shown in Figure 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*GwKpF9yMipPWuruXoTWKPQ.png" /><figcaption>Figure 10: Decoding of the sentence “the cat likes to eat pizza”</figcaption></figure><p>We can then compare the accuracy of this predicted translation to the actual translation of the input sentence to compute a loss. While there are several varieties of loss functions, a very common one to utilize is the Cross-Entropy Loss. The equation of this loss function is detailed in Figure 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*JZ-qea3BYaGOT4Vdhds9mQ.png" /><figcaption>Figure 11: Cross-Entropy Loss function</figcaption></figure><p>In essence, what this loss function does is sum over the negative log likelihoods that the model gives to the correct word at each position in the output sentence. Given that the negative log function has a value of 0 when the input is 1 and increases exponentially as the input approaches 0 (as shown in Figure 12), the closer the probability that the model gives to the correct word at each point in the sentence is to 100%, the lower the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*GLLqWJkqlF4RcbuftbIIDA.png" /><figcaption>Figure 12: Graph of the function y = -log(x)</figcaption></figure><p>For example, given that the correct first word in the output sentence above is “el”, and our model gave a fairly high probability to the word “el” at that position, the loss for this position would be fairly low. Conversely, since the correct word at time-step <em>t</em>=5 is “comer”, but our model gave a rather low probability to the word “comer”, the loss at that step would be relatively high.</p><p>By summing over the loss for each word in the output sentence a total loss for the sentence is obtained. This loss corresponds to the accuracy of the translation, with lower loss values corresponding to better translations. When training, the loss values of several sentences in a batch would be summed together, resulting in a total batch loss. This batch loss would then be used to perform mini-batch gradient descent to update all of the weight matrices in both the Decoder and the Encoder. These updates modify the weight matrices to slightly enhance the accuracy of the model’s translations. Thus, by performing this process iteratively, we eventually construct weight matrices that are capable of creating quality translations.</p><p><em>If you are unfamiliar with the concept of batches and/or mini-batch gradient descent you can find a short explanation of these concepts </em><a href="https://machinelearningmastery.com/gentle-introduction-mini-batch-gradient-descent-configure-batch-size/"><em>here</em></a><em>.</em></p><p>As mentioned in the introduction, an attention mechanism is an incredible tool that greatly enhances an NMT model’s ability to create accurate translations. While there are a number of different types of attention mechanisms, some of which you can read about <a href="https://arxiv.org/pdf/1508.04025.pdf">here</a>, the model built in this tutorial uses a rather simple implementation of global attention. In this method of attention, at each time-step, the Decoder “looks back” at all of the hidden vectors of the Encoder to create a memory vector. It then uses this memory vector, along with the hidden vector in the Decoder at that time-step, to predict the next word in the translated sentence. In doing this, the Decoder utilizes valuable information from the Encoder that would otherwise go to waste. A visual representation of this process is shown in Figure 13. I’d recommend reading the linked article in this paragraph to learn more about the various ways this memory vector can be calculated to gain a better understanding of this important concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*ff0Uh3mefwAMH7Z0gNrqTQ.png" /><figcaption>Figure 13: Attention mechanism for time-step t=1 in Decoder</figcaption></figure><p><em>Note: Attention mechanisms are incredibly powerful and have recently been proposed (and shown) to be more effective when used on their own (i.e. without any RNN architecture). If you’re interested in NMT I’d recommend you look into transformers and particularly read the article “</em><a href="https://arxiv.org/pdf/1706.03762.pdf"><em>Attention Is All You Need</em></a><em>”.</em></p><h3><strong>Coding Tutorial (Python)</strong></h3><p>Before beginning the tutorial I would like to reiterate that this tutorial is derived largely from the PyTorch tutorial “<a href="https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html">Translation with a Sequence to Sequence Network and Attention</a>”. However, this tutorial is optimized in a number of ways. Most notably, this code allows for the data to be separated into batches (thus allowing us to utilize the enhanced parallel computing power of a GPU), can split datasets into a train and a test set, and also has added functionality to run on datasets of various formats.</p><p>Before we dive into the code tutorial, a little setup is in store. If you’d like to run the model on a GPU (highly recommended), this tutorial is going to be using Google Colab; which offers free access to Jupyter notebooks with GPU capability. If you have other access to a GPU then feel free to use that as well. Otherwise, you can look into a variety of other <a href="https://towardsdatascience.com/training-machine-learning-models-online-for-free-gpu-tpu-enabled-5def6a5c1ce3">free online GPU options</a>. The code can be run on a CPU, but the capability of any model will be constricted by computational power (and make sure to change to batch-size to 1 if you choose to do so).</p><p>To get started, navigate to <a href="https://colab.research.google.com/">Google Colaboratory</a> and log into a Google account to get started. From here, navigate to File &gt; New Python 3 Notebook to launch a Jupyter notebook. Once you’ve opened up a new notebook, we first need to enable GPU capabilities. To do so, navigate to the top left of the page and select Edit &gt; Notebook Settings. From here select GPU in the dropdown menu under “Hardware accelerator.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*xPZ_B0b44kdYuRp9jhQI1A.png" /><figcaption>Figure 14: Enabling GPU capabilities on Google Colab</figcaption></figure><p>We now have a Jupyter notebook with GPU capabilities and can start working towards creating an NMT model! First, we will import all of the necessary packages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd69bfd55f042d4c045055b4561fc2e9/href">https://medium.com/media/bd69bfd55f042d4c045055b4561fc2e9/href</a></iframe><p>Now, run the following code to check if GPU capabilities are enabled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/118f6197a18173b97b6f93b4f69a0a29/href">https://medium.com/media/118f6197a18173b97b6f93b4f69a0a29/href</a></iframe><p>If TRUE is returned, GPU is available. Now, before we begin doing any translation, we first need to create a number of functions which will prepare the data. The following functions serve to clean the data and allow functionality for us to remove sentences that are too long or whose input sentences don’t start with certain words.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c118cd5ee74be2e066c9d99dd294f881/href">https://medium.com/media/c118cd5ee74be2e066c9d99dd294f881/href</a></iframe><p>Now, with functions that will clean the data, we need a way to transform this cleaned textual data into One Hot Encoding vectors. First, we create a <em>Lang </em>class which will essentially allow us to construct a vocabulary for both the input and output languages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b6b7c16f612f6761d67a62eafdc931/href">https://medium.com/media/61b6b7c16f612f6761d67a62eafdc931/href</a></iframe><p>Next, we create a <em>prepareLangs</em> function which will take a dataset of translated sentences and create <em>Lang</em> classes for the input and the output languages of a dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a4b9e8ea8632e5c6844b1bcc67ca6da/href">https://medium.com/media/5a4b9e8ea8632e5c6844b1bcc67ca6da/href</a></iframe><p>This function has the ability to work with input and output sentences that are contained in two separate files or in a single file. If the sentences are in two separate files, each sentence must be separated by a newline and each line in the files must correspond to each other (i.e. make a sentence pair). For example, if your input file is english.txt and output file in espanol.txt the files should be formatted as in Figure 15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCEe0bM_9WB00iZEYWj90Q.png" /><figcaption>Figure 15: Format for dataset stored in two separate files.</figcaption></figure><p>On the other hand, if the input and output sentences are stored in a single file, each sentence in the pair must be separated by a tab and each sentence pair must be separated by a newline. For example, if your single file name is data.txt, the file should be formatted as in Figure 16.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*hK9a8XjUdkyv-_nHd80KYw.png" /><figcaption>Figure 16: Format for dataset stored in one single file.</figcaption></figure><p><em>Note: In order for this function to work with both one and two files, the file_path argument must be in the tuple format with two elements in the tuple if the data is stored in two files, and one element in the tuple if the data is stored in a single file.</em></p><p>With a function that works to prepare the language vocabularies for both the input and output languages, we can use all of the above functions to create a single function that will take a dataset of both input and target sentences and complete all of the preprocessing steps. Thus, the <em>prepareData </em>function will creates <em>Lang</em> classes for each language and fully clean and trim the data according to the specified passed arguments. In the end, this function will return both language classes along with a set of training pairs and a set of test pairs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8af8b00bfe7b13a1bc44f37602c06e9/href">https://medium.com/media/a8af8b00bfe7b13a1bc44f37602c06e9/href</a></iframe><p>While we have created a vocabulary for each language, we still need to create functions which use these vocabularies to transform sentence pairs both to and from their One Hot Encoding vector representations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c08bbc45d47676da696d5b78e0fee0b/href">https://medium.com/media/6c08bbc45d47676da696d5b78e0fee0b/href</a></iframe><p>NMT is no different than normal machine learning in that <a href="https://machinelearningmastery.com/gentle-introduction-mini-batch-gradient-descent-configure-batch-size/">minibatch gradient descent is the most effective way to train a model</a>. Thus, before we begin building our model, we want to create a function to <em>batchify</em> our sentence pairs so that we can perform gradient descent on mini-batches. We also create the function <em>pad_batch</em> to handle the issue of variable length sentences in a batch. This function essentially appends&lt;EOS&gt; tags to the end of each of the shorter sentences until every sentence in the batch is the same length.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dabbf9329432bd02019676b4a428ea4/href">https://medium.com/media/9dabbf9329432bd02019676b4a428ea4/href</a></iframe><p>And with that, we have created all of the necessary functions to preprocess the data and are finally ready to build our Encoder Decoder model! With a general understanding of the Encoder Decoder architecture and attention mechanisms, let’s dive into the Python code that creates these frameworks. Rather than explain each aspect of the Encoder and the Decoder, I will simply provide the code and refer you to the <a href="https://pytorch.org/docs/stable/nn.html">PyTorch documentation</a> for any questions you may have on various aspects of the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab5858243109b65ba4955d1a9388ca54/href">https://medium.com/media/ab5858243109b65ba4955d1a9388ca54/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa0825d74b85e610860945aef1ae82b5/href">https://medium.com/media/fa0825d74b85e610860945aef1ae82b5/href</a></iframe><p>Now, in order to train and test the model, we will use the following functions. The <em>train_batch</em> function below performs a training loop on a single training batch. This includes a completing a forward pass through the model to create a predicted translation for each sentence in the batch, computing the total loss for the batch, and then back-propagating on the loss to update all of the weight matrices in both the Encoder and the Decoder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4017f05c5ffdbd73329597ff5ac0a367/href">https://medium.com/media/4017f05c5ffdbd73329597ff5ac0a367/href</a></iframe><p>The <em>train</em> function simply performs the <em>train_batch</em> function iteratively for each batch in a list of batches. In this way, we can pass a list of all of the training batches to complete a full epoch through the training data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/565cb44177dbda1652647dd73a426e43/href">https://medium.com/media/565cb44177dbda1652647dd73a426e43/href</a></iframe><p>The following <em>test_batch</em> and <em>test</em> functions are essentially the same as the <em>train_batch</em> and <em>train</em> functions, with the exception that these test functions are to be performed on the test data and do not include a back-propagation step. Thus, these functions do not update the weight matrices in the model and are solely used to evaluate the loss (i.e. the accuracy) on training data. In turn, this will help us track how the model performs on data outside of the training set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0fb61030e7bce77474bbaa6d916ae5f/href">https://medium.com/media/d0fb61030e7bce77474bbaa6d916ae5f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fda944e8f24fc716014caa77b5789b66/href">https://medium.com/media/fda944e8f24fc716014caa77b5789b66/href</a></iframe><p>During training, it will also be nice to be able to track our progress in a more qualitative sense. The <em>evaluate </em>function will allow us to do so by returning the predicted translation that our model makes for a given input sentence. And the <em>evaluate_randomly</em> function will simply predict translation for a specified number of sentences chosen randomly from the test set (if we have one) or the train set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a760c84a0855b1fcf81a252e3547dd2/href">https://medium.com/media/5a760c84a0855b1fcf81a252e3547dd2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9581f11b954cb58f0291bbc903684493/href">https://medium.com/media/9581f11b954cb58f0291bbc903684493/href</a></iframe><p>A few helper functions below will work to plot our training progress, print memory consumption, and reformat time measurements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f80e72a3719f6df455b816c8b9fdcdca/href">https://medium.com/media/f80e72a3719f6df455b816c8b9fdcdca/href</a></iframe><p>And finally, we can put all of these functions into a master function which we will call <em>train_and_test</em>. This function will take quite a few arguments, but will completely train our model while evaluating our progress on the train set (and test set if present) at specified intervals. Also, some arguments will specify whether we want to save the output in a separate .txt file, create a graph of the loss values over time, and also allow us to save the weights of both the Encoder and the Decoder for <a href="https://pytorch.org/tutorials/beginner/saving_loading_models.html">future use</a>. The next few cells after this function will outline how you can modify each argument, but just know that this function will essentially be all we need to run in order to train the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba5254761ac61bc2d648748a8df608fd/href">https://medium.com/media/ba5254761ac61bc2d648748a8df608fd/href</a></iframe><p>Now that we have everything in place we are ready to import our dataset, initialize all of the hyperparameters, and start training!</p><p>First, in order to upload a dataset, run the following cell:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29e76b165da70d8d808321308a08e9b1/href">https://medium.com/media/29e76b165da70d8d808321308a08e9b1/href</a></iframe><p>And you will see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*pHnANxJlp7IdPElhnvJWLw.png" /><figcaption>Figure 17: Upload data to Google Colab</figcaption></figure><p>Simply click on the “Choose Files” button and navigate to the dataset you wish to upload. In this tutorial, we are using the same dataset that was used in the original PyTorch tutorial. You can download that dataset of English to French translations <a href="https://github.com/qlanners/nmt_tutorial/blob/master/eng-fra.txt">here</a>. You can also experiment with a number of other datasets of various languages <a href="https://www.manythings.org/anki/">here</a>.</p><p>If you are looking to get more state-of-the-art results I’d recommend trying to train on a larger dataset. You can find some larger datasets <a href="http://www.statmt.org/wmt14/translation-task.html">here</a>, but also feel free to use any corpus of translated excerpts as long as they are formatted like in Figure 15 or Figure 16 above.</p><p><em>Note: You may have issues uploading larger datasets to Google Colab using the upload method presented in this tutorial. If you run into such issues, read </em><a href="https://www.freecodecamp.org/news/how-to-transfer-large-files-to-google-colab-and-remote-jupyter-notebooks-26ca252892fa/"><em>this article</em></a><em> to learn how to upload large files.</em></p><p>Now, run the following cell to ensure that your dataset has been successfully uploaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*TNecR90YCwzPKhiOZCNytg.png" /><figcaption>Figure 18: Run ls to ensure dataset has been uploaded</figcaption></figure><p>From here, edit the following cells to apply to your dataset and desires.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d4c039e1ad50572e039fab8c5069b60/href">https://medium.com/media/1d4c039e1ad50572e039fab8c5069b60/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7acaea7efff11aca26a6229229e7d266/href">https://medium.com/media/7acaea7efff11aca26a6229229e7d266/href</a></iframe><p>The following cell consists of the variety of hyperparameters that you are going to need to play with towards finding an effective NMT model. So have fun experimenting with these.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/153749da86a552396f6f5b337c8a7f1d/href">https://medium.com/media/153749da86a552396f6f5b337c8a7f1d/href</a></iframe><p>And finally, you just need to run the following cell to train your model according to all of the hyperparameters you set above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3db3f786423bee16cbf00e56a3b20a4f/href">https://medium.com/media/3db3f786423bee16cbf00e56a3b20a4f/href</a></iframe><p>And voilà! You have just trained an NMT model! Congrats! If you saved any graphs, output files, or output weights, you can view all of the saved files by running ls again. And to download any of these files simply run the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddfb20e15e57ca77421e58d1878758fc/href">https://medium.com/media/ddfb20e15e57ca77421e58d1878758fc/href</a></iframe><p>Now, if you’d like to test the model on sentences outside both the train and the test set you can do that as well. Just make sure the sentence you are trying to translate is in the same language as the input language of your model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7be36498a19c0a0b265758994f171a6/href">https://medium.com/media/f7be36498a19c0a0b265758994f171a6/href</a></iframe><p>I trained my model and the PyTorch tutorial model on the same dataset used in the PyTorch tutorial (which is the same dataset of English to French translations mentioned above). To preprocess the data, the trim was set to 10 and the eng_prefixes filters that PyTorch used was set to TRUE. With these restrictions, the dataset was cut to a rather small set of 10,853 sentence pairs. The PyTorch tutorial broke one of the fundamental rules of machine learning and didn’t to use a test set (not good practice!). So, just for comparison purposes, I kept all of these sentence pairs in my train set and didn’t use a test set (i.e. perc_train_set = 1.0). However, I’d recommend that you always use a test set when training any sort of machine learning model.</p><p>A comparison of the hyperparameters I chose for my model vs. the hyperparameters in the PyTorch tutorial model is shown in Table 1. The graph below in Figure 19 depicts the results of training for 40 minutes on an NVIDIA GeForce GTX 1080 (a bit older GPU, you can actually achieve superior results using Google Colab).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*ldHhAVYcbeRxZcQ4u3HPWQ.png" /><figcaption>Table 1: Hyperparameters comparison</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWMmg6860K7Q8uXhOKAk4A.png" /><figcaption>Figure 19: Loss over 40 minute training period for this tutorial model (My Model) vs PyTorch Tutorial Model</figcaption></figure><p>Since this dataset has no training set, I evaluated the model on a few sentences from the train set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*rUvPuDqINjJPUwnpe8uyEw.png" /><figcaption>Figure 20: Predicted translation of PyTorch tutorial model (Blue) vs. My Model (Orange)</figcaption></figure><p>From these results, we can see that the model in this tutorial can create a more effective translation model in the same amount of training time. However, when we try to use this model to translate sentences outside of the train set, it immediately breaks down. We can see this in the model’s attempted translation of the following sentence which was NOT in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*XpJeIJvIWRivzTtG5ZHxdw.png" /><figcaption>Figure 21: Failed translation on sentence outside the dataset.</figcaption></figure><p>This failure of the model is largely due to the fact that it was trained on such a small dataset. Furthermore, we were not aware of this problem because we had no test set to check the model’s ability to translate on sentences outside of the train set. To combat this issue, I retrained my model on the same dataset, this time with a trim=40 and without the eng_prefixes filter. Even when I set aside 10% of the sentence pairs for a train set, the test set was still over 10x the size of the one used to train the model before (122,251 train pairs). I also modified the hidden size of the model from 440 to 1080 and decreased the batch size from 32 to 10. Finally, I changed the initial learning rate to 0.5 and installed a learning rate schedule which decreased the learning rate by a factor of five after every five epochs.</p><p>With this larger dataset and updated hyperparameters, the model was trained on the same GPU. The loss on the train and test set during training, as well as the translation of the same sentence it failed on above, are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*6v4ywPVnzs2Km4HkAPlCZw.png" /><figcaption>Figure 22: Train and Test loss vs. time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*rAAWxzXj8zRfE6cfxrEzOQ.png" /><figcaption>Figure 23: Improved (yet still imperfect) translation of sentence outside of the dataset.</figcaption></figure><p>As you can see, the translation of this sentence is significantly improved. However, in order to achieve a perfect translation, we would probably need to increase the size of the dataset by even more.</p><h3>Conclusion</h3><p>While this tutorial provides an introduction to NMT using the Encoder Decoder structure, the implemented attention mechanism is rather basic. If you are interested in creating a more state-of-the-art model I’d recommend looking into the concept of local attention and attempting to implement this more advanced type of attention within the Decoder portion of the model.</p><p>Otherwise, I hope you enjoyed the tutorial and learned a lot! The basis of the material covered in this post was from my thesis at Loyola Marymount University. If you want to take a look at the PPT presentation I used to share these ideas (which includes the majority of the images in this article) you can find that <a href="https://github.com/qlanners/nmt_tutorial/blob/master/thesis_presentation.pptx">here</a>. You can also read the Thesis paper I wrote on the topic, which explains the math behind NMT in much greater depth, <a href="https://github.com/qlanners/nmt_tutorial/blob/master/quinn_thesis_final.pdf">here</a>. And lastly, the full Jupyter notebook for this project can be found <a href="https://github.com/qlanners/nmt_tutorial/blob/master/nmt_tutorial.ipynb">here</a> or alternatively a Python script version can be found <a href="https://github.com/qlanners/nmt_tutorial/blob/master/nmt_tutorial.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15ecf6b0b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/neural-machine-translation-15ecf6b0b">Neural Machine Translation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>