<?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 Ian Cassidy on Medium]]></title>
        <description><![CDATA[Stories by Ian Cassidy on Medium]]></description>
        <link>https://medium.com/@ianlcassidy?source=rss-f1cab5d085d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FVB3UY2nlmqYxWPfdflDVg.jpeg</url>
            <title>Stories by Ian Cassidy on Medium</title>
            <link>https://medium.com/@ianlcassidy?source=rss-f1cab5d085d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:52:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ianlcassidy/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[Building better machine learning feature validation using Pydantic]]></title>
            <link>https://medium.com/upside-engineering/building-better-machine-learning-feature-validation-using-pydantic-2fc99990faf0?source=rss-f1cab5d085d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fc99990faf0</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ian Cassidy]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 14:42:29 GMT</pubDate>
            <atom:updated>2020-01-21T14:42:29.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*XHEwfffrM-VZhVAjkOBBUw.png" /></figure><p>In the 2+ years that I’ve been at <a href="https://upside.com/">Upside</a>, I’ve continually struggled with productionalizing machine learning models. Like most data scientists, I prefer to perform feature engineering and develop my models in a <a href="https://jupyter.org/">Jupyter</a> Notebook while relying heavily on <a href="https://pandas.pydata.org/">pandas</a> and <a href="https://scikit-learn.org/stable/">scikit-learn</a>. Depending on the application, the features that I generate could come from multiple external APIs and have multiple preprocessing steps. Rarely am I thinking, “How am I going to re-create this feature in a production environment and check to make sure that the value I’ve produced isn’t totally nonsensical?”</p><p>When building machine learning APIs to serve predictions, I’ve typically defined some variant of an <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict">OrderedDict</a>¹ to keep track of feature names and values during feature engineering. I refer to this object as a “features container” and use it to eventually feed the values in the form of a <a href="https://numpy.org/">NumPy</a> array to the .predict method of a pre-trained machine learning model. This is less than ideal for many reasons and has driven the Python engineers that I work with crazy on several occasions. Usually, I just wave my hands and say, “Look I have a <a href="https://docs.python.org/3/library/unittest.html">unit test</a> for the output of my feature engineering/model prediction pipeline and that is sufficient to say that everything is working as expected.”</p><p><strong>My statement above isn’t entirely wrong, but we as data scientists can do better!</strong></p><p>Recently, I’ve started to really embrace the concept of typed variables in Python — even when I’m developing models in a Jupyter Notebook! <a href="https://docs.python.org/3/library/typing.html#typing.NamedTuple">NamedTuples</a> and <a href="https://docs.python.org/3/library/dataclasses.html">dataclasses</a> (available in Python 3.7+) are two of my favorite things to use when defining the inputs and outputs of various functions that I write. In the past few weeks, I completely re-wrote a backend service that I built about a year ago to <a href="https://labs.upside.com/delay">predict flight delays</a> using typed variables. But, when I got to the part of my code that was creating and storing features, something was still bugging me. I converted my features container from an OrderedDict to a dataclass², but the process of typing out every field and datatype seemed overly tedious and verbose, especially if I ever need to go back and change anything about my model. It also lacked the ability to type check and validate the value assigned to the field out of the box.</p><p>Thankfully we can use <a href="https://pydantic-docs.helpmanual.io/">Pydantic</a>³ and some simple helper functions to alleviate the concerns I mentioned above. The <a href="https://engineering.upside.com/upside-labs-one-year-in-9ebb90f71815">Upside Labs</a> team has been using Pydantic for several months now to type check and validate data models in several backend services and it’s been another extremely useful library. Let’s work through a simple example of how we can use it to create a more robust features container.</p><h3><strong>Example</strong></h3><p>Let’s say I’ve trained a model using the dataframe below (it’s probably not a very good model). The features cat_1 and cat_2 are <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html">one-hot-encoded</a> categorical features while dog and bird are continuous features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*xCR_ZgzpT7p7G2CyXCAxHQ.png" /></figure><p>The code snippet below shows how we can represent this dataframe as a features container using Pydantic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3dd273b1a78f2b79b3fc6689c3c12ef/href">https://medium.com/media/e3dd273b1a78f2b79b3fc6689c3c12ef/href</a></iframe><p>I’m not going to walk through every line of code above, but here are some of the main points I’d like to highlight:</p><ol><li>The Pydantic conint and confloat wrapper functions are used to create constrained integer and constrained float fields, respectively, using the inclusive bounds specified by the ge (greater than or equal to) and le (less than or equal to) parameters. If we attempt to assign a value to a field that does not match the defined datatype or is outside the specified bounds, a Pydantic ValidationError error will be raised. The values that I have defaulted to come from inspecting the original dataframe.</li><li>The fields are all defined as <a href="https://docs.python.org/3/library/typing.html#typing.Optional">T.Optional</a> with a default value of None so that the features container object can be instantiated and then passed from one function to another and feature value(s) can be assigned sequentially⁴.</li><li>The set_categorical_features helper method can be used to one-hot-encode a set of categorical features all at once! All you need to do is specify the feature prefix and positive_category (see the code snippet below for an example of this in action). I often have categorical features with tens or hundreds of categories so this method has been extremely handy.</li><li>The set_bulk_features helper method can also be used to set many feature values at once. Just pass it a mapping dictionary of field names and values and the method will take care of the rest (including the type checking and validation).</li><li>The numpy_array property can be used to create a NumPy array with the correct shape and order of field values specified in the original training dataframe. It has a check to make sure that all of the values have been assigned and will raise a custom FeatureIsNoneError error if any of the fields are None. This property would be used to pass the feature data to the .predict (or .predict_proba) method of a pre-trained machine learning model.</li></ol><p>Next, we can write a simple features container and model prediction pipeline using the AnimalFeatures container we defined above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c062d8f098bb6fc90d3df957447b68a8/href">https://medium.com/media/c062d8f098bb6fc90d3df957447b68a8/href</a></iframe><p>To protect against predictions made with erroneous feature values, I’ve added some try/except logic to catch any validation or missing feature errors, log a warning, and return a default prediction. If this happens I don’t want the code to blow up, I just don’t want the model to output a misleading prediction. Similar logic exists in the production services that I’ve recently worked on and it has been immensely helpful in finding bugs and features that aren’t working as expected.</p><p>Finally, we can convert the original dataframe to a features container using a simple script to automatically generate the field names, datatypes, and bounds by inspecting the values in each column of the data. I am constantly tweaking my models and don’t want to have to worry about how adding or moving around columns in my training dataframe will affect the production feature pipeline. The output of the function below can be used to produce the code that would become the features container object — the AnimalFeatures class defined in the above snippet was actually generated using this script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0e8aa192e270d94bac755859a0758c/href">https://medium.com/media/0b0e8aa192e270d94bac755859a0758c/href</a></iframe><h3><strong>Closing</strong></h3><p>I would love some feedback from other data scientists, machine learning engineers, or anyone else about whether you think the above concepts might be useful for your own applications. Thinking through the process of taking a machine learning model from a Jupyter Notebook into a production microservice has been a great learning experience for me and I hope the tips and tricks outlined in this article are valuable for other developers.</p><p>Oh… and we’re hiring — check out our <a href="https://upside.com/company/careers?utm_source=blog&amp;utm_medium=medium-engineering-blog&amp;utm_campaign=engineering-blog&amp;utm_content=labs">careers page</a>!</p><p><strong>Footnotes:</strong></p><p>[1]: Using an ordered dictionary instead of just a standard dictionary has the advantage of returning the values of the dictionary in a <em>specific order</em>. This is critical in machine learning applications because the model expects the features in the order that was used during training.</p><p>[2]: I initially used a dataclass instead of a NamedTuple for my features container because dataclasses are mutable. This allowed me to pass the container object through a series of functions that assign values to the various fields I’ve defined.</p><p>[3]: Huge shout out to <a href="https://www.linkedin.com/in/ramichowdhury/">Rami Choudhury</a> for introducing me to Pydantic and for helping me develop the code in this blog post!</p><p>[4]: This is not meant to be prescriptive, but is merely how I generally write production feature pipelines. Feel free to adapt any of this logic to fit your own needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fc99990faf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/upside-engineering/building-better-machine-learning-feature-validation-using-pydantic-2fc99990faf0">Building better machine learning feature validation using Pydantic</a> was originally published in <a href="https://medium.com/upside-engineering">Upside Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Content-Based Recommendations to Personalization: A Tutorial]]></title>
            <link>https://medium.com/upside-engineering/from-content-based-recommendations-to-personalization-a-tutorial-773c9903b521?source=rss-f1cab5d085d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/773c9903b521</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[personalization]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[travel]]></category>
            <dc:creator><![CDATA[Ian Cassidy]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 16:22:14 GMT</pubDate>
            <atom:updated>2018-12-19T16:22:14.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*-3RpKexlYXmTyrKDw4Z-rg.jpeg" /></figure><h3>Introduction</h3><p>A primary goal of the data science team at <a href="https://home.upside.com/welcome_home/?utm_source=blog&amp;utm_medium=medium-blog&amp;utm_campaign=EngineeringBlog&amp;utm_content=recs_and_personalize">Upside</a> is to present customers with flights and hotels that they are most likely to purchase. Additionally, we want our customers to feel like we know them, so personalizing the presented inventory is a great way to demonstrate this! One technique to personalize inventory is through <a href="https://en.wikipedia.org/wiki/Recommender_system">recommender systems</a>, which can take the properties of the inventory along with customer preferences into account in order to present items that are most relevant.</p><p>There are many ways to capture customer preferences (like the ubiquitous “thumbs up/thumbs down” button), but we found that content-based recommender systems, which don’t require direct customer feedback, provide a “quick and dirty” approach to testing personalization in our product. In this blog post, we’ll walk through the steps we took to implement content-based recommendations and personalization. Even though this tutorial is specifically geared towards the travel industry, the techniques presented here can be applied more generally across almost any e-commerce industry.</p><h3>The Data</h3><p>For the remainder of this post, we’ll examine real hotel inventory in New York City for a stay between January 7–10, 2019. Both the data and an accompanying <a href="https://jupyter.org/">Jupyter</a> notebook can be found <a href="https://github.com/ianlcassidy/blog-posts/tree/master/20181217-recs-and-personalization">here</a>.</p><p>Let’s start by examining the hotel inventory data by loading it in as a Pandas DataFrame and performing a <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html">.describe()</a> on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*dKoHh7651CIkMYtaOZgeSA.png" /><figcaption>Table 1. Summary of the hotel inventory data</figcaption></figure><p>A few things to note about the data:</p><ul><li>the hotel names have been removed and replaced by a hotel_id field, which is just an integer assigned to each row of data</li><li>the avg_rate field is the <em>minimum</em> average room rate per night returned by the hotel for the duration of the stay; i.e., if the hotel has multiple room rates available, this is the minimum rate</li><li>the distance field is in miles and is the distance to the location of the search performed to obtain this data, which is in Midtown Manhattan</li><li>the star_rating and user_rating fields are based on a 0–5 scale with .5 star increments and are a measure of the amenities and quality of the hotel</li></ul><p>Next, let’s perform some basic exploratory data analysis to visually inspect the data. Figure 1 illustrates histograms of the relevant fields — they seem normally distributed or slightly log-normal, which is good. Figure 2 shows that the avg_rate increases as star_rating and user_rating also increase — you get what you pay for!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*KUEiSbR6Tx18uDEyTcpwdg.png" /><figcaption>Figure 1. Histograms of the hotel inventory data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*XCMxSpcPQfmP0Fy3bQprWw.png" /><figcaption>Figure 2. Average rate vs star rating (left) and user rating (right)</figcaption></figure><h3>Content-Based Similarity</h3><p>The next step is to determine how you want to surface content-based recommendations. A simple approach in this example is by embedding the content of the hotel inventory into an N-dimensional space and finding the items that are the most similar to each other. In this case let’s construct our feature space as [lat, lng, avg_rate, star_rating, user_rating] — so the feature space of hotel_id = 10 is [40.714995, -74.015777, 326.4, 5, 4.5].</p><p>Now, let’s say a customer clicks on a particular hotel and wants to learn more about the room types/rates, amenities, and location. While they are exploring this hotel, we can present the customer with similar hotels so they can take them into consideration while shopping. At <a href="https://home.upside.com/welcome_home/?utm_source=blog&amp;utm_medium=medium-blog&amp;utm_campaign=EngineeringBlog&amp;utm_content=recs_and_personalize">Upside</a>, we use a carousel of 4 options in our hotel rates page to expose the recommendations. This allows customers to view similar hotel options that they may not have the chance to explore otherwise.</p><p>Once the customer selects a particular hotel, which we define as the “anchor,” we can provide recommendations of similar hotels by following these three steps:</p><ol><li>normalize the feature space by converting each feature (i.e., column) into a <a href="https://en.wikipedia.org/wiki/Standard_score">standard score</a></li><li>compute the <a href="https://en.wikipedia.org/wiki/Euclidean_distance">Euclidean distances</a> between the anchor hotel and the other pieces of inventory</li><li>sort the hotel inventory in ascending order by the Euclidean distance</li></ol><p>Below is some code to sort the hotels by the similarity_distance given an anchor hotel_id.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5591b06d6a0c51098b286a1722af85e/href">https://medium.com/media/b5591b06d6a0c51098b286a1722af85e/href</a></iframe><p>A few things to note here:</p><ul><li>Normalizing the feature space is <em>very important </em>since we are dealing with features that have different units. The choice of normalization scheme depends on the problem and the data — in this case we are using a standard score approach because the data is normally distributed — but, min/max scaling or <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">TF-IDF</a> (for comparing documents) may also be useful for other applications.</li><li>Choosing the right distance or similarity score can have a big impact on the quality of recommendations. We are using Euclidean distance because we are embedding geo-coordinates in our feature space. Using <a href="https://en.wikipedia.org/wiki/Cosine_similarity">Cosine similarity</a> instead would be a huge problem for hotels with the same heading that are far apart because they have the same angle in the [lat, lng] space (shoutout to <a href="https://www.linkedin.com/in/gilbertwatson/">Gilbert Watson</a> for pointing this out). Other types of similarity scores can be investigated using the convenient Scipy function <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html">cdist</a>.</li><li>It is important to backtest your recommendation algorithm to pick the best normalization scheme and similarity score and tune any other parameters. For example, looking at recent customer searches and purchases and using <a href="https://en.wikipedia.org/wiki/Evaluation_measures_%28information_retrieval%29#Precision_at_K">recall/precision rate at k</a> can help tune the hyperparameters to find the optimal algorithm configuration.</li></ul><p>Let’s see what happens when we make the anchor hotel_id = 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*gYLmepq2hY-v7nMjA9McwA.png" /><figcaption>Table 2. The 5 most similar hotels to hotel_id = 10</figcaption></figure><p>These results look promising! The algorithm found hotels of a similar price and rating to the anchor that are also nearby as measured by the distance_from_anchor field (in miles).</p><p>Next, let’s look at a second example where we set the anchor to be hotel_id = 21, which is much cheaper and has lower ratings than hotel_id = 10:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*pGxiNrJxnBjDpqKd9Nj_6w.png" /><figcaption>Table 3. The 5 most similar hotels to hotel_id = 21</figcaption></figure><p>Again, the algorithm is able to find similar and nearby hotels that are much different than the results in Table 2.</p><p>Regardless of the anchor, it is important to measure the goodness of the recommendations by tracking the number of customer views, clicks, and conversions and then iterating on the algorithm.</p><h3>Personalized Recommendations</h3><p>Building upon the content-based similarity algorithm, we can extend this methodology to create personalized recommendations for each customer. Instead of using the hotel that the customer clicked-on as the anchor and finding similar hotels, we can use purchase history to compute normalized features for each customer. The personalized anchor becomes the “virtual hotel” that we use to sort inventory in new markets based on a similarity score. This is akin to a look-a-like model where we try to recommend new hotels that are most similar to what customers have previously purchased.</p><p>Here is some example code of how we can modify the get_hotel_recommendations function from the previous section to provide personalized recommendations given a dictionary of pre-computed user features.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f5e7bfca665927f055e5c2cb9cba3ec/href">https://medium.com/media/3f5e7bfca665927f055e5c2cb9cba3ec/href</a></iframe><p>One lever we are using here to bias the model is to artificially set the distance feature equal to the minimum of the normalized distances for the set of available hotels. By doing this, we ensure that the algorithm penalizes hotels that are further away from the user specified search location. This technique can be extended to other concepts like recommending hotels that are more profitable (assuming we know or can calculate the amount of profit we can earn from each hotel). In that case, we can create a feature called profit and artificially set the value for the anchor equal to a high value.</p><p>Let’s look at the personalized hotel recommendations for 2 different customers. The first customer has features that are all equal to 0 (exactly at the mean) while the second customer has features that are all equal to 1 (above the mean). As we can see in the two tables below, the sorts are quite different and we are showing the second customer more expensive and higher quality hotels. This is expected because the second customer demonstrated historical affinity for purchasing hotels with prices and ratings above the population mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dzBp3Bwu6O0TR_FpvZx2cA.png" /><figcaption>Table 4. Personalized hotel sort for a customer with user_features = {“avg_rate”: 0, “star_rating”: 0, “user_rating”: 0}</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*l5a8AReF0FcMKQSm84yMdQ.png" /><figcaption>Table 5. Personalized hotel sort for a customer with user_features = {“avg_rate”: 1, “star_rating”: 1, “user_rating”: 1}</figcaption></figure><h3>Summary</h3><p>In this blog post we have shown how content-based recommendations can be extended to create lightweight personalized recommendations using historical customer search and purchase history. This approach was accomplished at <a href="https://home.upside.com/welcome_home/?utm_source=blog&amp;utm_medium=medium-blog&amp;utm_campaign=EngineeringBlog&amp;utm_content=recs_and_personalize">Upside</a> without a large data modeling or engineering effort — we were able to implement both techniques in our product in a matter of weeks! In addition, using the anchor concept and artificially setting or changing various features, we can weight or penalize different attributes of the items to fit any number of objective functions (like distance from search pin and expected profit).</p><p>Hopefully this tutorial provides some inspiration to get us all beyond the thumbs up/thumbs down button (but we’ll happily take your claps).</p><p>At Upside, we’re always looking to improve business travel. If you’d like to learn more about Upside Corporate, click <a href="https://home.upside.com/welcome_home/?utm_source=blog&amp;utm_medium=medium-blog&amp;utm_campaign=EngineeringBlog&amp;utm_content=recs_and_personalize">here</a>. Even better, if you’d like to join our team and work with Ian, visit our careers page <a href="https://upside.com/company/team?utm_source=blog&amp;utm_medium=medium-blog&amp;utm_campaign=EngineeringBlog&amp;utm_content=recs_and_personalize">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=773c9903b521" width="1" height="1" alt=""><hr><p><a href="https://medium.com/upside-engineering/from-content-based-recommendations-to-personalization-a-tutorial-773c9903b521">From Content-Based Recommendations to Personalization: A Tutorial</a> was originally published in <a href="https://medium.com/upside-engineering">Upside Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying Predictive Analytics to Flight Delays]]></title>
            <link>https://medium.com/upside-engineering/applying-predictive-analytics-to-flight-delays-85413ca4939f?source=rss-f1cab5d085d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/85413ca4939f</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <dc:creator><![CDATA[Ian Cassidy]]></dc:creator>
            <pubDate>Mon, 01 Oct 2018 14:07:47 GMT</pubDate>
            <atom:updated>2018-10-01T14:07:47.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MzWNA013cP6nbp-C.jpg" /></figure><h3>Motivation</h3><p>Flying for business is full of uncertainty. For travelers with a tight connection window or an arrival time close to an important meeting, even a short flight delay can cause serious anxiety. Nearly a third of <a href="http://bit.ly/2xEc5m1">Upside’s</a> business travelers encountered flight delays in the last 30 days alone. Of the delayed flights, 11% were delayed more than one hour and 4% were delayed more than two! Delays aren’t just a nuisance for the traveler either — in terms of lost productivity, companies could see losses into the hundreds of thousands, if not millions of dollars per year.</p><p>At Upside, we want to help our customers mitigate these scenarios by predicting flight delays prior to their trips and, when possible, providing alternate flight options to get them to their destinations on time.</p><p>According to the <a href="https://www.bts.gov/newsroom/december-2016-airline-on-time-performance">Bureau of Transportation Statistics</a>, domestic airlines reported an on time arrival performance of about 80% for 2015–2016. Of the delayed flights, anywhere between 25–35% of those flights (depending on the month of the year) were delayed due to bad weather. Another 5–10% of delayed flights were due to late arriving aircraft. If we can model these delays accurately, we’ll account for almost half of all delayed flights per year!</p><p><strong>This is how the Delay Predictor came to be.</strong></p><h3>Gathering the Data</h3><p>In order to produce monthly and yearly airline metrics, the Bureau of Transportation Statistics also publishes the underlying data that tracks the performance of every domestic flight operated by large air carriers. We downloaded this dataset for historical flights going back to 2012 and continuously append new data as it becomes available for more recent flights. A similar dataset was published by <a href="https://www.kaggle.com/usdot/flight-delays/home">Kaggle</a> for all flights in 2015. As of last count, we have over 40 million rows of on-time performance data stored in a <a href="https://engineering.upside.com/building-an-advanced-analytics-platform-with-snowflakes-cloud-data-warehouse-bba2e6d55485">Snowflake</a> table that is accessible to our entire data science team.</p><p>This dataset is amazingly clean in terms of having very few missing or extreme values. In addition to having expected fields such as flight number, flight duration, and scheduled departure/arrival times, it also has the delays broken out by type — like weather and late aircraft.</p><p>An obvious place to start the modeling effort was by predicting weather-induced flight delays. In order to do this, we chose to use <a href="https://darksky.net/dev">Dark Sky</a>’s API because it provides both historical <em>and</em> forecasted weather conditions using the same REST endpoint. At this point, I’d like to pause and bow down before whoever built the /forecast endpoint at Dark Sky. It’s super simple to use, relatively inexpensive, and almost always returns a valid response. Also, our <a href="http://bit.ly/2xOhnut">team at Upside</a> is obsessed with the <a href="https://darksky.net/app">Dark Sky smartphone app</a> and I encourage everyone to download and use it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*Z8vj8AuHCU6AmeT0.gif" /></figure><h3>Building the Model</h3><p>Originally, the model was constructed as a <a href="https://en.wikipedia.org/wiki/Binary_classification">binary classifier</a> — either we predict that a flight would be on time or that the flight would be delayed. This performed so well both in training as well as in testing on real-time data that we decided to turn it into a <a href="https://en.wikipedia.org/wiki/Multiclass_classification">multi-class</a> model in order to predict the magnitude of the delay.</p><p>Picking the delay classes was a bit tricky, but, with the help of the histogram below, we decided to go with 0–30 minutes, 30–60 minutes, 60–120 minutes, and 120+ minutes where the 0–30 minutes class is essentially “on time.” It’s interesting that there are clear dips in the histogram at 30, 45, 60, 80, and 110 minutes, which could suggest that the airlines are doing something to avoid being late by those exact durations. One thing we do know is most airlines issue travel waivers (whereby you can change your flight without paying a change fee) if your flight is delayed more<em> </em>than one hour. Thus including 60 minutes as one of the class boundaries made sense. Also, it’s worth noting that there aren’t any reported arrival delays under 15 minutes, which justifies the first delay class as being considered “on time.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJc8kkmxUTI-6Y9kO7zlxw.png" /><figcaption>Histogram of arrival delays</figcaption></figure><p>I’m not going to go into the details of the features or models we are using because, well, that’s proprietary (but hey, we’re <a href="http://bit.ly/2NE0SMs">hiring</a>). However, I will point out a few non-trivial techniques that we are using to improve model performance, which I think can be generally applied to machine learning solutions:</p><ol><li><strong>Remove the effects of seasonality.</strong> Weather-induced airline delays are heavily influenced by seasonality; e.g., hurricanes in the fall (h/t <a href="https://en.wikipedia.org/wiki/Hurricane_Florence">Florence</a>) and snowstorms in the winter result in higher occurrences of delays. Machine learning models tend to perform better if you remove these effects and only train on homogeneous data. For the problem at hand, that means using a small window of flight dates to train the model, and then retraining and updating the model in production as time goes on. More about how we’re doing this in the next section.</li><li><strong>Collect multiple samples of time-dependent signals.</strong> Since the weather is dynamic, we want to include these effects as features to our model. For example, for each flight we query the Dark Sky endpoint at multiple times (say right at take-off and 3 hours before take-off) and derive features based on the temporal derivatives of the weather signals. Luckily, this was easy to do because the Dark Sky API is so awesome (did I mention that already?).</li><li><strong>Balance your classes</strong>. Machine learning models are highly susceptible to bias and one of the biggest causes of bias in a model has to do with class balance (or imbalance). How to balance the classes in your training data should be done on a case by case basis to reduce bias and overfitting. A great tool that I’ve been using lately for class balance is called <a href="https://imbalanced-learn.readthedocs.io/en/stable/">imbalanced-learn</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*tOoeIMz9DwPZ52Ewog2W6w.gif" /></figure><p>To give some idea of how our model is performing, the figure below shows the results of the test data performance from a model that was trained using flights from late August. In the <a href="https://en.wikipedia.org/wiki/Confusion_matrix">confusion matrix</a>, the 0–3 labels correspond to our delay classes in ascending delay duration order; i.e., 0 = 0–30 minutes. A weighted <a href="https://en.wikipedia.org/wiki/F1_score">f1-score</a> of 0.62 is quite good for a 4-class problem since random guessing would result in a score of about 0.25.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*xqVQcHy4lX27vza3qjBPmg.png" /><figcaption>Test performance of the multi-class flight delay model using late August data</figcaption></figure><p>The above metrics provide an idea of how the good the model is at predicting the magnitude of the delay. If we “collapse” the delay classes (1–3) into a single delay class and present the above results as if they were from a binary classifier, we can examine the ability of the model to predict any delay. A <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">ROC-AUC</a> score of 0.83 for a binary classification problem of this complexity is pretty good! However, looking at the confusion matrix, there are many more false negatives than false positives. This may not be ideal when it comes to predicting flight delays as we’d like to be overly aggressive in notifying a customer of a possible delay (skew towards having more false positives). In the future, it may make sense to optimize the model for a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html#sklearn.metrics.recall_score">weighted recall</a> that puts a higher penalty on getting the on time flights incorrect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*v3wVedl4l8Qo-eodJpyZYg.png" /><figcaption>“Collapsed” test performance of the multi-class flight delay model using late August data</figcaption></figure><p>In testing the model on real-time data where we don’t know the exact cause of the delay, we have seen precision and recall scores around 0.4–0.5. In addition, we have been able to predict delays as far as 24 hours prior to the scheduled departure time! This is because we are relying on Dark Sky’s ability to forecast the weather, which is often very accurate.</p><h3>Retraining Pipeline</h3><p>As previously mentioned, we are handling the seasonality effects of weather-induced flight delays by only training the model on small windows of flight dates. As such, the model that is used in our production API for predicting flight delays must be retrained constantly. With the help of our amazing<a href="https://en.wikipedia.org/wiki/Site_Reliability_Engineering"> SRE</a> team, we built a worker that is scheduled using a cron job to automatically retrain the model and store the best result as a <a href="https://docs.python.org/3/library/pickle.html">pickle</a> file in an AWS S3 bucket. The retraining workflow and model API looks roughly like the block diagram pictured below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YopyjfsVuF8GF--XD10JTQ.png" /><figcaption>System architecture describing the model training worker and flight delay model API</figcaption></figure><p>One of the most important steps in this workflow is hyperparameter tuning of the different model architectures. We tune several different types of models using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html">RandomizedSearchCV</a> or <a href="https://hyperopt.github.io/hyperopt/">hyperopt</a> (depending on the type of model) and then pick the one that gives the best performance. It’s important to note that with any automated machine learning pipeline, logging the inputs and outputs of each step of the process is crucial to monitoring the overall health of the system. We log our results in <a href="https://www.splunk.com/">Splunk</a> and also post the outcome of the training process to a <a href="https://slack.com/">Slack</a> channel.</p><h3>Ongoing Work</h3><p>We are actively working to improve the flight delay model to include other types of delays. Late arriving aircraft delays and <a href="http://aspmhelp.faa.gov/index.php/Types_of_Delay#NAS_Delay">National Airspace System (NAS) delays</a> are two types of delays that we believe can have a big impact on the performance of our model. Combining the on time performance data with the <a href="https://flightaware.com/commercial/flightxml/v3/content.rvt">FlightAware API</a> is the approach we are pursuing to build separate models to predict these types of delays. Once built, we plan to ensemble them with the weather model with goal of not just predicting a delay magnitude, but also explaining the cause of the predicted delay.</p><p><strong>Interested in trying out the Delay Predictor?</strong> Check it out <a href="http://bit.ly/2Oapr2R">here</a> and let us know what you think!</p><p>If you’d like to learn more about Upside Corporate, click <a href="http://bit.ly/2N0tSJ9">here</a>! Even better, if you’d like to work with Ian &amp; join our team, visit our team page <a href="http://bit.ly/2xOhnut">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85413ca4939f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/upside-engineering/applying-predictive-analytics-to-flight-delays-85413ca4939f">Applying Predictive Analytics to Flight Delays</a> was originally published in <a href="https://medium.com/upside-engineering">Upside Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching Machines to Pick Flights for Business Travelers]]></title>
            <link>https://medium.com/upside-engineering/teaching-machines-to-pick-flights-for-business-travelers-f3f12e9464b0?source=rss-f1cab5d085d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f12e9464b0</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ian Cassidy]]></dc:creator>
            <pubDate>Wed, 21 Feb 2018 14:09:06 GMT</pubDate>
            <atom:updated>2018-02-21T14:27:00.175Z</atom:updated>
            <content:encoded><![CDATA[<p>Through personalized travel recommendations, <a href="https://upside.com/?utm_source=blog&amp;utm_medium=organic-social&amp;utm_campaign=Blog&amp;utm_content=IanMachine&amp;utm_promo=0">Upside</a>’s machine learning team makes it their primary mission to reduce customers’ cognitive load during the booking process. Simply put, we want to be able to predict the exact flight, hotel, and rental car that our customers ultimately choose from our site. Most online travel agencies (like Priceline or Kayak) initially present their inventory by lowest price. We’ve discovered that this approach is not ideal for business travelers, who have fundamentally different needs and constraints than leisure travelers, when it comes to things like flight duration, flight take off time, and number of layovers.</p><p>If anyone has been keeping up with the engineering blog updates written by our CTO Emily Dresner over the last few months, they’ll know that she likes to sprinkle little tidbits at the end of her posts like “the robots are taking over our product!” Here, I will reveal how we trained a supervised machine learning model to sort our flight inventory based on historical purchase data and how we plan to scale this framework to customer personalization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*rBgg--_uBju9YSdX." /></figure><h3><strong>In the Beginning…</strong></h3><p>When I first arrived at Upside a little over 5 months ago, the algorithm used to sort flights was designed with diversity of inventory in mind — showing customers a wide variety of potential options in the first 6 slots. For example, one slot would always show the cheapest flight and another would always show the flight with the shortest duration. One of the first questions I asked was, “how well is this model performing for our customers?” To answer that question, I took both a qualitative and quantitative approach. For the qualitative approach, I relied on running simulations of what our customers clicked on and how long they spent on each page during their visit to our website and app. At Upside, we do an amazing job of tracking these events and storing the information in our data warehouse, so creating these customer interaction simulations was fairly straightforward. Qualitatively, I found that customers seemed to be a bit confused by the initial sort, which frequently showed large market disparities (&gt;3 standard deviations in cost and time) and often reverted to applying filters around the number of stops or departure time. This makes complete sense, since business travelers need to arrive at their destination at a particular time and want to get there with the fewest number of layovers if economically feasible.</p><p>Building upon this qualitative knowledge, it was clear to me that we wanted to quantitatively measure the performance of this model (and all future models) in the context of <a href="https://en.wikipedia.org/wiki/Information_retrieval">information retrieval</a> (IR). One important measure used in many IR problems is called “top N recall” (or sometimes referred to as “recall rate @N”). Essentially, this measures the percentage of the time that our customers purchased a flight that appeared in the top N results (where N is any positive integer value). So, we can pose the flight sorting optimization problem as: “create a machine learning model that improves the top N recall as compared to the baseline sort.” For those of you who work on IR-type problems, what objective functions have you found to be predictive and performant?</p><h3><strong>Building the Model</strong></h3><p>When trying to build supervised machine learning algorithms for classification or regression problems, my first thought is usually “let’s throw <a href="https://en.wikipedia.org/wiki/Random_forest">random forest</a> and <a href="https://en.wikipedia.org/wiki/Gradient_boosting">gradient boosting</a> at this problem and see how they do.” However, getting to the model training step usually takes some work. The problem of sorting flights is no different because we have lots of information about the flights that our customers purchased and did not purchase, but this data is quite unstructured and messy. For many machine learning problems, there’s usually a reason why someone hasn’t done it already. In this case, it’s because the data required a lot of pre-processing to be useful. Don’t be discouraged — this is normal!</p><p>I’m not going to go into the nitty gritty details about our <a href="https://en.wikipedia.org/wiki/Feature_engineering">feature engineering</a> pipeline, <a href="https://en.wikipedia.org/wiki/Sampling_(statistics)">sampling techniques</a>, or <a href="https://en.wikipedia.org/wiki/Hyperparameter_optimization">hyperparameter tuning</a> methodologies since there are numerous blog posts and books written about those topics. Just know that many cycles were spent iterating through each of them. However, what I will say is that I spent a lot of time thinking about the features I can derive from our dataset that will best allow a machine to make predictions. For the flight sorting problem, the customer interaction simulations really helped me understand what was important to business travelers when they were selecting flights. Here is a non-exhaustive list of the features we are using in our flight sorting algorithm: price, trip duration, number of stops, departure time, arrival time, cabin class, aircraft code, day of the week, number of days until the trip, and time zone differences. Some of these features are continuous (like price and duration) while others (like cabin class and aircraft code) were converted to categorical variables.</p><p>One important step in machine learning pipelines that I think often gets overlooked is examining feature quality (sometimes this is referred to as <a href="https://en.wikipedia.org/wiki/Exploratory_data_analysis">exploratory data analysis</a>). Again, there are many ways to do this, but three techniques that I often use are <a href="https://github.com/pandas-profiling/pandas-profiling">Pandas Profiling</a> reports, measuring feature importance, and visualizing dimensionality reduction. For data scientists that prefer Python and <a href="http://jupyter.org/">Jupyter</a> Notebooks like me, Pandas Profiling is a great library that will quickly print out a report of a dataframe and do things like warn you if two or more columns are highly correlated (for you Spark folks, it’s been ported over <a href="https://github.com/julioasotodv/spark-df-profiling">here</a>). Next, I took our training data and ran it through an un-tuned random forest classifier to get the feature importance coefficients. For round trip flights, here are the top 10 features and their relative importance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*Wk3keZULkFV-yJEAGkZQhw.png" /></figure><p>In my opinion, looking at the feature importance is a really important sanity check in determining whether your data contains sufficient information for training a machine learning model. For business travelers, the feature importance list in the above table seems to be almost exactly in line with my qualitative observations from the customer interaction simulations, which is a really good sign.</p><p>The final step of my feature quality examination was to visualize the training data in two dimensions using <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">principal component analysis</a> (PCA). My co-worker Chris Poirier cleverly describes PCA in the following manner (I’m paraphrasing here): “Say I have this three-dimensional coffee mug. How can I orient this mug such that it’s two-dimensional projection onto a piece of paper will allow me to tell that it’s still a coffee mug?” So, I used <a href="http://scikit-learn.org/stable/">Scikit-Learn</a>’s built-in PCA function to reduce my training data to two dimensions and plotted the results below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*8rJJ9SHfX5w12TO8NaegnQ.png" /></figure><p>I know this scatterplot doesn’t quite look like a coffee mug, but look at all that signal! What I mean by this is that I can clearly draw a vertical line at the rightmost edge of the red dots that will allow me to separate the purchases from the non-purchases. From this analysis, it is clear that business travelers are buying similar types of flights — even though it’s difficult to interpret the information conveyed along the two principal components, since they consist of a linear combination of all the features — and that we should be able to train a model to predict the separation between the two classes. Without going into too much detail, the model we ultimately decided to go with in production is a popular gradient boosting library called <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a>.</p><h3>Champion vs. Challenger</h3><p>Once we had our trained machine learning model (i.e., the “challenger”), the next step was to deploy it in production and compare its performance against the existing model (i.e., the “champion”). At <a href="https://upside.com/?utm_source=blog&amp;utm_medium=organic-social&amp;utm_campaign=Blog&amp;utm_content=IanMachine&amp;utm_promo=0">Upside</a>, we use <a href="https://www.optimizely.com/">Optimizely</a> to run our A/B tests and use <a href="https://en.wikipedia.org/wiki/Conversion_marketing">conversion rate</a> as the primary metric to determine a winner. Our test took approximately two weeks to hit <a href="https://en.wikipedia.org/wiki/Statistical_significance">statistical significance</a>. At completion, we found that the machine learning model increased conversion rate from 4.65% to 5.67%, which is almost a 22% improvement!</p><p>Conversion rate is a great business KPI, but as I mentioned earlier, we are really interested in the top N recall metric. As such, we plotted the top N recall and compared our predicted values. To accomplish this, we used the validation portion of the training data by employing a simulation using the actual values measured from the live A/B experiment. The figure below shows that we improved top 10 recall from 22% to 38%, which is approximately a 73% improvement! It also shows that our predicted values were very close to the actual values for the challenger model. We believe the discrepancy in the champion performance was due to the fact that our flight inventory was significantly improved between the time when we trained the model and the completion of the A/B test. Simulations between the champion and challenger performance (i.e., the dotted lines) were crucial in making the decision to push our machine learning model to production and test it against the existing model in a live environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*mDHDdTA6Zfudi1TP1ESNdw.png" /></figure><h3><strong>Towards Personalization</strong></h3><p>A version of the machine learning model for sorting flights described in this post has been running in production on Upside’s website since late October. However, one drawback of this approach is that it is not personalized for each customer’s specific travel preferences. For example, if you only want to fly on early morning flights (say, before 7am), we should know that information and present those flights higher in the sort.</p><p>Our data science team is currently working on clustering our customers into multiple cohorts, which will allow us to define key purchase behaviors that uniquely define that group of customers. Using this cohort analysis, we can train a model that will sort flights for each cohort. We plan to start with 5–10 separate cohorts/models and slowly increase the number until we have a model for each customer — true personalization!</p><p>If this post piqued your interest, check out our open engineering positions and start working with <a href="https://www.linkedin.com/in/ian-cassidy-1a154450/">Ian</a> at Upside today: <a href="http://upsd.io/2okGoKb">http://upsd.io/2okGoKb</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f12e9464b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/upside-engineering/teaching-machines-to-pick-flights-for-business-travelers-f3f12e9464b0">Teaching Machines to Pick Flights for Business Travelers</a> was originally published in <a href="https://medium.com/upside-engineering">Upside Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>