<?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 Chris Moradi on Medium]]></title>
        <description><![CDATA[Stories by Chris Moradi on Medium]]></description>
        <link>https://medium.com/@chris.moradi?source=rss-f4d67dfaf29a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l6MjMADzPyktNd6EkkUoUw.jpeg</url>
            <title>Stories by Chris Moradi on Medium</title>
            <link>https://medium.com/@chris.moradi?source=rss-f4d67dfaf29a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:17:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chris.moradi/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[Focus on Maintainability and Break Those ETL Tasks Up]]></title>
            <link>https://medium.com/97-things/focus-on-maintainability-and-break-those-etl-tasks-up-f39aa988a8de?source=rss-f4d67dfaf29a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f39aa988a8de</guid>
            <category><![CDATA[data-engineer]]></category>
            <dc:creator><![CDATA[Chris Moradi]]></dc:creator>
            <pubDate>Thu, 11 Jul 2019 18:20:02 GMT</pubDate>
            <atom:updated>2019-07-11T18:20:02.042Z</atom:updated>
            <content:encoded><![CDATA[<p>As the data science tent widens, practitioners may excel at using prepared data, but lack the skills to do this preparation in a reliable way. These responsibilities can be split across multiple roles and teams, but enormous productive gains can be achieved by taking a full-stack approach where data scientists own the entire process from ideation through deployment.</p><p>Whether you’re a data scientist building your own ETLs or a data engineer assisting data scientists in this process, making your data pipelines easier to understand, debug, and extend will reduce the support burden for yourself and your teammates. This will enable greater iteration and innovation in the future.</p><p>The primary way to make ETLs more maintainable is to follow basic software engineering best practices and break the processing into small and easy to understand tasks that can be strung together — preferably with a workflow engine. Small ETL tasks are easier for new contributors and maintainers to understand, they’re easier to debug, and they allow for greater code reuse.</p><p>Doing too much in a processing step is a common pitfall for both the inexperienced and highly experienced. With less experience, it can be hard to know how to decompose a large workflow into small, well-defined transformations. If you’re relatively new to building ETLs, start by limiting the number of transformations you perform in each task by separating things like joining source tables, creating flag columns, and aggregating the results. You should seek advice and code reviewers from those with more experience and the teammates who will help support your ETLs in production. These reviews should focus on simplicity rather than performance.</p><p>Highly experienced data engineers can also produce overly dense pipelines because chains of complex transformations feel commonplace. While this is acceptable if they are the only ones maintaining these ETLs, it prohibits less experienced data scientists or engineers from supporting, modifying, or extending these pipelines. This can block innovation because the data scientists are reliant on a small number of experts to implement changes.</p><p>If you’re an experienced data engineer, you should consider how easy it is for someone with less experience to understand and build upon your work and consider refactoring so that it’s more accessible. Your work doesn’t need to be universally understood, but consider how much you and others are gaining from the added complexity.</p><p>There may be computational costs to breaking pipelines into small tasks as the work can’t be optimized across these boundaries. However, we sometimes focus too much on run-time performance when we should instead focus on the speed of innovation that’s enabled. There are cases where performance is critical, but optimizing a daily batch job to shave an hour off of the run-time may add weeks or even months to implement future enhancements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f39aa988a8de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/97-things/focus-on-maintainability-and-break-those-etl-tasks-up-f39aa988a8de">Focus on Maintainability and Break Those ETL Tasks Up</a> was originally published in <a href="https://medium.com/97-things">97 Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two New Stitch Fix Blog Posts]]></title>
            <link>https://medium.com/@chris.moradi/two-new-stitch-fix-blog-posts-da29876c2269?source=rss-f4d67dfaf29a------2</link>
            <guid isPermaLink="false">https://medium.com/p/da29876c2269</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <dc:creator><![CDATA[Chris Moradi]]></dc:creator>
            <pubDate>Tue, 21 May 2019 18:50:38 GMT</pubDate>
            <atom:updated>2019-05-21T18:50:38.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0wkqdpxmlPB6Lq6rwB8cfA.jpeg" /></figure><p>I’ve been a data scientist at Stitch Fix for just over a year now. If you’re not familiar with us, we’re an online clothing retailer, and our mission is to help our customers find clothing that they’ll love and that fits them perfectly. To do this, we’ve put data science at the core of the business.</p><p>One thing that drew my attention to Stitch Fix as I was looking for a new data science position is their incredible <a href="https://multithreaded.stitchfix.com/blog/">Multithreaded</a> blog. Today I became part of this with the publication of my post: <a href="https://multithreaded.stitchfix.com/blog/2019/05/21/maintainable-etls/">Maintainable ETLs: Tips for Making Your Pipelines Easier to Support and Extend</a>.</p><p><a href="https://multithreaded.stitchfix.com/blog/2019/05/21/maintainable-etls/">Maintainable ETLs: Tips for Making Your Pipelines Easier to Support and Extend | Stitch Fix Technology - Multithreaded</a></p><p>In this post, I give some of the hard-won tips that I’ve found over the years that help make ETLs easier to build, support and extend. These recommendations are not meant for all environments and applications. In particular, I’ve chosen to focus on teams with a mix of skills and expertise (not all software engineers) and on applications where the work will be continually iterated upon.</p><p>Hope you find these tips helpful! I’d be happy to post follow-ups here to answer questions or provide more context and code samples.</p><p><a href="https://multithreaded.stitchfix.com/blog/2019/05/06/noninferiority/">Suffering from a Non-inferiority Complex? | Stitch Fix Technology - Multithreaded</a></p><p>A couple weeks ago two of my colleagues published another post on the <a href="https://multithreaded.stitchfix.com/blog/2019/05/06/noninferiority/">design of non-inferiority experiments</a>. Usually we design experiments (A/B tests) with the goal of finding a better outcome: ads that improve the conversation rate, product recommendations that yield more sales, or interventions that improve long-term customer retention. However, there are many cases where we don’t need to do better, we just don’t want to implement something that’s significantly worse. The rationale for moving to a new solution — even one that’s not better — might include:</p><ul><li>The new solution is cheaper. This might include cheaper to purchase, implement or maintain.</li><li>A key dataset used in the old solution should be deprecated.</li><li>The new solution provides greater long-term innovation potential.</li></ul><p>In this post, Jasmine and Divya walk through how to design these experiments: the common pitfalls (failing to reject the null hypothesis isn’t enough), setting thresholds for similar performance, and how to calculate the sample size.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da29876c2269" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Prediction APIs in Python (Part 4): Decoupling the Model and API]]></title>
            <link>https://medium.com/data-science/building-prediction-apis-in-python-part-4-decoupling-the-model-and-api-4b5eaf2ed125?source=rss-f4d67dfaf29a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b5eaf2ed125</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Moradi]]></dc:creator>
            <pubDate>Sun, 18 Feb 2018 21:55:21 GMT</pubDate>
            <atom:updated>2018-02-19T13:28:19.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9KoTjJNB-_TEdxWQqrk3EQ.jpeg" /></figure><p><a href="https://towardsdatascience.com/building-prediction-apis-in-python-part-3-automated-testing-a7cfa1fa7e9d">In the last part</a>, we looked at automated testing with pytest to verify that our API is correctly scoring the model. In this post, we’ll look at how we can separate the API functionality — which is responsible for handling requests and preparing the responses — from the code necessary to prepare features and score the model.</p><p>If you’re new to this series, welcome! Also, you may want to start at the beginning just to review what we’ve already done.</p><p><a href="https://towardsdatascience.com/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3">Building Prediction APIs in Python (Part 1): Series Introduction &amp; Basic Example</a></p><p>Throughout this post, we’ll look at snippets of code, but <a href="https://github.com/cmoradi/prediction-apis/tree/master/part04-decoupling/code/01_wrap_model">the full files are available on GitHub</a>.</p><p><em>Side Note: I really appreciate the feedback I’ve received on this series. In the first three parts, I spent a lot of time revising drafts to make sure that things were presented as clearly as possible. I recently started interviewing, so I’m a little more time-constrained. I’m going to do my best to continue posting regularly, but there may be longer delays. I’m also going to try to spend less time revising. Please let me know if there are confusing sections, and I’ll try to clarify. Thanks!</em></p><h3>Tightly Coupled Code</h3><p>We’ll pick up with the final example of our iris prediction model from <a href="https://towardsdatascience.com/building-prediction-apis-in-python-part-3-automated-testing-a7cfa1fa7e9d">Part 3</a>. We’ll reject requests that are missing petal_width; all others we’ll score by using mean imputation for any other missing feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00c84985e7c9dd1403155a9288e13a63/href">https://medium.com/media/00c84985e7c9dd1403155a9288e13a63/href</a></iframe><p>As we can see, the API contains a fair amount of code related to this particular model. In fact, most of the code is specific to this model or a version of the iris model:</p><ol><li>We’re retrieving hard-coded query string parameters from the request, converting them to float values, and replacing them with default values if they’re missing or can&#39;t be converted.</li><li>We’re checking if petal_width is missing and are preparing a specific error message to send back to the caller.</li><li>We’re creating the feature vector; the API needs to know the correct order to put the features into a features list.</li><li>The class labels are contained in a global MODEL_LABELS variable.</li></ol><p>We could adapt this code to handle variations of this model. For example, using hard-coded default values for our features is bad coding practice in general. We could pull these out to a configuration file. This would allow us to score two versions of the model with different mean imputation values.</p><p>Unfortunately, we will quickly find that other changes would be difficult to accommodate. Suppose we want to implement two different model intents: the current version and one in which we’ll impute petal_width if it&#39;s missing, but reject requests missing sepal_width. What if the logic that handles missing values for one of the models becomes more complicated? What if we have a totally different model — one that predicts fraud using 40 features?</p><p>As mentioned in a prior post, we could create a separate API or endpoint for each type of model, but to quote Raymond Hettinger¹, “There must be a better way!”</p><h3>Pulling Apart the Ball of Twine</h3><p>In an ideal world, we’d separate this functionality as follows:</p><ul><li>API: Accepts the requests, finds the appropriate model to score, passes raw data to the model for scoring, and prepares the response based on the model output.</li><li>Model: Pulls out the correct fields, prepares the raw data into features, makes a prediction if it can score the record or raises an error if it cannot, and sends the results back to the API.</li></ul><h4>Wrapping Our Model</h4><p>There are a few ways to accomplish this, but we’ll begin with one easy approach. We’ll wrap our model in some extra code that will handle the feature retrieval and preparation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b820624eec45dcd8e8fa3c5508641bc9/href">https://medium.com/media/b820624eec45dcd8e8fa3c5508641bc9/href</a></iframe><p>The ModelWrapper class only has three methods: __init__, predict, and _prepare_features. When we create an instance, we&#39;ll pass in the Scikit-Learn model object (model_object) with the class_labels (stored previously in MODEL_LABELS), and the feature_defaults (dict containing the imputation values).</p><p>The predict method is the one that the API will call to get a prediction. The API will pass in the request.args object directly and the model will pull the correct fields out. This extraction and the handling of missing values has been moved to a separate method, _prepare_features. The code in these functions is nearly identical to the code we originally had in the API.</p><p>As a side note, if you’re unfamiliar with the single leading underscore convention in Python, this is a way of marking methods as “for internal use only” — code that’s only intended to be called by other methods defined within the class (or its base/sub-classes). However, there’s no mechanism for preventing anyone from calling this directly.²</p><p>The final thing to discuss is how we are returning predictions or errors back to the API code. If we were successful, we’ll return a dict with the label and probabilities. In the case of an error, we&#39;ll raise a custom exception, ModelError, that is defined at the top of the file. One odd implementation detail is that I&#39;ve chosen to include this exception as part of the ModelWrapper. Later, we’ll use this in the API to reference this exception in a try/except block. The cleaner approach would be to have a shared utilities module/library where this is defined. Then, the model wrapper code and the API can both reference the definition. I thought the shared library approach might be more confusing (separate files) which is why I went with this one.</p><h4>Revising the Model Build</h4><p>Now that we have our defined our wrapper code, we need to incorporate this into our model build process. That way we can use joblib to pickle/save the model and the feature extraction and scoring code together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/691b80475c94c03eeb2487b43f504910/href">https://medium.com/media/691b80475c94c03eeb2487b43f504910/href</a></iframe><p>Basically, we’re just creating a dict that has the feature names for the keys and the mean value for the feature as the corresponding value. We wrap the model and then save this wrapped version. I’ve left out the code to generate our testing datasets (see <a href="https://towardsdatascience.com/building-prediction-apis-in-python-part-3-automated-testing-a7cfa1fa7e9d">Part 3</a>) for clarity, but you can find <a href="https://github.com/cmoradi/prediction-apis/blob/master/part03-testing/code/04_test_reject_missing_petalwidth/build_model_v1.0.py">the complete file here</a>.</p><h4>The New API</h4><p>The final step is to modify our API to use the wrapped model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0cb4d8197a6ff776222e3520fe49c89/href">https://medium.com/media/c0cb4d8197a6ff776222e3520fe49c89/href</a></iframe><p>Mostly we need to remove all the feature extraction and scoring code. The MODEL is loaded in the same way (as a global), but this version contains all the ModelWrapper code in addition to our Scikit model. In a try/except block, we call MODEL.predict(), but now we are just passing in the request.args. We can catch an exception if one is raised, and turn the error message into a proper response (with the correct status code). If no exception is raised, we get back a dict with the label and class probabilities. The only thing left is to prepare the response through jsonify().³</p><h4>Running Our Tests</h4><p>We can copy over our test_predict_api.py file that we constructed in Part 3 (<a href="https://github.com/cmoradi/prediction-apis/tree/master/part03-testing/code/04_test_reject_missing_petalwidth">also available here</a>). Put it in the same directory along with all the other files, and run pytest. These tests should all pass.</p><h3>Limitations of This Approach</h3><p>We have successfully untangled our model scoring code from our general purpose API code. Now, there is nothing in the API’s predict endpoint that is specific to this model⁴, so we can quickly extend this API to score multiple models.</p><p>While this is a huge step forward, there are some challenges with this approach. The primary one is that the feature generation code is separate from the general model build code. It may be tough to see this because our model build is so simple. Our training dataset doesn’t even have any missing values, so we don’t need to do mean imputation. Suppose we were using a more realistic model that required dummy/one-hot encoding of categorical variables, imputation, or complicated feature calculations instead of just converting to float. With our current approach, we may need to maintain two versions of this featurization code: one that operates on the training data and one version that is part of the ModelWrapper.</p><p>There is enormous benefit in creating a unified featurization codebase that can be applied to both training and scoring contexts, but this can be challenging and is not always possible. By using a single version of the featurization code in both contexts, we reduce bugs and can deploy the model more quickly. The main reason why this is not always possible is that each context has different constraints. In the model build process, the entire training dataset must be prepared, so the implementation may be optimized to handle many records at once. For scoring, we only need to prepare a single record, but this should be done as quickly as possible.</p><p>We’re not going to cover it in this post, but Scikit-Learn has a pipeline feature that let’s us define preprocessing/featurization steps that are shared between the model build and scoring contexts. However, this is not a perfect solution either. There are some constraints on the types of steps that can be defined in the pipeline which may be limiting.⁵</p><h3>Footnotes</h3><ol><li>Raymond has been a Python core developer for 15+ years and is the creator of the collections and itertools modules. He also has been teaching Python for many years and is an exceptional educator. Google him and watch all of his talks because they&#39;re simply amazing.</li><li>You can think of these as private or protected methods in a Java class. However, Java explicitly prohibits calling these methods externally. Python will not.</li><li>Status wasn’t part of the result dict, so we need to add it. If you&#39;re unfamiliar with **result, this is performing keyword unpacking. A quick example: d = {&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}. Then, the call: myfuct(**d) is equivalent to the call: myfunct(a=1, b=2, c=3)</li><li>We still have the hard-coded MODEL global variable, but we&#39;ll look at fixing that in the future.</li><li>There may be a specific step that we’d want to run on the API platform that we don’t need to run as part of the model build process. In a future post, we will look at logging/DB storage. One thing we may want to store is the prepared feature vector so that if we experience problems on the API platform, we can verify that the features are being calculated correctly. To do this, we’d need to insert a “logging” step into the pipeline just before the model scoring happens (last step of the pipeline). I’m not sure if this is possible.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b5eaf2ed125" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-prediction-apis-in-python-part-4-decoupling-the-model-and-api-4b5eaf2ed125">Building Prediction APIs in Python (Part 4): Decoupling the Model and API</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[Building Prediction APIs in Python (Part 3): Automated Testing]]></title>
            <link>https://medium.com/data-science/building-prediction-apis-in-python-part-3-automated-testing-a7cfa1fa7e9d?source=rss-f4d67dfaf29a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7cfa1fa7e9d</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Moradi]]></dc:creator>
            <pubDate>Wed, 07 Feb 2018 21:32:45 GMT</pubDate>
            <atom:updated>2018-02-07T22:26:22.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRbPfMeUGoFvc0z5ziPn1A.jpeg" /></figure><p><a href="https://gist.github.com/cmoradi/XXXXADDLINKXXX">In the last post</a>, we improved the error handling of our prediction API and considered the nuanced decision about which records we should score. In this post, we’ll look at how we can test our API using pytest.</p><p><a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3">Building Prediction APIs in Python (Part 1): Series Introduction &amp; Basic Example</a></p><p>As always, we’re going to use Python 3, and I’m going to assume that you are either using Anaconda or that you’ve set up an environment with these packages installed: flask, scikit-learn, and pytest.</p><p><em>Note: I’ll walk through snippets of code in this post, but it may be helpful to see the full files in context. You can find the </em><a href="https://github.com/cmoradi/prediction-apis/tree/master/part03-testing/code"><em>complete examples on GitHub</em></a><em>.</em></p><h3>The Case for Testing</h3><p>While automated testing is a core practice in modern software development, it has yet to be fully embraced by many data scientists. Simply put, this is additional code that runs tests on your main code base. Testing frameworks, like pytest, make it easy to define and execute a suite of these tests. As new functionality is implemented or existing code is refactored, these tests help developers confirm that existing functionality hasn’t been broken or locate bugs that have been introduced.</p><p>Here are some common excuses for not writing tests with my (snarky) responses:</p><ul><li><em>There is very little code, so we don’t need tests. </em>What happens when you need to extend your current functionality? Each enhancement might be small, but in the long run you can end up with a large and untested code base. If there’s currently very little code, it should be easy to write tests, so do it!</li><li><em>I already checked each function against multiple test cases when I was writing the original code</em>. That’s great! One challenge with constructing tests is to come up with good test cases, and you’ve already done that. Won’t it be great to have the ability to run all those test cases every time you make a minor change?</li><li><em>I don’t make mistakes when I write code</em>¹. Of course! You don’t need test cases for <em>your </em>code, but what happens when someone else gets added to the project and starts modifying your beautiful, perfect code? How will we know if they broke something? Are you willing to check every commit they make in detail? Are you excited to maintain this code for the rest of your life?</li></ul><p>Before getting into the meat of this post, I want to point out that I’m going to be a hypocrite. We’ll focus on testing the API. Along the way, we’ll also need to modify the code that builds our model. Astute readers will notice that I’m not writing any tests for the model build pipeline. If it helps, I do feel bad about this.</p><h3>Adjustments for Better Testing</h3><p>Before we get into writing the actual tests, there’s one thing that I’d like to change about the API response we’re generating. Currently, we’re only sending back the predicted class (iris type). While this is what the users of our prediction API need, it doesn’t provide a ton of information for us to test. The predicted class is chosen as the class (iris type) with the highest model score. Because of this thresholding, the predicted class could be the same even if the underlying scores are somewhat different. This is analogous to a function that performs complicated and precise calculations, but returns a value that is rounded to the nearest integer. Even if the returned integer values for many inputs match the expected values, the underlying calculations may not be correct. Ideally, we’d like to verify that the precise results of the calculations are correct before they are thresholded or rounded.</p><p>To provide ourselves with more data to verify that we’re correctly scoring the model, we’re going to change the API response to include the probabilities of each class². This is accomplished by calling MODEL.predict_proba() instead of MODEL.predict(). We then use argmax() to get the index of the largest value which gives us the predicted class. We&#39;ll return the raw class probabilities to the user through probabilities (see below for an example response).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc871d06901ec1e2d6ab84ccb8e421b2/href">https://medium.com/media/bc871d06901ec1e2d6ab84ccb8e421b2/href</a></iframe><p>We can then run the API (python predict_api.py) and make a test call through requests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31e2c4fdb113f3cc8e49a9b03a4e8d01/href">https://medium.com/media/31e2c4fdb113f3cc8e49a9b03a4e8d01/href</a></iframe><h3>Basic Test of the API</h3><p>We’re going to begin with a simple example where we just score the same example as shown above, but we’ll use pytest to do this. We first need to create a testing file: test_predict_api.py. For now, we can put this in the same directory as our API file: predict_api.py. <em>Note: pytest is capable of automatically locating testing files and functions, but you need to assist it in doing this. By default, it will inspect any file whose name begins with the “test_” prefix and will run any test functions that begin with “test_”.</em></p><p>When we construct tests, we typically follow this pattern:</p><ol><li>Set Up (optional): Initialization for the test or environment. Examples: initialize a database, create instances of a class that will be used in the tests, initialize the state of the system, etc…</li><li>Run Code: Run some code from your main code base (code under test) on a predefined test case or within the predefined environment. This may include: calling a function/method, creating an instance of a class, initializing a resource, call an API, etc…</li><li>Verify Results: Check that effects of the code meet expectations through the use of assert statements: returned value of function call is correct, exceptions were appropriately raised, the system has changed to the correct state, etc…</li><li>Tear Down (optional): Clean up after the test has run to restore the environment back to a default.</li></ol><p>Here’s how this example will align with these steps:</p><ol><li>Set Up: Instantiate a test_client (described below) that will allow us to simulate calls to the API.</li><li>Run Code: Make a call to the /predict end point with a predefined set of features.</li><li>Verify Results: We get back a response with status_code of 200 and the content is JSON with the correct format and values.</li><li>Tear Down: This is somewhat implicit. We’re going to use a context manager during the “set up” of the test_client. Upon exit, the client will be cleaned up.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cebe0e923d1f1f916670f836271cec49/href">https://medium.com/media/cebe0e923d1f1f916670f836271cec49/href</a></iframe><p>As noted above, the test_client we’re using is a feature of Flask that allows us to simulate calls without having to run the server. Here, we create a new client using a context manager. From this, we make a GET request. The query_string keyword argument provides functionality similar to how params works in requests.get(); it allows us to pass data that is used to create the query string.</p><p>From the response, we’re checking that we received the “200 OK” status, and finally we check that the payload of response matches what we expected. Since it comes as bytes, we can use json.loads() to convert it into a dict.</p><p>We can now execute the tests using pytest³ at the command line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f06ab15513c1d407bc9a5ff4013761fd/href">https://medium.com/media/f06ab15513c1d407bc9a5ff4013761fd/href</a></iframe><h3>Always Fail First</h3><p>Whenever you’re writing automated tests, <strong>it’s important to verify that you’re actually testing something — that your tests can fail</strong>. While this is an obvious statement, a common pitfall is that tests are written that don’t actually test anything. When they pass, the developer assumes that the code that is being tested is correct. However, the tests are passing because the tests were poorly written.</p><p>One way of preventing this kind of error is to use test-driven development (TDD). We’re not going to go into this in depth, but it’s a development process where:</p><ol><li>You start by writing a test for a new feature.</li><li>You verify that the test fails.</li><li>You write code to implement the new feature.</li><li>You verify that the test now passes.</li></ol><p>If you haven’t tried TDD before, I definitely recommend it. It takes discipline, especially when getting started, and buy-in from other developers and stakeholders. However, dedication to the process is rewarded with fewer bugs and lower stress when implementing new features. To learn more, read Harry Percival’s excellent book, <a href="https://www.obeythetestinggoat.com/pages/book.html">Test-Driven Development with Python</a>, which he’s made available online for free.</p><p>If you’re not up for TDD, the lazy method that I’ve used to verify that each test is actually testing something is to change my assert expressions to explicitly fail. For example, we’d change assert response.status_code == 200 to assert response.status_code != 200. If you make this change and rerun the tests, you should receive a failure similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8eba310415367b4db614b6d6721de51/href">https://medium.com/media/e8eba310415367b4db614b6d6721de51/href</a></iframe><p>If you’re going to use this method, be aware that pytest will only report the first AssertionError that occurs. So, <strong>you must change each assert separately and retest</strong>.</p><h3>More Testing</h3><p>We now have a test call for our API, and it’s working. How can we extend this to test multiple calls with different feature values and different expected results (labels and probabilities)? One quick option is to use our test dataset that we created during the model build. However, we need to get the class probabilities and the predicted label to use as the expected result for each input record.</p><p>One important thing to note is that <strong>we are testing the API platform and not the model itself</strong>. Basically, this means that we don’t care if the model is making false predictions; we just want to verify that the model output as scored on the API platform matches the model output from the build/offline/development environment. We’ll also need to test that the preparation of features (e.g., mean imputation) is done correctly on the API platform, but we’ll save that for the next section of this post.</p><p>Since our test dataset may change with each new version of our model, we should incorporate the generation of these data into our model build. I did some light refactoring (more is needed) to our model build script and added the code for generating the test dataset after the model is built. We’ll store our test cases in a JSON file, and each test case will be structured as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11ac2b41b3ccf83828020440bf87349c/href">https://medium.com/media/11ac2b41b3ccf83828020440bf87349c/href</a></iframe><p>Here’s the modified version of our model build code that incorporates the test dataset generation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2535c8708da017a328c9d98d23afc1e/href">https://medium.com/media/d2535c8708da017a328c9d98d23afc1e/href</a></iframe><p>At the top, there’s a function called prep_test_cases() which just reformats the features, class probabilities, and predicted label for each test into our test case format.</p><p>Now that we’ve generated our test data, we need to add a new test to score all the records in this file and check the responses:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd19be3f749dd8bb2c903bdd4beaa13d/href">https://medium.com/media/fd19be3f749dd8bb2c903bdd4beaa13d/href</a></iframe><p>Because we structured the test data in a clean way where each test case has the features (API inputs) as well as the expected response (API outputs), the test code is fairly straightforward. One deficiency with this approach is that class probabilities are floats, and we’re doing an exact comparison of these values. Typically, some tolerance is allowed when comparing float values so that values that are very close are considered equivalent. To handle this, we’d need parse the expected response and use pytest.approx() when comparing each value in the probabilities. It doesn&#39;t require much more code, but I thought it would clutter this discussion a bit, so I&#39;m leaving out the implementation.</p><h3>Handling Missing Values</h3><p>Our API is configured to use mean imputation to replace bad or missing values, but our test dataset doesn’t include any records with missing values. However, this is not an issue since we can simulate these data using the data we already have. We simply need to replace the existing values with the mean value for a feature and rescore the records. To our model build script we’ll add the following after our original test data generation code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b58d8e83011cb9867f2162b95686e7e/href">https://medium.com/media/2b58d8e83011cb9867f2162b95686e7e/href</a></iframe><p>We likely don’t need to be this thorough, but for each record, we are testing every combination of features that could be missing. We create two versions of each record: one that has None for missing values and one that has the imputed by the mean value. The first will be stored (after None-valued features are dropped) in the test case as features. The second will be scored to get the prediction probabilities that we’ll expect to see returned by the API. In order to drop the None-valued features we must make a small change to the creation of feat_dict in the prep_test_cases function. Here&#39;s the revised function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1fe7b6b46ecadf869983bab64af3396/href">https://medium.com/media/b1fe7b6b46ecadf869983bab64af3396/href</a></iframe><p>We also need change our tests to use this new file. While we could just copy the last test function test_api() and replace the filename testdata_iris_v1.0.json, that would result duplicate code. Since we need the test function to be exactly the same except for the filename, a better approach is to use pytest’s parametrize functionality. We simply add a decorator that allows us to specify arguments for the test function and rerun the test for each of these values. In this case, we&#39;ll pass in the filename:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c331b4ba940b455d3c80c5e345374e0d/href">https://medium.com/media/c331b4ba940b455d3c80c5e345374e0d/href</a></iframe><h3>Testing Errors</h3><p>In the <a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-2-basic-error-handling-3ab87b7a93">last post on error handling</a>, I mentioned that we could be more selective in which records we were willing to score, but I did not provide an example of this. Here we’ll tweak our API to look at a simple example where we’ll reject requests that are missing data for petal_width. We&#39;ll score all other records, using mean imputation if needed.</p><p>As a slight tangent, how did I chose petal_width? Well, if we look at the feature importances (using model.feature_importances_), we see that the fourth feature (petal_width) has the highest value with a normalized score of 0.51. Since this is the most important feature in our model, it makes the most sense to reject records that are missing this feature.</p><p>A simple way to implement this is to remove the default value for petal_width and then handle the case if it&#39;s missing. Nearly all of the code remains the same, but I&#39;ve included it here for context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00c84985e7c9dd1403155a9288e13a63/href">https://medium.com/media/00c84985e7c9dd1403155a9288e13a63/href</a></iframe><p>We can do a quick test to make sure it works for a simple case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca59c7a2bc84f329ac26fe7b4a57f233/href">https://medium.com/media/ca59c7a2bc84f329ac26fe7b4a57f233/href</a></iframe><p>Great! It works! Now, we just need to add this to our test suite.</p><p>For simplicity, I’m going to skip showing how to modify our old missing value tests and just implement the new tests that handle missing or bad values for petal_width. Basically, I removed all tuples from missing_grps that had a 3 in them (index of petal_width) and the test where all features are missing.</p><p>For our new tests, we could use the same JSON format. This would be a cleaner implementation. For clarity though, I’m just going to implement these tests in a separate function that has two test cases for petal_width: the feature is missing and the feature has a bad value (&quot;junk&quot;).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ea4414c3262343da9b552e2698221d7/href">https://medium.com/media/7ea4414c3262343da9b552e2698221d7/href</a></iframe><p>We can rerun our tests and verify that these pass. Of course, we should also try to change the == to != to verify that they fail for each condition too. Again, this will help ensure that we&#39;re testing what we actually think we&#39;re testing.</p><h3>Identifying Issues</h3><p>Now that we have our tests, we might wonder if they’re actually going to catch bugs in our code. Perhaps, you already found some issues when you were creating these tests and running them on your API code. If not, here are some simple changes that you can make that should cause one or more of the tests to fail (do each of these independently):</p><ul><li>In the API code, change the default (mean imputation) value for sepal_length from 5.8 to 5.3.</li><li>In the API, put back the mean imputation for petal_width. This will allow the API to score records that are missing petal_width. You should see failures in the tests that are expecting the API to return &quot;400 Bad Request&quot; when petal_width is missing.</li><li>In the API, change the text of the error message that is sent when petal_width is missing.</li><li>We can also mimic the case where someone accidentally modifies the model and tries to deploy it. To test this, we can build an alternate version of your model, deploy it, but use the test data files (JSON) for the original model. A quick way to implement this is to use a different value for random_state in the training/test set split (e.g., random_state=30). Remember to change the model output filename in joblib.dump() to something else (e.g., <em>&#39;iris-rf-altmodel.pkl&#39;</em>); you&#39;ll need to change MODEL in the API to reference this file. Also, make sure you don&#39;t execute the code that generates the test data files as these will rebuild them based on the alternate model. When you rerun your tests, you will likely see failures in all tests except for the ones that reject requests when petal_width is missing or invalid. If your tests still pass, try another random_state as it&#39;s possible that the model will be equivalent because the training set may remain the same or the changes aren&#39;t enough to change the model.</li></ul><p>Our tests are definitely catching problems, but are we catching all of the problems? The simple answer is that we are probably not catching everything. While creating this post, I tried changing the mean imputation (default value) for sepal_width to 3.1 instead of 3.0. When I reran the tests, they all passed. Perhaps this isn&#39;t a big deal; perhaps our model just isn&#39;t that sensitive to small shifts in sepal_width around the mean value. This is the feature of lowest importance. However, we used our test set for test cases, and these data points don&#39;t necessarily fall near the boundary of different classes. If we had more test cases or just better test cases, we may have been able to catch this type of bug.</p><h3>Wrapping Up</h3><p>We have seen that automated tests can help us find bugs in our code. While we started with testing a single API call, we were able to quickly move towards a framework for running numerous test cases, and it only required adding a little extra code.</p><p>Testing is an important topic, so it’s likely we’ll revisit this in later posts. Here’s a quick preview of some areas that we didn’t cover, but may in the future:</p><ul><li>Speed of Tests: It’s beneficial to run tests often while you’re changing your code. This makes it easier to detect errors early when refactoring existing code or adding new features. If the tests take a while to run, developers are less likely to do this. One approach is to separate tests that run quickly from those that take more time. Developers can then run the quick test suite when they make incremental changes, and run the full suite before they integrate the changes back into the main repository.</li><li>Mocking &amp; Patching: We saw that small changes to the default (mean imputation) value for sepal_width didn&#39;t cause our tests to fail. If this was a requirement, we could use patching to intercept the call to model.predict_proba() during scoring to verify that the correct values are being substituted.</li><li>Fixtures: This is a feature of pytest that you create, configure, and destroy resources in order to establish a clean and consistent environment in which each test can run. If you’ve familiar with “setup” and “teardown” in many unit testing frameworks, fixtures are an extension of this idea.</li><li>Integration of Subsystems: Currently, we just have our model and our API. In subsequent posts, we’ll look at adding a database backend and perhaps some other services. How do we test these? How do we test the system as a whole?</li><li>Continuous Integration Tools: These help make it easier to integrate code into a shared repository. By making it easier, the hope is that it will be done more often and in smaller chunks. One common feature of these tools is that they will automatically the run test suite every time a pull request is submitted and the pass/fail results will be available to reviewers.</li><li>Test Coverage: Did we test every line of our code? We could create a test coverage report to help us see which lines of our code were run during testing and which were not. This won’t tell us if we’ve handled all possible cases, but it can give us information into where our test suite is falling short.</li><li>Advanced Testing Methodologies: We’re unlikely to cover these topics, but I wanted to mention them. With property-based testing (see <a href="https://github.com/HypothesisWorks/hypothesis-python">Hypothesis</a>), you create parameterized tests and the framework generates an extensive set of test cases for you. This can lead to more comprehensive tests without requiring you to think up all the edge cases. Mutation testing (see <a href="https://github.com/sixty-north/cosmic-ray">Cosmic Ray</a>) takes a very different approach. It works with your existing test cases and actually modifies your source code (code under test) in some small way (mutation) to see if your existing tests fail. If all tests still pass, your test code is incomplete as it’s unable to find the bugs that were introduced by the mutation.</li></ul><h4>FOOTNOTES</h4><ol><li>Not sure if anyone would actually says this, but on occasion you meet someone who seems to think this.</li><li>You may be thinking, <em>“My users don’t need to know the underlying scores for each class; they just need the prediction. So, why am I changing my response just for testing?”</em> Good question! We’re taking this approach somewhat out of convenience and for the sake of clarity. In a real implementation, you use a flag to specify whether underlying scores are returned and perhaps restrict this functionality to certain users. We could also use mocking and patching to access the scores without modifying the response to include model scores.</li><li>If you’re having trouble running pytest try these options instead: py.test or python -m pytest.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7cfa1fa7e9d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-prediction-apis-in-python-part-3-automated-testing-a7cfa1fa7e9d">Building Prediction APIs in Python (Part 3): Automated Testing</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[Building Prediction APIs in Python (Part 2): Basic Error Handling]]></title>
            <link>https://medium.com/data-science/building-prediction-apis-in-python-part-2-basic-error-handling-3ab87b7a93?source=rss-f4d67dfaf29a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ab87b7a93</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Moradi]]></dc:creator>
            <pubDate>Sun, 04 Feb 2018 18:25:51 GMT</pubDate>
            <atom:updated>2018-09-30T17:14:33.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*tLXzAPbIHL1HrkZFg4ILlg.jpeg" /></figure><p>In the <a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3">initial series post</a>, we created a simple API to score a Scikit-Learn random forest classifier built on the iris dataset. In this post, we’ll explore how we can handle errors that occur during scoring as well as look at the broader topic of defining when a model should be used.</p><p><a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3">Building Prediction APIs in Python (Part 1): Series Introduction &amp; Basic Example</a></p><h3>A Brief Motivating Tangent</h3><p>We can begin by thinking about testing a simple Python function. No model, no APIs, just a function that adds two numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45762c259ae87141d69fba0d1c4f7d90/href">https://medium.com/media/45762c259ae87141d69fba0d1c4f7d90/href</a></iframe><p>When we think about how to test this function, we should consider everything that can go wrong and assume it will go wrong at some point. This example is so simple that we only need to worry about bad input arguments for a and b. Here are some examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d38dd624aa8a2861fe2452a30cf17416/href">https://medium.com/media/d38dd624aa8a2861fe2452a30cf17416/href</a></iframe><p>Through this small set of examples, we can see three distinct categories based on the “acceptable?” column: the goods, the bads, and the uncertains. The “goods” are inputs that we would have expected — int or float values that we can add together. The “bads” are ones that raise an exception; inputs that Python doesn&#39;t know how to add. Python already raises an exception for us, but we see some inconsistency in the type of exception that&#39;s raised (TypeError or ValueError) based on the input arguments. We could catch these exceptions and raise a custom one that&#39;s consistent, or perhaps we might return None instead¹.</p><p>The final category, the “uncertains”, might be the most interesting. These produce valid results, but they don’t reflect what we originally intended to support. Here’s where we have a choice in how we want to address the inconsistency between our intention and our implementation. In Python, we generally don’t want to enforce types, so we could leave the code as is. We should denote the expected types in the docstring or through type hints so that users understand what we’re officially supporting in case future changes break the current functionality. However, there may be cases where we want to refuse to return a value unless some conditions are met. In these cases, we could explicitly check the types of the inputs or even restrict them to fall into a certain acceptable range of values (e.g., adding only small integers).</p><h3>Errors with Our Model Features</h3><p>Now that we’ve looked at a simple example, let’s go back to our original prediction API from <a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3">Part 1</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec0996f581fa0018a9533eeb313bd62c/href">https://medium.com/media/ec0996f581fa0018a9533eeb313bd62c/href</a></iframe><p>Starting with what we covered in the last section, we’ll consider bad input arguments passed through request.args. For each of these, we are expecting a value that can be converted to a float. However, using the method above, we&#39;ll obtain string values for each. Flask makes converting our query parameters easy by providing the type argument to the request.args.get() method:</p><p>request.args.get(&#39;sepal_length&#39;, default=None, type=float)</p><p>This will attempt to convert the value of sepal_length to a float and will return the default value, specified with the default keyword argument, if this conversion fails. <em>Note: the default value for the </em>default<em> keyword argument is </em>None<em>, so we could leave this argument out.</em></p><p>Along with the original version (not specifying type), we’re also handling the case where a query parameter is missing from the request. In both versions, the corresponding variable will be given a default value of None.</p><p>We can change the request.args.get() calls that retrieve sepal_width, pedal_length, and pedal_width in a similar manner. However, when we restart our server and test a request with bad values or missing parameters we&#39;re going to run into another problem: <strong>Our model can&#39;t handle missing values</strong>. Making such a request results in ValueError: Input contains NaN, infinity or a value too large for dtype(&#39;float32&#39;)².</p><h3>What Should We Score?</h3><p>With our adder function, input values from the &quot;uncertain&quot; category produce a result (no exception raised) but perhaps should not. In our model scoring, we&#39;ve found an analogous group that is handled in the opposite manner. Our current implementation is rejecting requests that are missing values (raising a ValueError), but perhaps we should find a way to return a prediction instead.</p><p><strong>Determining which requests should be scored and which should result in errors or warnings is a critical consideration in any model deployment.</strong> This is often a nuanced decision that involves the model developer, business partners, and product owners, and seeks to balance the benefits of a prediction against the costs of mistakes. I have intentionally left the software development role out as a stakeholder. This is because they will generally be able to implement the desired intent when provided with adequate time and resources. In the long-run, <strong>model usage should be driven by the data science, business, and product needs and not by the convenience of the scoring platform implementation</strong>. While I’ve listed these roles separately, the same person may satisfy many or all of them — making it more of a matter of which perspective we take when making these decisions.</p><p>Here are a few scenarios to help illustrate why we need to make a deliberate decision on which requests we’ll score:</p><ul><li>Online Advertising: Suppose we’ve built a model to predict which ad out of a set of possible ads we should show a particular visitor to our website. Through user tracking, we know the referring page or site for most visitors, but for some this is missing. This is a case where making a sub-optimal or even poor prediction might be fine as mistakes are low-cost. One concern might be how sub-optimal predictions would affect any A/B testing we’re doing on ads — especially if these low-quality predictions skew towards a particular ad — but visitors are unlikely to flee our site because they saw the “wrong” ad.</li><li>Extending Loans/Credit: An example of a high-cost decision is credit lending; our model will predict someone’s credit worthiness or risk. Often lending institutions will base many of the critical features of the model on credit bureau data. For example, if a customer is applying for a loan, we would like to know if they’ve had a default on another loan or have filed for bankruptcy in recent years. Credit bureau data are so critical to lending decisions that we would not want to score a customer’s application without having them.</li><li>Fraud Detection: Creating fraud defenses is often a balancing act between blocking suspicious activity and irritating good customers. Although fraud is typically rare in event rate as compared to legitimate use, it can result in enormous financial and reputational costs for companies. The gut reaction may be to aggressively use any fraud models that are available to reduce losses. However, fraud is also adversarial, and fraudsters will adapt their methods to circumvent existing defenses. Due to these reasons, it is often very challenging to make strong and consistent defenses against fraudulent behavior. In addition, events flagged as fraud may result in transactions being declined, accounts being restricted, or applications being denied. These treatments are highly effective when applied correctly, but false positives lead to poor customer experiences and can result in lower participation or attrition of valuable customers. Because of these factors, decisions based on a predictive model may be applied to only a small percentage of the total number of suspicious events.</li></ul><h3>Different Treatments of Missing &amp; Bad Inputs</h3><p>Now, let’s go back to our API example to show how we can implement some of these model usage strategies.</p><h4>Reject the Request</h4><p>We can begin by refusing to score any requests that have bad or missing values. The simplest way to do this is catch exceptions that are raised during scoring.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bd06c8a0338bd19c11b6b891e218b94/href">https://medium.com/media/3bd06c8a0338bd19c11b6b891e218b94/href</a></iframe><p>Here we add a try/except block around the MODEL.predict() so that we can catch any exception that&#39;s raised. Most of the code simply prepares an error response. Now, if the API is called with bad or missing values, the caller will receive this message: <em>Failed to score the model. Exception: Input contains NaN, infinity or a value too large for dtype(&#39;float32&#39;).</em></p><p>We also use the appropriate <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP status codes</a> to provide our users with additional feedback that not only was there an error that prevented us from scoring the request, but it was their fault. This was done by setting the status_code on the response to &quot;400 Bad Request&quot;. In the previous version of our API when an unhandled exception was raised, Flask still sent a response for us, but the status_code was &quot;500 Internal Server Error&quot;. While this provides a backstop, &quot;500&quot; errors just mean that something broke on the API server side. It doesn&#39;t inform the caller that their request was the cause, so they may try to repeat the call. Please note that we do not need to set the status_code when we&#39;re returning a successfully handled request because that response will automatically have a status_code of &quot;200 OK&quot;.</p><p>While this approach is successful and this error message is relevant, this is not an ideal way to handle input errors. We’re catching a base exception. Although we haven’t encountered any other exceptions, that doesn’t mean that they can’t occur. We should really try to isolate the input errors from other errors. In addition, we’re sending back the contents of the exception. If there’s sensitive information contained in this error message, we’ve just sent it out to a caller. This could be a security issue.</p><h4>Being Explicit</h4><p>One improvement might be to explicitly catch the ValueError exception which was raised in our initial tests. However, it&#39;s unclear if this would be the only exception raised if the values are bad or missing. Also, it&#39;s possible that a ValueError could occur somewhere else unrelated to bad/missing data supplied by the caller. Due to these factors, the best approach is to explicitly check and handle the input values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c2f8f2f52f624e5c1fb38a6d2f00ce0/href">https://medium.com/media/2c2f8f2f52f624e5c1fb38a6d2f00ce0/href</a></iframe><p>We’ve added the if block that checks if any of our feature values are None. This will occur if they were missing from the request or their values could not be converted into a float.</p><p>There are a few things that could be improved upon:</p><ul><li>We’re only addressing missing features or those that can’t be converted to a float. In a real scenario, we&#39;d also like to identify values that are out of an acceptable range. For example, all four features are measurements of the lengths of flower petals and sepals, so they must be positive. There&#39;s also an upper bound on these measurements; a 10,000 cm petal is not possible.</li><li>We should track whether a request was successfully scored or rejected. This could be done using Python’s logging module, but this is something we&#39;ll go into in more depth in another post.</li></ul><h4>Let’s Score Everything</h4><p>The iris dataset upon which we’ve built our model is already really clean. In most real-world scenarios, this cleaning and preparation process is a large part of model building. In particular, we didn’t encounter any missing values in our build dataset. This is a huge topic and is out of scope for this post. You can find a ton of excellent resources by searching for “handling missing data in machine learning” or “imputation machine learning”.</p><p>Here we’re going to use a simple method of handling missing values: use the mean value of the feature. This is called <em>mean imputation</em>.</p><p>We can get the mean values for each of our features by using: X_train.mean(axis=0). See the <a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3">original post</a> to see how our training set was constructed. This may vary based on the random_state that&#39;s used when constructed the training dataset, but it should be fairly similar to these (rounded for clarity):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a549b54e3ad4af0a3b0638a2b6beaf42/href">https://medium.com/media/a549b54e3ad4af0a3b0638a2b6beaf42/href</a></iframe><p>Implementing this is as simple as changing the default values when we get the request parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f811b9b2188b7acee54231a71602289/href">https://medium.com/media/3f811b9b2188b7acee54231a71602289/href</a></iframe><p>We can test this iteration and verify that it works correctly. In fact, we can see that it will score a request even when no parameters are supplied.</p><h4>Scoring in the Gray Area</h4><p>We’re going to skip over the implementation of a nuanced case where we reject requests that are missing important features but will use mean imputation if others are missing. This could be accomplished with some careful mixing of the techniques above along with some custom logic. As an exercise, you could implement an API that will only score requests that satisfy <strong>both of these conditions</strong>:</p><ol><li>sepal_length must be valid.</li><li>Only one of the remaining 3 features can be missing.</li></ol><h3>Next Steps</h3><p>There are several things about these implementations that we should improve upon. First, we’ve coupled the model and the API even more tightly than we had in our original example. In addition to retrieving specific query parameters, we’re now checking if their values are None or imputing them with specific values. Let&#39;s say we need to refit the model based on new data. With mean imputation, we&#39;d need to go through and update the default values for each feature in the API code base. Eventually, we&#39;d like to move toward building an API that can score multiple models, including ones that have different features. Ideally, we&#39;d like the models themselves to retrieve the features they need, prepare them, and perhaps raise an exception or return an error if they aren&#39;t supposed to score a record. Then the API would just be responsible for passing data to the model and prepare a response based on the results of model prediction— a clean separation of duties.</p><p>A second improvement would be to store data related to requests and errors that occur. If we have requests that we won’t score, we’d at least like to know how often this happens and perhaps bucket these rejections into categories. Since we’re not saving any data related to the requests we’re handling, we have no way answer these questions.</p><p>While these are both important, we’ll focus on how to test our API’s ability to score requests in the <a href="https://towardsdatascience.com/building-prediction-apis-in-python-part-3-automated-testing-a7cfa1fa7e9d">next post</a>.</p><p><a href="https://towardsdatascience.com/building-prediction-apis-in-python-part-3-automated-testing-a7cfa1fa7e9d">Building Prediction APIs in Python (Part 3): Automated Testing</a></p><h4>Footnotes</h4><ol><li>Returning None instead of raising an exception is helpful in functional programming. For example, if we’re computing a new column of a Pandas data frame using df.apply(my_funct, axis=1) and we expect the calculation to fail for some rows, we can have my_funct return None or numpy.nan. The resulting column will contain the correct values where the calculation was successful and will treat the failed calculations as missing. This is similar to the Maybe monad pattern.</li><li>We receive this error because our model will automatically convert our nested list into a numpy.ndarray with elements of data type float32. During this conversion, None elements will become numpy.nan.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ab87b7a93" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-prediction-apis-in-python-part-2-basic-error-handling-3ab87b7a93">Building Prediction APIs in Python (Part 2): Basic Error Handling</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[Building Prediction APIs in Python (Part 1): Series Introduction & Basic Example]]></title>
            <link>https://medium.com/data-science/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3?source=rss-f4d67dfaf29a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe89e12ffbd3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Chris Moradi]]></dc:creator>
            <pubDate>Wed, 31 Jan 2018 19:13:26 GMT</pubDate>
            <atom:updated>2018-02-07T17:22:08.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*Fz6aw1bcIJdL5aridrSf3g.jpeg" /></figure><p>Ok, so you’ve trained a model, but now what? All that work is meaningless if no one can use it. In some applications, you can simply create a batch job that will collect the records that need to be scored, prepare them, and the run the model. However, other applications require or at least highly benefit from a process for scoring models in real-time. Ideally, we’d even like to share the ability to use the model with others through a REST API. While deploying a simple model is fairly easy, there are challenges in extending and iterating on this starting point.</p><p>In this series, we’ll take an incremental approach to building a prediction API. For this post, we’re going to build the simplest possible API that will allow us to score our model and return a prediction. Each subsequent post will then focus on how we can improve on what we’ve already implemented. There won’t be a set end to this series. As new topics come up, I’ll try to expand on what’s already been done — depending on how much time I have and the interest level of readers.</p><h4>Intended Audience</h4><p>Throughout this series, we’ll primarily focus on the software engineering aspects of building a model scoring platform and discuss the gray area between engineering and data science. I’m going to assume for the most part that readers have a model that they want to deploy or that they are capable of producing such a model. As such, we generally won’t cover the process of building predictive models. There are many great tutorials and books that cover this topic.</p><p>There are two main audiences for this series. The first is full-stack data scientists who want to deploy their model through an API, but who aren’t sure how to do it effectively. The second is software engineers or technical product managers who haven’t worked in the data science space and may benefit from understanding how model deployment differs from general software deployment.</p><h4>Tools</h4><p>We’re going to use Python 3 as the primary language. In particular, I will be mostly using Python 3.6. Flask will be used for the initial APIs. All models will be built using Scikit-Learn. If you’re not sure how to setup a development environment with these packages, I recommend starting with <a href="https://www.anaconda.com/download/">Anaconda</a> as it provides everything you need to start already set up.</p><p>While this tool set is fairly narrow in scope, my hope is that the topics are broadly applicable to other programming languages and API frameworks.</p><h3>Basic Example</h3><p>Now that we’ve set the groundwork for this series, let’s build a basic model. We’ll start with a random forest classifier built on the iris dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e7f589c6ca99c2edaf24d02f30f83dc/href">https://medium.com/media/8e7f589c6ca99c2edaf24d02f30f83dc/href</a></iframe><p>Again, I’m going to skip discussing the model build process, so we’re not going to walk through this example in depth. The main thing to note is that once we’ve built the model, we are using joblib to save (pickle) it to a file. While this works, there are some concerns and limitations with this approach. Scikit has a great <a href="http://scikit-learn.org/stable/modules/model_persistence.html">article on this</a>, but the main issues are:</p><ol><li>Security: when you load a pickled object, you&#39;re essentially executing code stored in the file. Only load persisted objects that you trust.</li><li>Portability: any shifts in versions of scikit-learn (or potentially dependencies) between the build environment and the production scoring environment will cause warnings at a minimum and potentially unexpected behavior, such as failures or prediction errors.</li></ol><p>We’ll set these concerns aside for now, but these may be topics that we explore in subsequent posts.</p><h4>Building Our First API</h4><p>Now, we’re going to build the simplest possible API using Flask. We’ll include a single endpoint /predict that will allow us to pass the feature values through <a href="https://en.wikipedia.org/wiki/Query_string">query parameters</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec0996f581fa0018a9533eeb313bd62c/href">https://medium.com/media/ec0996f581fa0018a9533eeb313bd62c/href</a></iframe><p>We’re loading our model globally as MODEL. We also have a list of labels (MODEL_LABELS)¹ that correspond to the integer values that MODEL.predict() will output. We created our API endpoint using the @app.route(&#39;/predict&#39;)decorator and defined the predict() function to handle requests sent to this endpoint. Calls to this endpoint are expected to contain 4 parameters which correspond to our features²: sepal_length, sepal_width, petal_length, and petal_width. For example, a call would look something like this:</p><p><a href="http://localhost:5000/score?sepal_length=5&amp;sepal_width=3.1&amp;petal_length=2.5&amp;petal_width=1.2.">http://127.0.0.1:5000/predict?sepal_length=5&amp;sepal_width=3.1&amp;petal_length=2.5&amp;petal_width=1.2</a></p><p>Flask handles parsing the URL query string and adds the parameters to request.args which has an API similar to a python dict. Using get will retrieve a value if the key exists, and will return a default value otherwise. Since we didn&#39;t specify a default, None will be returned³. Also, by default, the values in args will be strings, but during scoring the model will automatically convert these to floats.</p><p>The feature values are then packed into a nested list (list of lists). This is necessary because our model expects a list of records where each record is the length of the feature set. We’re only scoring a single record at a time which is why the outer list contains only one inner list (record).</p><p>We use MODEL.predict() to obtain find the predicted class which will be 0, 1, or 2. Finally, we can get the label by using the class as an index into MODEL_LABELS.</p><h4>Running Our Prediction Service</h4><p>Now, we can start our Flask server from the command line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75374c71d0a8c891e0bc68d644842825/href">https://medium.com/media/75374c71d0a8c891e0bc68d644842825/href</a></iframe><p>From our browser, we can make a test request using the example above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*dkm-X1M0cSvrRKZ1w7kElw.png" /><figcaption>Test URL: http://127.0.0.1:5000/predict?sepal_length=5&amp;sepal_width=3.1&amp;petal_length=2.5&amp;petal_width=1.2</figcaption></figure><p>We could also use requests to do the same thing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95ed36cd0532174240f30c6beabf92d0/href">https://medium.com/media/95ed36cd0532174240f30c6beabf92d0/href</a></iframe><h3>What’s Ahead</h3><p>In 20–30 lines of code, we’ve built a simple model and created an API that will accept requests and return a prediction. However, there are several areas where we can and should improve on what we’ve done here. Exploration of these topics will be handled in later posts, but here’s a quick preview:</p><ol><li><strong>Error Handling</strong>: Currently, we’re not doing any error handling when we score the model. What happens when we receive bad data or data is missing (no sepal_length is provided)? What kind of feedback will the caller receive if there&#39;s a failure?</li><li><strong>Automated Tests</strong>: Do we have any bugs in our code? Rather than manually running a few requests, is it possible to automate this process?</li><li><strong>Extensibility</strong>: This API is only handling a single, global model. Should we create another one-off API for our next model? What if we create a new version of our current model? Should there be a separate API for each version?</li><li><strong>Data Collection</strong>: No data are collected from this API. How are we going to track how well our model is performing? Do we know when errors are being made? How long does it take to handle a request? If we start collecting data, where should we store it?</li><li><strong>Deployment</strong>: This is running locally, but we need to put it on a server. How do we scale? Should we go serverless? How do we handle load testing?</li><li><strong>Feature Engineering</strong>: This API expects the requester to have already prepared any features, but often we need to apply some transformations to the data before they’re ready to be consumed by the model. How and where should we do this?</li></ol><p>In <a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-2-basic-error-handling-3ab87b7a93">Part 2</a>, we’ll look at basic error handling for our API and cover the importance of defining when a model should be used.</p><p><a href="https://medium.com/@chris.moradi/building-prediction-apis-in-python-part-2-basic-error-handling-3ab87b7a93">Building Prediction APIs in Python (Part 2): Basic Error Handling</a></p><p><em>Special thanks to Geoff Svacha for providing feedback on this series.</em></p><h3>Footnotes</h3><ol><li>You can get these labels by using datasets.load_iris().target_names .</li><li>Similar to [1], use datasets.load_iris().feature_names and reformat these.</li><li>We’re going to go into this in more depth in Part 2 of this series.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe89e12ffbd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/building-prediction-apis-in-python-part-1-series-introduction-basic-example-fe89e12ffbd3">Building Prediction APIs in Python (Part 1): Series Introduction &amp; Basic Example</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>