<?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 Suhyun Kim on Medium]]></title>
        <description><![CDATA[Stories by Suhyun Kim on Medium]]></description>
        <link>https://medium.com/@logicdevildotcom?source=rss-1d1f38878ecd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vjNCwX_TslAa_hG7k9P2qw.jpeg</url>
            <title>Stories by Suhyun Kim on Medium</title>
            <link>https://medium.com/@logicdevildotcom?source=rss-1d1f38878ecd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:50:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@logicdevildotcom/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[Machine Learning Serverlessly Using AWS Lambda, Docker, ECR, S3 and API Gateway]]></title>
            <link>https://medium.com/data-science/machine-learning-serverlessly-1a532685fa7c?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a532685fa7c</guid>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[simple-storage-service]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[elastic-container-service]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Mon, 24 Jan 2022 18:50:17 GMT</pubDate>
            <atom:updated>2022-03-02T01:41:05.583Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>How to build a complicated Machine Learning web application serverlessly on AWS</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*iC88HAvkVlG-4MCj.gif" /><figcaption>GIF by author</figcaption></figure><p>A lot of work and effort goes into productionizing a machine learning based product. We recently finished developing a <a href="https://share.streamlit.io/gitskim/aqa_streamlit/main/main.py">web application</a> to predict an Olympic diver’s performance. Given an Olympic diver’s video, the web app predicts what score a human judge would give and outputs the score. The ML models were already trained on-premises and we had to deploy and productionize them into a service. We chose a serverless architecture so that we don’t have to provision, run and maintain servers but instead focus on developing a user-friendly application. Below is the React web app implementing the serverless architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*karsS_nGt7ao2NVlYiy7Gw.png" /><figcaption>image by author</figcaption></figure><p>In this post, we will introduce our deployment design and implementation of a simple but “complicated” Machine Learning web application hosted on AWS. It is a very simple project that only has one function, to make a prediction score of the diving action from a user uploaded video. But we do consider this project “complicated” for the following 3 reasons:</p><ol><li>The web application needs to receive a user-uploaded video, which is relatively large (up to 200MB), as an input.</li><li>The Machine Learning models that are involved in the prediction process are relatively large (564MB) in size.</li><li>The web application needs to wait for the prediction process which takes quite some time (maybe more than a few minutes) to finish.</li></ol><p>For the theory behind the Machine Learning part of our prediction process, you can find more<a href="https://medium.com/@logicdevildotcom/training-ai-to-score-olympic-events-649b41574160"> in this article</a> if you are interested. Here we will only introduce our deployment design and discuss the tools we use in detail. The following is our cloud architecture design diagram, and we will discuss each part of the architecture in detail below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MMyJAhzbtTpzcwEo" /><figcaption>image by author</figcaption></figure><p>In a nutshell, our front-end React service is hosted in AWS Amplify and it interacts with AWS API Gateway endpoints that are connected to AWS Lambda, AWS Simple Storage Service (S3), and AWS DynamoDB.</p><h3>How shall we handle (large) user uploaded data?</h3><p>The user uploads a video file as an input through our front-end React service. It’s not easy to handle a video file on the front end due to its large size. In our case, the user can upload one video at a time and each file has to be less than 200 MB. The red arrows (#1 — #8) describe handling of the input file from the client and that’s what we will describe below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9ZHN71Wu3HuZRQ46" /><figcaption>image by author</figcaption></figure><p>When the user is uploading a large file, the best way to handle it at the frontend is DON’T. We followed<a href="https://aws.amazon.com/blogs/compute/uploading-to-amazon-s3-directly-from-a-web-or-mobile-application/"> this documentation from AWS</a> about how to send the videos directly to S3, which will notify our backend when it detects a newly uploaded video. The video file originates on the user’s computer, and our front end code uploads the file into an S3 bucket (arrows 1 through 7); the S3 bucket has a trigger on it (arrow 8) so that once the upload is done, the lambda with the model in it gets invoked on the new video input (arrow 9).</p><p>In brief, our frontend does these 2 things:</p><ol><li>When receiving a video, the frontend sends a GET request to our HTTP API (arrow 1) and the lambda function behind it to get a pre-signed URL of the S3 bucket that stores all the user uploaded videos (arrows 2 and 3).</li><li>After getting the pre-signed URL (arrows 4, 5, and 6), the frontend sends a PUT request to that URL with the video in body as binary data, which gets deposited into the S3 bucket (arrow 7). Once the data is uploaded into the bucket, a trigger fires, alerting the model lambda that new data is ready (arrow 8).</li></ol><p>The above tutorial is detailed enough for one to follow and understand the basics of it. But sometimes adjusting a tutorial to our own specific needs can still be challenging. Hence we will link our codebase <a href="https://github.com/yumyumqing/AQA_s3_presigned_url">here</a>.</p><p>This is the lambda function that generates a pre-signed URL from S3.</p><p><a href="https://github.com/yumyumqing/AQA_s3_presigned_url/blob/main/getSignedURL/app.py">https://github.com/yumyumqing/AQA_s3_presigned_url/blob/main/getSignedURL/app.py</a></p><p>This is the <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html">SAM</a> template we have for this lambda function and the HTTP API in front of it.</p><p><a href="https://github.com/yumyumqing/AQA_s3_presigned_url/blob/main/template.yaml#L6-L70">https://github.com/yumyumqing/AQA_s3_presigned_url/blob/main/template.yaml#L6-L70</a></p><p>You can see that we implemented an AWS API gateway for our front-end application to get a pre-signed URL <a href="https://github.com/yumyumqing/AQA_s3_presigned_url/blob/main/template.yaml#L65">here</a>. When you deploy the stack using <strong><em>sam deploy –guided</em></strong>, following <a href="https://aws.amazon.com/blogs/compute/uploading-to-amazon-s3-directly-from-a-web-or-mobile-application/">this documentation from AWS</a>, you might encounter the AWS SAM CLI error:</p><blockquote>“Security Constraints Not Satisfied.” It occurs when you answer No to this question: HelloWorldFunction may not have authorization defined, Is this okay? [y/N]. You can find detailed information to fix the issue <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-deploying.html">here</a>.</blockquote><p>It might seem a bit complicated to set up all of these (it means we need to learn all these tools first!) when we could instead send the videos from the frontend directly to the host that runs the inference code. However, in this case we would be responsible for a great deal more operational detail: the multi-part transmission of the large video, waiting for the large file to arrive, the encodings, the checks, the temporary and permanent storage handling of these data and many more things we might not even think of.</p><h3>How to deploy large Machine Learning models serverlessly</h3><p>Next, the user data gets processed in AWS lambda. AWS Lambda is “a serverless event-driven compute service that lets you run code without provisioning or managing servers.” It’s pretty much an abstracted backend where you can implement it as if you are just implementing a function. AWS Lambda manages scaling, and supports high availability and fault tolerance on behalf of their clients. Lambda deployment package is a zip file, which contains code, libraries and dependencies. However, the package size limit for lambda got in our way because the total size of our files and ML models to be deployed is at least 564MB, but Lambda imposes the following size limits:</p><blockquote>Deployment package size limit for a zipped file: 50MB</blockquote><p>In December 2020, AWS started supporting the feature to deploy a Docker container image as a lambda function. You can check more information on Docker here (​https://www.docker.com/). It means a docker container image can be deployed to lambda instead of a zip file. One just has to make sure that container images are linux-based. The good thing for us about using a docker image for Lambda is that it provides more space. Our models don’t even come close to fitting inside the 50 MB Lambda allows, but do fit inside the limits you get when you deploy a Docker image to Lambda. These limits are a bit more complicated to deal with, but it still works out to a lot more space for your models.</p><p>As for serverless deployment of models, there were not a lot of options available and a lambda container was our best bet to be able to contain the half-gigabyte models. Unlike Sagemaker, lambda docker did not require multiple things such as endpoints and endpoint configurations to manage. Most importantly, lambda provided a true serverless solution without having to choose a particular instance for deployment. Lambda container deployment has the following limits that are important to keep in mind:</p><blockquote>Deployment package size limit for lambda container image: 10GB</blockquote><blockquote>Temporary file system storage at /tmp: 512 MB</blockquote><p>The information above is very important in order to figure out where ML models belong. We considered two options: (1) S3, and (2) attaching the models to the container image with the inference code files. With the option #1, the ML models need to be loaded from S3 into the container image. Any extra file that is loaded from somewhere else such as S3 gets written to temporary file storage at /tmp and that’s the only path available for external files to be downloaded to. The max size of the files that can be written to the path is 512 MB. However, the total size of our models is 564MB, which exceeds the limit of temporary file system storage. Therefore, we went with the option #2 to attach our models as one of the code files to a container image.</p><h4><strong>Step 1. Write a Dockerfile</strong></h4><p>In our example, we’re pulling an image from the public aws repositories and setting the base image with lambda python 3.7. It’s important to set up the base image to be a lambda base image. Most dockerfiles start with a FROM instruction and the image can be any valid image. Then the inference code package for lambda is copied to the working directory so that the code could be available for subsequent instructions. Since we have a brand new image, we’re installing necessary libraries and setting variables afterwards with the RUN, which executes commands inside your docker image. Requirements.txt contains every library we want to have installed in a brand new image. At the end, CMD executes a command line to call the lambda handler and specify the name of your file where your lambda handler is located.</p><h4><strong>Step 2. Write inference logic</strong></h4><ul><li><strong>Model location</strong></li></ul><p>We considered having our ML models in S3 and downloading them, but this time we attached the models to the docker container. It means when we packaged our container, we left our models as files for our inference logic to directly consume the models. Here, we attached the model and its weight files in our deployment.</p><ul><li><strong>Handler file</strong></li></ul><p>Under the handler function name you specified in the Dockerfile, you can add your inference logic. For the handler, the following template is suggested:</p><p><strong><em>def handler_name (event, context):</em></strong></p><p>You can choose to return a value or not. In our case, we return a prediction value so that a client application can display the prediction value.</p><h4><strong>Step 3. Add cloud formation template</strong></h4><p><a href="https://github.com/yumyumqing/AQA_s3_presigned_url/blob/main/template.yaml#L75">https://github.com/yumyumqing/AQA_s3_presigned_url/blob/main/template.yaml#L75</a></p><p>You can configure your lambda container for cloud formation to automate the deployment. Make sure the type is ‘AWS::Serverless::Function’ and the package type is “Image” to indicate that it’s a lambda docker image container. You can get further information on this from here: <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-images.html#configuration-images-cloudformation">https://docs.aws.amazon.com/lambda/latest/dg/configuration-images.html#configuration-images-cloudformation</a> Also, you can easily integrate lambda functions to be notified by changes in S3. As noted under the Events section, we made it so that S3 sends an event to a lambda function when an object is created or deleted.</p><h4><strong>Step 4. Local Test: Verify the functionality</strong></h4><p>In order to test its functionality locally, we will test by running <em>sam build</em>. Make sure to download docker and have it running before you test it locally. Then, make sure you have the right sample data information available in your sample_data.json. In our case, we are using the video file in s3, so we had our video and s3 information in sample_data.json. Then run sam local invoke &lt;function name&gt; -e &lt;sample event file&gt;</p><p><em>sam local invoke “ProcessPredictFunction” -e getPredScore/sample_event.json</em></p><p>There’s another way to test your lambda function locally, which does not involve aws sam, and it’s AWS Lambda Runtime Interface Emulator (RIE). You can get more information <a href="https://docs.aws.amazon.com/lambda/latest/dg/images-test.html">here</a>, but I found using SAM much easier to test my lambda function.</p><h4><strong>Step 5. Deploy with sam build</strong></h4><p>Then you can deploy the app using sam again. It’s simply <strong><em>sam deploy –guided</em></strong>. After the deployment is over, you will see that the docker image is deployed to AWS Elastic Container Registry (ECR) and the lambda function refers to the image in the ECR.</p><p>Lambda docker container image provided an interesting solution to launch our ML models serverlessly. It is simple to attach the models as code and deploy in a packaged container. The convenient integration of S3 with lambda provided a more independent and secure solution. It’s independent because our front-end application just has to put the inputted video data to S3 without having to touch other parts of the architecture and our lambda function gets automatically triggered to process the input video and make a prediction on it. It’s secure because the front-end application does not have to contain any authentication information in its attempt to directly invoke the lambda function.</p><h4><strong>How to handle long prediction requests?</strong></h4><p>Machine learning predictions can sometimes take quite a long time to process. We will now describe how we handled prediction results from our machine learning models, and the process is represented with red arrows in the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AWeabmhkccdt7poR" /><figcaption>image by author</figcaption></figure><p>Instead of keeping our frontend waiting and listening for slow response, we incorporated DynamoDB to store the results sent from our backend and make our React frontend ping the database every five seconds to check whether the result is ready and refresh the browser with the newest status. In this way, we are using more pings to avoid long open connections.</p><p>In our lambda function that makes the prediction, we send the score to our DynamoDB table whenever it’s ready, and you can see the code <a href="https://github.com/yumyumqing/AQA_s3_presigned_url/blob/e5e23e16cab7dad246f300e39c31d28b097576fe/getPredScore/process_predict.py#L93-L109">here</a>. Our frontend keeps pinging a HTTP Api that is tied to a lambda function which talks to our DynamoDB table. <a href="https://github.com/yumyumqing/aqa_frontend/blob/main/src/App.js#L108">Here’s</a> the front-end implementation to continuously pinging the DB for the prediction result availability.</p><p><strong>You can also check out HTTP Api and lambda function behind it</strong>:</p><p><a href="https://github.com/yumyumqing/AQA_s3_presigned_url/blob/e5e23e16cab7dad246f300e39c31d28b097576fe/template.yaml#L100-L118">https://github.com/yumyumqing/AQA_s3_presigned_url/blob/e5e23e16cab7dad246f300e39c31d28b097576fe/template.yaml#L100-L118</a></p><p><a href="https://github.com/yumyumqing/AQA_s3_presigned_url/blob/e5e23e16cab7dad246f300e39c31d28b097576fe/fetchScore/app.py">https://github.com/yumyumqing/AQA_s3_presigned_url/blob/e5e23e16cab7dad246f300e39c31d28b097576fe/fetchScore/app.py</a></p><p><strong>Our frontend deployment (AWS Amplify).</strong></p><p>We used AWS Amplify to deploy our frontend code. It has nice continuous deployment features and since our codebase resides on AWS CodeCommit, whenever we push a new change, it will rebuild and redeploy our app by default without our website down. AWS Amplify can also detect React apps well enough to pick up our configuration file directly and start working on itself. Here is more <a href="https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-one/?e=gs2020&amp;p=build-a-react-app-intro">information</a> about how to deploy a React app on AWS Amplify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hQH6WM-DxpGT6Qw7" /><figcaption>image by author</figcaption></figure><h4><strong>Conclusion</strong></h4><p>We demonstrated a serverless architecture design for our machine learning service. The design is not as simple as the functionality of our service sounds. Multiple AWS components were used including AWS Amplify, HTTP API Gateway, Lambda, Simple Storage Service (S3), Elastic Container Registry (ECR) and DynamoDB.</p><p><em>This is collaborative work with </em><a href="https://www.linkedin.com/in/yanqing-dai-2001948a/"><em>Yanqing Dai</em></a></p><h3>Note</h3><p><a href="https://www.linkedin.com/in/yanqing-dai-2001948a/"><em>Yanqing Dai</em></a><em> and </em>I started ourfreelance business. We accept freelance work focusing on productionizing machine learning services, data engineering and distributed systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a532685fa7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/machine-learning-serverlessly-1a532685fa7c">Machine Learning Serverlessly Using AWS Lambda, Docker, ECR, S3 and API Gateway</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[Deploying your ML models to AWS SageMaker]]></title>
            <link>https://medium.com/data-science/deploying-your-ml-models-to-aws-sagemaker-6948439f48e1?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6948439f48e1</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 13:58:17 GMT</pubDate>
            <atom:updated>2022-03-02T01:40:00.730Z</atom:updated>
            <content:encoded><![CDATA[<h4>For the 2021 Summer Olympics, we created this web <a href="https://share.streamlit.io/gitskim/aqa_streamlit/main/main.py">app</a> to predict the score that a human judge would give to a diving video. We made our app using the <a href="https://streamlit.io/">Streamlit.io</a> library.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DvAYkY7W9sdx1qg2LtcZPg.gif" /><figcaption>GIF created by Suhyun Kim</figcaption></figure><p>We faced some difficulties with Streamlit.io so we decided to deploy our ML models to AWS SageMaker. You can see our SageMaker implementation <a href="https://github.com/gitskim/AQA_SageMaker">here</a>. The purpose of this article is to provide a tutorial with examples showing how to deploy ML models to AWS SageMaker. This tutorial covers <strong>only deploying ML models that are not trained in SageMaker.</strong> It is more complicated to deploy your ML models that are trained outside of AWS SageMaker than training the models and deploy end-to-end within SageMaker. There is some example <a href="https://github.com/aws/amazon-sagemaker-examples/tree/master/advanced_functionality/scikit_bring_your_own/container">code</a> on how to deploy your models that are trained on-premises, but it wasn’t enough to support our product, so we had to take it a lot further. I will first describe the high level architecture of how SageMaker works with model deployment and then provide step-by-step instructions.</p><p>If you want to use SageMaker as the service to deploy your model, it involves deploying to 3 AWS services: <strong>AWS SageMaker</strong>, <strong>AWS Elastic Container Registry (ECR)</strong>, which provides versioning and access control for container images, and <strong>AWS Simple Cloud Storage (S3)</strong>. The diagram below describes the process in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hifjxx9zOkFyQYFe8O5wIQ.png" /><figcaption>Image Created by Suhyun Kim</figcaption></figure><p>It starts with putting your tarballed ML models into an AWS S3 bucket. Then you deploy your Docker image to AWS ECR, which will be consumed by your SageMaker. Docker is used to package your ML inference logic code into a containerized environment. SageMaker will also consume your models in S3 as well. As a client, you only interact with the SageMaker endpoint, which downloads your models from S3 first and invokes your ML inference code from ECR.</p><p>First, I want to describe what’s in the sample <a href="https://github.com/aws/amazon-sagemaker-examples/tree/master/advanced_functionality/scikit_bring_your_own/container">code</a> provided by AWS, which describes the architecture under ECR. The sample <a href="https://github.com/aws/amazon-sagemaker-examples/tree/master/advanced_functionality/scikit_bring_your_own/container">code</a> follows the basic server architecture and the code is meant to be deployed to ECR.</p><ol><li><strong>Nginx</strong> is a web server and it is where HTTP requests arrive first. It handles requests in a way to let only valid requests through.</li><li><strong>Gunicorn</strong> is “a WSGI pre-forking worker server that runs multiple copies of your application and load balances between them.” (<a href="https://github.com/aws/amazon-sagemaker-examples/tree/master/advanced_functionality/scikit_bring_your_own/container">cite</a>) It calls your Python code when a request comes in.</li><li><strong>Flask</strong> is a python web framework that lets you specify the logic of how to handle your ML inference requests. It lets you respond to <em>/ping</em> and <em>/invocations</em>.</li></ol><p>The sample <a href="https://github.com/aws/amazon-sagemaker-examples/tree/master/advanced_functionality/scikit_bring_your_own/container">code</a> provides <em>build_and_push.sh</em>, which builds the docker container and pushes it to AWS ECR by running the script. Before you run the script, I recommend that you go to the AWS ECR page and try to manually publish the image to the ECR. Then you will see the same commands inside the script recommended on the ECR page.</p><p>Now I will describe what needs to be done for the AWS SageMaker part. This is where you declare hardware instances for your inference. You also create the endpoint with which your client communicates with your ML service. In order to get a fully functioning instance, you need to create a SageMaker Model, SageMaker Endpoint Configuration and SageMaker Endpoint.</p><ol><li><strong>The Model</strong> refers to the location of the docker container and your ML models. One thing to note is that you can either attach your ML models to the docker container or you can put the compressed models, which must be in the tar.gz format, in your S3. Then SageMaker will download the compressed model files in the <em>opt/ml/model</em> directory and in your inference code, you need to refer to the model in that directory.</li><li><strong>The Endpoint Configuration</strong> is where you connect the Model (from step 1) to the endpoint (step 3). The endpoint is the part of Sagemaker that interfaces with the outside world. You can create different variants so that beta and prod use a different Model. That way, you can also configure the amount of traffic going into the different variants. For example, if you want to do A/B testing on your ML models, you can use production variants to divide the traffic and see how each of your ML models performs. For our example code, I didn’t use production variants other than prod.</li><li><strong>The Endpoint</strong> is what you call from your service to make an inference using your ML model. You invoke your endpoint in python, java, javascript or shell. Here’s the <a href="https://gist.github.com/mvsusp/b9de070b310af6876de7b59beda0fb4a">example</a>.</li></ol><h4>Step 1. Write a <a href="https://github.com/gitskim/AQA_SageMaker/blob/main/Dockerfile">Docker file</a></h4><p>In our <a href="https://github.com/gitskim/AQA_SageMaker/blob/main/Dockerfile">example</a>, we’re pulling an image from the public repositories and setting the base image with Ubuntu version 18.04. Most Dockerfiles start with a FROM instruction and the image can be any valid image. Since we have a brand new image, we’re installing necessary libraries and setting variables afterwards with the RUN, which executes commands inside your docker image. Then the inference code package for SageMaker is copied to the working directory so that the code is available for subsequent instructions.</p><h4>Step 2. Write health check code in the /ping function and inference logic in the /invocations</h4><p>There are two necessary functions that need to be defined: <em>/ping</em> and <em>/invocations</em>.</p><p>The container starts once CreateEndpoint and UpdateEndpoint APIs are called. After the container starts, SageMaker checks the container’s health by continuously pinging the service every now and then to see if the container is up and running. The health check ping goes through <em>/ping</em> and you will see the function is ready to return a static 200 response. You can add other health checks such as print statements to this call. If a container does not send a 200 response during the 4 minutes after the container started, CreateEndpoint will fail and, therefore, UpdateEndpoint will not be completed.</p><p>When the SageMaker endpoint is invoked, the call gets routed to <em>/invocations </em>by default, so the inference code needs to be under the invocations function. You can get the content that comes with this function from flask’s request object, like here: <a href="https://github.com/gitskim/AQA_SageMaker/blob/main/getPredScore/predictor.py#L61">https://github.com/gitskim/AQA_SageMaker/blob/main/getPredScore/predictor.py#L61</a></p><h4>Step 3. Local Test: Verify the functionality</h4><p>In order to test the inference logic in the docker image’s functionality locally, we will test by creating a docker container with some changes to the paths to the locations of the models. Make sure to download docker and have it running before you test. Sagemaker automatically downloads the models located in S3 under the <em>/opt/program/models/</em> directory, when you deploy code you should write it so it looks for its models in that directory. But in order to test the functionality locally, we need to relocate the models locally and refer to the local model location. When you create a container, as in the script above, we need AWS credentials because we provide the input data as a link to S3. The detailed description of why we do it this way will be described in a follow-up article.</p><h4>Step 4. Deploy with build_and_push.sh</h4><p>The starter sample code comes with the build_and_push.sh bash script to automate the deployment. You just have to <strong><em>chmod +x build_and_push.sh. </em></strong>Then run the script by typing <strong><em>./build_and_push.sh. </em></strong>To automate the creation of the three main components (Model, Endpoint Configuration, and Endpoint), you can use either Cloud Formation or SageMaker Studio. You can create all three components via Sagemaker Studio python console like this: <a href="https://github.com/gitskim/AQA_SageMaker/blob/main/sagemaker_one_click_create_with_integ_test.py">https://github.com/gitskim/AQA_SageMaker/blob/main/sagemaker_one_click_create_with_integ_test.py</a></p><p>In summary, the idea is to create a docker container and deploy it to AWS ECR and create a SageMaker instance to use the ECR image. I hope you find this explanation and the attached code useful but it’s worth mentioning that this whole interaction with SageMaker was quite frustrating.</p><p>Surprisingly, SageMaker’s ML deployment facilities turned out to be both primitive and complicated. SageMaker pretty much only provides the bare minimum for deployment, and it requires so many unexpected steps for deployment and maintenance, especially for ML models trained outside of AWS SageMaker. For such a well-promoted platform, we expected more mature deployment and version control tooling. Although the boiler plate code was given, working with nginx, gunicorn and flask resulted in a cumbersome system that’s hard to maintain. I might as well create my own machine learning server in AWS EC2.</p><blockquote>Good thing that AWS continues to work on improving SageMaker. <a href="https://aws.amazon.com/sagemaker/deploy/#Serverless_inference_for_intermittent_usage_patterns">AWS re:invent 2021</a> revealed a new serverless inference feature for SageMaker where you don’t have to specify a kind of host to run your SageMaker code. However, the architecture that I explained above still exists without much change, so the new release does not completely remove the complexity and cumbersome design that comes with deploying ML models to SageMaker. Also, I wonder how useful this feature is given that we already have a convenient serverless option: AWS Lambda.</blockquote><p>For those reasons mentioned above, in the actual implementation of our ML service, we went with AWS Lambda. Its serverless functionality handles scaling, fault tolerance and enables high availability for our service. In December 2020, AWS started supporting the feature to deploy a Docker container image as a lambda function. It means a docker container image can be deployed to lambda instead of a zip file. This is a useful feature for ML deployment since it now gives room for large sized files and dependencies for ML services. However, there are cons, including <a href="https://hevodata.com/blog/serverless-architecture-aws-lambda/">existing Lambda issues</a> such as start-up latency. Moreover, features specific to ML deployment, like continuous model deployment and model versioning, require extra layers to be implemented. They are not provided as convenient features.</p><p>At the end of the day, SageMaker did not prove convenient for ML Ops; ML deployment for models trained outside SageMaker was especially poor. Therefore, we went with AWS Lambda for our ML model deployment due to its convenient integration. There will be another article describing the architecture of our ML system based on AWS Lambda.</p><p><em>I wrote this blog in collaboration with </em><a href="https://www.linkedin.com/in/yanqing-dai-2001948a/"><em>Yanqing Dai</em></a><em>.</em></p><h3>Note</h3><p>I started my freelance business with <a href="https://www.linkedin.com/in/yanqing-dai-2001948a/"><em>Yanqing Dai</em></a>. We accept freelance work focusing on productionizing machine learning services, data engineering and distributed systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6948439f48e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploying-your-ml-models-to-aws-sagemaker-6948439f48e1">Deploying your ML models to AWS SageMaker</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[Training AI to Score Olympic Events]]></title>
            <link>https://medium.com/@logicdevildotcom/training-ai-to-score-olympic-events-649b41574160?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/649b41574160</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[olympics]]></category>
            <category><![CDATA[diving]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 07:22:02 GMT</pubDate>
            <atom:updated>2022-03-02T01:38:56.946Z</atom:updated>
            <content:encoded><![CDATA[<h4>Could we have an automated scoring system as a trusted, impartial second opinion?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvuBvCLPO-AuZq9mCuO7vg.jpeg" /><figcaption><a href="https://unsplash.com/photos/ZIoi-47zV88">https://unsplash.com/photos/ZIoi-47zV88</a></figcaption></figure><p>The 2021 Tokyo Olympics are here. I have been waiting for so long, especially since it was postponed due to the pandemic. While watching some of the games, I observed some decisions judges made that I did not agree with. Notably the 2002 and 2014 figure skating results bothered not only me but also millions of Olympics fans. And it made me wonder “can we teach AI to score Olympic games?” If possible, then we could have automated scoring systems as a trusted, impartial second opinion.</p><h4>What is action quality assessment?</h4><p>There actually has been research done on this topic for some time to see if a machine can assess <em>how well</em> a person performs an action. This concept is called Action Quality Assessment (AQA). AQA is the assessment of how well an action is performed by estimating a score after analyzing the performance. It is useful in many applications not only in sports but also in health care and music. For example, an injured player or player with mobility impairments would be able to exercise physical therapy on their own without having to pay for expensive physical therapy sessions. Similarly, automated evaluation of skills, for example, can make learning a musical instrument more accessible to those who are socioeconomically disadvantaged.</p><h4>Action Quality Assessment is not Action Recognition</h4><p>AQA is different from <em>action recognition </em>because action recognition does not quantify the quality of the action. Also, an important distinction is that an action can be classified from just one or a few images but in order to assess how well an action was performed, we need to go through the entire action sequence.</p><h4>How do we teach the machine to do it?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNhS73OiA3dgnsj1bZqAkg.png" /></figure><p>We can formulate AQA into the supervised learning problem, where the model learns to map the input videos of actions to an action quality score. Scores given out by human judges serve as our ground-truth. Since, typically, the action quality score has a continuous distribution, AQA is formulated as a regression problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKjNFgMdXrbDCxeWTfW3iw.png" /></figure><p>The assessment, generally, has the following two components: 1) what was performed and 2) how well it was performed. When a performance is measured in the Olympics, the judges have to recognize what action is performed by athletes. A performance with a higher difficulty score with some mistakes can lead to a higher overall score than the one with a lower difficulty.</p><h4>How do humans do it?</h4><p>For example, let’s talk about diving events in the Olympics. Before each diver competes, they show on the screen the name of the dive he’s going to perform and the associated difficulty.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FY4ARBzok9aU%3Fstart%3D3239%26feature%3Doembed%26start%3D3239&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DY4ARBzok9aU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FY4ARBzok9aU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d30ff3f23fef1d08be580d003f45537e/href">https://medium.com/media/d30ff3f23fef1d08be580d003f45537e/href</a></iframe><p>The dashboard contains a lot of information on what will be performed. As far as the body position goes, you can choose from the <em>straight, pike, tuck</em> or <em>free </em>position. The numbers in front of “somersault” and “twists” show how many of each will be performed. All of the fine-grained details of what was done are important when it comes to determining how well a diver performed. The judges are given all this information before the athlete dives. For this reason, learning the right features from the videos is crucial for AQA.</p><h4>What has been done so far?</h4><p>An initial study of AQA used human pose information as representations capturing the action quality. Given an image or video, pose estimation is the task of identifying, locating and tracking major joints in the human body such as the elbow or knee. From pose estimation, they extracted the human body movement features from the video and Support Vector Regression (SVR) was used to map athlete’s movements to Olympics event scores.</p><p>However, there is a problem with this approach. In the case of diving as the picture shows below, the form is very important in that you don’t want to have a lot of room between your chest and legs. Likewise, the splash created when the diver enters the water is an important part of the scoring criteria. You don’t want to have too big of a splash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zJzU73oE-kK7EwT1rBbFhg.png" /></figure><p>In order to capture such important visual cues in the quality of actions, instead of relying on pose estimation, we can try to capture spatio-temporal features from 3D convolutional neural networks (C3D), which showed promising results in a similar task that is action recognition. The research showed that a variation of C3D worked better than previous models.</p><p>To go a little bit further in catching the details from the videos, the <strong>multitasking approach </strong>was suggested. The concept of multi-task learning (MTL) is inspired by human learning. When we learn new tasks, we often learn simpler or related tasks that give us the necessary skills to acquire more complex techniques. Applying this concept, in order for the model to learn fine-grained details of the diving video, we teach the model to learn (1) <strong>how to classify an action</strong>, (2) <strong>how to generate commentary</strong> and (3) <strong>how to score the action</strong>. The motivation for this is that detailed action recognition is the answer to the question of ‘what was performed’. The commentary, which is verbal description containing good and bad points about action execution, is an answer to the ‘how well the action was performed’ part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKIBWweA0be3uamCEC4PUA.png" /><figcaption><a href="https://drive.google.com/file/d/1BbdPZDZlLwj0ekHJz54o-A2LYvU5h148/view">https://drive.google.com/file/d/1BbdPZDZlLwj0ekHJz54o-A2LYvU5h148/view</a></figcaption></figure><h4>Model Architecture</h4><p>It starts with extracting the input video into picture frames. In the example below, the total of 96 frames were extracted from the input. In order to learn shared representations, or general features, 3D CNNs were used but they require large memories, and the entire 96 frames cannot be learned all at once with the 3D CNNs. For that reason, 96 frames were divided into small clips: 6 sets of 16 frames each. They they go through the <em>common network backbone</em>, which learns shared representations. And we take the average of those 6 sets of the frames. So far, we have encoded the input video into representations that correspond to the total AQA points gathered by the athlete. Then the encoded representations go through the score regressor and action classifier. For the caption generator, the concatenated C3D representations are sent as an input without taking the average. At the end weighted 3 losses are summed together to get the final loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kxxhw18ZUWQgGDckd2C1pw.png" /><figcaption><a href="https://openaccess.thecvf.com/content_CVPR_2019/papers/Parmar_What_and_How_Well_You_Performed_A_Multitask_Learning_Approach_CVPR_2019_paper.pdf">https://openaccess.thecvf.com/content_CVPR_2019/papers/Parmar_What_and_How_Well_You_Performed_A_Multitask_Learning_Approach_CVPR_2019_paper.pdf</a></figcaption></figure><h4>AI-based App to Judge Olympic Events</h4><p>Based on the multitask AQA model, we created an app that can process Olympics diving videos and output a score, just like human judges would do! Try out our AI-based Olympics Judge here: <a href="https://share.streamlit.io/gitskim/aqa_streamlit/main/main.py">https://share.streamlit.io/gitskim/aqa_streamlit/main/main.py</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DvAYkY7W9sdx1qg2LtcZPg.gif" /></figure><p>For now, this machine learning model is only for diving videos. Nonetheless, it can be easily extended to other individual sports like Gymnastics, Snowboarding, Skiing, etc. The web app is made using StreamLit and its source code is here: <a href="https://github.com/gitskim/AQA_Streamlit">https://github.com/gitskim/AQA_Streamlit</a>.</p><h3>References</h3><ol><li><a href="https://openaccess.thecvf.com/content_CVPR_2019/papers/Parmar_What_and_How_Well_You_Performed_A_Multitask_Learning_Approach_CVPR_2019_paper.pdf">https://openaccess.thecvf.com/content_CVPR_2019/papers/Parmar_What_and_How_Well_You_Performed_A_Multitask_Learning_Approach_CVPR_2019_paper.pdf</a> (I have the permission to cite this paper from the author of the paper)</li><li><a href="https://www.tutorialspoint.com/diving/diving_body_positions.htm">https://www.tutorialspoint.com/diving/diving_body_positions.htm</a></li><li><a href="https://ruder.io/multi-task/">https://ruder.io/multi-task/</a></li></ol><h3>Notes</h3><p>I started my freelance business in 2022. I accept freelance work focusing on productionizing machine learning services, data engineering and distributed systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=649b41574160" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis the Machine Learning Perspective (Part 2)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/principal-component-analysis-the-machine-learning-perspective-part-2-a2630fa3b89e?source=rss-1d1f38878ecd------2"><img src="https://cdn-images-1.medium.com/max/1462/1*fJvDXx39tybuKH1yQhE9uA.png" width="1462"></a></p><p class="medium-feed-snippet">In my previous article, I went over principal component analysis from the statistical point of view. In this article, I will go over the&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/data-science/principal-component-analysis-the-machine-learning-perspective-part-2-a2630fa3b89e?source=rss-1d1f38878ecd------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/principal-component-analysis-the-machine-learning-perspective-part-2-a2630fa3b89e?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2630fa3b89e</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Sat, 27 Apr 2019 00:08:18 GMT</pubDate>
            <atom:updated>2019-05-05T12:50:16.690Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[3 Essential Things For Beginner Kernel Developers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@logicdevildotcom/3-essential-things-for-beginner-kernel-developers-dc2a0a374a8f?source=rss-1d1f38878ecd------2"><img src="https://cdn-images-1.medium.com/max/1464/1*WFB1SYXvCDO9hJMBqHPBOA.png" width="1464"></a></p><p class="medium-feed-snippet">My objective of writing this article is to provide readers with high-level understanding of important concepts needed for Linux kernel&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@logicdevildotcom/3-essential-things-for-beginner-kernel-developers-dc2a0a374a8f?source=rss-1d1f38878ecd------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@logicdevildotcom/3-essential-things-for-beginner-kernel-developers-dc2a0a374a8f?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc2a0a374a8f</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Sun, 03 Mar 2019 18:47:08 GMT</pubDate>
            <atom:updated>2019-03-03T19:11:44.141Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Back-propagation Demystified in 7 Minutes]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/back-propagation-demystified-in-7-minutes-4294d71a04d7?source=rss-1d1f38878ecd------2"><img src="https://cdn-images-1.medium.com/max/2340/1*tREDSx4n2ddslOygsuO6eA.png" width="2340"></a></p><p class="medium-feed-snippet">In the past 10 years, the best-performing machine learning implementations such as the facial recognition and the speech recognizers have&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/data-science/back-propagation-demystified-in-7-minutes-4294d71a04d7?source=rss-1d1f38878ecd------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/back-propagation-demystified-in-7-minutes-4294d71a04d7?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4294d71a04d7</guid>
            <category><![CDATA[gradient]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 08:30:16 GMT</pubDate>
            <atom:updated>2019-07-23T12:25:57.954Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Convolutional Neural Networks (CNNs)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/a-beginners-guide-to-convolutional-neural-networks-cnns-14649dbddce8?source=rss-1d1f38878ecd------2"><img src="https://cdn-images-1.medium.com/max/2196/1*EfXAnrwUObQmFtaxcHUlVg.png" width="2196"></a></p><p class="medium-feed-snippet">In convolutional networks, multiple filters are taken to slice through the image and map them one by one and learn different portions of an</p><p class="medium-feed-link"><a href="https://medium.com/data-science/a-beginners-guide-to-convolutional-neural-networks-cnns-14649dbddce8?source=rss-1d1f38878ecd------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/a-beginners-guide-to-convolutional-neural-networks-cnns-14649dbddce8?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/14649dbddce8</guid>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 01:54:35 GMT</pubDate>
            <atom:updated>2019-02-15T10:02:25.256Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis from Statistical and Machine Learning Perspectives (Part 1)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/principal-component-analysis-ceb42ed04d77?source=rss-1d1f38878ecd------2"><img src="https://cdn-images-1.medium.com/max/1092/1*buvbTe-AwrPNVeGmslAK9Q.png" width="1092"></a></p><p class="medium-feed-snippet">One of the common problems in analysis of complex data comes from a large number of variables, which requires a large amount of memory and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/data-science/principal-component-analysis-ceb42ed04d77?source=rss-1d1f38878ecd------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/principal-component-analysis-ceb42ed04d77?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceb42ed04d77</guid>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[statistical-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Sat, 05 Jan 2019 17:09:00 GMT</pubDate>
            <atom:updated>2021-11-22T07:55:06.934Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[K-Nearest Neighbors]]></title>
            <link>https://medium.com/@logicdevildotcom/k-nearest-neighbors-e45c5193da9e?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e45c5193da9e</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Fri, 06 Jul 2018 05:13:06 GMT</pubDate>
            <atom:updated>2018-07-13T15:50:14.522Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous article, I went over the Bayes’ classifier, which is proved to be optimal. But the problem here is that statistical approach requires a lot of extra work. So one option is to consider another classifier, which does not have parameters.</p><p>Parametrized classifiers like MLE classifier or Bayes’ classifier require the decision on probability models, which results in extra work in the beginning; thus, it’s error-prone. But with that underlying assumption of the probability model, one can get so much information about the data such as if a given point is an outlier or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WRvUXJRThNtjWsYXQ1s4Q.png" /></figure><p>Here, we will take a look at K-Nearest Neighbors classifier, which is an unparametrized classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*part05XunW0FsQn2836Uxg.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>In the figure above, we are trying to figure out if the white dot belongs to the red or blue. We can simply look at its nearest neighbors and predict what classification it belongs to. That is K-nearest neighbors classifier. K differs depending on how many data you want to look at before making a decision.</p><p>But the problem is <strong>how are we going to calculate the distance between data points</strong>?</p><ol><li>Euclidean distance:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLN2zWJwqQPrAQLac14pzw.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>2. Other normed distances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghiyBEH5yNyNT2zuJJd8lg.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p><strong>p = 2</strong>: euclidean distance</p><p><strong>p = 1</strong>: <a href="https://en.wiktionary.org/wiki/Manhattan_distance">manhattan distance</a> (no diagonal distance is calculated; only vertical and horizontal distance is calculated)</p><p><strong>p = ∞</strong>: Only maximum distance is of interest</p><p><strong>p = 0</strong>: count the number of non-zero distance e.g. if there are two dimensions and if there is a difference in dimension 1 and there is no difference in dimension 2, the count is 1.</p><p><strong>Instead of calculating distance, can we calculate something else?</strong></p><p>Yes, we can calculate similarities between data.</p><p>Typically, it is some sort of a relation from the distance calculation like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLqs0cc5kSdpEHP5as4v1w.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>But instead of that, we can use the angles between the data using <strong>cosine similarity</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cGRLmposr20w5AW0WdiCaw.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>Then, there is no distance calculated between data points at all. This is what’s actually used for recommendation for similar videos in Netflix.</p><p><strong>K-NN’s Optimality</strong></p><ol><li>For fixed <em>k</em>, as and <em>n </em>→ ∞, <em>k</em>-NN classifier error converges to no more than twice Bayes classifier error.</li><li>If <em>k </em>→ ∞, <em>k</em>/<em>n </em>→ 0, and <em>n </em>→ ∞, <em>k</em>-NN classifier converges to Bayes classifier. Therefore, if Bayes’ is optimal, k-NN is optimal.</li></ol><p><strong>But there is a drawback of K-NN that i</strong>t is sensitive to noise in data, which would result in noise in my prediction as well. This problem can be solved by taking majority of k-nearest neighbors. Also, there is no best of way to measure approximate closeness. More importantly, all the training data need to be kept in order to give relation between the given data and training data.</p><p>Another drawback is <strong>it takes time to find the k-nearest neighbors</strong>. The running time it takes is O(nd) where n is the number of training data and d is the dimension. In order to make this problem simpler, how about we turn this into a decision question: What are the k-nearest neighbors (optimization problem) -&gt; Does an element x exist in the nearest approximation (decision problem). In order to answer the decision problem, a naive approach would result in O(n).</p><p>In order to do it quickly, a k-d tree can be implemented. The k-d tree is “<a href="https://en.wikipedia.org/wiki/K-d_tree">a binary tree in which every node is a k-dimensional point</a>”. Areas are partitioned and represented in a tree form to implement the binary search. If the points are sorted, the search time significantly decreases from O(n) to O(log n).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTG-pISS1mL0KHT1HYMCkA.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p><strong>Drawback of K-d tree</strong></p><p>It doesn’t give the most accurate nearest neighbor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHHJO819GiCUQ65wCnkqOA.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>For example, if I am looking for the nearest neighbor of the red dot from the above diagram, instead of giving me the blue dot, it will give the green dot on the left hand side of the red dot, because the binary search implemented with k-d tree will result in the T1,1 area and will look for the nearest neighbor in that subregion. However, this drawback doesn’t stop people from using k-d tree, because O(log n) running time is more beneficial over O(n) and preciseness can be sacrificed.</p><p><strong>Another way to find the neighbor quickly: Binary search with median</strong></p><p>The diagram below is a 2-dimensional example. Instead of looking for the middle partitioned area, we can look for the medean data point instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yLtaJcfO0NjeQ_9sOh8VIA.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>On top of that, in order to accommodate to the 2-dimensional aspect, we can start with the dimension that has more data points than the other dimension. If the size of the data point matrix is m by n, and m &gt; n, we can do binary partition in the m dimension. Then the next time, if m &gt; n, we do the partition again in the m dimension. If m &lt; n, then we move onto the partition in the n dimension</p><p><strong>Metric learning</strong></p><p>How to make measurement robust depending on the parameters? We can give weights to each parameter and add the weights when we calculate the distance. Then now the question becomes how can we find the optimal weights?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmBSJTX756b-eWTL2EEv6A.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>We can define a cost function for the algorithm to learn the weight on its own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhSZ-WE9-VGf1qDNqMUepQ.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>But the problem is now we need to keep all the data around. So motivated by k-nearest neighbors implemented with k-d tree, there is another classifier, which is called decision tree.</p><p><strong>Decision Tree</strong></p><p>Decision trees in general are highly used in the industry. For instance, Amazon uses decision trees for their fraud order detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COMMH8O4SK6hKmrLhKfXzQ.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>With decision trees, we can choose the features and the thresholds that directly optimize for classification accuracy! The point is we want to select the feature and threshold that <strong>maximally reduces label uncertainty, </strong>rather than selecting arbitrary feature and splitting at the median.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi7UJsHnlwhQcd5rJV7IBA.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p><strong>The drawback of decision tree</strong></p><p>We can overfit the data, which means the model gets used to the training data too much so that the error rate goes up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnya50z8XDVNZOPQTltFiA.png" /><figcaption><a href="http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf">http://www.cs.columbia.edu/~verma/classes/ml/lec/lec1_intro_mle_bayes_naive_evaluation.pdf</a></figcaption></figure><p>In order to alleviate the issue, we stop splitting the tree in the testing phase if the error rate goes up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e45c5193da9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bayes’ classifier with Maximum Likelihood Estimation]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/bayes-classifier-with-maximum-likelihood-estimation-4b754b641488?source=rss-1d1f38878ecd------2"><img src="https://cdn-images-1.medium.com/max/1378/1*W-l8ROtLn-wvSbbSAujFVw.png" width="1378"></a></p><p class="medium-feed-snippet">The essential concept of supervised learning is you are given data with labels to train the model. And we assume that there is an optimal&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/data-science/bayes-classifier-with-maximum-likelihood-estimation-4b754b641488?source=rss-1d1f38878ecd------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/bayes-classifier-with-maximum-likelihood-estimation-4b754b641488?source=rss-1d1f38878ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b754b641488</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <dc:creator><![CDATA[Suhyun Kim]]></dc:creator>
            <pubDate>Fri, 06 Jul 2018 02:59:11 GMT</pubDate>
            <atom:updated>2019-07-09T18:29:09.186Z</atom:updated>
        </item>
    </channel>
</rss>