<?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 Jay Franck on Medium]]></title>
        <description><![CDATA[Stories by Jay Franck on Medium]]></description>
        <link>https://medium.com/@franckjay?source=rss-92614a6b781d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*REvmRzTkhrzmbrOoiFvo0Q.jpeg</url>
            <title>Stories by Jay Franck on Medium</title>
            <link>https://medium.com/@franckjay?source=rss-92614a6b781d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:17:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@franckjay/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[Learning to Rank — Contextual Item Recommendations for User Pairs]]></title>
            <link>https://medium.com/data-science/learning-to-rank-contextual-item-recommendations-for-user-pairs-dc4f56e24d94?source=rss-92614a6b781d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc4f56e24d94</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ránking]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jay Franck]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 13:39:52 GMT</pubDate>
            <atom:updated>2024-03-28T17:03:52.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning to Rank — Contextual Item Recommendations for User Pairs</h3><h4>Train a Machine Learning recommendation engine that learns the shared preferences of groups of people</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JNeA3R4Re3X3lVe7" /><figcaption>Photo by <a href="https://unsplash.com/@ciabattespugnose?utm_source=medium&amp;utm_medium=referral">Lucrezia Carnelos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>This walkthrough is for…</h3><ol><li>Anyone interested in DIY recommendations</li><li>Engineers interested in basic PyTorch ranking models</li><li>Coffee nerds</li></ol><h3>This walkthrough is not for…</h3><ol><li>Someone who wants to copy-paste code into their production system</li><li>Folks that wanted a TensorFlow model</li></ol><h3>Motivation</h3><p>Imagine you are sitting on your couch, friends or family present. You have your preferred game console/streaming service/music app open, and each item is a glittering jewel of possibility, tailored for you. But those personalized results may be for the solo version of yourself, and do not reflect the version of yourself when surrounded by this particular mix of others.</p><p>This project truly started with coffee. I am enamored with roasting my own green coffee sourced from Sweet Maria’s (no affiliation), as it has such a variety of delicious possibilities. <a href="https://www.sweetmarias.com/colombia-honey-aponte-hugo-agreda-7759.html">Colombian</a>? <a href="https://www.sweetmarias.com/java-dry-process-kuningan-robusta-7286.html">Java-beans</a>? <a href="https://www.sweetmarias.com/kenya-kiambu-ngaita-peaberry-7241.html">Kenyan Peaberry</a>? Each description is more tantalizing than the last. It is so hard to choose even for myself as an individual. What happens if you are buying green coffee for your family or guests?</p><p>I wanted to create a Learning to Rank (LTR) model that could potentially solve this coffee conundrum. For this project, I began by building a simple <a href="https://www.tensorflow.org/ranking">TensorFlow Ranking</a> project to predict user-pair rankings of different coffees. I had some experience with TFR, and so it seemed like a natural fit.</p><p>However, I realized I had never made a ranking model from scratch before! I set about constructing a very hacky PyTorch ranking model to see if I could throw one together and learn something in the process. This is obviously not intended for a production system, and I made a lot of shortcuts along the way, but it has been an amazing pedagogical experience.</p><h3>Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DF-RFrg0EmJuGlPn" /><figcaption>Photo by <a href="https://unsplash.com/@pritesh557?utm_source=medium&amp;utm_medium=referral">Pritesh Sudra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Our supreme goal is the following:</p><ul><li>develop a ranking model that learns the pairwise preferences of users</li><li>apply this to predict the listwise ranking of `k` items</li></ul><p>What signal might lie in user and item feature combinations to produce a set of recommendations for that user pair?</p><p>To collect this data, I had to perform painful research of taste-testing amazing coffees with my wife. Each of us then rated them on a 10-point scale. The target value is simply the sum of our two scores (20 point maximum). The object of the model is to Learn to Rank coffees that we will both enjoy, and not just one member of any pair. The contextual data that we will be using is the following:</p><ul><li>ages of both users in the pair</li><li>user ids that will be turned into embeddings</li></ul><p>SweetMarias.com provides a lot of item data:</p><ul><li>the origin of the coffee</li><li>Processing and cultivation notes</li><li>tasting descriptions</li><li>professional grading scores (100 point scale)</li></ul><p>So for each training example, we will have the user data as the contextual information and each item’s feature set will be concatenated.</p><p>TensorFlow Ranking models are typically trained on data in <a href="https://www.tensorflow.org/ranking/tutorials/ranking_dnn_distributed#elwc_data_formats_for_ranking">ELWC </a>format: ExampleListWithContext. You can think of it like a dictionary with 2 keys: CONTEXT and EXAMPLES (list). Inside each EXAMPLE is a dictionary of features per item you wish to rank.</p><p>For example, let us assume that I was searching for a new coffee to try out, and some candidate pool was presented to me of k=10 coffee varietals. An ELWC would consist of the context/user information, as well as a list of 10 items, each with its own feature set.</p><p>As I was no longer using TensorFlow Ranking, I made my own hacky ranking/list building aspect of this project. I grabbed random samples of k items from which we have scores and added them to a list. I split the first coffees I tried into a training set, and later examples became a small validation set to evaluate the model.</p><h3>Feature Intuition</h3><p>In this toy example, we have a fairly rich dataset. Context-wise, we ostensibly know the users’ age and can learn their respective preference embeddings. Through subsequent layers inside the LTR, these contextual features can be compared and contrasted. Does one user in the pair like dark, fruity flavors, while the other enjoys invigorating citrus and fruity notes in their cup?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rexor5VxSR37KuC5" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=medium&amp;utm_medium=referral">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For the item features, we have a generous helping of rich, descriptive text of each coffee’s tasting notes, origin, etc. More on this later, but the general idea is that we can capture the meaning of these descriptions and match the descriptions with the context (user-pair) data. Finally, we have some numerical features like the product expert tasting score per item that (should) have some semblance to reality.</p><h3>Preprocessing</h3><p>A stunning shift is underway in text embeddings from when I was starting out in the ML industry. Long gone are the GLOVE and Word2Vec models that I used to use to try to capture some semantic meaning from a word or phrase. If you head on over to <a href="https://huggingface.co/blog/mteb">https://huggingface.co/blog/mteb</a>, you can easily compare what the latest and greatest embedding models are for a variety of purposes.</p><p>For the sake of simplicity and familiarity, we will be using <a href="https://huggingface.co/BAAI/bge-base-en-v1.5">https://huggingface.co/BAAI/bge-base-en-v1.5</a> embeddings to help us project our text features into something understandable by a LTR model. Specifically we will use this for the product descriptions and product names that Sweet Marias provides.</p><p>We will also need to convert all of our user- and item-id values into an embedding space. PyTorch handles this beautifully with the <a href="https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html">Embedding </a>Layers.</p><p>Finally we do some scaling on our float features with a simple <a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.RobustScaler.html">RobustScaler</a>. This can all happen inside our Torch Dataset class which then gets dumped into a DataLoader for training. The trick here is to separate out the different identifiers that will get past into the forward() call for PyTorch. This <a href="https://towardsdatascience.com/deep-learning-using-pytorch-for-tabular-data-c68017d8b480">article </a>by Offir Inbar really saved me some time by doing just that!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac78f9e98e7f54b65263585ec9bcc3ad/href">https://medium.com/media/ac78f9e98e7f54b65263585ec9bcc3ad/href</a></iframe><h3>Model Building and Training</h3><p>The only interesting thing about the Torch training was ensuring that the 2 user embeddings (one for each rater) and the k coffees in the list for training had the correct embeddings and dimensions to pass through our neural network. With a few tweaks, I was able to get something out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/340d679973d7b846d285febcfc9e3883/href">https://medium.com/media/340d679973d7b846d285febcfc9e3883/href</a></iframe><p>This forward pushes each training example into a single concatenated list with all of the features.</p><p>With so few data points (only 16 coffees were rated), it can be difficult to train a robust NN model. I often build a simple sklearn model side by side so that I can compare the results. Are we really learning anything?</p><p>Using the same data preparation techniques, I built a LogisticRegression multi-class classifier model, and then dumped out the .predict_proba() scores to be used as our rankings. What could our metrics say about the performance of these two models?</p><h3>Results</h3><p>For the metrics, I chose to track two:</p><ol><li>Top (`k=1`) accuracy</li><li><a href="https://en.wikipedia.org/wiki/Discounted_cumulative_gain#Normalized_DCG">NDCG</a></li></ol><p>The goal, of course, is to get the ranking correct for these coffees. NDCG will fit the bill nicely here. However, I suspected that the LogReg model might struggle with the ranking aspect, so I thought I might throw a simple accuracy in there as well. Sometimes you only want one really good cup of coffee and don’t need a ranking!</p><p>Without any significant investment in parameter tuning on my part, I achieved very similar results between the two models. SKLearn had slightly worse NDCG on the (tiny) validation set (0.9581 vs 0.950), but similar accuracy. I believe with some hyper-parameter tuning on both the PyTorch model and the LogReg model, the results could be very similar with so little data. But at least they broadly agree!</p><h3>Future Work</h3><p>I have a new batch of 16 pounds of coffee to start ranking to add to the model, and I deliberately added some lesser-known varietals to the mix. I hope to clean up the repo a bit and make it less of a hack-job. Also I need to add a prediction function for unseen coffees so that I can figure out what to buy next order!</p><p>One thing to note is that if you are building a recommender for production, it is often a good idea to use a real library built for ranking. TensorFlow Ranking, XGBoost, LambdaRank, etc. are accepted in the industry and have lots of the pain points ironed out.</p><p>Please check out the repo <a href="https://github.com/franckjay/UserPairRecommendationEngine">here</a> and let me know if you catch any bugs! I hope you are inspired to train your own User-Pair model for ranking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc4f56e24d94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/learning-to-rank-contextual-item-recommendations-for-user-pairs-dc4f56e24d94">Learning to Rank — Contextual Item Recommendations for User Pairs</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[Embarrassingly Shallow Autoencoders (EASE) for Recommendations]]></title>
            <link>https://medium.com/data-science/embarrassingly-shallow-autoencoders-ease-for-recommendations-f91117f02851?source=rss-92614a6b781d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91117f02851</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jay Franck]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 19:57:53 GMT</pubDate>
            <atom:updated>2021-01-04T19:57:53.540Z</atom:updated>
            <content:encoded><![CDATA[<h4>Recommendations without the Ruffles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l-kBIwAuL_McbiQ6" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Recommendations without the Ruffles</strong></p><h4>Post Summary</h4><ol><li>Learn about a new(<em>ish</em>) State-of-the-Art recommender engine, EASE</li><li>See its total 5 lines of code in action, step by step</li><li>Understand the intuition behind why it works</li><li>Discover some side benefits of its use (speed, diversity, …)</li><li>Check out the full implementation in my PyTorch <a href="https://github.com/franckjay/TorchEASE">repo</a></li></ol><p><strong>Background</strong></p><p>I always enjoy learning about Recommendation Systems that are both simple and effective. Too often I hear stories about complex engines that have so many moving parts, and/or are incredibly expensive to train, which then fail when in a production environment. Two authors that I consistently see on the Leaderboards of PapersWithCode.com are <a href="https://paperswithcode.com/sota/collaborative-filtering-on-movielens-1m">Steffen Rendle</a> (Google) and <a href="https://paperswithcode.com/sota/collaborative-filtering-on-million-song">Harald Steck</a> (Netflix). The amazing thing about their research?</p><ol><li>Simple models that are easily understood</li><li>Implementation is quick</li><li>Requires only user + item interactions as features</li><li>Both have SOTA performance</li></ol><p>I am often guilty of jumping on the bandwagon of complexity when seeing a new deep learning architecture. It can be fun and exciting to exist on the “cutting edge” of whatever domain you are interested in, adding layer upon layer of complexity. Do these actually produce the best results, though?</p><p>If you read my <a href="https://towardsdatascience.com/build-a-react-flask-app-that-suggests-novel-novels-with-a-python-graph-9491e714bbdf">Graph-based recommender</a> article, you may have noticed I referenced a great paper by <a href="https://arxiv.org/abs/1907.06902">Dacrema et al</a>. (2019). In many domains/datasets, the best algorithms can be simple approaches:</p><ol><li>Matrix factorization</li><li>Popularity-based</li><li>Item or user similarity</li></ol><p>Let’s embrace Occam’s Razor and stick to algorithms that produce great results without all of the rest of the fluff. This is where EASE comes into play. It is essentially an item-item similarity model, but with the provision that we enforce an item to not be similar to itself. This makes the model more generalized and can produce results that are both interesting and diverse.</p><p><strong>Example</strong></p><p>I found out about EASE while browsing through <a href="http://paperswithcode.com/">PapersWithCode.com</a> . It is the best algorithm by a far margin on the Million Song Database, as well as in the Top 5 for a number of other datasets. The <a href="https://github.com/Darel13712/ease_rec">implementation </a>was written in Numpy, and while it worked pretty well, I wanted to speed it up a bit with PyTorch. So I refactored it while attempting to learn how it worked, and you, dear reader, can follow me on this journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*ojxOIrSla2dWvKEnWIAiOQ.png" /></figure><p>Let’s make a dummy example to see how this all works before we try to run it on a real dataset. We can make a few users + item (ratings optional) pairs and store them in a DataFrame. For each user and item, we will use an integer token to identify it. This will be our <strong><em>X </em></strong>matrix.</p><p>Now, we could store this as a Dense PyTorch Tensor, but it probably will be very sparse in a real world application. Instead, we are going to keep it as a sparse tensor until we need it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8559b8dc7686c5aca4d60c091c7ef567/href">https://medium.com/media/8559b8dc7686c5aca4d60c091c7ef567/href</a></iframe><p>From here, we need to build our <strong><em>B </em></strong>matrix, which is our item to item weight matrix that will be the source of our predictions:</p><p>P(user, item) = X[user]*B[item]</p><p><strong>Steps</strong></p><p>The <a href="https://arxiv.org/pdf/1905.03375.pdf">EASE paper</a> explains all of the steps needed to form this closed-form solution, but here are the basics:</p><ol><li>Build the Gram matrix: G = X.t() * X</li><li>Add in a regularization value (<em>lambda</em>) along the diagonal of G</li><li>P = G.inverse()</li><li>B = -P/diagonals(P)</li><li>Set diagonals of B to 0</li></ol><p>Personally, I think it is easier to see these steps when trying to understand what they are doing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87edc8382fe61746b82848a6fc032ae8/href">https://medium.com/media/87edc8382fe61746b82848a6fc032ae8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c47753456947c25fd828af10cbc99c4/href">https://medium.com/media/5c47753456947c25fd828af10cbc99c4/href</a></iframe><p><em>Step 1</em></p><p><em>Step 2</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2fc5414be3b717b19eb26ba3a483684/href">https://medium.com/media/c2fc5414be3b717b19eb26ba3a483684/href</a></iframe><p><em>Step 3</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38a67ebb04ded711b612754a683b1d57/href">https://medium.com/media/38a67ebb04ded711b612754a683b1d57/href</a></iframe><p><em>Steps 4 , 5</em></p><p>This is our weight matrix! Now we just multiply any vector that contains all of the interactions for a given user by <strong><em>B, </em></strong>and the output will be a scored list of predictions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5edd6beab59b323d5b2b4dc09144d6f/href">https://medium.com/media/c5edd6beab59b323d5b2b4dc09144d6f/href</a></iframe><p>These predictions should make some intuitive sense. High scores are assigned to items the user has already interacted with. The 4th item has not been interacted with, and has the next largest score. We should recommend it! We can recommend a block of users by multiplying our entire X matrix by B (<em>sparse.to_dense()@B</em>) to get the entire set of predictions.</p><p><strong>Intuition</strong></p><p>I think of the matrix multiplication step like this:</p><ol><li>As a user, you have interacted with some items</li><li>For each of those items, there are a number of similar items that are stored in the columns of <strong><em>B</em></strong></li><li>Each returned item recommendation is based on how similar it is to other items that you have already interacted with</li><li>The best way to visualize these Matrix Multiplications might be with <a href="http://matrixmultiplication.xyz/">http://matrixmultiplication.xyz/</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sbaUpPfAxUhUBer6" /><figcaption>Photo by <a href="https://unsplash.com/@michael_marais?utm_source=medium&amp;utm_medium=referral">Michael Marais</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here I am using the term <em>similar </em>in a broad way: <em>The Matrix</em> and <em>Wall-E</em> may not be similar in genre, tone, etc., but it is possible that these two items are generally both watched by similar users, a weighted co-occurrence. If you liked <em>Wall-E, </em>other items watched by <em>Wall-E</em> watchers might be relevant to you as well. Possibly.</p><p>Now, we can go through our predicted scores, select the TopK items for each user, and then return those item names. Simple! We did not even have to use gradient descent or chain rule once.</p><p>What other reasons might we use an approach like EASE, apart from how simple it is to get SOTA results? The paper’s author makes the case:</p><ol><li>A single hyper-parameter to tune (<em>lambda</em>), which seemed to have a marginal impact on diversity or performance</li><li>Trains in minutes for most academic datasets, compared to hours/days</li><li>Recommends more uncommon, unique items</li></ol><p>For me, I personally enjoy being recommended something rare and interesting that I would enjoy, rather than something popular that I was probably aware of already. The novelty and joy of discovery of something wonderful is uniquely satisfying.</p><p>For those of you that may be asking “Why is this an autoencoder? Where is the dense layer here?” That’s why this is a shallow AE! There is no need for a dense layer to compress the user vector. Rather, we store the weights of <strong><em>B </em></strong>for the output layer.</p><p>Then why is this <em>Embarrassing</em>? I think the only embarrassment here is the fact that such a simple set of transformations remains so powerful as to be SOTA, while complex neural nets and ensembles lag behind.</p><p><strong>Ratings</strong></p><p>EASE can also handle explicit user feedback as well (e.g., five star ratings) to make predictions. I have not fully tested that part of the code, but it should work in theory! More work to be done.</p><p><strong>Metrics</strong></p><p>Typically for these types of systems, I like to use HitRate@K as my metric of choice. It’s simple to understand (p<em>redicted [“1984”, “Attack Surface”, “Guards! Guards!”] with actual [“1984”] being a Hit</em>). Plus, it aligns nicely with most business use cases.</p><p>As a test case, I grabbed the GoodReads dataset, filtered books in English, and trained EASE (<em>lambda = 250.0</em>) on 5 million book ratings. I then made 20 predictions for 100k users and compared the results: HitRate@20 of 9.1%! Not too bad. If I just predicted the most popular books on the GoodReads data, I would have only gotten 6%, so a definite improvement along with some personalization. The entire pipeline took less than a minute to run!</p><p><strong>Conclusion</strong></p><p>I would encourage you all to check out my repo <a href="https://github.com/franckjay/TorchEASE">here</a>, as well as the original Numpy version <a href="https://github.com/Darel13712/ease_rec">here</a>. The <a href="https://arxiv.org/pdf/1905.03375v1.pdf">paper </a>itself is worthy of a read, as it is short and to the point. <a href="https://towardsdatascience.com/building-my-own-2021-book-recommendation-engine-903ea10d5021">Tuan </a>also just posted an article on other simple recommendation systems that you might want to check out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91117f02851" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/embarrassingly-shallow-autoencoders-ease-for-recommendations-f91117f02851">Embarrassingly Shallow Autoencoders (EASE) for Recommendations</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[Build a React + Flask App that Suggests Novel Novels with a Python Graph]]></title>
            <link>https://medium.com/data-science/build-a-react-flask-app-that-suggests-novel-novels-with-a-python-graph-9491e714bbdf?source=rss-92614a6b781d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9491e714bbdf</guid>
            <category><![CDATA[books]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jay Franck]]></dc:creator>
            <pubDate>Tue, 12 Nov 2019 18:10:30 GMT</pubDate>
            <atom:updated>2019-11-12T18:10:30.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mKBURb0rWo076BhA" /><figcaption>Photo by <a href="https://unsplash.com/@kqpho?utm_source=medium&amp;utm_medium=referral">Kourosh Qaffari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Project Summary</strong>:</p><ul><li>Build a Graph database of Users and the Books they read</li><li>Develop a Flask App that serves up rare, interesting Books to Users based on their submitted favorites</li><li>Implement a React App that integrates with Flask + our Graph to showcase to users their next favorite book</li></ul><p>There are a lot of great resources for learning Data Science techniques out there: MOOCS, blogs, tutorials, and bootcamps are all avenues for learning. Personally, I learn best by working on projects that I find interesting and engaging. Nothing motivates me more to push my level of understanding to new heights than by working on an intriguing problem. How do I identify new avenues that I can explore? Generally by reading other people’s work!</p><p>The idea for this project was first realized by reading Vicki Boykis’ great <a href="https://vicki.substack.com/p/big-recsys-redux-recs-at-netflix">blog</a> post about the changing nature of <em>Netflix</em>’s recommendation engine. In short (sorry for the hack job, Vicki), gone are the days of minimizing the RMSE of a user’s rating preferences with Matrix Factorization or Deep Learning. Recommendations are still partly an art form, with context, nuance, and design all playing a large part in providing a great experience to the user. In addition, the business value of a recommendation is not simply to provide the best content to the user. In the case of <em>Netflix</em>, it may be to provide the best <em>Netflix</em> content to the user.</p><p>I had the great pleasure of attending <a href="https://recsys.acm.org/recsys19/">RecSys 2019</a> in Copenhagen this year. The winner for <a href="https://arxiv.org/abs/1907.06902">Best Paper</a> was one that was <em>not</em> a State of the Art neural network approach. Instead, it was a careful examination of previous, open source recommendation systems, public datasets, and their actual performance in a head-to-head matchup. The results, you may ask? Simple models (Graph based, User/Item Nearest Neighbors, Top Popular items) nearly always outperform the best deep neural networks.</p><p>It is safe to say I have been rethinking Recommender Systems in light of these revelations. What do I, as a user, want from <em>YouTube</em>’s recommendation engine? What about a Search Engine like <a href="http://ecosia.org/">Ecosia</a>/DuckDuckGo? In the former example, I might want to see videos that entertain/inform me in that moment. In the latter example, I want to find the most relevant information, quickly, without worrying about conflicts of interest. In either case, the returned items may not be the most popular, highly rated, or controversial. Advertisers sometimes find virality to be profitable, but I may not be a fan.</p><p>So what do I truly want? How can I build a system that optimizes for this elusive, <em>unprofitable </em>goal? There was a landmark moment of clarity in my mind as I was walked to the library the other day: I absolutely love when I find a new author or book that I had not considered or heard of. The sheer discovery, novelty of that moment can inspire weeks of happiness as I flip through the pages.</p><p>Time spent reading a book is an investment, and so it can be a difficult proposition to try out anything new (explore vs. exploit). A system that just recommends random items may provide unexpected results, but they may not be good ones. I want to have my cake and eat it, too. I want to find great books that I would never have considered before.</p><p>This idea is simple:</p><ul><li>People who read and like the same books as I may have roughly similar tastes to me</li><li>These same neighbors probably have read multiple books, some of which I have not read</li><li>Some of these unread books may be so obscure/unpopular, that I would be unlikely to discover them on my own</li></ul><p>None of the above statements should be that surprising to you, particularly the first two points. The last point, of course, is the most fundamental to this work. What if I built a Graph database of books, authors, and readers, and then walked along the nodes of the graph to find these hidden gems of books?</p><p>The site GoodReads has published a dataset of 10,000 books, 50,000+ users, and nearly 6 million ratings (1–5 Stars) of books. Surely I could find something interesting in this treasure trove! I have never built a real graph before in my life, so I thought this would be a great trial by fire. Nodes and Edges, how hard could it be? The Nodes of this Graph are the Users, Books, and Authors:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec46ec702417c5efc8fc8eee8026ab2/href">https://medium.com/media/bec46ec702417c5efc8fc8eee8026ab2/href</a></iframe><p>The Edges are the ratings associated with each (User, Book, Author, rating) tuple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20b67292aaae40853215329f31999e40/href">https://medium.com/media/20b67292aaae40853215329f31999e40/href</a></iframe><p>I first created 4 Classes to account for my Graph components. Each Node will also have a List associated with it: Users will have a shelf of Books, Authors will have their bibliography, and Books will have their audience. The Graph will connect all of these objects together into a cohesive unit that can be traversed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdbc5e42c0db7b8dddf4c2c424c49c0f/href">https://medium.com/media/fdbc5e42c0db7b8dddf4c2c424c49c0f/href</a></iframe><p>The above block of code is pretty chunky, and there are a number of methods inside that are not going to be explored here. We will focus on one that can be directly used with an easy, consumer facing React App API: _book2book. So let’s say that we can now walk around our Graph, and everything compiles fine. How might we find meaningful Books to present to a User? In our mind, let us take a hypothetical walk:</p><ol><li>You, as a User , love a Book by an Author (e.g., a five star rating)</li><li>This Author has many fans, and she has written similar Books you may also love. These are not <em>novel </em>Novels, as you may be aware of them already.</li><li>This Author has many fans, some of whom may be similar to you</li><li>One of these Users, selected randomly, will have a shelf of favorite Books</li><li>Select the least popular, five star rated Book from this shelf</li><li>Either present this to the User, or head back to Step 1 and keep walking through the Graph</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*OD6tX0sf_4d5Rm0ngLG5VA.png" /><figcaption>Simplistic example of our graph</figcaption></figure><p>Now we just have to return this Book to our User as a possible great discovery! We are missing the key ingredient to this project, though. We need the App to deliver these interesting Books. Let’s start with the part that is still Python based, for familiarity: we need to build the back end of our App that handles API requests, and so, of course, we are going to use <a href="https://franckjay.github.io/blog/2019/11/02/%22https://palletsprojects.com/p/flask/%22">Flask</a>. Flask allows us to make a small web server in Python, and it is pretty easy to use. I found two tutorials to be extremely useful, and they were nicely linked to one another: a Flask <a href="https://franckjay.github.io/blog/2019/11/02/%22https://www.youtube.com/watch?v=Urx8Kj00zsI&amp;t=421s%22">tutorial</a>, and a <a href="https://franckjay.github.io/blog/2019/11/02/%22https://www.youtube.com/watch?v=06pWsB_hoD4&amp;t=233s%22">React App</a> that calls the aforementioned Flask app.</p><p>So we first make a new directory that we will call api/. Inside this folder, we will have two python files. __init__.py will build up the basics of our Flask app, import the necessary variables, etc.:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8810c76c17d4bfe1d2782989891492f1/href">https://medium.com/media/8810c76c17d4bfe1d2782989891492f1/href</a></iframe><p>and then an app.py (or whatever you want to call it):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c315e65055f671628e2380b243ac696d/href">https://medium.com/media/c315e65055f671628e2380b243ac696d/href</a></iframe><p>Inside the app.py, we are doing a number of important things. First, we call our python code that builds our graph database for finding new books. It also sets up the Blueprint of our backend, so when we make API calls to this service, we are pointing in the correct direction. Let’s unpack these things at a very basic level:</p><ul><li>Our app name is initialized to be @main, but we could have other stuff here as well</li><li>We are hosting two .routes in our @main app: /input_book and /novel_novel</li><li>You can think of these as separate pages on our Web app, and they both handle different behaviors</li><li>The HTTP methods of GET and POST, which get something from our backend or post something to it (good terminology!)</li></ul><p>For the /input_book call, what we are doing is receiving a raw text input from the User on the webpage, packaging it as a JSON that looks like {&quot;book&quot;: &quot;book_title&quot;}, and then updating the back end server. In this case, we are using this initial book to find a similar, rare book the User may enjoy. We call out Graph with this input, and set a global python variable to the image URL of the output book.</p><p>Now you can imagine that the WebApp would make a 2nd API call to the Flask App, saying “What is the output of that input?”. This is our GET call in /novel_novel, which returns a JSON as well. This probably sounds pretty reasonable to most of you right now, and it did to me as well. You may have even used Flask before. But have you ever built a React App before?</p><p><a href="https://reactjs.org/">React</a> is a Facebook sponsored open source JavaScript library for making UIs easier to code up. It still took me a bit of time to learn some JavaScript basics, understand the syntax for React, and try to get everything to look decent. The two important resources that I used are <a href="https://franckjay.github.io/blog/2019/11/02/%22https://www.youtube.com/watch?v=06pWsB_hoD4&amp;t=233s%22">this previously mentioned YouTube</a> and <a href="https://towardsdatascience.com/create-a-complete-machine-learning-web-application-using-react-and-flask-859340bddb33">this</a> TowardsDataScience article. The video guide utilizes a second React library, semantic-ui-react, that makes App building even easier, and so I mostly followed their advice. And honestly, you should too. The basics of installing the necessary tools, building the boilerplate App.js file, and explanation of writing functions are better left to the JavaScript professionals.</p><p>I will go into a little detail about the actual React components I hacked together to integrate with our Graph, though. The main function here is the App.js file, so we will unpack that first. We import our necessary libraries, initiate App(), and then return some HTML/JavaScript-like entities (Divisions, Containers, Images, etc.):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/921492637a0267a49681156efcdd0a93/href">https://medium.com/media/921492637a0267a49681156efcdd0a93/href</a></iframe><p>You will notice inside the Container we have two components: &lt;BookEntry/&gt; and &lt;GrabBook/&gt;. These correspond to our two API calls in our Flask app which POST a title that our Graph understands, and then does a GET call to grab our interesting new novel for the user. Let us look at the more complicated component first, the BookEntry:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42b49e4ff19136770db21e17842dd54a/href">https://medium.com/media/42b49e4ff19136770db21e17842dd54a/href</a></iframe><p>We import a few extra packages from semantic-ui-react in this component: { Form, Input, Button }. We want the user to type text input into a Form corresponding to the title of the book they love, and then hit a submit Button. First, we initialize a few variables (const [title, setTitle]) and set the default value = useState(&#39;&#39;); , an empty string.</p><p>Next, we build the &lt;Form.Field&gt;, and we add in a placeholder value that provides instructions to the user on what to do. Once the user has entered some text, we set the useState of title to that of the entered text. Easy!</p><p>Next, we add a new &lt;Form.Field&gt; in the shape of a Button that the user can click on right underneath the text input. On the click of the button (&lt;Button onClick= ...), we make our first call to our API via the await fetch(&quot;/input_book&quot; call. Recall that in our Flask app, our Blueprint has @main.route(&#39;/input_book&#39;, so this call hits our backend at this contact point. The returned value of this POST call is just a response that says everything went OK if and only if we find the title in our Graph. Otherwise we return a 400 and ask the user to submit a new title. It is possible that our database does not have the title, or maybe it is spelled differently, etc., so we do not want our App to break in these cases.</p><p>Prior to moving on to the next component, I would encourage anyone trying to build one of these web apps to use console.log() calls all over the place in your code. Not only do they serve a double purpose as a comment, they can be so helpful in debugging your code. Recall that you just right click on any webpage in Chrome, Inspect, and then open up the console tab and you can see everything that is going on.</p><p>So, let’s assume that everything went perfectly and we have found the relevant title. Now we actually have to return a new book for the user in our GrabBook component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1a723605573d9add82c85fd86955ec0/href">https://medium.com/media/e1a723605573d9add82c85fd86955ec0/href</a></iframe><p>Here we make another API call to the POST endpoint via a fetch(&quot;/novel_novel&quot;). Remember that we are returning a JSON object that looks like {&quot;image_url&quot;: &quot;http://image_of_book.png&quot;}. We then pass this into an &lt;Image&gt; block that renders the image and returns it to our App. Cool!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*3EgdIAaV-XF5E8lFZHAXMw.png" /><figcaption>The input was Neuromancer by William Gibson. The output is a great book!</figcaption></figure><p>To be fair, the page does not look great. If you are a React expert, please let me know how I can make the layout look better:</p><ul><li>After submitting a request, it requires a refresh of the page to display the correct image.</li><li>I would also prefer if the background image covered the entire page, and the form fields were in the foreground of it.</li></ul><p><strong>This work is not intended to be a commercialized, production ready system.</strong> It is meant to be a learning adventure that is fun to use and thought provoking in its scope. Here is a link to the <a href="https://github.com/franckjay/GoodReadsGraph">repo</a> if you are interested in checking it out.</p><p>Thank you for stopping by! Feel free to comment below and ask for books. I personally have checked out 10+ recommendations from the Graph, and I was nearly always surprised by the results. I was glad I investigated the suggestions, and although some were not my cup of tea, others are wonderful discoveries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9491e714bbdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/build-a-react-flask-app-that-suggests-novel-novels-with-a-python-graph-9491e714bbdf">Build a React + Flask App that Suggests Novel Novels with a Python Graph</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[Bayesian Modeling of Pro Overwatch Matches with PyMC3]]></title>
            <link>https://medium.com/data-science/bayesian-modeling-of-pro-overwatch-matches-with-pymc3-f1b7d5fc22f1?source=rss-92614a6b781d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b7d5fc22f1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[esport]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[overwatch]]></category>
            <dc:creator><![CDATA[Jay Franck]]></dc:creator>
            <pubDate>Sun, 17 Mar 2019 23:30:52 GMT</pubDate>
            <atom:updated>2019-03-17T23:30:52.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tP89Ae1du7CFCbuF" /><figcaption>Photo by <a href="https://unsplash.com/@acfromspace?utm_source=medium&amp;utm_medium=referral">AC De Leon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Professional eSports are becoming increasingly popular, and the industry is growing <a href="https://www.forbes.com/sites/mattperez/2018/02/21/report-esports-to-grow-substantially-and-near-a-billion-dollar-revenues-in-2018/#35be63c02b01">rapidly</a>. Many of these professional game leagues are based on games that have two teams that battle it out. <em>Call of Duty</em>, <em>League of Legends</em>, and <em>Overwatch</em> are all examples. Although these are comparable to traditional team sports, the novelty of eSports means that less attention has been paid to predicting the outcomes of this burgeoning industry.</p><p>How do you model adversarial team games? I was first inspired to start this project by reading Christopher Bishop’s new machine learning <a href="http://mbmlbook.com/TrueSkill_Inferring_the_players_skills.html">eBook</a>, which has a chapter devoted to calculating player rankings in games using the <a href="https://en.wikipedia.org/wiki/Arpad_Elo">Elo</a> rating system. For those of you familiar with Chess, you may have encountered this metric before. I found a very instructive blog post on <a href="http://dataskeptic.com/blog/methods/2017/calculating-an-elo-rating">The Data Skeptic</a> for this exact topic. All equations posted below were borrowed from the aforementioned <a href="http://dataskeptic.com/">Skeptic</a>.</p><p>In essence, Elo is a framework where the strength of a player is measured by a single number (r_1 = 2000). The predicted strength of any given team is represented by a Logistic Function (<em>R</em>), and the outcome of a given match as a ratio of the strength of a single team over the sum of their rating (<em>E</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*tlnsNcM-ORHZaDisN6ATDA.png" /><figcaption>Logistic Function for player i.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*XVgRl8E4q69sfSqW6LmBig.png" /><figcaption>Expected Outcome for player i</figcaption></figure><p>If a player of strength 2000 is to face off against a player with an Elo rating of 1000, we would predict a very likely win for the former player (<em>E=0.9968</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*g19Eh6c0s_KH4DBNl8RJaA.png" /><figcaption>Rating update for player i (K~32 in Chess)</figcaption></figure><p>At the end of each match, the players’ scores are updated based on their relative strengths. If the favored player wins (S_i = 1.0), they gain a small positive adjustment in their score. If the underdog wins the match, they can gain a larger amount, as the result was unexpected. In the given example of the underdog winning, their score would change from 1000 to 1031. The favored player’s score would also decrease.</p><p>What does this have to do with <a href="https://playoverwatch.com/en-us/">Overwatch</a>, the immensely popular team-based shooter? I wondered how someone could model the incredible complexity of a team-based sport that is so dynamic without resorting to incredibly convoluted architectures? I saw an example code on the PyMC3 website about encoding professional rugby teams using <a href="https://docs.pymc.io/notebooks/rugby_analytics.html">Hierarchical Normal Distributions</a>. Having just done a blog post on <a href="https://towardsdatascience.com/hierarchical-bayesian-modeling-for-ford-gobike-ridership-with-pymc3-part-ii-23f84fb4a5e7">Hierarchical models</a>, I thought I could try something similar!</p><p>Essentially, we are treating each team as a single entity. This is in spite of the fact that teams consist of multiple players, each working autonomously. We will justify this choice in two ways: 1) It is easier to model a team as a single rating, rather than each individual player, 2) the teammates are working together (ideally), so they can be modeled as a collective unit. The Elo rating is also incredibly helpful if two teams have not played against one another before. Without any historical matchups, we can leverage team matches that the two adversaries had in common to make predictions.</p><p><a href="https://overwatchleague.com/en-us/schedule">Data</a> were scraped from the 2018 season of The Overwatch League. Unfortunately, there are not that many matches from which we can train our model. <em>As the 2019 season is currently ongoing, any interested reader could begin to add this data to the model and see how well it performs! </em>The raw data format had to be cleaned and processed prior to training our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*zBo10wG4u9bQumICFWgJMA.png" /><figcaption>Win/Loss aggregations for the regular season</figcaption></figure><p>There are two basic ways we can represent our data, which will change how we construct the model. The simplest approach is to make this a classification challenge. Each Overwatch matchup involves multiple rounds, and the winner of the match secures the most winning rounds. For instance, <em>San Francisco Shock</em> beats <em>Florida Mayhem</em> 3–2 . We can represent this as a total of 5 records in the data with varying levels of success and failure (0/1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*KXsE53t54wtJzQOFrz3eUA.png" /><figcaption>Classification or Bernoulli trial for this simple example</figcaption></figure><p>We can construct our data split as follows. For each matchup in the regular season, we model each win and loss as a binary target. Each team’s Elo rating will be inferred based on the equations listed above, which transform a rating into a Bernoulli trial. Then, we will use our learned ratings to predict all of the matches in the playoffs. Our PyMC3 model will then consist of a Binomial: for a given matchup, do we predict a success or a failure?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*wK0XVusKfu-q-03YpO6FGg.png" /><figcaption>A sample trace of our simple model.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*-dd34M_O9V3uTo9-yTYKow.png" /></figure><p>We can also represent our matchups as fractions. For the same example of a 3–2 match, with <em>San Francisco Shock</em> winning, we can encode this as a 0.6 win. Now we have slightly more flexibility, as we can model this as a regression task, or still keep it as a classification. This result offers the model more nuance as well. A 0.8 win is a much more favorable outcome than a 0.6 versus the same opponent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*7FCSh8LxAxsMlUk1ovgFJw.png" /><figcaption>The ROC suggests the model is decent at predicting matchups</figcaption></figure><p>Regardless of your choice, the training error seems to be pretty stable. Our model is able to predict which teams will win based on their Elo distributions. What will happen when we apply this model to the Playoffs?</p><p>We are making a few assumptions during our playoffs evaluation:</p><ol><li>Teams at the end of the regular season are fixed in skill, players, strategy, etc.</li><li>That the playoffs are substantive enough that less probable events cannot dominate the results (small number of samples)</li><li>That our regular season matchups were fairly distributed among all teams (round-robin)</li></ol><p>These assumptions will definitely rear their ugly head. There are only 12 playoff matches in 2018, and eliminations come quickly. This means that if a team had a fairly poor match that is un-characteristic of their true skill, they may not have a chance to redeem themselves. Teams also can gain in strength when a true challenge appears, as is the nature of playoffs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*DavGWhZX1v8846fo2YjyPA.png" /></figure><p>When we apply our model to the playoff data, we get very poor performance. Our model might as well be randomly guessing! What happened here?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*6ouLS2pVt1NGsvO-qf_tNA.png" /><figcaption>Playoff Record and the predictions</figcaption></figure><p>In the simplest terms, we had a few teams that upset the apple cart. <em>Philly Fusion</em> (Team 9) beat both <em>Boston</em> and <em>New York</em> (winning 4/5 matches) , despite having a lower Elo rating. <em>Fusion </em>then lost to <em>London Spitfire</em>, who ended up winning the tournament, despite being lower ranked than <em>LA Valiant</em>. Go figure! This is why people love to watch sports, as you never know who might win.</p><p>If you are itching to try a few different Bayesian methods to games like this, Allen Downey’s book <a href="http://www.greenteapress.com/thinkbayes/thinkbayes.pdf">Think Bayes</a> has a section on modelling teams via Poisson processes and their historical scoring record. Recently Tuan posted an <a href="https://towardsdatascience.com/making-big-bucks-with-a-data-driven-sports-betting-strategy-6c21a6869171">article </a>on Towards Data Science on building a betting strategy for professional soccer leagues, which I think would also apply here.</p><p>Feel free to download the data and my notebooks via my Kaggle <a href="https://www.kaggle.com/franckjay/overwatch-elo-ratings-pymc3">repo</a>. I also have a Git <a href="https://github.com/franckjay/BayesianOverwatchElo">repo </a>with some selected notebooks. Leave a comment or a question below and I will do my best to answer it. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b7d5fc22f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/bayesian-modeling-of-pro-overwatch-matches-with-pymc3-f1b7d5fc22f1">Bayesian Modeling of Pro Overwatch Matches with PyMC3</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[Hierarchical Bayesian Modeling for Ford GoBike Ridership with PyMC3 — Part II]]></title>
            <link>https://medium.com/data-science/hierarchical-bayesian-modeling-for-ford-gobike-ridership-with-pymc3-part-ii-23f84fb4a5e7?source=rss-92614a6b781d------2</link>
            <guid isPermaLink="false">https://medium.com/p/23f84fb4a5e7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jay Franck]]></dc:creator>
            <pubDate>Mon, 28 Jan 2019 01:38:19 GMT</pubDate>
            <atom:updated>2019-01-28T01:38:19.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hierarchical Bayesian Modeling for Ford GoBike Ridership with PyMC3 — Part II</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fPqk4Pr-C_nk5WHX" /><figcaption>Photo by <a href="https://unsplash.com/@momhasapples?utm_source=medium&amp;utm_medium=referral">sabina fratila</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the <a href="https://towardsdatascience.com/bayesian-modeling-for-ford-gobike-ridership-with-pymc3-part-i-b905104af0df">first part</a> of this series, we explored the basics of using a Bayesian-based machine learning model framework, <a href="https://docs.pymc.io/">PyMC3</a>, to construct a simple Linear Regression model on Ford GoBike data. In this example problem, we aimed to forecast the number of riders that would use the bike share tomorrow based on the previous day’s aggregated attributes. That trivial example wass merely the canvas on which we showcased our <em>Bayesian Brushstrokes</em>.</p><p>To summarize our previous attempt: we built a multi-dimensional linear model on the data, and we were able to understand the distribution of the weights. This is in contrast to the standard linear regression model, where we instead receive point value attributes. These distributions can be very powerful! How certain is your model that <em>feature i</em> drives your target variable? With probabilistic programming, that is packaged inside your model. We matched our model results with those from the familiar <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html">sklearn Linear Regression</a> model and found parity based on the RMSE metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*EzdqhNkWwZbZEfC0kbk2dw.png" /><figcaption>Some fairly strong correlations in our data.</figcaption></figure><p>Truthfully, would I spend an order of magnitude more time and effort on a model that achieved the same results? Even with slightly better understanding of the model outputs? Probably not in most cases. I want understanding <em>and</em> results. We can achieve this with Bayesian inference models, and PyMC3 is well suited to deliver.</p><p>One of the features that PyMC3 is so adept at is customizable models. My prior knowledge about the problem can be incorporated into the solution. The measurement uncertainty can be estimated. I can account for numerous biases, non-linear effects, various probability distributions, and the list goes on. <em>With packages like </em><a href="https://pypi.org/project/sklearn/"><em>sklearn </em></a><em>or </em><a href="https://spark.apache.org/docs/latest/ml-guide.html"><em>Spark MLLib</em></a><em>, we as machine learning enthusiasts are given hammers, and all of our problems look like nails. </em>With PyMC3, I have a 3D printer that can design a perfect tool for the job.</p><p>One of the simplest, most illustrative methods that you can learn from PyMC3 is a hierarchical model. Many problems have structure. On different days of the week (seasons, years, …) people have different behaviors. Climate patterns are different. If we were designing a simple ML model with a standard approach, we could one hot encode these features. Our model would then learn those weights. We could also build multiple models for each version of the problem we are looking at (e.g., Winter vs. Summer models).</p><p>The fact is, we are throwing away some information here. Individual models can share some underlying, latent features. In a hierarchical Bayesian model, we can learn both the coarse details of a model <em>and </em>the fine-tuned parameters that are of a specific context. Our Ford GoBike problem is a great example of this. If we plot all of the data for the scaled number of riders of the previous day (X) and look at the number of riders the following day (<em>nextDay</em>), we see what looks to be multiple linear relationships with different slopes. In the last post, we effectively drew a line through the bulk of the data, which minimized the RMSE. Sure, we had a pretty good model, but it certainly looks like we are missing some crucial information here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*FpOnVGokM2DuPq74d1ebRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*70zYUOTSPHGK5UXpOx1m0A.png" /></figure><p>If we plot the data for only Saturdays, we see that the distribution is much more constrained. Real data is messy of course, and there is scatter about the linear relationship. Compare this to the distribution above, however, and there is a stark contrast between the two. So what to do? We could simply build linear models for every day of the week, but this seems tedious for many problems. I would guess that although Saturday and Sunday may have different slopes, they do share some similarities. A clever model might be able to glean some usefulness from their shared relationship.</p><p>Let us build a simple hierarchical model, with a single observation dimension: yesterday’s number of riders. Our target variable will remain the number of riders that are predicted for today. We start with two very wide Normal distributions, <em>day_alpha </em>and <em>day_beta</em>. Think of these as our coarsely tuned parameters, model intercepts and slopes, guesses we are not wholly certain of, but could share some mutual information. <em>From these broad distributions, we will estimate our fine tuned, day of the week parameters of </em>alpha <em>and </em>beta. This where the hierarchy comes into play: <em>day_alpha </em>will have some distribution of positive slopes, but each day will be slightly different. The slope for Mondays (<em>alpha[0]</em>) will be a Normal distribution <em>drawn</em> from the Normal distribution of <em>day_alpha </em>. Wednesday (<em>alpha[1]</em>) will share some characteristics of Monday, and so will therefore by influenced by <em>day_alpha</em>, but will also be unique in other ways. This is the magic of the hierarchical model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*8CaqhzGD4YI4_gqs8-EUgg.png" /></figure><p>Once we have instantiated our model and trained it with the NUTS sampler, we can examine the distribution of model parameters that were found to be most suitable for our problem (called the <em>trace)</em>. We can see that our <em>day_alpha (</em>hierarchical intercept) and <em>day_beta </em>(hierarchical slope) both are quite broadly shaped and centered around ~8.5 and~0.8, respectively. Moving down to the <em>alpha </em>and <em>beta </em>parameters for each individual day, they are uniquely distributed within the posterior distribution of the hierarchical parameters. Some slopes (<em>beta</em> parameters) have values of 0.45, while on high demand days, the slope is 1.16!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*dK_n_BVBYCEy6gRHmAePpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*0q6R4kDpdKudfoMuK4MXgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*NSvkkq6bDjs7vk0V3ZvVsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*HUnLPBeaB_L3rMkPaIvZhA.png" /></figure><p>Furthermore, each day’s parameters look fairly well established. We can see this because the distribution is very centrally peaked (left hand side plots) and essentially looks like a horizontal line across the last few thousand records (right side plots).</p><p>We can see the trace distributions numerically as well. The hierarchical alpha and beta values have the largest standard deviation, by far. Each individual day is fairly well constrained in comparison, with a low variance.</p><p>As in the last model, we can test our predictions via RMSE. On the training set, we have a measly +/- 600 rider error. In <a href="https://towardsdatascience.com/bayesian-modeling-for-ford-gobike-ridership-with-pymc3-part-i-b905104af0df">Part I</a> of our story, our 6 dimensional model had a training error of 1200 bikers!</p><p>Our unseen (forecasted) data is also much better than in our previous model. The sklearn LR and PyMC3 models had an RMSE of around 1400. This simple, 1 feature model is a factor of 2 more powerful than our previous version.</p><p>We could even make this more sophisticated. What if, for each of our 6 features in our previous model, we had a hierarchical posterior distribution we were drawing from? We could add layers upon layers of hierarchy, nesting seasonality data, weather data and more into our model as we saw fit.</p><p>In PyMC3, you are given so much flexibility in how you build your models. It absolutely takes more time than using a pre-packaged approach, but the benefits in understanding the underlying data, the uncertainty in the model, and the minimization of the errors can outweigh the cost.</p><p>As always, feel free to check out the Kaggle and Github repos. Please add comments or questions below! Thank you for reading.</p><p><a href="https://www.kaggle.com/franckjay/hierarchical-mvp">Hierarchical_MVP | Kaggle</a></p><p><a href="https://github.com/franckjay/HierarchicalFordGoBike">Github Repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23f84fb4a5e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/hierarchical-bayesian-modeling-for-ford-gobike-ridership-with-pymc3-part-ii-23f84fb4a5e7">Hierarchical Bayesian Modeling for Ford GoBike Ridership with PyMC3 — Part II</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[Bayesian Modeling for Ford GoBike Ridership with PyMC3 — Part I]]></title>
            <link>https://medium.com/data-science/bayesian-modeling-for-ford-gobike-ridership-with-pymc3-part-i-b905104af0df?source=rss-92614a6b781d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b905104af0df</guid>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <category><![CDATA[pymc3]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <dc:creator><![CDATA[Jay Franck]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 20:05:42 GMT</pubDate>
            <atom:updated>2019-01-14T18:09:28.107Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bayesian Modeling for Ford GoBike Ridership with PyMC3 — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LCfpAVS6B_byxfBk" /><figcaption>Photo by <a href="https://unsplash.com/@andrew_gook?utm_source=medium&amp;utm_medium=referral">Andrew Gook</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bike shares are a large part of the transport equation for cities around the world. In San Francisco, one of the major players in the bike share game is Ford with its GoBike program. Conveniently, they kindly release their <a href="https://www.fordgobike.com/system-data">data </a>for people like me to study. I wonder if it is possible to easily forecast the ridership of the next day in order to ensure enough bikes are available to riders, based on past information?</p><p>This would be a fairly trivial task to complete if I were to use sklearn to build a Linear Regression model. Often I find myself looking for data sets to learn a new tool or skill in Machine Learning. I have been trying to find an excuse to try one of the probabilistic programming packages (like <a href="https://pystan.readthedocs.io/en/latest/">PyStan </a>or <a href="https://docs.pymc.io/">PyMC3)</a> for years now, and this bike share data seemed like a great fit.</p><p>A number of companies are looking towards Bayesian inference for their internal predictive models. As computational cost goes down, the notoriously long training time for these systems decreases. Notably Uber released <a href="https://eng.uber.com/pyro/">Pyro</a>, an open source framework that can appears to be fairly flexible and easy to use. <a href="https://www.quantopian.com/">Quantopian </a>is a frequent user of PyMC3. Booz Allen Hamilton and GoDaddy are two other firms that I am aware of that are pursuing these types of ML models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*7q5pWiG7tEme4nhHUGUlCw.png" /></figure><p>In this post I have constructed a simple example that I hope will be instructive to a PyMC3 beginner. I downloaded GoBike data from 2017 — September 2018. I then aggregated the data on a day-by-day basis to assemble information about the ridership details (e.g., mean age, subscription membership), the length of their rides, and the number of total riders.</p><p>The issue with these Bayesian ML tools is that they can take a long time to train, especially on massive data. For this aggregated dataset, I have only 100s of rows, which is easily trainable on a laptop. After a little research, I settled on learning PyMC3 as my package of choice. It seems like it has a number of great tutorials, a vibrant community, and a fairly easy to use framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*c_lhnK3Fb-hMG8uExxskAQ.png" /></figure><p>I begin this illustrative example by scaling the data with a RobustScaler and plotting the seaborn correlation heatmap to see if there are any patterns our model could learn. We are attempting to predict the value of <em>nextDay. </em>From the heatmap, we can see some simple relationships between variables, <br>both positive (<em>scaled_total_riders</em>) and negative (<em>scaled_duration_hrs</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*MlFTZofLXD6VJxy9o4-yDg.png" /></figure><p>Let us make a naive prediction and use that as a baseline. What would the RMSE be if we just took the average number of daily riders and used that as our prediction? We would expect to be off by approximately 1900 riders per day by taking this easy approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*RT53i9Pu28aA2DfTjZPduQ.png" /></figure><p>A linear model with sklearn performs slightly better in RMSE, and is quite easy to implement. The model is a series of weights for each variable in our data, in addition to an intercept. How do we interpret the confidence our model has in each of those individual parameters?</p><p>This can be where the Bayesian magic really shines. It undoubtedly takes more lines of code, more thought, and longer training time than the sklearn example above. I promise you, dear reader, that it can all be worth it.</p><p>First, PyMC3 runs on Theano under the hood. We have to make some slight changes to our pandas/numpy data, and the most major change is by setting a shared tensor, as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*s7KQjVVD4VAt5cybutvZ3g.png" /><figcaption>When we look to make predictions for our model, we can swap out X_train for X_test and use the same variable name.</figcaption></figure><p>Now that we have our data set up, we need to build our model, which we initialize by calling pm.Model() . Inside of this model context, we need to build our complete set of assumption about our priors (parameters) and output. Normal (Gaussian) distributions are fairly safe bets for your first model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*ikAtCgEHM2Zm0BoZb0ugaw.png" /></figure><p>This constitutes our model specification. Now we have to learn what the posterior distribution of our model weights could be. Unlike sklearn, the coefficients are now a distribution of values, not a single point. We sample a range of possible weights, and the coefficients that appear to fit our data well are retained in something called a <em>trace</em>. The sampling functions (NUTS, Metropolis, <em>et al.</em>) are well beyond the scope of this post, but there are vast <a href="https://docs.pymc.io/api/inference.html#module-pymc3.sampling">repositories of knowledge</a> describing them. Here we build our trace from our model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*S3E_glAKJNVLamf3jBY9pQ.png" /></figure><p>The NUTS sampler complains that using find_MAP() is not a good idea, but frequently this is used in <a href="https://people.duke.edu/~ccc14/sta-663/PyMC3.html">tutorials</a>, and did not seem to hurt my performance.</p><p>We can also try a different sampler that tries to approximate the posterior distributions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*D8zll3b3SqU1J6x3yCKoBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*d0O80khcKbanp7iv5mGe1g.png" /></figure><p>The trace can be plotted, and generally looks like this. The <em>beta </em>parameters look fairly constrained in distribution (left plots) and seem to be reasonably consistent across the last 1000 sampled items in our trace (right plot). The <em>alpha </em>parameter looks less certain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*oQWRUchwm29A86suJAEhrw.png" /></figure><p>Now that we have our posterior samples, we can make some predictions. We generally observe a so-called ‘burn in’ period in PyMC3 where we discard the first thousand samples of our trace (<em>trace[1000:]</em>), as these values may not have converged. We than draw 1000 sample weights from this trace, calculate what the predictions might be, and take the mean of that value as our most probable prediction for that data point. From here, we simply calculate the RMSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*pICUOHkmLCYGZ-atHEE99w.png" /></figure><p>If we want to test on our holdout dataset :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*Ubv63-iWMdX79WMb_9V14w.png" /></figure><p>So this model that we built performs better than our naive approach (average ridership) but slightly worse than our sklearn model. In an included example in the Github repo, I was able to build a similar model that beat the sklearn model by scaling the Y value, and modeling it as a Normally distributed variable.</p><p>Further tuning of the model parameters, using different scalings, assuming a wider range of possible beta parameters can all be employed to lower the RMSE of this example. The goal of this post is to introduce the basics of model building and provide an editable example that you can play around with and learn from! I encourage you to provide feedback in the comments section below.</p><p>To recap, there is a price to pay for Bayesian models. It certainly takes longer to implement and write a model. It requires some background knowledge on Bayesian statistics. The training time is orders of magnitude longer than using sklearn. However, tools like PyMC3 can offer greater control, understanding, and appreciation for your data and the model artifacts.</p><p>Although there are a number of good tutorials in PyMC3 (including its <a href="https://docs.pymc.io/notebooks/getting_started.html">documentation page</a>) the best resource I found was a <a href="https://www.youtube.com/watch?v=rZvro4-nFIk">video </a>by Nicole Carlson. It explores how a sklearn-familiar data scientist would build a PyMC3 model. Careful readers will find numerous examples that I adopted from that video. I also learned a lot from <a href="https://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Prologue/Prologue.ipynb">Probabilistic Programming and Bayesian Methods for Hackers</a>, which is a free notebook based tutorial on practical Bayesian models using PyMC3. These two resources are absolutely amazing. Duke also has an example website that has numerous data <a href="https://people.duke.edu/~ccc14/sta-663/PyMC3.html">situations </a>that I found informative. Towards Data Science has also hosted a number of cool posts throughout the year that focused on <a href="https://towardsdatascience.com/search?q=Bayesian">Bayesian analysis</a> and have helped inspire this post.</p><p>In the next blog post, I will illustrate how to build a Hierarchical Linear Model (HLM) that will greatly improve the performance of our initial approach. Below are a Kaggle kernel that you can fork and a Github repo that you can clone to play around with the data and develop your own PyMC3 models with. Thank you for reading!</p><p><a href="https://www.kaggle.com/franckjay/daybydaypredictions">DayByDayPredictions | Kaggle</a></p><p><a href="https://github.com/franckjay/FordGoBike">Github Repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b905104af0df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/bayesian-modeling-for-ford-gobike-ridership-with-pymc3-part-i-b905104af0df">Bayesian Modeling for Ford GoBike Ridership with PyMC3 — Part I</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[Brewing a Batch of Machine Learning with TPOT]]></title>
            <link>https://medium.com/data-science/brewing-a-batch-of-machine-learning-with-tpot-2930c376b884?source=rss-92614a6b781d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2930c376b884</guid>
            <category><![CDATA[solar-energy]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Jay Franck]]></dc:creator>
            <pubDate>Mon, 16 Jul 2018 15:32:23 GMT</pubDate>
            <atom:updated>2018-07-16T15:32:23.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXGbl5gpAearD1ShGiOb2g.png" /></figure><p>When approaching a new dataset, I often think about the best tools to visualize, analyze, and build models in an iterative fashion. Perhaps it is difficult for me to comprehend some aspect of the data. I might investigate some Kaggle kernels devoted to visualization on a similar problem set in order to glean some new ideas. I may also ask some friends and colleagues for advice. I continue to try new approaches to find a sufficient solution.</p><p>If my model pipeline is not producing the desired result, there are a large number of feature selection, scaling, and algorithmic choices I might make. Some of these choices are based on experience, while others are intuitive. However, most of the time I end up doing a lot of work trying out a series of different models and hyperparameters, feature engineering, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*XF3akvvCtNu3u2745BPBLQ.jpeg" /></figure><p>In recent years, tools like <a href="http://h2o.ai/">h2o.ai</a> and <a href="https://www.automl.org/">AutoML</a> have become increasingly popular by automating some of these more tedious tasks. While I occasionally enjoy trying out different model architectures for pedagogical purposes, there are other instances in which I want to automate some of these choices. While these tools are impressive, I recently became aware of an open source project that delivers a nearly full pipeline of machine learning directly into your hands: <a href="http://epistasislab.github.io/tpot/">TPOT</a>.</p><p>TPOT uses an evolutionary framework for optimizing hyperparameters, selecting features, and even selecting the algorithm for you. Conveniently, it utilizes the <a href="http://scikit-learn.org/">sklearn</a> algorithms, which are familiar and usable by nearly all practicing Data Scientists. At first glance, TPOT looked almost too powerful to believe, so I knew I had to try it out.</p><p>In addition, I have recently become quite enamored with evolutionary systems and their <a href="https://blog.openai.com/evolution-strategies/">continued success</a> in Machine Learning. This <a href="http://blog.otoro.net/2017/10/29/visual-evolution-strategies/">blog post</a> inspired me to even build my own <a href="https://www.linkedin.com/pulse/evolutionary-amoebas-playing-space-invaders-deep-learning-franck/">evolutionary algorithm</a> that plays Space Invaders. Towards Data Science has a few really <a href="https://towardsdatascience.com/learning-about-algorithms-that-learn-to-learn-9022f2fa3dd5">good articles</a> as well. Once I heard about TPOT’s use of ES, I was further inspired to wade into a trial project.</p><p>As I mentioned earlier, usually I have a task at hand and I choose a set of tools for the job. In this post, I am breaking the mold: TPOT is my one and only tool, and I will collect a dataset to test it on! I wanted something relatively simple, composed of open data, and that I was passionate about. An auxiliary goal was for the data to be small enough that anyone could load it on a laptop or use on Kaggle (which is where I ended up storing the <a href="https://www.kaggle.com/franckjay/openpv-solar-data-with-opendatagov-zipcodes">dataset</a> if you are interested).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rqj5jfk1aLkgyUIw5WvCdA.jpeg" /></figure><p>I am incredibly excited about renewable energy and the environment. In a previous blog <a href="https://www.linkedin.com/pulse/san-francisco-energy-efficiency-community-focused-data-jay-franck/">post</a> I used open data from San Francisco on building energy efficiency within the city to characterize trends in that data. For this exercise, I thought I would leverage a <a href="https://openpv.nrel.gov/">dataset </a>from the National Renewable Energy Labs (NREL) on solar energy at a zip code level. I joined this data with zip code information from <a href="https://catalog.data.gov/dataset/zip-code-data">catalog.data.gov/dataset/zip-code-data</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*McIzFVls5EKVFt_62C48Gw.png" /></figure><p>I quickly looked for a important feature to be designated for my target variable in this dataset. I settled on letting TPOT determine the best model to predict the <em>cost_per_watt </em>of solar installations. There are a few main reasons why:</p><ul><li>As a society, we need to transition quickly from fossil fuels to carbon neutral-based energies.</li><li>Unfortunately, this is not happening quick enough, despite the incredible cost (human suffering, environmental, et al. ) that <em>is</em> linked to climate change.</li><li>Fortunately, costs in renewable sources are on the <a href="https://www.vox.com/energy-and-environment/2018/7/13/17551878/natural-gas-markets-renewable-energy">decline</a>. Action only seems to occur in the US when a monetary gain is attached to that action.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RXcWNA12DYtuKgCjvrJHMg.png" /><figcaption>Median cost_per_watt at the state level</figcaption></figure><p>If I (or rather TPOT) can effectively learn some driving features in the data that can predict low <em>cost_per_watt </em>in some regions, maybe this result can be further explored in other areas of the country.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yc5A3nvnQjC8k7HGdsXFxg.png" /></figure><p>Intentionally I did very little lifting for TPOT<strong>. </strong>My experiment is attempting to ascertain the out-of-the-box effectiveness of the system. The algorithm claims to handle nearly every piece in the data science pipeline. I wrote a quick <a href="https://www.kaggle.com/franckjay/kernel1dea72c27c">Kaggle Kernel</a> that loads the data, joins it, drops some NaNs, and unleashes the fury of TPOT. What might we expect? From the TPOT <a href="http://epistasislab.github.io/tpot/using/#what-to-expect-from-automl-software">Docs</a>:</p><ol><li>For the default TPOT parameters, 100 ‘gene samples’ will be run for 100 generations on your dataset, each one consisting of various algorithms and hyperparameters</li><li>Each sample (10,000 unique ones, in this case) will be given a 10-fold cross-validation procedure. You can even use a custom loss-function if you prefer!</li><li>If a best-pipeline has been found, the CV score and the pipeline parameters will be outputted.</li></ol><p>The API call could not be simpler, and looks much like any ML algorithm you have used in Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*g8dX-clA81Dj0Q-T-X_Bzw.png" /><figcaption>Pretty simple!</figcaption></figure><p>I would definitely suggest running this on multiple CPUs (<em>n_jobs=-1</em>) and heading off to make lunch, because this may take a long time. On the Free Kaggle machines, I kept the generations and population size small, and still needed to reduce my feature space to only 5–10 relevant features. The documentation for TPOT warns users that it may take full days to achieve a converged model! At the end of the session, I received an output like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyJkNPpgtojEp-TAWz3Zug.png" /><figcaption>Best negative Mean Squared Error: -0.137</figcaption></figure><p>Now I could go to <em>sklearn</em>, do a little feature engineering, and then use the relatively simple ExtraTreesRegressor to build this model. The above model used a sampling of features solely from the OpenPV dataset. A later test, using only zip code data, did not perform nearly as well.</p><p>However, the goal of this post was not to dive deeper into this particular data problem, and so we will not discuss it further. This should all be about TPOT! The overall conclusion is that TPOT deserves further exploration. On the positive side:</p><ul><li>It is dangerously easy to use. It integrates with your normal, everyday Python data workflow. An absolute beginner could load it up and use it.</li><li>It explores polynomial features, lots of hyperparameters, and algorithms in various combinations.</li><li>Once the pipeline has decided on a model, you can construct it in <em>sklearn </em>later without using TPOT ever again.</li><li>The documentation was written in a straightforward manner.</li><li>You can supply custom loss functions easily.</li></ul><p>The only real negative I found was the speed and memory issues I encountered using a Kaggle kernel. Is that really an issue, though? On a more adequately equipped data science platform, TPOT could really shine.</p><p>Over the last few years, I have heard the foretelling doom of the data science career as AutoML becomes more powerful. There are some compelling counter-arguments that have not gained as much attention. What is one chunk of a data scientist’s workflow that is not included in the TPOT pipeline? <em>Data Cleaning. </em>In my daily work, this single item can consume 80% of my time and mental energy.</p><p>What about formulating the right question? In a Kaggle-like competition, with the problem set and data prepared nicely for data scientists, this gets little thought. When working in a business environment, simply asking the right question is a sizable component of what makes a successfully project. What are you optimizing for? What does the business need? How can you make this explainable to decision makers? TPOT does not help with this.</p><p>TPOT, and AutoML in general, will make data scientists more efficient. Computation is cheap, but our time is precious. Use these tools to enhance your workflow, and spend your time asking the right questions, cleaning/analyzing the data effectively, and communicating your results. Grid searching hyperparameters is not an effective use of your time. I will certainly use TPOT again, and I hope that you will try it out as well. If you enjoyed this article, please check out some of my other posts! I appreciate your readership.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2930c376b884" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/brewing-a-batch-of-machine-learning-with-tpot-2930c376b884">Brewing a Batch of Machine Learning with TPOT</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>