<?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 Lucas Correa on Medium]]></title>
        <description><![CDATA[Stories by Lucas Correa on Medium]]></description>
        <link>https://medium.com/@lukec-correa?source=rss-f868b483e3a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4xt7-LOqaznIipp1H-yPvg.jpeg</url>
            <title>Stories by Lucas Correa on Medium</title>
            <link>https://medium.com/@lukec-correa?source=rss-f868b483e3a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:38:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lukec-correa/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[Predicting Churn with user log data from a digital music streaming app]]></title>
            <link>https://medium.com/data-science/predicting-churn-with-user-log-data-from-a-digital-music-streaming-app-7c30d7206daf?source=rss-f868b483e3a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c30d7206daf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <dc:creator><![CDATA[Lucas Correa]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 04:47:21 GMT</pubDate>
            <atom:updated>2020-11-11T03:53:21.674Z</atom:updated>
            <content:encoded><![CDATA[<h4>What should you consider when you don&#39;t know how to start</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6VIU_lFdUPgIuxyaKtYVg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mantashesthaven">@mantashesthaven</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Predicting Churn is one of the most interesting things a company could do in order to better understand clients and anticipate changes in revenue. In this post, I will use the data from a digital music streaming platform called Sparkfy to explain how to create a machine learning model that predicts the users churn.</p><p>In this post we are going to discuss how this dataset is organized and what can we do in order to define churn for this problem. After having a business understanding, I will walk through ways to find features that help us better identifying churned users. Further, I will use these features to build some basic models that should predict whether a user is going to churn. Finally, I will use some evaluation metrics to help me pick the best model and parameters for predicting.</p><p>At the end of these steps, we will have a machine learning model that receives information about user activity and says who are the ones more likely to leave the platform.</p><p>First things first, it is important to explain how this company works. Sparkify is basically like Spotify, it has free and premium accounts. The free accounts show advertisements from time to time and the premiums one don&#39;t. The main goal here is to predict which users are going to stop using Sparkfy streaming services, regardless of its account type.</p><p>The following database was provided by Udacity in its nano degree for Data Scientists and represent the logs of every interaction a user had within the platform. The full dataset has a 12GB size and that is why the code for this post was written in pyspark. This way I could write a basic code with a smaller subset of the data (124MB) and then scale up to a cluster. For this post, I will use the small subset as an example of each step.</p><h3>1. Data Understanding and Cleaning</h3><p>Getting the first line of the dataset provides us with a preview of what to expect in each field of a log. Columns like <em>artist</em>, <em>firstname</em>, <em>gender</em> are pretty straightforward to understand what it is. It also has some identifications fields like <em>itemSession</em>, sessionId, and userId that we should keep in mind when we operate some aggregation functions. For this id&#39;s, It is important to say that every user has its own Id and every time he login the user starts a session, where every interaction is an item in that session until he logs off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULNOdi8t5qg8qC-6rRp4dw.png" /></figure><p>Other important columns are <em>ts</em> which stands for the timestamp of the log, <em>registration </em>that represents the timestamp of when the user registered his account, and page which is basically what is that interaction. Below are some of the possible pages in the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*TMYNOM3esgI7ILOGSMXxnA.png" /></figure><p>After understanding what each element of your database means, you can now start looking for some errors or unwanted registers. I started checking for rows with no Id&#39;s and end up finding that there are some registers from guests users, which is described in the <em>auth </em>column. This is not in our interest since we could not predict churn for non-clients.</p><pre>user_log = user_log.filter(~user_log.auth.isin([‘Guest’,’Logged Out’]))</pre><p>A second step that could help a lot in the future analyzes is to convert the <em>ts </em>and<em> registration </em>columns into date-time formats so we can read date and time information and perform some date operations.</p><pre>get_date = udf(lambda x: dt.fromtimestamp(x / 1000.0).strftime(“%d/%m/%Y”) )</pre><pre>user_log = user_log.withColumn(“date”, to_date(get_date(user_log.ts),’dd/mm/yyyy’))</pre><pre>user_log = user_log.withColumn(&quot;RegistrationDate&quot;, to_date(get_date(user_log.registration),&#39;dd/mm/yyyy&#39;))</pre><p>The log base doesn’t seem too messy to demand a lot of cleaning and for that reason, these two steps may be enough for now. Usually, many of the cleaning steps appear after we put some effort into the next steps.</p><h3>2. Define Churn</h3><p>Defining what is churn for the experiment is crucial. In this example, churn will be defined as the users who visited the page <em>Cancellation Confirmation. </em>This page appears when a user clicks on this cancellation option and finished the operation by confirming it. This page could be accessed by both paid and free accounts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c21f1d5119b3ae940d8a01efd422e30/href">https://medium.com/media/0c21f1d5119b3ae940d8a01efd422e30/href</a></iframe><p>The churn definition could suit your predictions goal. For instance, you may be interested in keep users in a paid account and for this, your churn definition would-be users that have access to the <em>Submit Downgrade </em>page. This definition should follow a clear change of behavior that you can measure and wants to avoid.</p><h3>3. Exploratory Data Analysis (EDA)</h3><p>After defining churn it is time to work on a preliminary hypothesis for the event. Exploring the data gives you the opportunity to find and test some patterns as well as discover some new uncleaned parts of the data. A good start is showing up some basic statistics about the base.</p><p>The small subset has 225 unique users Id&#39;s where 52 of them are Canceled ones. Just with these basic stats, we can see that our data is imbalanced, that is, it has considerably more of one type of label. In this case, 23% of all users have churned users and 77% are not. This kind of data brings some problems in building the model that we are going to discuss further.</p><p>Thinking a little bit about the problem, I come up with some hypothesis of what could influence user churn:</p><ul><li>Churned users have fewer Items in Sessions</li><li>Churned users have lower Song Variety</li><li>Churned users listen to fewer Songs</li><li>Churned users interact less with friends</li><li>Churned users have fewer Sessions in the last month of usage</li></ul><p>To see if this is a good hypothesis, I started to get some simple aggregations around each label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b19dcdb74e933db844841cba674812/href">https://medium.com/media/96b19dcdb74e933db844841cba674812/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4ebbA_3CwnP3EgoalrOSg.png" /><figcaption>Aggregation by canceled users and active users. Cancelled = 1 means churned and 0, active</figcaption></figure><p>The table above shows a small difference in items per session, distinct songs listened and total songs played. This gives a direction about the first three hypotheses, but one could say an active user has more time in the platform and therefore more time to increase all the numbers for these stats.</p><p>Exploring user interactions, we could see that churned users have fewer friends added and pretty much less <em>Thumbs Up </em>in their songs. Despite <em>Thumbs Down </em>doesn&#39;t show too much difference, on average, the number of interactions a user has seems to have a strong difference in the user choice of churn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b0f64d8c7583d042e3590f0c736352a/href">https://medium.com/media/3b0f64d8c7583d042e3590f0c736352a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*9GGkOYR_Akq3rzj-OEuFww.png" /><figcaption>Cancelled = 1 means churned and 0, active</figcaption></figure><p>Finally as mentioned before, one could question the time that churned users stayed in the platform. For this reason, the next table considers the number of sessions in the last 30 days. Apparently, it doesn&#39;t show too much of a difference like before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc4163621f02deba4b1e6e82cb21c85/href">https://medium.com/media/9fc4163621f02deba4b1e6e82cb21c85/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*INOOZuJr-k0bXAYpkuK76g.png" /><figcaption>Sessions in the last 30 days. Cancelled = 1 means churned and 0, active</figcaption></figure><h3>4. Feature Engineering</h3><p>After playing around with some ideas, you should pick the ones you have the most expectations based on the EDA. After some consideration, I end up with the following features:</p><ul><li><strong>AvgSongsPlayes</strong>: Average songs played by each user. It is expected that users who canceled their account have less engagement in the platform, therefore less played songs</li><li><strong>LikedSongsProportion</strong>: The ratio of disliked songs for liked songs by each user id. If the user dislikes the songs of the platform, it is expected him to leave</li><li><strong>FriendsAdded</strong>: How many times a user pressed the Add Friend Button. Users that engage more with others tend to stay longer on the platform</li><li><strong>DaysInPremium</strong>: How many days a user is with the premium account. This feature was created to control landmarks in users&#39; accounts life. Probably users behave in different manners according to how much time they are in the premium account.</li><li><strong>SessionsLast30days</strong>: How many sessions a user had in the last 30 days. It is expected that users reduce the number of sessions before they canceled.</li><li><strong>Gender</strong>: Gender of the user.</li><li><strong>Days in Sparkfy: </strong>how many days a user kept their account.</li></ul><p>For some of the features is important to normalize the values. In this case, I only transform the gender categorical data into binary numerical data so it could be used in the model.</p><h3>5. Split train/test and Define evaluation metrics</h3><p>You understood the dataset, made some assumptions, tested hypotheses and now it is the time to put it all together in a machine learning model! Before testing some models, let divide the dataset into random samples with 80% for training and 20% for testing the model.</p><pre>features = [ &quot;Avg_Songs_Played_Session&quot;,<br>             &quot;genderIndexed&quot;,<br>             &quot;ThumbsProportion&quot;,<br>             &quot;Friends_Added&quot;,<br>             &quot;Days_In_Premium&quot;,<br>             &quot;SessionsLast30days&quot;,<br>             &quot;DaysInSparkfy&quot;]</pre><pre>assembler = VectorAssembler(inputCols=features,outputCol=&quot;features&quot;)</pre><pre>ModelData = assembler.transform(ModelData)</pre><pre>train, test = ModelData.randomSplit([0.8, 0.2], seed=42)</pre><p>Before fitting any model, we should define how are we going to compare them. For this sake, accuracy is always a good starting point, after all, we want the model to predict as many as possible correct labels. However, usually, we give higher importance to a type of error in classifications models and for that reason, we are going to consider other evaluation metrics as Recall and Precision. If you want to have a better understanding of what each of the metrics is, I recommend the following <a href="https://towardsdatascience.com/accuracy-precision-recall-or-f1-331fb37c5cb9">post</a>.</p><p>In this specific problem, the whole point of finding possible churning users is to interact with them in order to avoid their accounts&#39; cancellation. Maybe giving them discounts or offering new specially designed playlists to keep them active in the platform. So, worst-case scenario, if we predict a user is going to cancel its account when he is not, Sparkfy will keep an already active user more engaged in the platform.</p><p>However, when the model predicts that a user is not likely to churn when in fact he is, this classification error is costing Sparkfy a client, which means that we are falling in the main goal of the classification problem. Therefore, in our evaluation, we should prioritize recall over precision.</p><h3>6. Building the Model</h3><p>There are a number of possible models that we could apply in this case of binary classification. I will try 3 different models that are very mainstream for this kind of problem and compare their results. One of the best performances is going to be the one we are going to tune. The models chose for this first trial are the Logistic Regression, Gradient Boosted Decision Trees, and Supported Vector Machine Classifier.</p><p>The Logistic Regression classifier is the simplest and therefore is going to be our baseline to compare the rest of the models. I created a basic function that takes the resulting data frames from our classifiers and displays the metrics we are going to compare.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05e8db31232ee236e95edf89e68547b6/href">https://medium.com/media/05e8db31232ee236e95edf89e68547b6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*v_i76fOC88gC73cEpUfXgA.png" /><figcaption>Logistic Regression 1</figcaption></figure><p>Despite the good accuracy, the precision and recall of this model are bellows acceptable. This happened because of the imbalanced data, as mentioned before. Since active users are more predominant over the churned ones, the model will classify most of the user as active and still get a good accuracy, which is the only metric the model is trying to improve.</p><p>For this reason, I will consider a weight correction for this model in order to make it robust to the unbalancing of classes. This technique gives more importance to labels that appear less. I used the code below from this <a href="https://danvatterott.com/blog/2019/11/18/balancing-model-weights-in-pyspark/">post of Dan Vatterott</a> to create a column in my data frame that creates the desirable balancing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8ea98d996d802b587ed36c28e89a346/href">https://medium.com/media/b8ea98d996d802b587ed36c28e89a346/href</a></iframe><p>After creating the weights, we should put it on a column before the split:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f337b8893d8b789ced6158fc5ef78d/href">https://medium.com/media/c8f337b8893d8b789ced6158fc5ef78d/href</a></iframe><p>With the class balancing, the model greatly increased its precision and recall, with a minor penalty in the accuracy metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*OshTijFUhzILbVFY9r6-uA.png" /><figcaption>Logistic Regression 2 — Use of weights</figcaption></figure><p>For the Gradient Boost Tree Classifier, we don&#39;t need to use class weights. Boosting Classifiers works through a number of interactions that penalize wrong predictions. This makes them good statistical models to apply over imbalanced data because they naturally place more weight on those cases which were incorrectly classified in the last interactions. You could dive deeper into this subject in this <a href="https://www.analyticsvidhya.com/blog/2017/03/imbalanced-data-classification/#:~:text=Dealing%20with%20imbalanced%20datasets%20entails,as%20it%20has%20wider%20application.">post</a>.</p><pre>gbt = GBTClassifier(labelCol=”Cancelled”, featuresCol=”features”)<br>gbtModel = gbt.fit(train)<br>results = gbtModel.transform(test)<br>ShowMetrics(results)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*0zESHpCiY9O9GSwUN_dglQ.png" /><figcaption>Gradient Boosted Decision Trees Classifier</figcaption></figure><p>The best base model among the three classifiers is the Logistic Regression. It predicts more corrected labels with a good recall value. Also, we didn&#39;t need to give up much precision in this classifier in order to get a good recall. The next step is going to be hyper tuning the model.</p><p>For tuning a model you should get an intuition of what each of the available parameters does to the classifier. For Logistic Regression I chose 2 parameters that I think could improve the model. The first one is <em>regParam </em>that represents a regularization to the model or a modification in the model that helps it <a href="https://www.kdnuggets.com/2016/06/regularization-logistic-regression.html">generalize better to unseen data</a>. The second one is the number of iterations. The default is 100 but I tried to 150 and 50 so we can check if the classifier could do better with more iterations or if it is losing performance for too much of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94ee2b7dd678a1997aeb374df1d3ed02/href">https://medium.com/media/94ee2b7dd678a1997aeb374df1d3ed02/href</a></iframe><p>The results of the cross-validation were the same as the default linear regression model. However, the parameters of the best model are different from the default one. The number of iterations was set at 50 and the regularization rate, at 0.1. Since the training dataset contains only 191 observations, the hyper tuning couldn&#39;t get too much of a difference in results.</p><p>In this post I walked through the basics steps to creating a machine learning model for predicting churn:</p><ol><li>Problem Motivation</li><li>Definition of the Problem and Strategy for solution</li><li>Basic Data Cleaning</li><li>Exploratory Data Analysis</li><li>Creation of Features</li><li>Defining metrics to compare models</li><li>Handling class imbalance</li><li>Test and choose models</li><li>Tuning the final model</li></ol><p>As a result, we have a classification model that can predict on regular basis and with 79% accuracy what registered users are more likely to cancel their accounts. This way, Sparkify can act before it loses its clients most of the time.</p><p>It is a great result so far, but there is a lot more it could be done to improve this model. For instance, we could train the classifier on a larger dataset. As mentioned before, these results are considering a small subset of the full data and can change drastically with the inclusion of new registers.</p><p>Another improvement would be to not only predict churn for users who cancel their accounts but also for users that downgrade from paid accounts to free ones. This way Sparkfy could operate on their most important users which are the ones who keep the cash income.</p><p>The details for the code of this post could be found at this <a href="https://github.com/Lucas-Correa/Churn-in-Sparkfy">git repository</a>. Hope you enjoyed it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c30d7206daf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/predicting-churn-with-user-log-data-from-a-digital-music-streaming-app-7c30d7206daf">Predicting Churn with user log data from a digital music streaming app</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>