<?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 Xiaoyou Wang on Medium]]></title>
        <description><![CDATA[Stories by Xiaoyou Wang on Medium]]></description>
        <link>https://medium.com/@xiaoyou.wang?source=rss-e79cfb810635------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gt0eKfFAAxZRKDTS76Js6g.jpeg</url>
            <title>Stories by Xiaoyou Wang on Medium</title>
            <link>https://medium.com/@xiaoyou.wang?source=rss-e79cfb810635------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:45:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xiaoyou.wang/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[End-to-end machine learning lifecycle]]></title>
            <link>https://m.mage.ai/end-to-end-machine-learning-lifecycle-d69f75fd67fa?source=rss-e79cfb810635------2</link>
            <guid isPermaLink="false">https://medium.com/p/d69f75fd67fa</guid>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[lifecycle]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Xiaoyou Wang]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 22:11:12 GMT</pubDate>
            <atom:updated>2021-11-02T23:19:46.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KrxpevoVVrkdbT_P0Xw69Q.jpeg" /></figure><h3>TLDR</h3><p>A machine learning (ML) project requires collaboration across multiple roles in a business. We’ll introduce the high level steps of what the end-to-end ML lifecycle looks like and how different roles can collaborate to complete the ML project.</p><h3>Outline</h3><ul><li>Introduction</li><li>Define problem</li><li>Collect data</li><li>Prepare data</li><li>Train, evaluate, and improve model</li><li>Deploy and integrate model</li><li>Monitor model</li><li>Conclusion</li></ul><h3>Introduction</h3><p>Machine learning is a powerful tool to help solve different problems in your business. The article “<a href="https://www.mage.ai/blog/building-your-first-machine-learning-model">Building your first machine learning model</a>” gives you basic ideas of what it takes to build a machine learning model. In this article, we’ll talk about what the end-to-end machine learning project lifecycle looks like in a real business. The chart below shows the high level steps from project initiation to completion. Completing a ML project requires collaboration across multiple roles, including product manager, product developer, data scientist, and MLOps engineer. Failing to accurately execute on any one of these steps will result in misleading insights or models with no practical value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RFitKJduU1v_fE9a" /></figure><h3>Define problem</h3><p>When talking about machine learning, people usually have high expectations on what it can achieve. Before starting a machine learning project, the product team should collaborate to come up with the problem definition. Here are some questions that should be clarified at this step:</p><p><strong>What’s the problem?</strong></p><p>Machine learning can be used to solve various problems (e.g. reduce manual work, rank products, etc). Before starting the project, we need to clearly define the problem and expected outcome. We should think about whether this is a valuable problem to solve and estimate how much value machine learning can bring.</p><p><strong>How should we measure the success of the model?</strong></p><p>There are different objectives when using machine learning. We should be clear how to measure the success of the model based on different objectives. If we want to use a machine learning model to reduce manual work, we should measure whether the model can give results as well as a human does. If we want to use machine learning to rank products on a website, we can measure whether we get a higher <a href="https://en.wikipedia.org/wiki/Click-through_rate">click-through rate</a> after using the model to rank the products.</p><p><strong>Do we have enough data to build the model?</strong></p><p>Now that we have the idea, we need to think about one practical thing: do we have the data? The machine learning model learns from the past data and predicts for the new data. If you don’t have enough data, machine learning won’t be a good choice for you.</p><h3>Collect data</h3><p>No matter what model we want to build, we first need to collect two types of data. The first type of data contains the labels (the target variable we want to predict) or can be used to create the labels. The second type of data can be used to generate features that’ll affect the model predictions. For example, if we want to build a model to predict whether a user will churn. We at least need to get a table which contains data indicating whether the user has churned. In addition, we also want to collect user events to generate more features which can contribute to the model predictions.</p><p><strong>Product developers</strong> are usually responsible for collecting the data after getting data requirements from data scientists. If you have a good habit of logging the events, then you’ll be relieved when building machine learning models. If you don’t have good logging in your product, start doing it. This data will help you understand your product better even if you don’t have immediate needs for machine learning models. Next, the work can be handed over to <strong>data scientists</strong> to prepare the data and train the model.</p><h3>Prepare data</h3><p>Data preparation is one of the most complex steps in the machine learning lifecycle, which is also called “Feature Engineering”. If you don’t have data processing experience and want to learn it, this <a href="https://www.mage.ai/blog/tags/development">Developer Education</a> series will be a good resource for you. Here are the basic steps of feature engineering:</p><p><strong>Create labels</strong></p><p>In machine learning, “label” is the target variable you want to predict with the model. To prepare the data for model training, we need to identify whether we have a label column in our dataset. If there’s no explicit label column in our datasets, we need to create labels first.</p><p><strong>Create features</strong></p><p>Machine learning algorithms learn from the features. Here are some ways to create features:</p><ul><li>Expand the existing features. For example, you can expand your date feature to “year”, “month”, “day”, and “days since holiday” features.</li><li>Aggregate the events feature. One example is to count the number of user events over the past 7 days, 30 days, or 90 days. Another example is to count the number of page view events from Google and Facebook respectively.</li></ul><p><strong>Impute, encode and scale</strong></p><p>After creating labels and features, we need to get our data ready for machine learning algorithms.</p><ul><li>Impute: The real-world datasets usually have missing values. Machine learning algorithms don’t handle missing values well. Thus, we need to fill in the missing value with data inferred from existing data.</li><li>Encode: Machine learning algorithms require data to be numbers. Thus, we need to convert the text features to numbers.</li><li>Scale: Numbers with larger ranges will have a higher impact on the model output. We need to adjust the values of number columns to fall within similar ranges so that large numbers (such as seconds since epoch) don’t affect the prediction disproportionately as much as smaller values (such as age).</li></ul><h3>Train, evaluate, and improve model</h3><p>After data is prepared, we split the dataset into a training set and a test set, select an algorithm, and then start training the model with the training set. We briefly introduced some machine learning algorithms in the <a href="https://m.mage.ai/roadmap-to-ai-ml-sorcerer-supreme-2fc4bdbe89bf">Fundamentals of being an AI/ML sorcerer supreme</a> article. We’ll discuss different algorithms in detail in a future blog article.</p><p>After model training completes, we need to evaluate the model’s performance with the test set. We use <a href="https://www.mage.ai/blog/definitive-guide-to-accuracy-precision-recall-for-product-developers">Precision and Recall</a> to evaluate a classification model’s performance, and use <a href="https://www.mage.ai/blog/product-developers-guide-to-ml-regression-model-metrics">Mean Absolute Error and Root Mean Squared Error</a> to evaluate a regression model’s performance.</p><p>The article “<a href="https://www.mage.ai/blog/how-to-improve-the-performance-of-a-machine-learning-(ML)-model">How to improve the performance of a machine learning (ML) model</a>” introduced the strategies for improving models, including comparing multiple algorithms, hyperparameter tuning, and more feature engineering.</p><h3>Deploy and integrate model</h3><p>Once you’re done with the model training and are satisfied with the model performance, the <strong>data scientist</strong> can now hand over the model to the <strong>MLOps engineer </strong>to deploy the model to production. Then the <strong>product developer</strong> will integrate the model into the product.</p><p>There are generally two ways to integrate models and make predictions: online predictions and offline batch predictions.</p><p><strong>Online prediction</strong></p><p>For online prediction, we can deploy the model to an online web service and make API calls to the online service to get predictions. This is useful when we need to get real-time predictions, e.g. realtime product ranking.</p><p><strong>Offline batch prediction</strong></p><p>For other models, we don’t necessarily need to get real-time predictions. We can use an offline batch prediction job to get predictions for a large amount of data points on a regular basis. These predictions are then stored in a database and can be made available to developers or end users. For example, for the demand forecast model, we can estimate the demand for products on a daily basis for upcoming one year with an offline batch prediction job.</p><p><strong>Experimentation</strong></p><p>After integrating the model into production, you can run an experiment to evaluate the model performance with real production traffic. For example, if you build a ranking model for your e-commerce website. You can split the website traffic into 50/50. Half of the users will see the products in the original order (control group). Another half of the users will see products in the ranked order determined by the ranking model (treatment group). We can compare the target metrics (e.g. click-through rate) between the users in the control and the treatment groups.</p><h3>Monitor model</h3><p>Congratulations! With the team’s hard work, your model is finally live! You evaluated the model via experimentation and got the expected outcome. Is this everything you need to do for the model? The answer is no. Model performance can degrade over time. It’s important to set up a good monitoring system to make sure the model works correctly in production over time.</p><p>Multiple things could go wrong in production. One of the most common issues is data drift, which means the distribution of the target variable or the input data changes over time. The model- monitoring system should monitor the model performance with production data, detect the data drift issue, and provide feedback for further model improvement (e.g. model retrain). Stay tuned for a future article about model monitoring.</p><h3>Conclusion</h3><p>The whole machine learning lifecycle is a lengthy process, which requires expertise across multiple roles.</p><ul><li>The product team defines the problem.</li><li>The product developer collects the data.</li><li>The data scientist prepares the data and trains the model.</li><li>The MLOps engineer deploys the model into production.</li><li>The product developer integrates the model into the product.</li><li>The MLOps engineer sets up the model monitoring system.</li></ul><p>If you wonder whether there’s a way to simplify the process, <a href="https://www.mage.ai/">Mage</a> helps handle all the work from “prepare data” to “monitor model”. Mage also provides suggestions on what type of problems you can solve with ML and what data is needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d69f75fd67fa" width="1" height="1" alt=""><hr><p><a href="https://m.mage.ai/end-to-end-machine-learning-lifecycle-d69f75fd67fa">End-to-end machine learning lifecycle</a> was originally published in <a href="https://m.mage.ai/">Mage AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to improve the performance of a machine learning (ML) model]]></title>
            <link>https://m.mage.ai/how-to-improve-the-performance-of-a-machine-learning-ml-model-409b05b2a5f?source=rss-e79cfb810635------2</link>
            <guid isPermaLink="false">https://medium.com/p/409b05b2a5f</guid>
            <category><![CDATA[shap-values]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[model-tuning]]></category>
            <category><![CDATA[product-developer]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Xiaoyou Wang]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 16:13:35 GMT</pubDate>
            <atom:updated>2021-09-16T18:44:20.947Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3Saax9lLZJf0iA9gCqa3g.png" /></figure><h3>TLDR</h3><p>Without good performance, machine learning (ML) models won’t provide much value in real life. We’ll introduce some common strategies to improve model performance including selecting the best algorithm, tuning model settings, and adding new features (aka feature engineering).</p><h3>Outline</h3><ul><li>Introduction</li><li>Is the model good or bad?</li><li>Strategies for improving the model</li><li>When to stop improving the model</li><li>Conclusion</li></ul><h3>Introduction</h3><p>With the right developer education (e.g. <a href="https://www.mage.ai/blog/building-your-first-machine-learning-model">Building your first machine learning model</a>), it’s easy to start training machine learning models. However, it’s difficult to get great results on the first try that meets your product goals. After training the model, it can take a long time to tune the model and improve performance (we’ll use tuning model and improving model performance interchangeably in this article). Different types of models have different tuning strategies. In this article, we’ll introduce common strategies for model tuning.</p><h3>Is the model good or bad?</h3><p>Before tuning the model, we first need to know whether the model performance is good or bad. If you don’t know how to measure a model’s performance, you can check our previous blog articles: <a href="https://www.mage.ai/blog/definitive-guide-to-accuracy-precision-recall-for-product-developers">The definitive guide to Accuracy, Precision, and Recall for product developers</a> and <a href="https://www.mage.ai/blog/product-developers-guide-to-ml-regression-model-metrics">A product developer’s guide to ML regression model metrics</a>.</p><p>Each model has baseline metrics. As introduced in our previous <a href="https://www.mage.ai/blog/definitive-guide-to-accuracy-precision-recall-for-product-developers">article</a>, we can use “mode category” as the baseline metric for classification models. If your model’s performance is better than the baseline metric, then congratulations, your model isn’t bad and you’re off to a good start. If the model’s performance metrics are worse than the baseline metrics, it means the model doesn’t find valuable insights from the data. Then, there’ll be a lot to do in order to improve the performance.</p><p>Another scenario is when the model performs “too good”, e.g. 99% precision and 99% recall. This isn’t a good sign and probably indicates some issues in your model. The possible reason is “data leakage”. We’ll talk about how to solve this problem in the “Remove data leakage features” section.</p><h3>Strategies for improving the model</h3><p>Generally, there are 3 directions for model tuning: select a better algorithm, tune model parameters, and improve data.</p><h4>Compare multiple algorithms</h4><p>Comparing multiple algorithms is a straightforward idea to improve the model performance. Different algorithms are better suited for different types of datasets. We can train them all together and find the one with the best performance. For example, for classification models, we can try <a href="https://en.wikipedia.org/wiki/Logistic_regression">Logistic Regression</a>, <a href="https://en.wikipedia.org/wiki/Support-vector_machine">Support Vector Machine</a>, <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a>, <a href="https://en.wikipedia.org/wiki/Artificial_neural_network">Neural Network</a>, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4CEJ3J6P0yQor8EK" /><figcaption><em>(Source: </em><a href="https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html)"><em>https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html)</em></a></figcaption></figure><h4>Hyperparameter tuning</h4><p>Hyperparameter tuning is a common approach to tune models. In machine learning models, there are some parameters chosen before the learning process starts, which are called hyperparameters. Some examples are the maximum depth allowed for <a href="https://en.wikipedia.org/wiki/Decision_tree">decision tree</a>, and the number of trees included in <a href="https://en.wikipedia.org/wiki/Random_forest">random forest</a>. Hyperparameters will influence the outcome of the learning process. Hyperparameter tuning is choosing the optimal set of parameters so that we can get optimal outcomes from the learning process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*C5QGL3maM_eBrSV-" /><figcaption><em>(Source: </em><a href="https://image.slidesharecdn.com/sparkfornlp4x3-160521214311/95/data-by-the-bay-2016-may-17-2016-20-638.jpg?cb=1463867059"><em>Slideshare</em></a><em>)</em></figcaption></figure><p>We recommend using publicly available libraries to help with hyperparameter tuning, e.g. <a href="https://optuna.org/">optuna</a>. We’ll have a separate article for hyperparameter tuning in the future.</p><h4>Trade precision with recall</h4><p>For classification models, we usually measure the model performance with 2 metrics: precision and recall. Depending on the problem, you may want to optimize for either precision or recall. There’s a quick way to tune models to make a trade-off between the 2 metrics. Classification model predicts the probability of a label class. We can simply increase or decrease the probability threshold to get higher precision or recall.</p><p>For example, if we build a model to predict whether a passenger survives in the Titanic disaster, the model can predict the probability of the passenger living or dying. If the probability is above 50%, the model will predict that the passenger will survive. Otherwise, the model will predict the passenger won’t survive. If we want a higher precision, we can increase the probability threshold. Then, the model will predict fewer passengers surviving but will be more precise. If we want to increase recall and cover more passengers that’ll possibly survive, we can decrease the probability threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tPxHSM4l8C5XFsRy" /></figure><h4>Feature engineering</h4><p>Besides selecting the best algorithm and tuning parameters, we can generate more features from existing data, which is called feature engineering.</p><p><strong>Create new features</strong></p><p>Creating new features requires some domain knowledge and creativity. Here are some examples of newly created features:</p><ul><li>Create a feature for counting the number of letters in the text.</li><li>Create a feature counting the number of words in a text.</li><li>Create a feature that understands the meaning of the text (e.g. word embeddings).</li><li>Aggregate user event count over the past 7 days, 30 days, or 90 days.</li><li>Extract “day”, “month”, “year”, and “days since holiday” features from a date or timestamp feature.</li></ul><p><strong>Enrich training data with public datasets</strong></p><p>When you exhaust your ideas of generating new features from existing datasets, another idea is to get features from public datasets. For example, you want to build a model to predict whether a user will convert to membership but you don’t have too much user information in your datasets. However, you find the dataset contains ‘email’ and ‘company’ columns. Then you can get user and company data from a third-party, including user location, user age, company size, etc. This data can be used to enrich your training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*LkmNxIBycT9ApxcS" /><figcaption><em>Third-party, but I guess enriched data is worth celebrating. (Source: </em><a href="https://c.tenor.com/_nFK_VtPnykAAAAC/olympics-nbc.gif"><em>Tenor</em></a><em>)</em></figcaption></figure><p><strong>Feature selection</strong></p><p>It’s not always good to add more features. Removing irrelevant and noisy features could help reduce model training time and improve model performance. There are multiple <a href="https://scikit-learn.org/stable/modules/feature_selection.html#feature-selection">feature selection</a> methods in scikit-learn that can be used to get rid of irrelevant features.</p><p><strong>Remove data leakage features</strong></p><p>As we mentioned earlier, 1 scenario is that the model’s performance is “too good”. However, when you deploy the model and use it in production, you get very poor performance. The possible reason for this issue is “data leakage”, which is a common pitfall for model training. Data leakage means we use some features that happen after the target variable and contain the information of the target variable. In real life, we won’t have those data leakage features when we make predictions.</p><p>For example, you want to predict whether or not a user will open an email but your features include whether or not the user clicked on the email. A user can only click the email if they opened it. If the model sees that a user clicked it, then it will 100% predict they will open it. The problem is in a real life scenario, we can’t know whether someone will click an email before they open the email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*k1D3UMoFEHEW-TLF" /><figcaption><em>Remove data leakage! (Source: </em><a href="https://c.tenor.com/u8ukYJDixewAAAAC/leaking-water-leaking.gif"><em>Tenor</em></a><em>)</em></figcaption></figure><p>We can debug the data leakage issue with <a href="https://www.mage.ai/blog/how-to-interpret-explain-machine-learning-models-using-shap-values">SHAP values</a>. With the <a href="https://shap.readthedocs.io/en/latest/index.html">SHAP</a> library, we can plot the chart to show features with the most impact and how they impact the model’s output directionally. If the top features are highly correlated with the target variable and have very high weights, they’re potentially data leakage features and we can remove them from the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*Yp-_Oeh06TsJ9Ly8" /></figure><p><strong>More data</strong></p><p>Last but not least, getting more training data is an obvious and efficient way to improve model performance. More training data enables the model to find more insights and get better accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*9ytaqfGBHK9GvMDq" /><figcaption><em>More data! (Source: </em><a href="https://media.giphy.com/media/lrc1TZHRYxj7lGM3Vg/giphy.gif?cid=ecf05e47aoqjaushyaf8xrt1si85acq050hrb3os40a7iheh&amp;rid=giphy.gif&amp;ct=g"><em>Giphy</em></a><em>)</em></figcaption></figure><h3>When to stop improving the model</h3><p>Knowing when to stop is a tough question with no perfect answer. There’s no hard stopping point for model tuning. There could always be new ideas to bring on new data, create new features, or tune algorithms. The bare minimum criteria is that the model performance should at least be better than baseline metrics. Once we meet the minimum criteria, this is the process we recommend for improving models and deciding when to stop:</p><ul><li>Try all the strategies to improve models.</li><li>Compare the model performance with some other metrics you have to verify whether the model metrics make sense.</li><li>After doing several rounds of model tuning, evaluate whether it’s worth spending time trying new ideas with the improvements you get.</li><li>If the model performs well and you can barely get improvements after trying out a handful of ideas, deploy the model to production and measure the performance in production.</li><li>If the performance is similar between production and training, then your model is good to go. If the production performance is worse than the performance in training, that indicates some issues in the training. The issues could be the model is <a href="https://en.wikipedia.org/wiki/Overfitting">overfitting</a> the training data, or the model has data leakage issues. You’ll need to go back and further tune the model.</li></ul><h3>Conclusion</h3><p>Model tuning is a lengthy and repetitive process to test new ideas, retrain the model, evaluate the model, and compare the metrics. If you wonder how this process can be simplified, stay tuned for future articles about how <a href="https://www.mage.ai/">Mage</a> can help you improve models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=409b05b2a5f" width="1" height="1" alt=""><hr><p><a href="https://m.mage.ai/how-to-improve-the-performance-of-a-machine-learning-ml-model-409b05b2a5f">How to improve the performance of a machine learning (ML) model</a> was originally published in <a href="https://m.mage.ai/">Mage AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to interpret and explain your machine learning models using SHAP values]]></title>
            <link>https://m.mage.ai/how-to-interpret-and-explain-your-machine-learning-models-using-shap-values-471c2635b78e?source=rss-e79cfb810635------2</link>
            <guid isPermaLink="false">https://medium.com/p/471c2635b78e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[modeling]]></category>
            <category><![CDATA[shap-values]]></category>
            <category><![CDATA[model-explanation]]></category>
            <category><![CDATA[shap]]></category>
            <dc:creator><![CDATA[Xiaoyou Wang]]></dc:creator>
            <pubDate>Thu, 19 Aug 2021 18:20:18 GMT</pubDate>
            <atom:updated>2021-08-19T18:20:18.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*jS19oHk3ShZIYZxu" /></figure><h3>Outline</h3><ul><li>Introduction</li><li>What are SHAP values?</li><li>Walkthrough example</li><li>How does Mage explain models?</li><li>Conclusion</li></ul><h3>Introduction</h3><p>Machine learning models are usually seen as a “black box.” It takes some features as input and produces some predictions as output. The common questions after model training are:</p><ul><li>How do different features affect the prediction results?</li><li>What are the top features that influence the prediction results?</li><li>The model performance metrics look great, but should I trust the results?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*dk-Jg5tLln9yxPYj" /><figcaption>Whatever you say Prince Ali (Source: <a href="https://media.giphy.com/media/voF2A48B0XQje/giphy.gif?cid=ecf05e47430ryauf2jpw4w1oacjhmbw51o9ou95uvzgl9po4&amp;rid=giphy.gif&amp;ct=g">Giphy)</a></figcaption></figure><p>Thus, model explainability plays an important role in the machine learning world. Model insights are useful for the following reasons:</p><ul><li>Debugging</li><li>Informing feature engineering</li><li>Directing future data collection</li><li>Informing human decision-making</li><li>Building trust</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*jEUedEhjhqCYCyhu" /><figcaption>Model insights doing its part! (Source: <a href="https://media.giphy.com/media/duL28c2tptZ0zAopCf/giphy.gif?cid=ecf05e47fytvtx25jt2n69lsx6y69vlwfq5x5gv4r3fe5isq&amp;rid=giphy.gif&amp;ct=g">Giphy</a>)</figcaption></figure><p>We talked about the metrics used for model evaluation in a previous article “<a href="https://m.mage.ai/the-definitive-guide-to-accuracy-precision-and-recall-for-product-developers-71e4887d0da7">The definitive guide to Accuracy, Precision, and Recall for product developers</a>.” Those metrics help you understand the overall performance of a model. However, we need more insights into how different features impact the model’s prediction.</p><p>There are multiple techniques to explain the models. In this article, we’ll introduce SHAP values, which is one of the most popular model explanation techniques. We’ll also walk through an example to show how to use SHAP values to get insights.</p><h3>What are SHAP values?</h3><p>SHAP stands for “SHapley Additive exPlanations.” <a href="https://en.wikipedia.org/wiki/Shapley_value">Shapley values</a> are a widely used approach from cooperative game theory. The essence of Shapley value is to measure the contributions to the final outcome from each player separately among the coalition, while preserving the sum of contributions being equal to the final outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*GQNk4Gw-P9tOY7hb" /><figcaption>Oh SHAP! (Source: <a href="https://media.giphy.com/media/fs62ZydKjn6lbJ0pAU/giphy.gif?cid=ecf05e47tk7q5rzu84chni9fvuv7w5hal3874xdxds4v506m&amp;rid=giphy.gif&amp;ct=g">Giphy</a>)</figcaption></figure><p>When using SHAP values in model explanation, we can measure the input features’ contribution to individual predictions. We won’t be covering the complex formulas to calculate SHAP values in this article, but we’ll show how to use the <a href="https://github.com/slundberg/shap">SHAP</a> Python library to easily calculate SHAP values.</p><p>There are some other techniques used to explain models like <a href="https://scikit-learn.org/stable/modules/permutation_importance.html">permutation importance</a> and <a href="https://scikit-learn.org/stable/modules/partial_dependence.html">partial dependence plots</a>. Here are some benefits of using SHAP values over other techniques:</p><ol><li>Global interpretability: SHAP values not only show feature importance but also show whether the feature has a positive or negative impact on predictions.</li><li>Local interpretability: We can calculate SHAP values for each individual prediction and know how the features contribute to that single prediction. Other techniques only show aggregated results over the whole dataset.</li><li>SHAP values can be used to explain a large variety of models including <a href="https://en.wikipedia.org/wiki/Linear_model">linear models</a> (e.g. <a href="https://en.wikipedia.org/wiki/Linear_regression">linear regression</a>), <a href="https://sdcastillo.github.io/PA-R-Study-Manual/tree-based-models.html">tree-based models</a> (e.g. <a href="https://en.wikipedia.org/wiki/XGBoost">XGBoost</a>) and <a href="https://en.wikipedia.org/wiki/Neural_network">neural networks</a>, while other techniques can only be used to explain limited model types.</li></ol><h3>Walkthrough example</h3><p>We’ll walk through an example to explain how SHAP values work in practice. If you’ve followed Mage’s blog articles, you might’ve already read “<a href="https://m.mage.ai/how-to-get-started-with-ai-ml-8630fecfd776">Build your first machine learning model</a>.” We’ll use the same dataset <a href="https://app.box.com/s/zrpzj8zw35zbs8njcij40gy45gcgwsyl">titanic_survival</a> to demonstrate how SHAP values work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*gJHvQsqNjieiVYdi" /><figcaption>The SHAP has sailed (Source: <a href="https://media.giphy.com/media/OJw4CDbtu0jde/giphy.gif?cid=ecf05e47mu4d3inc0360lu6wzbdzw95gf5d0aptehgo6bpnz&amp;rid=giphy.gif&amp;ct=g">Giphy</a>)</figcaption></figure><p>We use XGBoost to train the model to predict survival. “Sex”, “Pclass”, “Fare”, and “Age” features are used in the model training. “Survived” is the label feature with values 0 and 1.</p><p>We use this <a href="https://github.com/slundberg/shap">SHAP</a> Python library to calculate SHAP values and plot charts. We select TreeExplainer here since XGBoost is a tree-based model.</p><pre>import shap</pre><pre>explainer = shap.TreeExplainer(model)<br>shap_values = explainer.shap_values(X)</pre><p>The shap_values is a 2D array. Each row belongs to a single prediction made by the model. Each column represents a feature used in the model. Each SHAP value represents how much this feature contributes to the output of this row’s prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*7mAmjQz8J0x2cduN" /></figure><p>Positive SHAP value means positive impact on prediction, leading the model to predict 1(e.g. Passenger survived the Titanic). Negative SHAP value means negative impact, leading the model to predict 0 (e.g. passenger didn’t survive the Titanic).</p><h4>Feature importance</h4><p>We can use the <strong>summary_plot</strong> method with plot_type “bar” to plot the feature importance.</p><pre>shap.summary_plot(shap_values, X, plot_type=&#39;bar&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/0*6nvv918Xh4vpjKZt" /></figure><p>The features are ordered by how much they influenced the model’s prediction. The x-axis stands for the average of the absolute SHAP value of each feature. For this example, “Sex” is the most important feature, followed by “Pclass”, “Fare”, and “Age”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*m0LejZlDxjacOd1E" /><figcaption>(Source: <a href="https://media.giphy.com/media/XR9Dp54ZC4dji/giphy.gif?cid=ecf05e47i4ukbk09nk2hn4175kvwh9hwrpez5s8w1zvnq2v9&amp;rid=giphy.gif&amp;ct=g">Giphy</a>)</figcaption></figure><h4>Directionality impact</h4><p>With the same <strong>summary_plot</strong> method, we can plot dot charts to visualize the directionality impact of the features.</p><pre>shap.summary_plot(shap_values, X)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/0*Vkc741CfBrRLsZIr" /></figure><p>In this chart, the x-axis stands for SHAP value, and the y-axis has all the features. Each point on the chart is one SHAP value for a prediction and feature. Red color means higher value of a feature. Blue means lower value of a feature. We can get the general sense of features’ directionality impact based on the distribution of the red and blue dots.</p><p>In the chart above, we can conclude the following insights:</p><ul><li>Higher value of “Sex” (male) leads to lower chance of survive. Lower value of “Sex” (female) leads to higher chance of survival.</li><li>Higher value of “Pclass” leads to lower chance to survive as well. Lower value of “Pclass” leads to higher chance of survival.</li><li>Lower value of “Fare” leads to lower chance to survive.</li><li>Higher value of “Age” leads to lower chance to survive.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*KnkLoaneaxFPxoN_" /><figcaption>Well, you get the point (Source: Titanic)</figcaption></figure><p>By comparing these insights with general understanding of the problem, we can trust that the model is intuitive and making the right decisions. For example, the model will more likely predict survival if the passenger had a Sex of female. This is intuitive because women and children were put on lifeboats before men were allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*AfIyONhu6L9BH4WM" /><figcaption>When it sinks in (Source: <a href="https://media.giphy.com/media/nkJKkyfNlGrNm/giphy.gif?cid=ecf05e47v4c9f6newaxtq1u4jsgy4fxerb7u7laqtn1l7fa4&amp;rid=giphy.gif&amp;ct=g">Giphy)</a></figcaption></figure><h4>Individual predictions</h4><p>Besides seeing the overall trend of feature impact, we can call the <strong>force_plot</strong> method to visualize how features contribute to individual predictions.</p><pre>shap.force_plot(<br>    explainer.expected_value,<br>    shap_values[idx, :],<br>    X.iloc[idx, :],<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t-1FNfI8aEQT_iHy" /></figure><p>In this case, feature “Fare” and “Sex” have a positive impact on the prediction, while “Pclass” and “Age” have a negative impact on the prediction.</p><h3>How does Mage explain models?</h3><p>After the model is trained, Mage provides an Analyzer page to show the model performance and insights. In addition to model performance metrics (precision, recall, accuracy, etc), we leverage SHAP values to show features that have the most impact on model output and how those features impact the model output.</p><p>“Top Influencers” chart is similar to the summary bar chart from the `shap` library. We calculate the average of the absolute SHAP values for each feature and use it to show which features were the most important when making a prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1VLt5Gf4-Hqg5_w76EMxjQ.png" /><figcaption>Mage Analyzer page: top features</figcaption></figure><p>We also translate SHAP values to this “Directionality” chart to show how features impact the output in a more intuitive way. Green plus icon means higher feature value and red minus icon means lower feature value. Horizontally, the right side means positive impact on the prediction and the left side means negative impact. We also summarize all the insights into text to make it easier to understand.</p><p>For the Titanic example, we can easily see when sex is female, pclass is smaller, fare is higher, or younger age, there is a higher chance to survive. These insights align with our understanding of what actually happened during the Titanic incident in real life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZNaNuAYvhldbLNyjpk86A.png" /><figcaption>Mage Analyzer page: SHAP values</figcaption></figure><h3>Conclusion</h3><p>Model explainability is an important topic in machine learning. SHAP values help you understand the model at row and feature level. The <a href="https://github.com/slundberg/shap">SHAP</a> Python package is a useful library to calculate SHAP values, visualize the feature importance, and directionality impact using multiple charts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*tMgd4P8urdnn-dbf" /><figcaption>(Source: Titanic)</figcaption></figure><h3>Resources</h3><ul><li>Original paper for SHAP: <a href="https://arxiv.org/pdf/1705.07874.pdf">https://arxiv.org/pdf/1705.07874.pdf</a></li><li>Documentation for `shap` library : <a href="https://shap.readthedocs.io/en/latest/index.html">https://shap.readthedocs.io/en/latest/index.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=471c2635b78e" width="1" height="1" alt=""><hr><p><a href="https://m.mage.ai/how-to-interpret-and-explain-your-machine-learning-models-using-shap-values-471c2635b78e">How to interpret and explain your machine learning models using SHAP values</a> was originally published in <a href="https://m.mage.ai/">Mage AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>