<?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 Chuangxin Lin on Medium]]></title>
        <description><![CDATA[Stories by Chuangxin Lin on Medium]]></description>
        <link>https://medium.com/@lcxustc?source=rss-890a7b9564d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Lmypsgo8U503C2Kyl-zKdA.jpeg</url>
            <title>Stories by Chuangxin Lin on Medium</title>
            <link>https://medium.com/@lcxustc?source=rss-890a7b9564d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:43:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lcxustc/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[Salary, Satisfaction, Trend of Data Jobs]]></title>
            <link>https://medium.com/data-science/salary-satisfaction-trend-of-data-jobs-f47bdf72afa3?source=rss-890a7b9564d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f47bdf72afa3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Chuangxin Lin]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 00:21:36 GMT</pubDate>
            <atom:updated>2021-06-07T03:37:43.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>Salary, Job Satisfaction, Trend of Data Jobs</h3><h4>What Can We Learn From Stack Overflow Survey Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwh4ElgPDfTIF0AfGxrdxQ.jpeg" /><figcaption>Image from unsplash.com</figcaption></figure><p>We are now in the ear of data and the job market has witnessed a continuous demand for data-related jobs in the last few years. Data Scientist, Data Analyst and Data Engineer are the three main streams of data-related jobs. For anyone who is interested in entering the field or who is already inside the field, it will be beneficial to understand the current situation of the data job market. Information such as job demands, salary, and satisfaction can give you more insight when you make the next move in the data career path. In this post, I used a particular dataset, <a href="https://insights.stackoverflow.com/survey">Stack Overflow Annual Developer Survey</a>, to explore some questions that will be interesting. The post will cover some data analyses and modeling, with three main parts:</p><p><strong>Part 1: Salary</strong></p><ul><li>What data role earns the highest salary?</li><li>Salaries of data roles among different countries;</li><li>Salaries with different work years;</li><li>Salaries among different genders in the data field;</li><li>Salaries v.s. Job Satisfaction.</li></ul><p><strong>Part 2: Change of data jobs, comparing 2020 data to 2019</strong></p><ul><li>Change of the numbers of data roles;</li><li>Change of Salary;</li><li>Change of Job Satisfaction.</li></ul><p><strong>Part 3: Job Satisfaction</strong></p><ul><li>Multi-class classification using XGBoost to predict job satisfaction;</li><li>Insight from modeling.</li></ul><h3>Notes on data:</h3><p>Before presenting the analysis results, it is worth explaining some important data processing steps. But feel free to skip this section and return back when you find it necessary.</p><p>The survey focused on questions for people with a general developer background, including both software development and data analytics. The 2020 Survey data consists of 64,461 responses. I leveraged the question “DevType” and pre-processed the data so only responders who possess a data-related role will be analyzed. The question from the questionnaire is as followed.</p><blockquote><strong>Which of the following describe you? Please select all that apply.</strong></blockquote><blockquote>[] Academic researcher<br><strong>[] Data or business analyst (named as DA)<br>[] Data scientist or machine learning specialist (named as DS)</strong><br>[] Database administrator<br>[] Designer<br>[] Developer, back­end<br>[] Developer, desktop or enterprise applications <br>[] Developer, embedded applications or devices <br>[] Developer, front­end<br>[] Developer, full­stack<br>[] Developer, game or graphics Developer, mobile<br>[] Developer, QA or test<br>[] DevOps specialist<br>[] Educator<br><strong>[] Engineer, data (named as DE)</strong><br>[] Engineer, site reliability Engineering manager<br>[] Marketing or sales professional Product manager<br>[] Scientist<br>[] Senior Executive (C­Suite, VP, etc.) Student<br>[] System administrator<br>[] Other</blockquote><p>Note that a responder can have more than one choice for the DevType, and even choose more than one data role (i.e., DA, DS, DE). I keep only data entries that are associated with a data role and separate them by different types of data roles. Therefore, two new-created instances may come from the same data instance which has multiple data roles.</p><p>To make the analytic result more consistent, I also filtered the “Employ Status” and keep only responders that are currently employed. With such data preparation, there are 11,186 instances for our analyses on the data roles. Same data preparation has been applied to 2019 survey data, and 17,370 instances are created, which will be used to compared to the 2020 data in <strong>Part 2</strong>.</p><h3>Part 1: Facts on Salary</h3><p>Let’s first check the distribution of these three data jobs. Here we can see their numbers are very close, with DA ranked first and then DS, DE (Fig. 1a). In terms of the average salary (in USD), we can see DS and DE are almost the same, while DA has a slightly lower salary (Fig. 1b).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*lWQ1wp7NC_jzWsRF3lGouQ.png" /><figcaption>Fig.1. (a) Distribution of data roles from the 2020 survey. (b) Salaries of data jobs. Image by author.</figcaption></figure><p>When further displaying the salaries among different countries (top 9 countries with the most responses), we can see some interesting details in Fig. 2:</p><ul><li>Data jobs in the United States earn the most. The average salary in the United States is substantially higher than in other countries, even than that in other developed countries in the western world (i.e., Germany, UK, Canada).</li><li>DS (and DE) is not necessarily a higher-income job, compared to DA. Indeed, we see the salary of DA is quite higher than DS in Canada and France. This may remind you of the saying: data scientist is the sexiest job of 21st century. It may not be that sexy as you thought, at least from what the salary from the survey data tells us. However, the Stack Overflow survey data does not necessarily represent the real-world population.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*93MhqCmXjGIx7dwbSGAfvQ.png" /><figcaption>Fig. 2. Salaries of data jobs in different countries. Image by author.</figcaption></figure><p>An important factor related to the salary is the years of work experience. In the survey data, we use the “Year of Professional Coding” as a proxy of work experience, and divide the responders into four groups by “Year of Professional Coding”. In Fig. 3, from “0–3 years” to “6–13 years”, we can see the salaries gradually and slowly increase, and in the group “13+ years” the salary has a substantial raise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*NrF-2AxccGoxqS4e9qsueQ.png" /><figcaption>Fig. 3. Salaries of data jobs in different “Year of Professional Coding” groups. The groups are dived in such a way that the sizes are as equal as possible. Image by author.</figcaption></figure><p>Another interesting and important point to check is the gender distribution in this field. The gender disparity in the developer field has been a long-term concern. Here we see this issue in the data field as well (Fig. 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*fk9xfRykYZcluV4bkLA0YQ.png" /><figcaption>Fig. 4 Gender distribution in data jobs. For the simplicity of plotting, all non-binary genders have been considered into the “Others” group. Image by author.</figcaption></figure><p>In terms of the salary, we can see there is no substantial difference between man and woman (Fig. 5a), but the salary for woman has a wider range (high variance, Fig. 5b).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*2rabfMV6WaNJ65QyPw6ZIw.png" /><figcaption>Fig. 5. Salaries in data jobs by gender. (a) Bar plot. (b) Violin plot. Image by author.</figcaption></figure><p>Finally, let’s see how job satisfaction is related to salary. As you may expect, job satisfaction is not always positively correlated with salary and that’s also what the data shows us in Fig. 6a. It may also suggest that there are a bunch of data engineers who are very dissatisfied with their job while having very good pay (see the high green bar in the rightmost of Fig. 6b). Of course, there are many other factors that will contribute to our job satisfaction in the real world. And in <strong>Part 3</strong>, I will apply machine learning modeling to predict job satisfaction and find more insight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*2qmp4XZKWq4X_AVdsVDmnQ.png" /><figcaption>Fig. 6. Salary v.s. Job Satisfaction. Image by author.</figcaption></figure><h3>Part 2: Change of data jobs, comparing 2020 data to 2019</h3><p>In this part, let’s see some trends in the data field. Because our analyses rely on the Stack Overflow survey data and the survey form in 2018 was quite different from 2019 and 2020, we will use 2019, 2020 data only and perform the comparison. We first note that the total number of valid survey responses filtered from raw data in 2020 is 53,159 and 15.69% of the responders have a data-related job. In comparison, the 2019 survey data has 77,420 valid survey responses and 16.71% of the responders have a data-related job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*a2gyMi52xcxbTcfQXkCOig.png" /><figcaption>Fig. 7. Numbers of data roles and distributions, 2019 v.s. 2020. Note that due to the way we created the data instances, the total numbers are larger than the numbers of survey responses. Image by author.</figcaption></figure><p>First, the data shows that the distribution of data roles has little change among these three roles (Fig. 7). The counts from 2019 are larger because there were more responses in the 2019 survey, which doesn’t necessarily mean the number of data-related jobs has decreased in 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*FqTXNMYH0oS3Jk0093T9Iw.png" /><figcaption>Fig. 8. Comparison of salaries between 2019 and 2020. Image by author.</figcaption></figure><p>When it comes to the change of salary, perhaps it’s the most surprising result I encountered. We can see the decrease in salary in all three data jobs and the overall decrease is about $16,000 (Fig. 8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*SautY6bwynl1y0GaxegpGA.png" /><figcaption>Fig. 9. Comparison of salaries between 2019 and 2020, US data only. Image by author.</figcaption></figure><p>To further verify this change, I made the plot with only US data. And a similar decrease in salary is observed (Fig. 9). This time we see the salary of DS has only a slight decrease while DA and DE have a more substantial decrease. It will be interesting to use other data sources to cross-check if this decrease is true for data jobs in the job market. And if so, what would be the reason and what implications can we have here? As a side note, I first thought this decrease in Salary may be due to Covid-19 and thus the downturn of the market. But the 2020 survey data was actually collected in February 2020 so the pandemic hasn’t come into play yet.</p><p>Last, let’s look at job satisfaction, another important factor to help get insight into the job market. The questionnaire has the question on job satisfaction as follows:</p><blockquote><strong>How satisfied are you with your current job? (If you work multiple jobs, answer for the one you spend the most hours on.)</strong></blockquote><blockquote>o Very dissatisfied (-2)<br>o Slightly dissatisfied (-1)<br>o Neither satisfied nor dissatisfied (0)<br>o Slightly satisfied (1)<br>o Very satisfied (2)</blockquote><p>I converted different grades of satisfaction into values ranging from -2 to 2. And the average scores are given in Fig. 10. We can observe that DS has the highest satisfaction score and then followed by DE and DA, in both 2019 and 2020. Moreover, the satisfaction from 2019 to 2020 has decreased across all three data jobs, which moved in the same direction as the salaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*37RV36KaCgmuvabbaS3aQQ.png" /><figcaption>Fig. 10. Comparison of job satisfaction between 2019 and 2020. Image by author.</figcaption></figure><h3>Part 3: Job Satisfaction Prediction</h3><p>In the last part of this post, I am interested in building a machine learning model to predict job satisfaction. As we have seen before, there are five possible answers to the job satisfaction question. Therefore, the prediction will be a multi-classification problem.</p><p>To avoid the inconsistency of data distribution from different years, only the 2020 survey data will be used for modeling. Also, note that the data is imbalanced. “Very satisfied” and “Slightly satisfied” have taken more than 60% of the total data while there are less than 10% “Very dissatisfied”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*Ag9r7xEFAoYlH6sbkXqGuQ.png" /><figcaption>Image by author.</figcaption></figure><p>Some important data processing steps include: 1) data cleaning; 2) missing data imputation; 3) categorical data encoding; 4) feature selection/engineer. I will skip these technical details here and you can refer to the notebook and code in the <a href="https://github.com/Chancylin/StackOverflow_Survey">GitHub repository</a> for more details. For the modeling, I used the XGBoost algorithm with the oneVsRest approach for this multi-classification problem.</p><h4>3.1. Exploratory Data Analysis (EDA)</h4><p>Before presenting the modeling result, I will show some EDA as the routine of data science projects, to give you some quick insight into job satisfaction. As shown in <strong>Part 1</strong>, salary and job satisfaction do not necessarily correlate with each other (Fig. 6). How about the other important factors that will potentially affect job satisfaction?</p><p>There is certainly some pattern between company size and job satisfaction as shown in Fig. 11, but it will be difficult to draw a general conclusion. Plausibly, in the small company, the percentage of “Very satisfied” tends to be higher than “Slightly satisfied”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*lqPtP09NCHy-Qj-IQNz5Eg.png" /><figcaption>Fig. 11. Job satisfaction distributions among companies of different sizes. Image by author.</figcaption></figure><p>Overtime is another factor that should relate to job satisfaction in a general sense. However, the pattern is vague if there is any (Fig. 12). Indeed, in the group that never overworks, the “Very satisfied” class is not the most response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*owudG9Cx43-QE4vAHjhXdQ.png" /><figcaption>Fig. 12. Job satisfaction distributions among groups with different overtime. Image by author.</figcaption></figure><p>Last let’s check the job satisfaction distributions across different countries. One observation stands out: the percentage of “Very satisfied” is relatively low in developing countries such as India and Brazil. Nevertheless, it will be hasty to conclude this is a particular phenomenon in the data field. Instead, the lower percentage of “Very satisfied” in developing countries can be a general phenomenon regardless of whichever field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*oM5yzsIrzsBaA9HT76lZxQ.png" /><figcaption>Fig. 13. Job satisfaction distributions across different countries. Note that we don’t use Country as a feature in the modeling step for simplicity. Country is a high-cardinality feature and more advanced encoding techniques should be used rather than simple one-hot-encoding. Image by author.</figcaption></figure><h4>3.2. Multi-classification with XGBoost</h4><p>Here we jump to the model performance by checking the confusion matrix. There are two observations on our model:</p><ul><li>There is an overfitting issue for the model, even though several techniques have been applied to combat the overfitting issues in the modeling step;</li><li>The model can predict the minor classes correctly on a reasonable level, although many mistakes are made by predicting the instances as “Very satisfied” and “Slightly satisfied”.</li><li>The model is confused by “Very satisfied” and “Slightly satisfied” (Fig. 14, right).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*KH5Fr0WgfcYTaG-mVltvjg.png" /><figcaption>Fig. 14. Model performance by confusion matrix. left: confusion matrix for training data. Right: confusion matrix for test data. Image by author.</figcaption></figure><p>Certainly, there is room to improve the model, but the model performance is reasonably good compared to the baseline model using Naive Bayes which I haven’t shown here. Moreover, the dataset itself could be challenging and thus difficult to learn the general pattern (i.e., overfitting issue) anyway.</p><h4>3.3. Model explainability and insight</h4><p>In order to understand the model and get more insight, let’s check the top features calculated during the tree-building process (Fig. 15).</p><p>The use of one-hot-encoding introduces some inconvenience for the interpretation, because the original feature is now broken into multiple binary features. The two most important features are about “NEWOnboardGood”: “NEWOnboardGood_1” means “Yes” response to the question “Do you think your company has a good onboarding process” and “NEWOnboardGood_2” means “No”. It’s straightforward to see a good onboarding process usually is associated with high job satisfaction.</p><p>We also see “UndergradeMajor” plays as an important feature following “NEWOnboardGood”. Indeed, what the model has learned from the data is:</p><ul><li>If the responders have an undergraduate major in natural science (such as biology, chemistry, physics, etc.), it’s more likely that they are “Very satisfied”;</li><li>Similar for responders who have an undergraduate major in another engineering discipline (such as civil, electrical, mechanical, etc.)</li></ul><p>The feature “Bash/Shell/PowerShell” is interesting, responders who use “Bash/Shell/PowerShell” as one of their programming languages is more likely to be “Very satisfied” than those who don’t. At least that’s what the model learned from the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*afd_SCsQzqpqNbsj-HP5TA.png" /><figcaption>Fig. 16. Feature importance calculated by gain during the tree-building process of XGBoost. Image by author.</figcaption></figure><p>We can use <a href="https://github.com/slundberg/shap">SHAP</a>, a very versatile tool for model explainability, to better understand the model behavior. You are encouraged to explore more in the notebook. Here I will show you the top features based on SHAP values and also post two examples of dependence plots for Salary and Company Size.</p><p>First, we will see the top features given by SHAP values (Fig. 17) are different from those calculated from information gain during node splitting (Fig. 16). SHAP values approach is considered more consistent for evaluating feature importance (see SHAP paper for reference). Here, the top features are “Salary”, “NEWOnboardGood_1”, “Age”, “YeasCode”, “OrgSize”, which are more consistent with common sense in my opinion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*UALN1CqUmgKg674P7fAdlw.png" /><figcaption>Fig. 17. Top features from SHAP values, in contrast to those from information gain in Fig. 16. From Class 0 to 4: ‘Neither satisfied nor dissatisfied’, ‘Slightly dissatisfied’,<br> ‘Slightly satisfied’, ‘Very dissatisfied’, ‘Very satisfied’. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*tawu33qJgKJ19LRxPApCyQ.png" /><figcaption>Fig. 18. SHAP dependence plot for Salary. Image by author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*9nNHWvv8Vc7Xsqs3w4QMsA.png" /><figcaption>Fig. 19. SHAP dependence plot for Company Size. The mapping of OrgSize is: {1: ‘Just me — I am a freelancer, sole proprietor, etc.’, 2: ‘2 to 9 employees’, 3: ’10 to 19 employees’, 4: ’20 to 99 employees’, 5: ‘100 to 499 employees’, 6: ‘500 to 999 employees’, 7: ‘1,000 to 4,999 employees’, 8: ‘5,000 to 9,999 employees’, 9: ‘10,000 or more employees’, -1: ‘Missing’}. Image by author.</figcaption></figure><p>The SHAP dependence plot in Fig. 18 tells us how the Salary will contribute to predicting if an instance is “Very satisfied”. We can see that overall, a higher salary will contribute to predicting the instance is more likely “Very satisfied”, as the increasing trend indicates.</p><p>For Company Size, the smaller size tends to make a positive contribution to predicting “Very satisfied” (Fig. 19).</p><h4>Conclusion</h4><p>In this post, we used the Stack Overflow Survey data to do some exploratory analyses and got some insight into the data field.</p><ol><li>We analyze the salary distribution of different data roles, and also take into account other factors such as countries, year of experience, genders.</li><li>We compare the 2019 survey data with the 2020 data. And it’s quite surprising to see the salaries have decreased for the data-related jobs as well as the job satisfaction.</li><li>Finally, we built an XGBoost multi-classification model to predict job satisfaction and extract some insight into job satisfaction by checking the feature importance and dependence relationship.</li></ol><p>The analyses and modeling in this post are more of the practice purpose and no solid conclusions can be drawn without further investigation. Most importantly, the Stack Overflow survey data itself could be biased and not necessarily the representation of the real-world population. I hope you have some fun reading through this post. To see more technical details, please refer to the <a href="https://github.com/Chancylin/StackOverflow_Survey">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f47bdf72afa3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/salary-satisfaction-trend-of-data-jobs-f47bdf72afa3">Salary, Satisfaction, Trend of Data Jobs</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[How to Build a Real-Time Twitter Analysis Using Big Data Tools]]></title>
            <link>https://medium.com/data-science/how-to-build-a-real-time-twitter-analysis-using-big-data-tools-dd2240946e64?source=rss-890a7b9564d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd2240946e64</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[making-sense-of-big-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Chuangxin Lin]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 21:21:07 GMT</pubDate>
            <atom:updated>2020-12-15T22:19:53.694Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/making-sense-of-big-data">Making Sense of Big Data</a></h4><h3>How to Build a Real-Time Twitter Analysis Application Using Big Data Tools</h3><h4>Crack into Apache Spark and AWS Ecosystem</h4><p>Data Science/Machine Learning applications have been everywhere now and radically changing our lives and business. With tons of awesome out-of-the-box ML packages today, everyone is able to build models in a fast and cheap fashion. This is particularly true when working on your own laptop as a local playground. However, to build a more exciting and practical machine learning application, big data tools and cloud platforms are what you should take into account in your toolbox. In this article, I will give you a quick tour of building a (near) real-time system using big data tools and cloud platform. Hopefully, you can grasp a big picture of all these “LEGO pieces” after the read.</p><h3><strong>The Roadmap</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*hI52jqDU-qXKYbF7ikV_zA.png" /><figcaption>Streaming pipeline (Image by Author)</figcaption></figure><p><strong>Goal:</strong></p><ul><li>A real-time analysis to explore the underlying topics and the sentiment for live tweets;</li></ul><p><em>Note: (1) To avoid flooding ourselves with the tweets on the Internet, I will collect the live tweets filtered by the hashtags #AI, #MachineLearning. In other words, we will explore the latent topics for tweets that are talking about AI and Machine Learning. With the sentiment analysis, we can also catch a glimpse of the public attitudes towards this field. (2) In the end, we will also build a dashboard for visualization.</em></p><p><strong>Python Packages:</strong></p><ul><li><a href="https://www.tweepy.org/">Tweepy</a> to create a stream and listen to the live tweets;</li><li><a href="https://textblob.readthedocs.io/en/dev/">TextBlob</a> to do simple sentiment analysis on tweets (demo purpose only).</li></ul><p><strong>Data Processing Engine:</strong></p><ul><li><a href="https://spark.apache.org/">Apache Spark</a>;</li></ul><p><em>Note: we will use Spark’s machine learning library to train an LDA (Latent Dirichlet Allocation) model for topic modelling, which will give you a quick taste of ML model training in a distributed system. We also use Spark to process the Streaming, for model scoring/inference.</em></p><p><strong>Cloud Platform: </strong>AWS;</p><p><strong>AWS Services:</strong></p><ul><li><a href="https://aws.amazon.com/s3/">S3</a>: Amazon Simple Storage Service</li><li><a href="https://aws.amazon.com/kinesis/data-streams/">Kinesis Data Streams</a>: streaming service to collect and process large streams of data record in real time.</li></ul><p><em>Note: the Tweepy streaming will be the producer that will put data into the Kinesis Data Stream.</em></p><ul><li><a href="https://aws.amazon.com/kinesis/data-firehose/?kinesis-blogs.sort-by=item.additionalFields.createdDate&amp;kinesis-blogs.sort-order=desc">Kinesis Firehose</a>: service to deliver real-time streaming data to destinations such as Amazon S3, Redshift, ElasticSearch, etc.</li></ul><p><em>Note: We use a Kinesis Firehose deliver stream as a consumer of the Kinesis Data Stream, and save the raw tweets into the S3 directly.</em></p><ul><li><a href="https://aws.amazon.com/emr/?whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc">EMR</a>: service that utilizes a hosted Hadoop framework running on the Amazon <a href="https://aws.amazon.com/ec2/?ec2-whats-new.sort-by=item.additionalFields.postDateTime&amp;ec2-whats-new.sort-order=desc">EC2</a> (computing instance) and Amazon S3.</li></ul><p><em>Note: we use EMR to run Spark for data processing and model training, in a distributed fashion.</em></p><ul><li><a href="https://aws.amazon.com/athena/?whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc">Athena</a>: a serverless, interactive query service to query data and analyze big data in Amazon S3 using standard SQL.</li></ul><p><em>Note: we will use Athena to access the processed tweets that have been saved in S3.</em></p><ul><li><a href="https://aws.amazon.com/quicksight/">QuickSight</a>: a cloud-scale business intelligence (BI) service that you can use to deliver easy-to-understand insights.</li></ul><p><em>Note: We will use QuickSight to connect to Athena to build a dashboard for visualization.</em></p><h3>1. Collect tweets from the Twitter Streaming API Using Python</h3><p>To collect tweets in real time is the very first step for two purposes:</p><p>(1) Create the dataset for the ML model training purpose.</p><p>(2) The streaming will be used to demonstrate the real-time analysis.</p><p>You will need to apply for a <a href="https://developer.twitter.com/en/apply-for-access">Twitter Developer account</a> in order to set up the Twitter streaming. Otherwise, using the <a href="http://docs.tweepy.org/en/v3.5.0/streaming_how_to.html">Tweepy streaming API</a> is straightforward. An important step is to overload the “<em>on_data</em>” method in the “<em>StreamListener</em>” class so we can put the tweets into Kinesis Data Stream. In this way, we have the <strong>producer</strong> in our streaming pipeline.</p><p>The complete code can be found on <a href="https://github.com/Chancylin/twitter_data_analysis/tree/master/spark_streaming/aws_kinesis">GitHub</a>. Here are some highlights:</p><ol><li>Have the Kinesis Data Stream ready so we can put the streaming tweet data into it;</li><li>Overload the “<em>on_data</em>” method for the StreamListner. Usually, you can have some simple processing on the coming tweets (e.g., what fields to keep) in this step meanwhile you may not want to alter the raw data too much (i.e., keep the raw data is a good practice).</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c1fc750762c2c61feb4248d8b4a512/href">https://medium.com/media/12c1fc750762c2c61feb4248d8b4a512/href</a></iframe><h3>2. The Streaming Pipeline</h3><h4>2.1. Kinesis Data Stream</h4><p>If you are an observant reader, you may find out that we have not created the Kinesis Data Streaming yet when introducing the Tweepy Streaming in the previous section. And yes, you are right! Indeed we need to have the Kinesis Data Stream ready beforehand, so we can ingest the streaming twitter data. Simply sign in to your AWS console, go to Amazon Kinesis and create a Data Stream. It is worth noting the difference between <a href="https://jayendrapatil.com/aws-kinesis-data-streams-vs-kinesis-firehose/#:~:text=Kinesis%20data%20streams%20%E2%80%93%20Kinesis%20data,streaming%20data%20for%20specialized%20needs.&amp;text=Firehose%20also%20allows%20for%20streaming,for%20processing%20through%20additional%20services.">Kinesis Data Stream and Kinesis Data Firehose</a>. Firehose loads data streaming directly into the destination (e.g., S3 as data lake). But in this use case, Kinesis Data Stream fits our need better, since aside from saving the raw data into S3 directly, we are interested in analyzing/processing the tweets in real time. The step of creating a Kinesis Data Stream will be like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*W7xeCahws8tgETHttNnVIQ.png" /><figcaption>Create a Kinesis data stream in AWS. (Image by Author)</figcaption></figure><p>There are two important points to consider when creating a data stream:</p><ol><li><a href="https://aws.amazon.com/kinesis/data-streams/faqs/#:~:text=Shard%20is%20the%20base%20throughput,you%20create%20a%20data%20stream.">Number of Shards</a>. More shards mean higher throughput capacity. You should estimate the input and output data rate to choose a proper number of shards;</li><li><a href="https://docs.aws.amazon.com/streams/latest/dev/kinesis-extended-retention.html">Retention Period</a>. The time period from when a record is added to when it is no longer accessible is called the retention period. A Kinesis data stream stores records from 24 hours by default, up to 8760 hours (365 days) according to <a href="https://docs.aws.amazon.com/streams/latest/dev/kinesis-extended-retention.html">AWS documentation</a>.</li></ol><h4>2.2. Consumers</h4><p>Now with the Tweepy Streaming as the producer to our Kinesis Stream, we will have the consumers on the other side to consume the data in the Stream. The consumers are essentially the applications you will build to process or analyze the streaming data. Refer to the diagram in <a href="https://docs.aws.amazon.com/streams/latest/dev/key-concepts.html">AWS documentation</a> for Kinesis Data Streams High-Level Architecture.</p><p>The Kinesis Firehose is one consumer in our data pipeline because we would like to deliver the raw data into S3 (for the purpose of backups as well as creating our training dataset). Setting up a Kinesis Firehose delivery stream as the consumer for Kinesis Stream is straightforward. You can create it directly from the page of the active Kinesis Data Stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HXQdDKlfFoXpq1vtYLEWQ.png" /><figcaption>Create Kinesis Firehose as one consumer of the Kinesis Data Stream. (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*-uINRvA-c73RGdc0ORIvwQ.png" /><figcaption>Create Kinesis Firehose: configurations. (Image by Author)</figcaption></figure><p>Simply follow the steps and configure the setting wisely in Step 4: how much data to buffer before delivering them into the destination. We will use the S3 bucket as the destination in Step 3. The rationale here is we want to save the raw data from future use, for example, to train our topic model.</p><p>Great. When all is set, you can go to the “Monitoring” Tab on the dashboards to inspect the streaming for both Kinesis Data Streaming and Kinesis Firehose. For example, the stream metrics will give you some idea about your data input/output rate for the Kinesis Data Stream. You can dynamically adjust the number of shards within your data stream via <a href="https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-resharding.html">resharding</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1p5Wnk6ueE2quC0rIAI-A.png" /><figcaption>Stream metrics for Kinesis Data Stream. (Image by Author)</figcaption></figure><p>Our ultimate goal is to perform real-time analysis on the live tweets. Thus, we will create a Spark streaming as one consumer for the Kinesis Data Stream. In other words, the Kinesis Data Stream will be the source of the Spark streaming that we will discuss later. But before we step into the details on that part, let’s make a detour and see how to use Spark for data processing and machine learning model training.</p><h3>3. Spark for data processing and ML model training</h3><p>Python + scikit-learn is the must-have tool for Data Scientist’s daily work. But it becomes awkward when you try to handle tens or hundreds of GB of data in a single machine. Spark comes to the rescue. <a href="https://spark.apache.org/">Apache Spark</a> is a unified engine designed for large-scale distributed data processing. I really like the description of Spark from the great book “<a href="https://www.oreilly.com/library/view/learning-spark-2nd/9781492050032/">Learning Spark</a>”:</p><blockquote>The central thrust of the Spark project was to bring in ideas borrowed from Hadoop Map‐ Reduce, but to enhance the system: make it highly fault tolerant and embarrassingly parallel, support in-memory storage for intermediate results between iterative and interactive map and reduce computations, offer easy and composable APIs in multiple languages as a programming model, and support other workloads in a unified manner.</blockquote><p>The Spark DataFrame (Python) API is very easy to work with if you come from a Pandas background. But watch out for the pitfalls. You need to tune the configuration knobs in order to optimize the performance for the Spark job, given the fact that the data resides in a distributed system. I will give you some simple examples shortly to illustrate this point.</p><p>You can have Spark installed on your laptop and run it in standalone mode (a single machine). But in practice, you will run your Spark job in cluster mode in order to leverage the computing power with the distributed machines (i.e., executors). In cluster mode, you will submit a pre-compile Jar file (Java/Scala) or a Python script. In your PySpark application, the boilerplate code to create a SparkSession is as follows.</p><pre>from pyspark.sql import SparkSession</pre><pre># create a SparkSession:<br># an object that provides a point of entry to interact with underlying Spark functionality and allows programming Spark with its APIs.</pre><pre>spark = SparkSession.builder.\<br>    config(&quot;spark.driver.cores&quot;, 2).\<br>    config(&quot;spark.driver.memory&quot;, &quot;10g&quot;).\<br>    config(&quot;spark.executor.instances&quot;, 1).\<br>    config(&quot;spark.executor.memory&quot;, &quot;10g&quot;).\<br>    config(&quot;spark.executor.cores&quot;, 2).\<br>    config(&quot;spark.sql.shuffle.partitions&quot;, 4).\<br>    appName(&quot;twitter LDA&quot;).getOrCreate()</pre><pre>sc = spark.sparkContext<br>sc.setLogLevel(&quot;WARN&quot;)<br># ship your own written python module for processing<br>sc.addPyFile(&quot;sparkLDA.zip&quot;)</pre><p>How to configure the resource for your Spark Application depends on the computational demand and the available resources in your cluster. DataBricks provides an easy solution to working with Spark. The <a href="https://databricks.com/product/faq/community-edition">community edition</a> allows you to access a micro-cluster and play with Spark. Alternatively, you can use Amazon EMR which utilizes a <strong>Hadoop framework</strong> running on Amazon EC2 for your computing-intensive Spark job. Here let’s stick to Amazon EMR. You can easily find the tutorial to set up an Amazon EMR cluster, but there is a super useful step worth highlighting here. You can create a bootstrap action when spinning up the EMR cluster, and this can be used to install additional packages across all cluster nodes. For example, the following shell script will install the NLTK Python package in all cluster nodes; just put the script in a location in AWS S3.</p><pre><strong>#!/bin/bash<br></strong>sudo python3 -m pip install --upgrade pip<br>sudo python3 -m pip install nltk==3.4.4</pre><h4>3.1. Spark and YARN</h4><p>Here I set up an EMR cluster with one master node and two core nodes (worker nodes), both of which are m5.xlarge EC2 instances (4 CPU and 16 GB Memory).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*TML0g9VCjmCwqb2rvBLL0A.png" /><figcaption>An EMR cluster with one master node and two worker nodes. (Image by Author)</figcaption></figure><p>Note that we will submit our Spark Job in the cluster mode with <strong>YARN</strong> as the Cluster manager. For the configuration of the Spark job submission, there are some important concepts to understand how Spark and YARN interact. I will put some useful resources at the end for your reference. Here are some important notes you may find useful:</p><ul><li>YARN ResourceManager runs on the master node and NodeManager runs on the worker node(s). They are daemons that form the YARN framework. <a href="https://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-site/YARN.html">Note that ResourceManager has two main components: Scheduler and ApplicationsManager.</a></li><li>In cluster mode, when a Spark application is launched, the Spark driver runs inside an ApplicationMaster. ApplicationMaster is created by ApplicationsManeger for each Spark application to negotiate resources from ResourceManager. Confusingly enough, the ApplicationMaster (with the Spark driver) has its own container in the worker node. Contrastly, in <strong>client mode</strong>, the Spark driver runs in the client process on the client machine, which is commonly referred to as gateway machines or edge nodes. <a href="https://stackoverflow.com/questions/34930108/spark-driver-worker-configuration-does-driver-run-on-master-node">For the AWS EMR, if you connect to the master node via ssh and run Spark in client mode, then the Spark drive sits in the master node.</a></li><li>In the architecture of Spark application, we have driver and executors. Each Spark executor runs in a YARN container. So there can be many Spark executors in one worker node as long as the resource (CPUs, memory, etc.) is enough to create the containers.</li></ul><p>The following figure can give you a better idea of how Spark and Yarn interact in the use case I created. The Spark Application only has one executor. And I configured 2 cores for the driver and the executor. The rationale here is to <a href="https://aws.amazon.com/blogs/big-data/submitting-user-applications-with-spark-submit/">leave some cores (usually one) for the OS</a>, given that there are 4 cores on each worker node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*-vxExgioXhHyvUJJU1gkZA.png" /><figcaption>YARN Framework and Spark Application Architecture, an example. A spark application is launched in cluster mode, with one executor. (Image by Author)</figcaption></figure><p>Another important note on the configuration is about the number of executors (<em>spark.executor.instances</em>) and the number of executor cores (<em>spark.executor.cores</em>), and how these ultimately relate to the number of partitions to achieve better performance (i.e., parallelism) for a Spark job. Use my Spark application as an example here:</p><pre>spark = SparkSession.builder.\<br>    config(&quot;spark.driver.cores&quot;, 2).\<br>    config(&quot;spark.driver.memory&quot;, &quot;10g&quot;).\<br>    config(&quot;spark.executor.instances&quot;, 1).\<br>    config(&quot;spark.executor.memory&quot;, &quot;10g&quot;).\<br>    config(&quot;spark.executor.cores&quot;, 2).\<br>    config(&quot;spark.sql.shuffle.partitions&quot;, 4).\<br>    appName(&quot;twitter LDA&quot;).getOrCreate()</pre><ul><li>Only one Spark Executor. This is bad (low parallelism) because we don’t have multiple executors executing tasks in parallel, but to save the cost I do not want to spin up another worker node : (</li><li>Two cores per Executor. You will see I partitioned the dataframe into 4 partitions. Ideally, two cores will work on two partitions in parallel at a time (we call a single core working on a single partition as a <strong>task</strong>). So the parallelism here is acceptable. You may wonder why I don’t partition the dataframe into 2 partitions. You can do that, but it should not affect too much here. For a core of the executor, the matter is just processing one big task v.s. processing two small tasks. Another point is, by using 4 partitions, each of the partition has a size of ~ 60 MB given the size of my training data, which is considered reasonable. A large partition can cause <em>memory pressure</em> during shuffles (although this is not an issue here because we have 10 GB for the executor memory). On the other hand, it’s a bad idea to create too many small partitions that will slow down the system due to the communication between driver and executors. In general, a good practice is to have the lower bound of the number of partitions as 2 x the total number of cores (this is also the default for <em>spark.default.parallelism</em> in AWS EMR, see <a href="https://aws.amazon.com/blogs/big-data/best-practices-for-successfully-managing-memory-for-apache-spark-applications-on-amazon-emr/">AWS blog</a>). Another bad example is to partition the data into 3 partitions given the total number of cores is 2. One core could be idle awaiting the other core to finish the task.</li><li>You may also want to configure <em>spark.sql.shuffle.partitions</em> to control the shuffle partitions created during the shuffle stage. The default value for <em>spark.sql.shuffle.partitions</em> is 200, which is too high for small workloads. In my example, I set it as 4: 2 x the total number of cores.</li></ul><p>You may find <a href="https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-configure.html"><em>maximizeResourceAllocation</em></a><em> </em>and <em>dynamicAllocation </em>useful when running the Spark application in EMR. Overall, performance tuning is a big deal for Spark usage and we only mentioned some important aspects. Another common practice is to use <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.cache"><em>cache</em></a> wisely to avoid repeated computation. There are many posts and tutorials out there discussing more details on the <a href="https://spark.apache.org/docs/latest/tuning.html">configuration</a> and they are definitely worth your time.</p><h4>3.2. LDA in Spark ML</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*W7cRhCblJ4BbzoW-WhwN5A.png" /><figcaption>Data preprocessing and ML pipeline in Spark. (Image by Author)</figcaption></figure><p>Since we are interested in discovering the underlying topics for the tweets, we need to go through some common steps for the NLP task and extract the features that can be fed to the LDA model. The details of the LDA model are out of the scope here. I owe you a clear explanation and will write a post on this topic in the future. But the core idea is: we treat each tweet as a document and a document is a mixture of multiple topics, where each topic is characterized by a distribution over words. Given the fact that a document is a collection of words, we can learn the underlying topic mixture of each document.</p><p>Let’s move on to the Spark part. First, we need to load the raw tweets we have collected. Here I used the Tweets in November as the training dataset and Tweets on December 1-2 as the test dataset.</p><pre>Total tweets in training dataset:<br>1,280,121<br>Total tweets in test dataset:<br>97,921</pre><p>Here is the code snippet for loading data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/258f6c00753cf562827d5b7310192522/href">https://medium.com/media/258f6c00753cf562827d5b7310192522/href</a></iframe><p>The following code snippet for text processing should give you some idea of how the Transformer transforms one DataFrame to another DataFrame (you can use chaining for concise syntax).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b572cf3b23ff24a725243ab9477819e0/href">https://medium.com/media/b572cf3b23ff24a725243ab9477819e0/href</a></iframe><p>Note that I used stemming instead of lemmatization for efficiency. Spark’s native library doesn’t provide Stemming and Lemmatization functionalities. A quick solution is to create your own user-defined functions (UDF). An alternative is to adopt <a href="https://nlp.johnsnowlabs.com/">Spark-NLK</a>. I also found that further removing trivial stemmed words helps for the LDA model. Then we build the ML pipeline to fit the LDA model. We use <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">TF-IDF</a> to build the features for LDA model training. It’s worth noting that the IDF step is very important, otherwise our model will be overwhelmed by the common words that occur too often in every tweet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/322272bd55cd6c1cf631bc63abeb9fef/href">https://medium.com/media/322272bd55cd6c1cf631bc63abeb9fef/href</a></iframe><p>Choosing the numbers of topics as 5, we got the underlying topics with the associated top words as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*vWtJDPAKzRRtNBmMhiLBQw.png" /><figcaption>Topic distribution of LDA model. (Image by Author)</figcaption></figure><p>The choice of numbers of topics (k) involves many nuances such as the prior information you have, or simple trial-and-error. The output topics should achieve your desired level of interpretability, while this is usually subjective and challenging. We can see Topic 1 associated with [neural, network, google], so it could be tweets about the latest research in machine learning and AI. For Topic 3, it could be marketing promotion on data science training. And Topic 4 seems like some big topic on human society with the development of machine learning and AI (it is also interesting to see the word “<em>health</em>”).</p><p>We saved the trained LDA model in S3, and use it to discover the underlying topics for the live tweets later. To enrich the data analysis, I also introduce the text sentiment as another dimension. This is achieved by simply including TextBlob in Spark Streaming which I will show you in the next section. Note that TextBlob sentiment is not considered as a machine learning approach since it simply determines the sentiment score <a href="https://planspace.org/20150607-textblob_sentiment/">by the average of the pre-defined score of each word in the text</a>.</p><h3>4. Spark Structured Streaming</h3><p>We will use <a href="https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html">Spark Structured Streaming</a> to process real-time data.</p><blockquote>Internally, by default, Structured Streaming queries are processed using a micro-batch processing engine, which processes data streams as a series of small batch jobs thereby achieving end-to-end latencies as low as 100 milliseconds and exactly-once fault-tolerance guarantees. (from <a href="http://Structured Streaming queries">Spark documentation</a>)</blockquote><p>Spark Structured Streaming provides a simple API interface for both batch and streaming workload, compared to <a href="https://spark.apache.org/docs/latest/streaming-programming-guide.html">Spark Streaming</a> which is powered by RDDs (strictly speaking, we are not dealing with real-time processing here since Spark processes streaming data on a micro-batch basis). Coding with Spark Structured Streaming is very easy; you just define the DataFrame from a streaming data source and the DataFrame operations are the same. The basic concept is to treat a stream as an unbounded, continuously appended table (check <a href="https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html">Spark documentation</a> for more details).</p><p>We will work in a Notebook environment (DataBricks Community Edition) to illustrate how this works, but eventually, a Spark Streaming will run in your machine (AWS EC2 or EMR) 24/7 in production for the (near) real-time processing purpose.</p><h4>4.1. Set up a Spark cluster on DataBricks</h4><p>First, create a cluster on DataBricks. Two additional steps may require:</p><ul><li>Install the Python libraries if needed. In my case, I installed <a href="https://www.nltk.org/">NLTK</a> for stemming, and TextBlob for naive sentiment analysis.</li><li>Mount the AWS S3 bucket to dbfs file system, so that we can load our pre-trained Spark model and save the streaming processed data into S3 as our destination.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*BfTMMNIMFSIGe64CyayG3A.png" /><figcaption>Screenshot: creating a cluter on Databricks. (Image by Author)</figcaption></figure><h4>4.2. Set up Spark Streaming</h4><p>The syntax is almost the same as we read the DataFrame, but now we use “<em>readStream</em>”. Note that:</p><ul><li>Kinesis Data Stream is the <strong>source</strong> for our Spark Streaming, which has been set up in Section 2.</li><li>We configure the “intialPosition” as “latest”, which means the streaming reads starting from <a href="https://docs.aws.amazon.com/streams/latest/dev/developing-consumers-with-sdk.html">the most recently added record</a>. You may switch to “TrimHorizon” so it will start from the oldest record available (in our case, it’s 1 day since the retention period is 24 hours for Kinesis Data Stream).</li></ul><p>Refer to the <a href="https://docs.databricks.com/spark/latest/structured-streaming/kinesis.html">DataBricks documentation</a> for more details on Kiensis for Structured Streaming.</p><pre>kinesisStreamName = &quot;twitter-data-kinesis&quot; <br>kinesisRegion = &quot;us-east-1&quot;</pre><pre>awsAccessKeyId = &quot;your_awsAccessKeyId&quot;<br>awsSecretKey = &quot;your_awsSecretKey&quot;</pre><pre>kinesisDF = (spark<br>            .readStream<br>            .format(&quot;kinesis&quot;)<br>            .option(&quot;streamName&quot;, kinesisStreamName)<br>            .option(&quot;region&quot;, kinesisRegion)<br>            .option(&quot;awsAccessKey&quot;, awsAccessKeyId)<br>            .option(&quot;awsSecretKey&quot;, awsSecretKey)<br>            .option(&quot;initialPosition&quot;, &quot;latest&quot;)<br>            .option(&quot;format&quot;, &quot;json&quot;)<br>            .option(&quot;inferSchema&quot;, &quot;true&quot;)<br>            .load())</pre><p>The KinesisDF will be a streaming DataFrame, with the schema as follows:</p><pre>DataFrame[partitionKey: string, data: binary, stream: string, shardId: string, sequenceNumber: string, approximateArrivalTimestamp: timestamp]</pre><p>The data of the live tweets are in the “data” field, so we need to first parse it to the schema we defined before (i.e., the way you collect the tweet data in the Tweepy Streaming), and then we can process the data and use the Spark LDA model to find the underlying topics for every tweet. The code snippet is as follows and you can find the <a href="https://github.com/Chancylin/twitter_data_analysis/blob/master/notebook/spark_streaming_write_to_S3_clean.ipynb">notebook</a> here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4178b19734c40de6bab92b60c94d5c2/href">https://medium.com/media/b4178b19734c40de6bab92b60c94d5c2/href</a></iframe><p>Let’s check the schema of the result DataFrame:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*Sc2rXYCmH8JFmot-IbFBCA.png" /><figcaption>Schema of the result DataFrame. (Image by Author)</figcaption></figure><p>We will write the result DataFrame to an <strong>output sink</strong>. It could be a DataBase in AWS RedShift, or an AWS ElasticSearch. Here we choose S3 as the output sink.</p><pre>outputPath = &quot;your_S3_location_to_save_spark_streaming_result&quot;<br>ckp_location = &quot;your_S3_location_to_save_spark_streamingcheckpoint&quot;</pre><pre>query = (df_with_topics_sentiment<br>         .writeStream<br>         .outputMode(&quot;append&quot;)<br>         .format(&quot;csv&quot;)<br>         .option(&quot;sep&quot;, &quot;\t&quot;)<br>         .trigger(processingTime=&quot;15 minutes&quot;)<br>         .start(path=outputPath, checkpointLocation=ckp_location))</pre><pre>query.awaitTermination()</pre><p>This code snippet will start the query and write the result DataFrame to the desire S3 bucket. Note that:</p><ul><li>“Append” mode is used because we simply add new rows to the result DataFrame (i.e. stateless transformation on DataFrame). Choosing <em>append/complete/update mode</em> depends on the logic of your data processing.</li><li>We trigger the process every 15 minutes. There are <a href="https://spark.apache.org/docs/latest/structured-streaming-programming-guide.html#triggers">other options</a> to meet a more real-time need, but here our data input rate is not very high so let’s stick to an interval of 15 minutes for a demo purpose.</li></ul><p>After a while, we will see the output data show up in the S3 bucket, cool! Now with the data (which keeps increasing in real-time), let’s move to the analysis step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9M5x-jKkPSw7MRLacpK6g.png" /><figcaption>Spark streaming output in AWS S3. (Image by Author)</figcaption></figure><h3>5. AWS Athena for Data Analysis</h3><p>Definition from <a href="https://aws.amazon.com/athena/?nc=sn&amp;loc=1&amp;whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc">AWS documentation</a> for Athena is as follows. Although it makes more sense to have a DataBase in production, we use Athena which is <strong>serverless</strong> to access data in S3, so we can save the cost by avoiding spinning up a cloud database service such as <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/welcome.html">AWS RedShift</a>.</p><blockquote>Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run.</blockquote><blockquote>Athena is easy to use. Simply point to your data in Amazon S3, define the schema, and start querying using standard SQL. Most results are delivered within seconds. With Athena, there’s no need for complex ETL jobs to prepare your data for analysis. This makes it easy for anyone with SQL skills to quickly analyze large-scale datasets. (from <a href="https://aws.amazon.com/athena/?nc=sn&amp;loc=1&amp;whats-new-cards.sort-by=item.additionalFields.postDateTime&amp;whats-new-cards.sort-order=desc">Amazon documentation</a>)</blockquote><p>Log in to the AWS console and go to the Athena service. We first need to create a Table which connects to the data in S3. The procedure is quite straightforward. Note that you need to provide the schema for the table because the raw data stored in the S3 bucket is schemaless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*P560L8spj948xkwoh1ezYQ.png" /><figcaption>Create database in Athena. (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2U4YnANnhzr5z_8LwbmMDg.png" /><figcaption>Create database in Athena, connecting to S3. (Image by Author)</figcaption></figure><p>After creating the table, now you can write the query in the Query editor to do the analysis. For example. show some samples of the tweets and their associated topics and sentiment results:</p><pre>SELECT tweet_text_processed, topic_1, topic_2, topic_3, topic_4, topic_5, sentiment FROM &quot;twitterdb3&quot;.&quot;twitter_data_analysis&quot;  where sentiment is not null limit 20;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-jlDxZh4tJR_A8VqxTDVw.png" /><figcaption>Sample tweets (Image by Author)</figcaption></figure><p>Check how the topics distributed on the live tweets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_gExOrRpmj9fuTbZfZA4A.png" /><figcaption>Topic distribution on the live tweets. (Image by Author)</figcaption></figure><p>Run some more complicated query to get the aggregation information: count the number of tweets in different topics grouped by sentiment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CcShpZKLb1i8xn3QYdH5fg.png" /><figcaption>Number of tweets in different topics grouped by sentiment. (Image by Author)</figcaption></figure><p>Note that Spark Streaming writes new data into the S3 bucket every 15 minutes, so when you run the query again later, you will get the latest result.</p><h3>6. AWS QuickSight for Visualization</h3><p>Being able to run the query on the data streaming is nice but not enough, because you will find data visualization is always necessary to provide more insight, particularly in the business. Here we will use <a href="https://docs.aws.amazon.com/quicksight/latest/user/welcome.html">QuickSight</a> as a handy tool that can <a href="https://docs.aws.amazon.com/quicksight/latest/user/create-a-data-set-athena.html">connect to Athena</a> directly. And the in-memory engine, SPICE can make the real-time analysis very efficient.</p><p>Go to the Datasets Tab and create your “dataset” choosing the existing data source in Anetha (see <a href="https://docs.aws.amazon.com/quicksight/latest/user/create-a-data-set-athena.html">documentation</a>). Here I had one extra step since I wanted to create a new field “sentiment_type” from the sentiment score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*J6Rkp9CJigatNNEEM2sJeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*q659XO_Cfsr7NXmvUNlHgQ.png" /><figcaption>Create Table by connecting to Athena. (Image by Author)</figcaption></figure><p>With the dataset, now you can play with Visual Types to create the desired analysis. Some examples for our tweets analysis are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*DHcEaVos4oomK-qOzlczeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*XsrNla8xl8Jyz4BMvFHwOw.png" /><figcaption>Left: Sentiment distribution. Right: topic distribution grouped by sentiment. (Image by Author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*cb6kRbEH43wLeOfpAdvz8g.png" /><figcaption>Summary table of topics counts. (Image by Author)</figcaption></figure><p>Another nice feature is you can schedule the refresh, so the analysis results can be updated automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*AYOMLwujPlcDDBvWnHYoEw.png" /><figcaption>Schedule a refresh in QuickSight. (Image by Author)</figcaption></figure><h3>7. What Is Next</h3><p>I glad you reach this point of reading. The post is much longer than I expected when I started writing. We began with creating our Tweepy Streaming, and used the big data tools for data processing, machine learning model training and streaming processing, then build a real-time dashboard. We had a quick dive into some important concepts in Spark, Streaming. We got a sense of how to build the data architecture for a streaming application. But there are many other important aspects that we can further explore.</p><h4>Data Drift and Model Retrain</h4><p>There will be data drift or model performance degradation in the real world, so we need to update our model as time goes by. In most of the use cases, we don’t need the ML model to be updated very frequently. Here, for example, retraining our LDA model monthly will be reasonable. The other extreme case is we want to update the model in real time, which is a very challenging task in practice (<a href="https://spark.apache.org/docs/latest/streaming-programming-guide.html#mllib-operations">Spark supports Streaming Linear Regression and Streaming KMeans</a>). And the latency will be a problem. A more common scenario is batch retraining, and the model retraining can be scheduled periodically or be triggered when drift is detected. This falls into the topic of AutoML and you will find <a href="https://www.tutorialspoint.com/kubernetes/index.htm">Kubernetes</a> very useful. See a great <a href="https://mlinproduction.com/model-retraining/">post</a> on this topic.</p><h4>Real-Time Scoring</h4><p>In this post, we use Spark Streaming to get a balance between throughput and latency. It’s barely near real-time. The Spark framework cannot meet the low latency requirement for real-time scoring because of the mini-batch processing.</p><p>However, the question here is: do we really need such low latency? The answer is no. The tweet analysis application we built is not latency-critical, so we can roll it back to the Batch mode and score the new data, let say every 3 hours. Then we need to reflect on this and change our pipeline architecture accordingly. For example,</p><ul><li>we don’t need Spark Streaming, which means we can use Kinesis Firehose to put the records from Tweepy Streaming into S3 directly, instead of using Kinesis Data Stream.</li><li>Now we use Spark for batch processing every 3 hours. This is good because we don’t need to keep the Spark cluster running which could be costly. We can run the Spark cluster periodically for batch processing. Then <a href="https://airflow.apache.org/docs/apache-airflow/stable/index.html">Airflow</a> will fit our needs here. We can write the script to schedule our workflow: set up an AWS EMR, run the Spark job for the new data, save the result into S3, then shut down the EMR cluster.</li></ul><p>Airflow will be the magic to orchestrate the big data pipeline. I will write a post on it following our example here. So please stay tuned!</p><h4>Other Thoughts</h4><p>There are more to discuss regarding different components in our data architecture. At the end of the day, you have to choose what fits your best depending on the use case. For example, you may find a database is necessary in production instead of using Athena to run ad-hoc queries. Therefore, we can use AWS RedShift as a data warehouse, then leverage Tableau/SuperSet as more powerful data visualization tools rather than QucikSight. Another possible scenario is loading the streaming data into AWS ElasticSearch if your application requires heavy text analysis.</p><h3>8. A Closing Note</h3><p>Big Data tools and Cloud Computing are exciting but can also be intimidating for beginners. I hope you have found this post shed some light on this topic. Thanks for your time! I am interested in discussing best practices in Machine Learning. Feel free to leave your comments and thoughts.</p><p>P.S., I have cited many definitions for AWS and Spark from online documentation. Please kindly let me know if you think any of your work is not properly cited.</p><h4>Resources and References:</h4><p>[1] <a href="https://www.oreilly.com/library/view/learning-spark-2nd/9781492050032/">Learning Spark, 2nd Edition</a>.</p><p>[2] Post: <a href="https://sujithjay.com/spark/with-yarn#:~:text=YARN%20is%20a%20generic%20resource,Spark)%20in%20addition%20to%20MapReduce.">Understanding Apache Spark on YARN</a>.</p><p>[3]Post: <a href="https://spoddutur.github.io/spark-notes/distribution_of_executors_cores_and_memory_for_spark_application.html">Distribution of Executors, Cores and Memory for a Spark Application running in Yarn</a>.</p><p>[4] Blei, D. M., Ng, A. Y., &amp; Jordan, M. I. (2003). <a href="https://www.jmlr.org/papers/v3/blei03a">Latent Dirichlet Allocation</a>. Journal of Machine Learning Research, 3(Jan), 993–1022.</p><p>[5] <a href="https://github.com/Chancylin/twitter_data_analysis">GitHub Code Repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd2240946e64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-build-a-real-time-twitter-analysis-using-big-data-tools-dd2240946e64">How to Build a Real-Time Twitter Analysis Using Big Data Tools</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[Use SHAP loss values to debug/monitor your model]]></title>
            <link>https://medium.com/data-science/use-shap-loss-values-to-debug-monitor-your-model-83f7808af40f?source=rss-890a7b9564d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f7808af40f</guid>
            <category><![CDATA[shap]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Chuangxin Lin]]></dc:creator>
            <pubDate>Mon, 22 Jun 2020 00:35:46 GMT</pubDate>
            <atom:updated>2020-06-23T22:54:48.355Z</atom:updated>
            <content:encoded><![CDATA[<h4>How you should understand the SHAP loss value and use it</h4><p>Responsible AI has been a very hot topic in recent years. Accountability and explainability now become the necessary components of your machine learning models, particularly when the models make decisions that will impact people’s life, such as medical diagnostic, financial service. This is a very large topic for machine learning and a lot of ongoing work has been dedicated to various aspects. You can check more resources on this topic[1]. In this post, I will focus on <a href="https://github.com/slundberg/shap">SHAP</a> (SHapley Additive exPlanations), which is one of the most popular explainability packages, due to its versatile (local/global explainability; model-specific/agnostic) and the solid theoretical foundation from game theory. You can find many posts and tutorials to understand how SHAP can help you understand how your ML model works, i.e., how each of your features contributes to the model prediction. However, in this post, I will talk about SHAP loss values that many people may be less familiar with. I will walk through some key concepts by presenting an example. I will also share some of my thoughts.</p><p>To begin with, you may want to check the <a href="https://github.com/slundberg/shap/blob/master/notebooks/tree_explainer/Explaining%20the%20Loss%20of%20a%20Model.ipynb">example</a> provided by SHAP package. And there are two important notes:</p><ul><li>The shap loss values will show you how each feature contributes to the logloss value from the expected value. Note, in this post, when I say loss value, it refers to logloss, since we will look at the classification problem)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRVvBOloozyUQvxUm5HIXQ.png" /><figcaption>Just like the SHAP values for prediction, the SHAP loss values represent how each feature contributes to the logloss. The expected value is the baseline value which depends on the label. The expected value is calculated by setting the labels of all instance to True when a data instance is True (setting to False when a data instance is False)</figcaption></figure><ul><li>You should use “interventional” method for the calculation of SHAP loss values</li></ul><p>Essentially, this means when integrating out the absent features, you should use the marginal distribution instead of the conditional distribution. And the way to achieve the marginal distribution is to assign the absent features with the values from the background dataset.</p><p>The use of “interventional” (i.e., marginal distribution) or “tree_path_dependent” (i.e., conditional distribution) is an important nuance (see <a href="https://github.com/slundberg/shap/blob/fc30c661339e89e0132f5f89e5385e3681090e1f/shap/explainers/tree.py#L39">docstring</a> in SHAP package) and it’s worth further discussion. But I don’t want to confuse you in the very beginning. You just need to know that in the common practice, TreeShap calculates shap values very fast because it takes advantage of the conditional distribution from the tree structure of the model, but the use of conditional distribution can introduce the problem of causality[2].</p><h3>Train an XGBoost Classifier</h3><p>The example in this post is modified from <a href="https://github.com/slundberg/shap/blob/master/notebooks/tree_explainer/Census%20income%20classification%20with%20XGBoost.ipynb">the tutorial example</a> in SHAP package and you can find the full code and notebook <a href="https://github.com/Chancylin/shap_loss">here</a>. I first trained an XGBoost classifier. The <a href="https://archive.ics.uci.edu/ml/datasets/adult">dataset</a> uses 12 features to predict if a person makes over 50K a year.</p><pre>[&#39;Age&#39;, &#39;Workclass&#39;, &#39;Education-Num&#39;, &#39;Marital Status&#39;, &#39;Occupation&#39;, &#39;Relationship&#39;, &#39;Race&#39;, &#39;Sex&#39;, &#39;Capital Gain&#39;, &#39;Capital Loss&#39;, &#39;Hours per week&#39;, &#39;Country&#39;]</pre><p>You can use the SHAP package to calculate the shap values. The force plot will give you the local explainability to understand how the features contribute to the <strong>model prediction</strong> for an instance of interest (Fig. 1). The summary plot will give the global explainability (Fig. 2). You can check Part 1 in the Jupyter Notebook. There is nothing new but just the common use of SHAP, so I will leave the details to you and jump to Part 2,<strong> shap values for the model loss</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E20JclnUiDHpdVgGAmtoAg.png" /><figcaption>Fig. 1. Force plot shows how each feature contributes to pushing the model output from the base value to the model output. Note the output is in log odds ratio space.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMFNZo1qlL0DHMIezllmYw.png" /><figcaption>Fig. 2. SHAP summary plot gives the global explainability. A feature with a large magnitude means it has a more important impact on the prediction.</figcaption></figure><h3>Explain the Log-Loss of the Model</h3><p>Now the contribution to the model loss is more of interest, so we need to calculate shap loss values. In some sense, this is similar to residual analysis. The code snippet is as follows. Note that you need to</p><ul><li>provide a background data since we use “interventional” approach. And the computational cost could be expensive. So you should provide a background data of a reasonable size (here I use 100).</li><li>Now the model_output is “log_loss”.</li></ul><pre># subsample to provide the background data (stratified by the target variable)</pre><pre>X_subsample = subsample_data(X, y)</pre><pre>explainer_bg_100 = shap.TreeExplainer(model, X_subsample, <br>                                feature_perturbation=&quot;interventional&quot;, <br>                                      model_output=&quot;log_loss&quot;)</pre><pre>shap_values_logloss_all = explainer_bg_100.shap_values(X, y)</pre><p><strong>Force Plot</strong></p><p>Now the fore plot for a data instance has a similar interpretation as that in Fig. 2, but in terms of log loss instead of prediction. A successful prediction (ground truth as True and prediction as True) is given in Fig. 3, while a wrong prediction (ground truth as True and prediction as False) in Fig. 4. You can see how the features with blue color try to reduce the logloss from the base value, and the reds increase the logloss. It’s noteworthy that the base values (expected values) of the model loss depend on the label (True/False) so it is a function instead of a single number. The calculation of expected values is by first setting all the data labels to True (or False), and then calculate the average log loss, for which you can check more details on the notebook. I am not sure if there is a particular reason for such a calculation of base values, but after all, the base values just serve as a reference value so I think it should not matter very much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM8jOFgk1i_BE3PCAFGH3g.png" /><figcaption>Fig. 3. Force plot for a data instance, ground truth is True and mode predicts True.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3rlLkl2ez2AdRgnhV5xtQ.png" /><figcaption>Fig. 4. Force plot for a data instance, ground truth is True and mode predicts False.</figcaption></figure><p><strong>Summary Plot</strong></p><p>Similarly, we have the summary plot for the model logloss (Fig. 5). This will tell you how the features contribute to the model logloss (the calculation is based on absolute mean). A feature with a large contribution means it contributes a lot to the model loss, could be increasing the logloss for some data instance or reducing the logloss for other data instances. Therefore, the summary plot here should show the consistency with the top features by shap values in Fig. 2. But we can see the ranking orders are a bit different. While “Relationship” remains the top one, the order of “Age”, “Education-Num”, “Capital Gain”, “Hours per week”, “Occupation” is different. And “Capital Gain” in Fig. 5 has a relatively large contribution than it does in Fig. 2. This suggests that “Capital Gain” plays an important role in reducing the log loss while relatively speaking it may not be that important for the model to make the prediction compared to “Relationship”. It’s noteworthy that the summary plot in Fig. 5 should be interpreted with cautions, since the bar plot in Fig. 5 is calculated based on absolute mean, which means both the effect of reducing logloss and increasing logloss are taken into account to rank the importance of a feature. In plain language, a large magnitude of (absolute) contribution may not necessarily mean a feature is a “good” feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFAg1aRBHj07ywoRuk9iBA.png" /><figcaption>Fig. 5. Similar to Fig. 2, but based on model logloss.</figcaption></figure><p>Of course, you can use the scatter summary plot instead of the bar summary plot to see the detailed distribution to dive deeper for your model debugging (i.e., improve your model performance). The other way I investigate it is to decompose the shap loss values into negative component (Fig. 6) and positive component (Fig. 7). And in terms of the model debugging, you want to achieve a more negative value and reduce the positive value for all the features since you wish all the features reduce the final model logloss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*6ZABoTMU_fujUJKDqnuUxA.png" /><figcaption>Fig. 6. Sum of all the negative shap loss values for each feature.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*8hqE6t9bNR43SE49Py7szQ.png" /><figcaption>Fig. 7. Sum of all the positive shap loss values for each feature.</figcaption></figure><h4>Monitoring plot</h4><p>Now we come to the most interesting part: use the shap loss value to monitor your model. Model drift and data drift are real-world problems that your model deteriorates and leads to unreliable/inaccurate predictions. But these usually happen silently, and it is very hard to identify the root cause. In a recent paper[3] by the SHAP author, they use the shap loss values to monitor the model health. The idea is very appealing and I wish to explore more on that. Note that the <a href="https://github.com/slundberg/shap/blob/master/shap/plots/monitoring.py">API</a> is available but seems under ongoing development.</p><p>First we need to calculate the shap loss values for the training data and test data. In the context of monitoring, you need to calculate the shap loss values for dataset from different time-snapshot. You may recall that we have done this in the beginning of this section. But note that we use the background data sampled from the entire dataset. For the rationale of monitoring, it makes more sense to calculate the shap loss values for the training dataset and the test dataset separately, by using the background data from the training dataset and the test dataset. The code snippets are as follows:</p><pre># shap loss values for training data<br>X_train_subsample = subsample_data(X=X_train, y=y_train)</pre><pre>explainer_train_bg_100 = shap.TreeExplainer(model, X_train_subsample, <br>                                            feature_perturbation=&quot;interventional&quot;, model_output=&quot;log_loss&quot;)</pre><pre>shap_values_logloss_train = explainer_train_bg_100.shap_values(X_train, y_train)</pre><pre># shap loss values for test data<br>X_test_subsample = subsample_data(X=X_test, y=y_test)</pre><pre>explainer_test_bg_100 = shap.TreeExplainer(model, X_test_subsample, <br>                                           feature_perturbation=&quot;interventional&quot;, model_output=&quot;log_loss&quot;)</pre><pre>shap_values_logloss_test = explainer_test_bg_100.shap_values(X_test, y_test)</pre><p>The monitoring plots for the top features are shown in Fig. 8. First all the data instances will be ordered by the index. And here we assume the index indicates the evolution of time (from left to right along the axis). In this toy example, we don’t have data from different time snapshot so we simply treat the training data as the current data and the test data as the future data we would like to monitor.</p><p>There are some important points to understand these monitoring plots, based on the current implementation in the SHAP pakcage. In order to see if the shap loss values are time-consistent, t-test will be repeatedly conducted to compare two data samples. The current implementation uses an increment of 50 data points to split the data. That means, the first t-test will compare data[0: 50] to data[50:]; and the second will compare data[0: 100] to data[100:], and so on. The t-test will fail if the p value is smaller than 0.05/n_features. In other words, it uses the confidence level of 95% and Bonferroni correction has been applied. Where the t-test fails, a vertical dash line will be plotted to indicate the location. A bit surprising, we see the monitoring plots show the inconsistency of shap loss values for [“Relationship”, “Education-Num”, “Capital Gain”], and that happens when we enter the time snapshot of test data (Fig. 8).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*YMoH7FK_c5Nus2ApQj8RpA.png" /><figcaption>Fig. 8. Monitoring plots for top features. The training dataset and test dataset are concatenated to mimic data from different time snapshots. Note that the test data starts from index 26047.</figcaption></figure><p>The reason for the use of an increment of 50 data points is not very clear to me. And in this example, since we know [0:26048] is the training data, and [-6513:] is the test data. I modified the increment to 6500 and see if it will give a different result. But the monitoring plots still show the same inconsistency (i.e., the failure of t-test) when it comes to comparing the test data (Fig. 9).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*E0BA3OD2t6bgqAnPQ-ff6w.png" /><figcaption>Fig. 9. Monitoring plots for top features. Similar to Fig. 8 but now we use the increment of 6500 data points. The purpose is to compare the test data to the last “time segment” of the training data directly.</figcaption></figure><p>Finally, I think it’s a good idea to check the t-test on the training data and test data directly. And this verifies the conclusion again, the shap loss values are inconsistent between the training dataset and the test dataset.</p><pre># t-test for top features (assume equal variance)<br>t-test for feature:  Relationship , p value:  2.9102249320497517e-06<br>t-test for feature:  Age , p value:  0.22246187841821208<br>t-test for feature:  Education-Num , p value:  4.169244713493427e-06<br>t-test for feature:  Capital Gain , p value:  1.0471308847541212e-27</pre><pre># t-test for top features (unequal variance, i.e., Welch’s t-test,)<br>t-test for feature:  Relationship , p value:  1.427849321056383e-05<br>t-test for feature:  Age , p value:  0.2367209506867293<br>t-test for feature:  Education-Num , p value:  3.3161498092593535e-06<br>t-test for feature:  Capital Gain , p value:  1.697971581168647e-24</pre><p>The inconsistency of shap loss values between training data and test data is actually very unexpected, and can be troublesome. Remember that we simply use training/test split from the entire dataset, so there is a good reason to believe that training dataset and test dataset should be consistent, in terms of data distribution or shap loss values contribution. By any means, this is just a simple experiment and more investigations should be performed to draw any firm conclusion. But I think there may be some reasons why the SHAP package indicates the monitoring functionality is just preliminary, for example:</p><ul><li>the use of an increment of 50 data points looks arbitrary to me;</li><li>the t-test looks very sensitive and can give many false alarms.</li></ul><p>Another interesting discussion point is the use of background data. Note that for the monitoring plots, the shap loss values on the training dataset and the test dataset are calculated using different background data (subsamples from training dataset/test dataset). Since the “interventional” approach to calculate shap loss values is very expensive, I only tried the subsamples data of a size of 100 data instances. That could yield a high-variance result of the shap loss values. Perhaps a background data of a large size will reduce the variance and give the consistency of shap loss values in the monitoring plots. And when I used the same background data (subsamples from the entire dataset), there will not be inconsistency in the monitoring plot. So how you choose the background data matters a lot!</p><h3>Conclusions and Discussions</h3><p>I hope this post can give you a useful introduction to the shap loss values. You can better debug your ML models by investigating the shap loss values. It can also be a useful approach to monitoring your ML models for model drift and data drift, which is still a very big challenge in the community. But note the limitation: in order to use the shap loss values for monitoring, you need to have the ground truth for the new coming data, which is usually only available after a certain period. Also, unfortunately this functionality is still under development, and the appropriateness of the use of t-test needs to be further justified.</p><p>Last but not least, calculating shap values (TreeShap) by marginal distribution or conditional distribution can give different results (see the equations). The use of conditional distribution will introduce the problem of causality, while marginal distribution will provide unlikely data points to the model[4]. There seems no consensus about which one to use, depending on what scenarios[2,5]. This paper[6] has some interesting comments on this topic which I would like to quote here:</p><blockquote>In general, whether or not users should present their models with inputs that don’t belong to the original training distribution is a subject of ongoing debate.</blockquote><blockquote>….</blockquote><blockquote>This problem fits into a larger discussion about whether or not your attribution method should be “true to the model” or “true to the data” which has been discussed in several recent articles.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujL32eGCxAOtwA2tlM2Ilw.png" /><figcaption>llustration of the use of marginal distribution and conditional distribution to integrate out missing values (i.e., absent features). Here X1 is presented feature and X2, X3 are absent features. Reproduced from [2].</figcaption></figure><p>Thank you for your time. And don’t hesitate to leave any comments and discussions!</p><p>All the plots in this post are created by the author by using the SHAP package. Please kindly let me know if you think any of your work is not properly cited.</p><p>[1] <a href="https://jphall663.github.io/GWU_rml/">Introduction to Responsible Machine Learning</a></p><p>[2] Janzing, D., Minorics, L., &amp; Blöbaum, P. (2019). Feature relevance quantification in explainable AI: A causality problem. <a href="https://arxiv.org/abs/1910.13413">https://arxiv.org/abs/1910.13413</a></p><p>[3] Lundberg, S.M., Erion, G., Chen, H., DeGrave, A., Prutkin, J.M., Nair, B., Katz, R., Himmelfarb, J., Bansal, N. and Lee, S.I. (2020). From local explanations to global understanding with explainable AI for trees. <em>Nature machine intelligence</em>, <em>2</em>(1), 2522–5839.</p><p>[4] <a href="https://christophm.github.io/interpretable-ml-book/shap.html">https://christophm.github.io/interpretable-ml-book/shap.html</a></p><p>[5] Sundararajan, M., &amp; Najmi, A. (2019). The many Shapley values for model explanation. <a href="https://arxiv.org/abs/1908.08474"><em>arXiv preprint arXiv:1908.08474</em></a>.</p><p>[6] Sturmfels, P., Lundberg, S., &amp; Lee, S. I. (2020). <a href="https://distill.pub/2020/attribution-baselines/">Visualizing the impact of feature attribution baselines</a>. <em>Distill</em>, <em>5</em>(1), e22.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f7808af40f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/use-shap-loss-values-to-debug-monitor-your-model-83f7808af40f">Use SHAP loss values to debug/monitor your model</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>