<?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 Joshua Jarvis on Medium]]></title>
        <description><![CDATA[Stories by Joshua Jarvis on Medium]]></description>
        <link>https://medium.com/@refactorednoise?source=rss-793ec061bbf4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KKV6N9B8phigOBaE.</url>
            <title>Stories by Joshua Jarvis on Medium</title>
            <link>https://medium.com/@refactorednoise?source=rss-793ec061bbf4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 13:10:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@refactorednoise/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[How We Used Transfer Learning to Create an Image Classifier in the Browser]]></title>
            <link>https://medium.com/carnegie-mellon-robotics-academy/how-we-used-transfer-learning-to-create-an-image-classifier-in-the-browser-57a0abb4ccd3?source=rss-793ec061bbf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a0abb4ccd3</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[educational-technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Joshua Jarvis]]></dc:creator>
            <pubDate>Tue, 11 Aug 2020 17:52:12 GMT</pubDate>
            <atom:updated>2020-08-11T17:52:12.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjdxb1JRzCCeWWr3lAVirQ.png" /></figure><h4>Introduction</h4><p>We recently released an interactive activity that provides an introductory understanding of how an Image Classifier might be used in a factory context. The goal of this activity is to produce as many ‘good’ widgets as possible while also minimizing ‘defective’ widgets. The robot can be trained to classify any part coming down the assembly line and can also be told to remove an object that is identified as ‘defective’.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsmsCQb_5mkc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsmsCQb_5mkc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsmsCQb_5mkc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b89979ee3f182cf63aa33f00ec1c9074/href">https://medium.com/media/b89979ee3f182cf63aa33f00ec1c9074/href</a></iframe><p>We developed the conveyor belt and camera scenes in Unity. We have an article that takes a deeper dive into how we like to do Unity and JS communication <a href="https://medium.com/carnegie-mellon-robotics-academy/rapid-prototyping-with-unity-and-react-f3f12b5d7707">here</a>.</p><p>Initially, we thought that it might be a good idea to invoke an image classifier endpoint on a remote server. This would offset the computation demands from the client to the server but wouldn’t be without its own pitfalls. For our requirements ‘training’ an image classifier needed to take place in real time. So the communication over the network would have to be fast. This would scale poorly if the activity is used by many concurrent users and each client was capable of sending a few hundred requests. There had to be a better way to do this. We talk about how you can host a ML model on a serverless backend in another <a href="https://medium.com/carnegie-mellon-robotics-academy/going-serverless-for-your-ml-backend-with-sam-cli-5332912019ef">article</a>.</p><p>Fortunately for us, the answer to our problems was <a href="https://www.tensorflow.org/js">TensorFlow.js</a> (TF). The most convenient part was that we could use an existing model, train it through transfer learning, and immediately run inferences against the classifier without leaving the browser.</p><h4>Image Classification through Transfer Learning</h4><p>TF provides two trained models that we can use to build a custom image classifier —Knn-classifier (KNN) and MobileNet.</p><p>The MobileNet model is an image classifier model designed to run in low resource environments like a browser. However, if we use the model to predict our game’s widget parts we won’t get the predictions we want. We will instead get a label based on the very large training set that MobileNet was generalized on.</p><p>Transfer Learning allows us to take the existing capabilities of the MobileNet model and ‘teach it new tricks’. In our case we would like to teach it to identify the difference between the defective and pristine widgets coming down the conveyor belt. We will need another use another model — KNN to achieve this.</p><p>The TF MobileNet API provides a convenient method to extract the features of the image. We can use these features along with a custom label such as ‘defective gear’ or ‘good gear’ and add the examples to our KNN model. The KNN model takes the K (default 3 for this model) nearest neighbors of similar images. For each prediction. we will take the output of the MobileNet and feed that into the KNN model to see which zone the image falls into. The KNN zone maps to the identifying label and gives us our custom prediction ‘defective gear’ or ‘good gear’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*pjs3-aEN7EvUa7KQ.png" /><figcaption>A KNN can be used to group the K nearest neighbors of a dataset</figcaption></figure><h4>Implementing our Image Classifier</h4><p>The image classifier activity was built with Unity, React, Redux, and Tensforflow.js. We used React for our interactive GUI, Redux to manage and store the activity’s state, and Tensorflow.js models to build our image classifier. The source of the project can be viewed <a href="https://github.com/cmroboticsacademy/Image-Classifier-Activity">here</a>.</p><p>For this article we will mostly focus on the Tensorflow.js code used to build the image classifier.</p><p>The MobileNet model is loaded asynchronously via a Redux action when the game is loaded. The model takes some time to load so we want to make sure that the model is available before the activity begins.</p><pre>// Redux Action</pre><pre>import * as MobileNetModule from &#39;@tensorflow-models/mobilenet&#39;;</pre><pre>const loadMobileNet = (model) =&gt; {<br>  return {<br>    type: &#39;LOAD_MOBILENET&#39;,<br>    model,<br>  };<br>};</pre><pre>export const loadMobileNetAsync = () =&gt; {<br>  return (dispatch) =&gt; {<br>    MobileNetModule.load().then((m) =&gt; {<br>      dispatch(loadMobileNet(m));<br>    });<br>  };<br>}</pre><pre><br>// Redux Reducer</pre><pre>const featureExtractor = (state = {}, action) =&gt; {<br>  switch (action.type) {<br>    case &quot;LOAD_MOBILENET&quot;:<br>      return action.model;<br>    default:<br>      return state;<br>  }<br>};</pre><pre>export default featureExtractor;</pre><p>The KNN classifier can be instantiated synchronously and is initiated as part of the default state for the classifier reducer.</p><pre>import * as knn from &#39;@tensorflow-models/knn-classifier&#39;;</pre><pre>const classifier = (state = knn.create(), action) =&gt; {<br>  switch (action.type) {<br>    default:<br>      return state;<br>  }<br>};</pre><pre>export default classifier;</pre><h4>Adding Examples to the KNN</h4><p>Each example comes from a binary file sent from Unity using the unity comms protocol between Unity and React. The MobileNet model (labeled as the feature extractor in the function) expects the file to be of type Image. We process the binary from Unity as an image.</p><pre>export const addExample = (binary, label) =&gt; {<br>  const { featureExtractor, classifier } = store.getState();<br>  preProcessImageWithCallback(binary, (img) =&gt; {<br>    const features = featureExtractor.infer(img, &quot;conv_preds&quot;);<br>    classifier.addExample(features, label);<br>  });<br>};</pre><p>The important part to note here is that we do so asynchronously and only call the preProcessImageWithCallback function once image onload event triggers. The callback function uses the MobileNet model (featureExtractor) to generate a set of extracted features for the KNN model (classifier) to add an example.</p><pre>const preProcessImageWithCallback = async (binary, callback) =&gt; {<br>  let img = new Image(800, 600);<br>  img.src = `data:image/png;base64, ${binary}`;<br>  img.onload = () =&gt; {<br>    callback(img);<br>  };<br>};</pre><h4>Predicting Images</h4><p>Once the KNN has been built with a sufficient set of examples, predictions become remarkably accurate. The predict function returns a Promise that is resolved once the classifier.predict method returns a result. If the result label does not map to the KNN’s label classes, we reject the predict promise and rebuild the model.</p><p>We also send a defaultLabel class in cases where the predict method is invoked before the KNN has examples.</p><pre>export const predict = (binary, uid) =&gt; {<br>  return new Promise((resolve, reject) =&gt; {<br>    const { featureExtractor, classifier, labelClasses } = store.getState();</pre><pre>preProcessImageWithCallback(binary, (img) =&gt; {<br>      const features = featureExtractor.infer(img, &quot;conv_preds&quot;);<br>      classifier<br>        .predictClass(features)<br>        .then((result) =&gt; {<br>          const labelClass = getLabelClassByName(<br>            labelClasses.list,<br>            result.label<br>          );<br>          const confidences = result.confidences;<br>          if (labelClass) {<br>            resolve({<br>              ...labelClass,<br>              uid,<br>              confidences,<br>            });<br>          } else {<br>            reject(&quot;rebuilding model&quot;);<br>          }<br>        })<br>        .catch((_) =&gt; {<br>          resolve({<br>            ...defaultLabelClass,<br>            uid,<br>            rgb: {<br>              a: 0,<br>              r: 0,<br>              g: 0,<br>              b: 0,<br>            },<br>          });<br>        });<br>    });<br>  });<br>};</pre><h4>Reloading and Deleting Labels</h4><p>Our activity interface allows the learner to delete individual labels. Unfortunately, this behavior was not directly supported in the KNN API. To support this feature, we had to delete all examples and then reload the examples from the Redux state for each deletion.</p><p>Clearing an entire set of class labels is pretty straight forward.</p><pre>export const deleteExamples = (label) =&gt; {<br>  const { classifier } = store.getState();<br>  try {<br>    classifier.clearClass(label);<br>  } catch (e) {}<br>};</pre><p>Reloading the examples involved taking all of the KNN’s class labels and adding the examples back the KNN. The KNN’s classDatasetMatrices method only returns the label names and does not provide the full object for each label. We store the full object in the labelClasses reducer and iterate over each object, clear all examples, and then add back each example for each image. This is a little computationally inefficient and could be improved by adding direct support for individual label deletions directly to the KNN object. Fortunately, the challenge can be completed with a small number of examples and does not run into problems even if the reload examples function is O(n²) .</p><pre>export const reloadAllExamples = () =&gt; {<br>  const { classifier, labelClasses } = store.getState();<br>  const labels = Object.keys(classifier.classDatasetMatrices);</pre><pre>labelClasses.list.forEach((label) =&gt; {<br>    const labelObject = labels[label.id - 1];<br>    classifier.clearClass(labelObject);<br>    label.images.forEach((img) =&gt; addExample(img, label.name));<br>  });<br>};</pre><h4>Conclusion</h4><p>Hopefully this article helps demystify the use of an image classifier in a Javascript application. In review, we managed to build an image classifier by first extracting the features of our image using the MobileNet model, feeding those features into a KNN model with a label, and then invoking the KNN predict function using the MobileNet features of subsequent images for a prediction. We managed to do customize a model in real time without too much overhead. We recommend TensorFlow.js models for any JS developer interested in conveniently leveraging ML in there applications without depending on a remote server. Be sure to checkout other <a href="https://www.tensorflow.org/js/models">TF.js model</a>s for your next project.</p><p><strong>This material is based upon work supported by the National Science Foundation under Grant Number 1937063.</strong></p><p><a href="https://github.com/cmroboticsacademy/Image-Classifier-Activity">Github Repository</a></p><p><a href="https://rah-tensorflow-js-transfer-learning-demo.s3.amazonaws.com/index.html">Online Demo</a></p><p><a href="https://medium.com/carnegie-mellon-robotics-academy/rapid-prototyping-with-unity-and-react-f3f12b5d7707">Rapid Prototyping with Unity and React</a></p><p><a href="https://medium.com/carnegie-mellon-robotics-academy/going-serverless-for-your-ml-backend-with-sam-cli-5332912019ef">Deploying a Machine Learning Model to a Serverless Backend with SAM CLI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a0abb4ccd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carnegie-mellon-robotics-academy/how-we-used-transfer-learning-to-create-an-image-classifier-in-the-browser-57a0abb4ccd3">How We Used Transfer Learning to Create an Image Classifier in the Browser</a> was originally published in <a href="https://medium.com/carnegie-mellon-robotics-academy">Carnegie Mellon Robotics Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless for Your ML Backend with SAM CLI]]></title>
            <link>https://medium.com/carnegie-mellon-robotics-academy/going-serverless-for-your-ml-backend-with-sam-cli-5332912019ef?source=rss-793ec061bbf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5332912019ef</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Joshua Jarvis]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 19:30:50 GMT</pubDate>
            <atom:updated>2020-08-10T20:32:59.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying a Machine Learning Model to a Serverless Backend with SAM CLI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFUICr9f9flPdNOmQjJ1xw.jpeg" /></figure><h3>Introduction</h3><p>Over the last year at CMRA, we have been incorporating more machine learning models into our applications. There are plenty of data science blogs about developing models. However, there are very few tutorials about deploying models into production. Fortunately, there are options available for this and it continues to get easier.</p><p>Popular options for deploying models developed in Python include using services written in Flask or Django for client applications to interface with. AWS, Azure, and Google Cloud each offer their own brand of Machine Learning as a Service (MLaaS) products. These services offer convenient workflows, cloud based notebooks, and marketplaces for models. As nice as both options are there are drawbacks when it comes to costs and scaling.</p><p>We chose to create a Serverless application using the popular Lambda service from AWS. A Serverless Architecture offers several compelling advantages over the other options:</p><ol><li>Out of the box integration with AWS Services like S3 and DynoDB (to name a few).</li><li>Automated deployments with SAM CLI.</li><li>Pay as you go model.</li><li>Automatic scaling.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*LPyWspvSB9QJSlLzRCBvmw.png" /><figcaption>Serverless Vs. Traditional Cloud Computing Solution</figcaption></figure><h3>Prerequisites</h3><p>You will need to have the following technologies installed to follow along with this tutorial:</p><ol><li>Python 3.8.3 64 Bit (Preferably with <a href="https://www.anaconda.com/products/individual">Anaconda</a>)</li><li>A free <a href="https://aws.amazon.com/">AWS</a> Account</li><li>SAM CLI by following the instructions <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">here</a></li></ol><p><strong>Important note</strong> — Make sure that you config your AWS CLI with the IAM account that you created as part of the SAM CLI instructions. You can configure AWS CLI by running $ aws configure and filling in all of the prompts for your IAM credentials.</p><h3>Background</h3><p>Earlier this year, CMRA was working on developing several virtual activities designed to teach learners how ML technologies will work in an Advanced Robotics Manufacturing context.</p><p>One such activity was a game where you are in charge of a factory with machines that periodically breakdown. Predicting when the machines breakdown and assigning a technician to fix the machine results in lost money.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I7_ZSVFD0nQtVpvzmwy97Q.png" /><figcaption>Machine Factory Screenshot</figcaption></figure><p>Fortunately there is a dataset available which contains machine sensor data. The sensor values have a simple linear relationship to the state of the machine — breaking or working. Predicting the breaking state allows for the player to put a technician on a machine before the machine goes offline and requires even more time to repair.</p><p>The dataset pictured below is pretty simple. Each instance of the data sample has a labeled state and each individual feature has a linear relationship to the state. The other features of the dataset include temperature, vibration, current, and noise. Noise, no pun intended, has no linear relationship to the working or breaking state of machines.</p><pre>[<br>  {<br>    &quot;state&quot;: &quot;Breaking&quot;,<br>    &quot;temp&quot;: &quot;88&quot;,<br>    &quot;vibration&quot;: &quot;79&quot;,<br>    &quot;current&quot;: &quot;12&quot;,<br>    &quot;noise&quot;: &quot;84&quot;<br>  },<br>  {<br>    &quot;state&quot;: &quot;Working&quot;,<br>    &quot;temp&quot;: &quot;27&quot;,<br>    &quot;vibration&quot;: &quot;47&quot;,<br>    &quot;current&quot;: &quot;59&quot;,<br>    &quot;noise&quot;: &quot;48&quot;<br>  },<br>  <br>  ...</pre><pre>  {<br>    &quot;state&quot;: &quot;Working&quot;,<br>    &quot;temp&quot;: &quot;73&quot;,<br>    &quot;vibration&quot;: &quot;11&quot;,<br>    &quot;current&quot;: &quot;84&quot;,<br>    &quot;noise&quot;: &quot;29&quot;<br>  }<br>]</pre><h3>Deploying a Trained Model</h3><p>We won’t spend a lot of time on this topic since the primary focus of this article is to deploy a model.</p><p>Pictured below is the script that trains on the machine factory dataset located <a href="https://github.com/cmroboticsacademy/serverless_ml_tutorial/blob/master/training_data.json">here</a>. A simple python script will load the data, process the data, train a model, and save a pickled version of that model. I recommend running the training script with Python 3.8 in a Jupyter Notebook. The linked repository at the end of this article includes the script in notebook form. I also recommend using VS Code’s wonderful Python <a href="https://code.visualstudio.com/docs/languages/python">package</a> to take advantage of builtin notebooks with linting and VS Code keybindings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4b8fc176eb96c72207e18ac676ebe45/href">https://medium.com/media/d4b8fc176eb96c72207e18ac676ebe45/href</a></iframe><p>This script converts the JSON data into a Pandas DataFrame object and normalizes the features and encodes the 2 states into 0 and 1.</p><p>The model is built using Scikit Learn’s LogisticRegression model with the ‘liblinear’ default solver. The accuracy comes in at an impressive 97%! As we previously said, the machine states are pretty predictable and probably wouldn’t require an ML model in the real world.</p><p>The model and the encoding ( a mapping of the state labels to the encoded values) are pickled and saved to a local file. The resulting pickled file can be set aside for now. This is the last time we will use the above training script. Assume that this was work completed by your talented data scientist.</p><h3>Deploying the Model with SAM CLI</h3><h4>Meet SAM</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FIdrsdAFaocsfQAS213%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fdoritos-hat-tip-sam-elliott-cool-ranch-IdrsdAFaocsfQAS213&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2FIdrsdAFaocsfQAS213%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ab7ab8e9e4f5362785faee097168d5/href">https://medium.com/media/66ab7ab8e9e4f5362785faee097168d5/href</a></iframe><p>Now that we have SAM CLI installed, let’s take it for a quick test drive. We will start by initializing our application:</p><pre>$ sam init</pre><pre>Which template source would you like to use?<br> 1 - AWS Quick Start Templates<br> 2 - Custom Template Location<br>Choice: <strong>1</strong></pre><pre>Which runtime would you like to use?<br> 1 - nodejs12.x<br> 2 - python3.8<br> ...<br>Runtime: <strong>2</strong></pre><pre>Project name [sam-app]: <strong>your_app_name</strong></pre><pre>Cloning app templates from <a href="https://github.com/awslabs/aws-sam-cli-app-templates.git">https://github.com/awslabs/aws-sam-cli-app-templates.git</a></pre><pre>AWS quick start application templates:<br> 1 - Hello World Example<br> ...<br>Template selection: <strong>1</strong></pre><p>This will be our actual app, but to start out we will choose to checkout the quick start template, install Python 3.8, name our project, and use the ‘Hello World Example’.</p><p>We will start by invoking the HelloWorld Lambda function. The function can be invoked by simply running $ sam local invoke in the project’s root directory. If everything is wired up properly, SAM CLI should run a simulated Docker container of the AWS Lambda environment and return a 200 response with the message ‘Hello World’.</p><p>Opening up HelloWorld/app.py reveals the Lambda function. All Lambda functions have an event and context parameter. The event parameter is usually a Python dict with data about the event that triggered the function. This can be data from an API request or from a direct invocation coming from any event that is configured to trigger the Lambda function (e.g. S3 file upload). The context parameter will go unused for our application. This parameter returns a Context object that provides data about the environment that the function is running in.</p><p>The HelloWorld function uses neither parameter. Instead, it returns the requisite response all Lambda functions are required to return when invoked by API Gateway. This is a JSON response with an HTTP status code and a message body.</p><pre>def lambda_handler(event, context): </pre><pre>  return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: json.dumps({<br>            &quot;message&quot;: &quot;hello world&quot;,<br>            # &quot;location&quot;: ip.text.replace(&quot;\n&quot;, &quot;&quot;)<br>        }),<br>        }</pre><h4>Creating Our Own Lambda Function</h4><p>We are ready to write our own function now that we have the basic feel for how to invoke Lambda functions locally. Let’s rename the folder containing the HelloWorldFunction ‘model_inference’ and replace the app.py code with the following snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17031cb034c08e5f99568cbc643697ba/href">https://medium.com/media/17031cb034c08e5f99568cbc643697ba/href</a></iframe><p>There’s a lot to decompose here. First of all we want to take the pickled model that we uploaded to S3 and load it into memory. Lambda provides a convenient Python library called Boto3 that can directly interface with any service that the Lambda function is authorized to work with. We will setup the Lambda’s policy but for right now let’s assume that the load pickle file will return the pickled model and encoding map when given the S3 Bucket and key (file name).</p><p>The load_pickle function instantiates an S3 client and receives a download_file method which saves the pickle to a specified local path.</p><p>Once the model is loaded, the event is processed and the JSON request payload data is converted to the Python dict format. The rest of the code mirrors the training script. The features are extracted by name, normalized, and then fed into the model’s predict method. The prediction is mapped back to the state of ‘working’ or ‘breaking’ and is passed to the JSON response message.</p><h3>Configuring the Template</h3><p>Getting this all to work requires a few more steps. SAM CLI projects include a template.yaml file at the root of the project. This template has 3 major sections — Globals, Resources, and Outputs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0780c9ba085fdfebe729468d5e51fba8/href">https://medium.com/media/0780c9ba085fdfebe729468d5e51fba8/href</a></iframe><p>The Globals section holds all of the global settings that apply to all Lambda functions in your project. The warmup request takes a little bit of time. To be on the safe side we increased the Timeout for all functions to be 60 seconds.</p><p>Resources specifies each function in the project. Every function has a type. The ModelInferenceFunction has a type ofAWS::Serverless::Function. Properties about the function are set below each resource. The CodeUri matches the function’s parent directory name (model_inference). Policies for the Lambda function are set under Policies. We would like this function to read from S3 and download the pickled file that we uploaded. Therefore, we gave this function an S3ReadPolicy and specified the bucket name. Other policies can be added to allow access to other AWS services as needed.</p><p>All functions are triggered by an event. In our case the API Gateway service will be the service that triggers Lambda invocations. That is to say that once deployed the API Gateway service will give us an endpoint that we can send HTTP requests to and trigger our Lambda function. We also specify the API’s properties which include the the path name and the HTTP method.</p><p>The outputs specify the values for your application’s components once the stack is deployed. Calling the aws cloudformation describe-stacks command will return the API endpoint, Lambda ARN, and Lambda IAM Role ARN. SAM CLI applications are deployed using the CloudFormation service which acts as an orchestration tool for spinning up and connecting multiple AWS services that work together.</p><h3>Installing Dependencies</h3><p>If you run the updated function by calling sam invoke local you will be in for a disappointing surprise. None of the included dependencies are available. Fortunately, installing dependencies for a SAM CLI application is pretty straight forward.</p><p>We need to create a requirements.txt file in the root directory for all of the requisite dependencies that will be used by our function. In our case we just need to install Pandas and Sklearn.</p><p>It works best if we create a pristine environment and freeze only the dependencies that we need for the project in the root directory. We can create an environment in python by running python3 -m venv env. This will create an env/ folder that will hold all of the data for our virtual environment. We can activate the environment by running source env/bin/activate.</p><p>You can tell when you have the environment activated when the environment name (env) appears to the left of the command line. We can now install our dependencies and‘freeze’ dependencies into a requirements.txt file.</p><pre>(env) $ pip install sklearn pandas<br>(env) $ pip freeze &gt; requirements.txt</pre><p>After we are done, we can exit the environment by simply calling the deactivate command.</p><p>Now we can build our lambda function with the included dependencies by including the requirements.txt manifest. This will create a build directory under .aws-sam/ that will be be packaged and sent to AWS when we are ready to deploy.</p><pre>$ sam build -m requirements.txt</pre><h3>Invoking Custom Events</h3><p>We still need to pass inference data to our Lambda function. We can do this by creating a custom event called single_inference.json and saving it within the events folder. This json file will be passed to the Lambda function upon invocation by calling sam local invoke -e events/single_Infernce.json.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;temp&quot;: &quot;10&quot;,<br>    &quot;vibration&quot;: &quot;1.0&quot;,<br>    &quot;current&quot;: &quot;0&quot;,<br>    &quot;noise&quot;: &quot;78&quot;<br>  }<br>}</pre><h3>Testing the API Endpoint Locally</h3><p>Sam also offers a convenient local server that will allow us to perform a full integration test of our API endpoint and Lambda function. We can start the server at localhost:3000 by calling sam local start-api.</p><p>When testing the API endpoint, you will notice that the event data looks slightly different than a direct invocation. This is why we process all incoming events with the parse_event function. API Invocations are in JSON. The ‘body’ and ‘data’ of the request needs to be extracted from the JSON. A direct invocation only requires us to select the ‘data’ key of a Python dict. Other services that can be used to trigger functions likely have different types or shapes to the event data. It’s best to log the event and become familiar with what a particular service’s event looks like.</p><pre><em>def</em> parse_event(<em>event</em>):<br>  if &#39;body&#39; in event.keys():<br>    return json.loads(event[&#39;body&#39;])[&#39;data&#39;]<br>  else:<br>    return event[&#39;data&#39;]</pre><p>The local endpoint can now be called with a simple curl request that includes the factory data in JSON format.</p><pre>$ curl --request POST \<br>  --url <a href="https://qzkb44b1ni.execute-api.us-east-1.amazonaws.com/Prod/inferences">https://localhost:3000/inferences</a> \<br>  --header &#39;content-type: application/json&#39; \<br>  --data &#39;{<br>  &quot;data&quot;: {<br>    &quot;temp&quot;: &quot;1&quot;,<br>    &quot;vibration&quot;: &quot;1.0&quot;,<br>    &quot;current&quot;: &quot;88&quot;,<br>    &quot;noise&quot;: &quot;23&quot;<br>  }<br>}</pre><pre>=&gt; {&quot;prediction&quot;: &quot;Working&quot;}</pre><h3>Deploy to AWS</h3><p>We are now ready to deploy our little ML Serverless application to AWS! Deploying an application couldn’t be simpler. Simply call sam deploy --guided and follow the prompts to deploy to your AWS account.</p><p>Once the deploy completes, you can sign into AWS console and see the creation of your Lambda function, API Gateway Endpoint, and your CloudFormation stack. At this point we can also test our production endpoint by calling our endpoint at the given endpoint url. The invocation URL can be found at API Gateway -&gt; API -&gt; Stages -&gt; Prod. On this screen you will see the ‘invocation url’ and you can test the endpoint by sending another CURL request.</p><pre>$ curl --request POST \<br>  --url <a href="https://qzkb44b1ni.execute-api.us-east-1.amazonaws.com/Prod/inferences">https://&lt;your-endpoint-url&gt;/Prod/inferences</a> \<br>  --header &#39;content-type: application/json&#39; \<br>  --data &#39;{<br>  &quot;data&quot;: {<br>    &quot;temp&quot;: &quot;1&quot;,<br>    &quot;vibration&quot;: &quot;1.0&quot;,<br>    &quot;current&quot;: &quot;88&quot;,<br>    &quot;noise&quot;: &quot;23&quot;<br>  }<br>}</pre><pre>=&gt; {&quot;prediction&quot;: &quot;Working&quot;}</pre><h3>Conclusion</h3><p>Congratulations! We have successfully deployed a simple logistical regression model that can now be invoked on demand without running a server.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FH1w7oo1qZVVGhOVAt8%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Ffocusfeatures-the-big-lebowski-focus-features-H1w7oo1qZVVGhOVAt8&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FH1w7oo1qZVVGhOVAt8%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce6e8bc1816b83a69f16c541fd7d94bf/href">https://medium.com/media/ce6e8bc1816b83a69f16c541fd7d94bf/href</a></iframe><p>In review, we used SAM CLI to quickly set up an AWS-connected project, then transplanted code from the provided CMRA template into it, so that it would load a saved (pickled) model and execute it. We then configured the YAML config file to point to the right functions, and installed the necessary dependencies. We set up single instance inference testing, tested it locally, and finally deployed it to AWS.</p><p>We can add more lambda functions that handle other tasks. For instance, it wouldn’t take a lot of effort to create a TrainingFunction that is invoked each time a new dataset is uploaded to a particular S3 bucket. The training set can be loaded within the function and the model can be saved for the InferenceFunction to use.</p><p>I hope this article demystifies what it takes to deploy an ML model to a serverless backend. Do not hesitate to respond in the comments with any feedback or questions.</p><p><strong>This material is based upon work supported by the National Science Foundation under Grant Number 1937063.</strong></p><p><a href="https://github.com/cmroboticsacademy/serverless_ml_tutorial">Github Repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5332912019ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/carnegie-mellon-robotics-academy/going-serverless-for-your-ml-backend-with-sam-cli-5332912019ef">Going Serverless for Your ML Backend with SAM CLI</a> was originally published in <a href="https://medium.com/carnegie-mellon-robotics-academy">Carnegie Mellon Robotics Academy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heroku and AWS Route 53 SSL Configuration]]></title>
            <link>https://medium.com/@refactorednoise/heroku-and-aws-route-53-ssl-configuration-1b3fd85e615a?source=rss-793ec061bbf4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b3fd85e615a</guid>
            <category><![CDATA[route-53]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Joshua Jarvis]]></dc:creator>
            <pubDate>Wed, 01 May 2019 03:29:55 GMT</pubDate>
            <atom:updated>2019-05-01T03:49:04.202Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I migrated most of the production applications for <a href="http://cs2n.org/">Carnegie Mellon Robotics Academy</a> over to Heroku. I decided that it would also be a good opportunity to migrate my personal blog over to Heroku as well. Overall the transition has been smooth on both ends. With that said, I really struggled with configuring SSL redirects for my naked domains. Heroku published an <a href="https://devcenter.heroku.com/articles/route-53">article</a> that suggested creating an S3 Bucket to redirect to a default subdomain like www.example.com and assigning that bucket to example.com. However, S3 will not allow you to add an SSL certificate which is a nonstarter for most sites. Fortunately, there is an easy enough work around.</p><h3>Getting an SSL Certificate for a Subdomain</h3><p>This process is simple enough. On Heroku, go to your settings page and click configure SSL under ‘Domains and Certificates’. Select ‘Automatically configure using Automated Certificate Management’. Add a domain with a default subdomain that you would like to have the naked domain redirect to. In return, you will receive a CNAME that will then need to be added to Route53 for the corresponding domain. It will take a few minutes before you receive an ACM status of ‘Ok’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TpiWr6NM5zGA8TWW.png" /></figure><p>At this time you should be able to securely access your application at <a href="http://www.example.com./">www.example.com.</a></p><h3>Redirecting a Naked Domain to a Default Subdomain</h3><p>This is where things get interesting. Create a bucket and name it example.com. Once the bucket is created, navigate to the bucket&#39;s properties tab and click &#39;Static website hosting&#39; and select &#39;Redirect Requests&#39; to <a href="http://www.example.com./">www.example.com.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2LmWRX0OZD_rhaaF.png" /></figure><p>As previously mentioned, AWS does not allow you to add an SSL Certificate to an S3 Bucket directly. The workaround requires the creation of an AWS Cloudfront Distribution that points to the S3 Bucket endpoint.</p><h3>AWS Cloudfront</h3><p>Cloudfront is a fast and efficient content delivery network. Typically I use these networks to host my assets. In this case, Cloudfront satisfies our need to add an SSL certificate and the resulting domain can be added to a naked domain in Route 53.</p><p>Copy the S3 endpoint from the previous section and create a cloudfront distribution. The ‘Origin Domain’ will be the S3 endpoint. Update the ‘Alternate Domain Names (CNAMEs)’ field to the naked domain name. Select ‘Custom SSL Certificate (example.com)’ and choose the SSL cert for your naked domain. If you don’t have one, click the option to create one. Be sure to request a certificate for both example.com and *.example.com.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4CG6O_vCUP-qqoA9.png" /></figure><p>All of the other options can be left at their default settings. It usually takes about 15 minutes for AWS to build a CDN once the request has been submitted.</p><h3>Conclusion</h3><p>At this point you should have a working CDN domain that securely redirects to the default subdomain of your application. Simply add this domain to example.com as an Alias Record. It generally takes a few minutes to an hour for the changes to take effect. Feel free to reach out if you have any questions.</p><p><em>Originally published at </em><a href="https://refactorednoise.io/"><em>https://refactorednoise.io</em></a><em> on May 1, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b3fd85e615a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>