<?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 Kaustubh Ursekar on Medium]]></title>
        <description><![CDATA[Stories by Kaustubh Ursekar on Medium]]></description>
        <link>https://medium.com/@kaustubh.ursekar?source=rss-aad6b6fcd9ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*oUpb7hhCype3V-_IToxEOg.jpeg</url>
            <title>Stories by Kaustubh Ursekar on Medium</title>
            <link>https://medium.com/@kaustubh.ursekar?source=rss-aad6b6fcd9ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:58:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaustubh.ursekar/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 Credit Card Approvals]]></title>
            <link>https://medium.com/@kaustubh.ursekar/predicting-credit-card-approvals-c5c30f405f92?source=rss-aad6b6fcd9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5c30f405f92</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[credit-cards]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <dc:creator><![CDATA[Kaustubh Ursekar]]></dc:creator>
            <pubDate>Fri, 07 Feb 2020 00:19:40 GMT</pubDate>
            <atom:updated>2020-02-07T02:34:38.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><h4>Business Use Case:</h4><p>Reducing efforts and costs associated with credit card Application approval process by deploying a machine learning model to select valid candidates</p><h4>Introduction:</h4><p>Commercial banks receive <em>a lot</em> of applications for credit cards. Many of them get rejected for many reasons, like high loan balances, low income levels, or too many inquiries on an individual’s credit report, for example. Manually analyzing these applications is mundane, error-prone, and time-consuming (and time is money!). Luckily, this task can be automated with the power of machine learning and pretty much every commercial bank does so nowadays. In this notebook, we will build an automatic credit card approval predictor using machine learning techniques, just like the real banks do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLsdDr8xP3h2j66YFXyMXQ.jpeg" /></figure><p>We’ll use the <a href="http://archive.ics.uci.edu/ml/datasets/credit+approval">Credit Card Approval dataset</a> from the UCI Machine Learning Repository. The structure of this notebook is as follows:</p><ul><li>We will first start with gaining few business insights.</li><li>Then preprocess the data to prepare it for machine learning modelling</li><li>Finally, we will build a machine learning model that can predict if an individual’s application for a credit card will be accepted.</li></ul><p>The features of this dataset have been anonymized to protect the privacy, but <a href="http://rstudio-pubs-static.s3.amazonaws.com/73039_9946de135c0a49daa7a0a9eda4a67a72.html">this blog</a> gives us a pretty good overview of the probable features.</p><p>The dataset has a mixture of numerical and non-numerical features. This can be fixed with some preprocessing, But first we shall gain some business insights.</p><h4>Do find the link to entire Jupyter Notebook in the GitHub repo here:</h4><p><a href="https://github.com/ursekar/Credit-Card-Applications">https://github.com/ursekar/Credit-Card-Applications</a></p><h4>Scope of Blog Post:</h4><p>In this blog, we shall only discuss on the business insights and brief non-technical overview of modelling.</p><h3>Key Business Insights:</h3><h4><strong>1.)</strong> <strong>Is a customer’s debt background too validated along with credit score to while approving their credit card application?</strong></h4><p>This insight is important to understand that obviously a strong credit score does have an impact on application of individual to be approved. But there can be debt levels associated this very individual as well. Is this something that historical application processes took into account?</p><p>Because if they dont then there is possibility that one fine day the customer might go bankerupt and would not be able to pay to bank inspite of the person’s strong credit history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*TJ8UVC6uBwfcEZL9ivlCHA.png" /></figure><p>We can discern that <strong>there is no clear correlation between the credit score of an individual and the debt associated with them</strong>. Though it seems like individual with lower credit scores had their applications declined, still the applications were approved for people with higher debt and higher credit score was approved. Hence, the business must set some factor of debt to credit score for making sure that in case of major national or global financial adversity or the adversity faced by individual’s own financial decisions, they are still able to maintain payments of their bill to considerable extent.</p><h4><strong>2.) Is a customer’s income as well as credit score taken into account to determine whether a credit card must be given or not?</strong></h4><p>This is an obvious understanding that people with higher income as well as good credit score deserve to be rewarded. Hence let us understand as well as confirm if we are able to approve applications for people with higher credit score and decline for those who do not so well on both of these features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*0YUsuEjV7DODuyOgghv59A.png" /></figure><p><strong>Its confirmed ! The individuals having higher Income and higher credit score get their applications approved</strong>. Whereas, the ones who do not have good Income and good credit score lie on the bottom left corner of our chart in orange which means that they are the ones who were declined.</p><p>The other insight that is easily discernible from above is the people good credit history and lower income do get their applications approved. Hence, this bolsters our assumption or generic fact in market that the people with good credit history get credit cards easily. Thus, <strong>credit score is dominating variable it seems in determining the dependent variable</strong>.</p><h4><strong>3.)</strong> <strong>Is there any racial discrimination within the approval process? If so, then it shall hamper business image and hence must strictly be avoided.</strong></h4><p>Ethnicity is a protected status and the decision to approve or deny an application cannot be based on the applicant’s ethnicity. Therefore, such discrimination can downgrade business image and to prevent this it is necessary to understand whether applications knowingly or unknowingly were granted to the customers based on their racial background.</p><p><strong>Cramer’s Rule</strong>:</p><p>What we need is something that will look like correlation, but will work with categorical values — or more formally, we’re looking for a measure of association between two categorical features. Introducing: Cramér’s V. It is based on a nominal variation of Pearson’s Chi-Square Test</p><p>After applying the Cramer’s rule, <strong>the association between <em>Ethnicity</em> and <em>Approved Status</em> variables has value of 0.22864958978031563.</strong></p><p>The closer the Cramers number to one, the higher is the association within the variables. In our case it would have meant that the application process does involve some racial discrimination. But fortunately, in our case, this number is closer to one which means that <strong>there is no racial biases</strong> while approving or declining one’s credit application.</p><h3>PreProcessing the Dataset:</h3><h4>Handling missing values:</h4><p>The missing values in the dataset are labeled with ‘?’, which can be seen in the last cell’s output. We shall replace all the missing values in the dataset with NaN.</p><p>1.) For numeric columns, we shall replace these NaNs with the mean of that column. Thus we are going to impute the missing values with a strategy called mean imputation.</p><p>2.) For categorical columns, we shall replace missing values (NaNs) with most frequently occurring category in that column. This is <a href="https://www.datacamp.com/community/tutorials/categorical-data">good practice</a> when it comes to imputing missing values for categorical data in general.</p><h4>Scaling Data and Label Encoding:</h4><p>There is still some minor but essential data preprocessing needed before we proceed towards building our machine learning model. We are going to divide these remaining preprocessing steps into three main tasks:</p><ol><li>Convert the non-numeric data into numeric.</li><li>Split the data into train and test sets.</li><li>Scale the feature values to a uniform range.</li></ol><p>First, we will be converting all the non-numeric values into numeric ones. We do this because not only it results in a faster computation but also many machine learning models (like XGBoost) (and especially the ones developed using scikit-learn) require the data to be in a strictly numeric format. We will do this by using a technique called <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html">label encoding</a>.</p><h4>Dropping redundant variables:</h4><p>features like DriversLicense and ZipCode are not as important as the other features in the dataset for predicting credit card approvals. We should drop them to design our machine learning model with the best set of features. In Data Science literature, this is often referred to as <em>feature selection</em>.</p><h3>Modelling:</h3><h4>Fitting and Predicting:</h4><p>Essentially, predicting if a credit card application will be approved or not is a <a href="https://en.wikipedia.org/wiki/Statistical_classification">classification</a> task. <a href="http://archive.ics.uci.edu/ml/machine-learning-databases/credit-screening/crx.names">According to UCI</a>, our dataset contains more instances that correspond to “Denied” status than instances corresponding to “Approved” status. Specifically, out of 690 instances, there are 383 (55.5%) applications that got denied and 307 (44.5%) applications that got approved.</p><p>This gives us a benchmark. A good machine learning model should be able to accurately predict the status of the applications with respect to these statistics.</p><p>Which model should we pick? A question to ask is: <em>are the features that affect the credit card approval decision process correlated with each other?</em> Although we can measure correlation, that is outside the scope of this notebook, so we’ll rely on our intuition that they indeed are correlated for now. Because of this correlation, we’ll take advantage of the fact that generalized linear models perform well in these cases. Hence, we chose a Logistic Regression model (a generalized linear model).</p><p>Our model was pretty good! It was able to yield an accuracy score of almost 84%.</p><h4>Parameter Tuning:</h4><p>Let’s see if we can do better. We’ll end the notebook by storing the best-achieved score and the respective best parameters for our model out of several ones. We were able to get better performance after tuning on test set with 85% accuracy.</p><h3>Conclusion:</h3><p>While building this credit card predictor, we tackled some of the most widely-known preprocessing steps such as <strong>scaling</strong>, <strong>label encoding</strong>, and <strong>missing value imputation</strong>.</p><p>We also gained some key business insights by which we can direct our sales and marketing teams to mold their approaches of attracting customers. Hence, we influenced a business decision making process and acted as key in directing business processes.</p><p>We finished with some <strong>machine learning</strong> to predict if a person’s application for a credit card would get approved or not given some information about that person.</p><h3>Thank You Note:</h3><p>Thank you to all my readers for reading this post. Please mention your response below in comment section or at-least applaud if you liked the article. Feel free to criticize too if you wish, as this would improve my work.</p><p>Hope you enjoyed reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5c30f405f92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part IV: A Beginner’s step by step guide to build Machine Learning Models of Customer Churn for a…]]></title>
            <link>https://medium.com/@kaustubh.ursekar/part-iv-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-85dc64257e0d?source=rss-aad6b6fcd9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/85dc64257e0d</guid>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaustubh Ursekar]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 17:29:35 GMT</pubDate>
            <atom:updated>2020-01-21T17:45:30.454Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step IV: A Beginner’s step by step guide to build Machine Learning Models of Customer Churn for a Music Company in PySpark.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KqyEkOC_bT9Kx5PJ0S7usA.jpeg" /></figure><p><em>The link for the preceding part is here:</em></p><p><a href="https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8"><em>https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8</em></a></p><h4>Modelling:</h4><ul><li><strong>Normalizing and Scaling</strong>:</li></ul><p>Finally !! The section you readers would have waited and longed for. If you have reached till here, then know that finish line is in sight from here where you are currently. Get yourself another coffee on this new day. I say that because I personally understand that its not possible to read such huge articles in one go or even in a day.</p><p>As we have gathered all our features from the previous section, we have to make sure that none of these feature introduces a bias in our model. None of these features shall dominate the model’s output. If it happens, then there is not point of this journey we made till here. Hence, <strong>we turn to normalization of our features that gives us this assurance that any independent variable alone or few of them would not influence the dependent variable to an extent where other features become redundant</strong>.</p><p>We shall substract the mean of each feature from every value of that feature and then divide it by standard deviation of each feature. This is called scaling. There are different types of scaling methods too. But for now, we will follow this one which is widely used with various modifications and is also academic.</p><p>Thus, we will use <strong>vector assembler</strong> and <strong>standard scaler</strong> for this purpose. We will make use of their <em>.transform()</em> property for this.</p><pre># Vector assembler<br>cols = [&quot;lifetime&quot;, &quot;total_songs&quot;, &quot;num_thumb_up&quot;,      &#39;num_thumb_down&#39;,&#39;add_to_playlist&#39;,&#39;add_friend&#39;,&#39;listen_time&#39;,&#39;avg_songs_played&#39;,&#39;gender&#39;,&#39;artist_count&#39;]</pre><pre>assembler = VectorAssembler(inputCols=cols, outputCol=&quot;NumFeatures&quot;)<br>data = assembler.transform(data)</pre><pre># standard scaler<br>scaler = StandardScaler(inputCol=&quot;NumFeatures&quot;,outputCol=&quot;features&quot;, withStd=True)<br>scalerModel = scaler.fit(data)<br>data = scalerModel.transform(data)</pre><ul><li><strong>Train — Test Split</strong>:</li></ul><p>We have an unbalanced dataset here with only 52 churners. We have only 44864 churner records in total of 278154 records. Therefore, the data is highly skewed. To address this problem, there are several other approaches but to keep this guide close to academic while taking in account the industry experience of real-life datascientists, we shall use 3 splits in total:</p><ol><li>) Train set</li><li>) Validation Set</li><li>) Test Set</li></ol><p>and <em>follow the </em><strong><em>base model</em></strong><em> approach</em> you soon about to see.</p><p>The <em>seed=42</em> parameter of <em>randomSplit()</em> ensures that same pseudorandom number is generated every-time by preserving the copy of first time generated pseudo number. Hence, this ensures same split every-time giving us the same output in next steps via models no matter how many times you run this notebook.</p><pre># train test split<br>train, rest = data.randomSplit([0.7, 0.3], seed=42)<br>validation, test = rest.randomSplit([0.6, 0.4], seed=42)</pre><ul><li><strong>Base Model</strong>:</li></ul><p>We will check for churned as well as non-churn. Because, the dataset is uneven. The churners are far less than non-churners. Hence we will create two base models for both churners as well as non-churners. Thus making 2 base models for label <em>churn = 1</em> (churned) and <em>churn = 0</em> (non-churned).</p><p><em>MulticlassClassificationEvaluator()</em> is the fellow which shall help us here in understanding how each of our class or labels are performing. Simply saying, it is helping here understand how well both the classes of <em>churner</em> and <em>non-churner</em> the model is able to predict. The <em>evaluate()</em> is the kid of <em>MulticlassClassificationEvaluator()</em>, that will take in the results of each class and gives us the number by the particular metric of our desire we ask that kid to do. Here that metric is <em>“accuracy”</em> and <em>“f1”</em>.</p><pre>results_base_all_1 = test.withColumn(&#39;prediction&#39;, lit(1.0))</pre><pre>evaluator = <br>MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;)</pre><pre>print(&#39;Test set metrics:&#39;)<br>print(&#39;Accuracy: {}&#39;.format(evaluator.evaluate(results_base_all_1, {evaluator.metricName: &quot;accuracy&quot;})))<br>print(&#39;F1 Score:{}&#39;.format(evaluator.evaluate(results_base_all_1, {evaluator.metricName: &quot;f1&quot;})))</pre><pre><strong>Test set metrics:<br>Accuracy: 0.25<br>F1 Score:0.10000000000000002</strong></pre><pre>results_base_all_0 = test.withColumn(&#39;prediction&#39;, lit(0.0))</pre><pre>evaluator = MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;)</pre><pre>print(&#39;Test set metrics:&#39;)<br>print(&#39;Accuracy: {}&#39;.format(evaluator.evaluate(results_base_all_0, {evaluator.metricName: &quot;accuracy&quot;})))<br>print(&#39;F1 Score:{}&#39;.format(evaluator.evaluate(results_base_all_0, {evaluator.metricName: &quot;f1&quot;})))</pre><pre><strong>Test set metrics:<br>Accuracy: 0.75<br>F1 Score:0.6428571428571428</strong></pre><ul><li><strong>Final Models</strong>:</li></ul><ol><li>) <strong>Gradient Boosted Tree</strong>:</li></ol><p>Trees are always good when it comes to classification. My favourite is XGBoost. But I wish to stick with my books for the purpose of this article. Therefore, gradient boosted tree is one of best when it comes to using classification in real life of datascientists.</p><p>We would not indulge in much higher iterations as our data is comparatively small and we do not wish an overfitting as it is always bad and in this case it would be worst as we have an unbalanced dataset. Hence, with 5 iterations and setting the seed we will use <em>MulticlassClassificationEvaluator()</em> with <em>“f1”</em> metric. The <em>ParamGridBuilder()</em> uses its default parameters here while <em>CrossValidator()</em> picks best model based on <em>f1</em> metric.</p><p>Then we fit the best model to <em>train</em> and use it on our <em>validation</em> set and verify if our approach is on the destined road.</p><pre># initialize classifier<br>GradBoostTree = GBTClassifier(maxIter=5,seed=42)</pre><pre># set evaluator<br>f1_evaluator = MulticlassClassificationEvaluator(metricName=&#39;f1&#39;)</pre><pre># build paramGrid<br>paramGrid = ParamGridBuilder().build()</pre><pre>crossval_GradBoostTree = CrossValidator(estimator=GradBoostTree,<br>                          estimatorParamMaps=paramGrid,<br>                          evaluator=f1_evaluator,<br>                          numFolds=5)</pre><pre>cvModel_GradBoostTree = crossval_GradBoostTree.fit(train)<br>cvModel_GradBoostTree.avgMetrics</pre><pre>results_GradBoostTree = cvModel_GradBoostTree.transform(validation)<br>evaluator = MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;)</pre><pre>print(&#39;Gradient Boosted Trees Metrics:&#39;)<br>print(&#39;Accuracy: {}&#39;.format(evaluator.evaluate(results_GradBoostTree, {evaluator.metricName: &quot;accuracy&quot;})))<br>print(&#39;F1 Score:{}&#39;.format(evaluator.evaluate(results_GradBoostTree, {evaluator.metricName: &quot;f1&quot;})))</pre><pre><strong>Gradient Boosted Trees Metrics:<br>Accuracy: 0.7857142857142857<br>F1 Score:0.7542857142857142</strong></pre><p>Well ! the output is good but not yet impressive. Lets see what does our Logistic Regression model bring.</p><p><strong>2.) Logistic Regression</strong>:</p><p>Here everything is similar as above except the number of iterations. We shall use 10 iterations here. Do not worry, I was not inclined to make this model better. The Gradient Boosted Tree did not yield any noticeable difference upon increasing iterations. Hence, we maintained 5 iteration of GBT.</p><pre># initialize classifier<br>lr = LogisticRegression(maxIter=10)</pre><pre># set evaluator<br>f1_evaluator = MulticlassClassificationEvaluator(metricName=&#39;f1&#39;)</pre><pre># build paramGrid<br>paramGrid = ParamGridBuilder() \<br>    .build()</pre><pre>crossval_lr = CrossValidator(estimator=lr,<br>                          evaluator=f1_evaluator, <br>                          estimatorParamMaps=paramGrid,<br>                          numFolds=3)</pre><pre>cvModel_lr = crossval_lr.fit(train)<br>cvModel_lr.avgMetrics</pre><pre>results_lr = cvModel_lr.transform(validation)</pre><pre>evaluator = MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;)<br>print(&#39;Logistic Regression Metrics:&#39;)<br>print(&#39;Accuracy: {}&#39;.format(evaluator.evaluate(results_lr, {evaluator.metricName: &quot;accuracy&quot;})))<br>print(&#39;F-1 Score:{}&#39;.format(evaluator.evaluate(results_lr, {evaluator.metricName: &quot;f1&quot;})))</pre><pre><strong>Logistic Regression Metrics:<br>Accuracy: 0.8571428571428571<br>F-1 Score:0.7912087912087912</strong></pre><p>The Logistic Regression clearly won here. It proved itself. This also gives us a learning lesson that several times, the fundamental models outperform the complicated ones like here the LogR did to GBT.</p><p>Out of both the tested models, I suppose that LogR performed much at par than Gradient Boosted Tree. Therefore, proceeding with parameter tuning for LogR and using it as our model for further steps.</p><p>I am more focussed on <em>F1</em> score as its a paramter to understand the swing between precision and recall. For the purpose of our model, we should be focussing on higher precision since we want to make sure that the likely churning customers should be detected and even if it increases the likelihood of falsely turning some non-churning customers as churning, it wont harm because here we are focussing on people who should not leave our business rather than seeing someone who’s life is at stake like in healthcare.</p><ul><li><strong>Test Deployment &amp; Hyperparameter Tuning</strong>:</li></ul><p>Do not worry much. We shall set the learning parameter alpha to <em>0.001 and 0.01</em> and penalize our model with <em>RegParam </em>where we<em> start with no penalty i.e. 0 and try other value as 0.1</em>. But as we have performed feature engineering from deep EDA, we do not wish to penalize much. Hence, I have taken this small number 0.1 to begin with.</p><p>Also, we do this to make sure that we have not overdone anything and we prevent overfitting. We also wish to keep away redundancy from variables perspective. <strong>We compensate faster learning and higher penalty to some extent with increase in number of iterations</strong>.</p><pre>f1_evaluator = MulticlassClassificationEvaluator(metricName=&#39;f1&#39;)<br>lr = LogisticRegression()<br>paramGrid = ParamGridBuilder().addGrid(lr.maxIter, [10,12])\<br>                                .addGrid(lr.regParam, [0,0.1]) \<br>                                .addGrid(lr.elasticNetParam, [0.001,0.01]) \<br>                                .build()<br>lr_cv = CrossValidator(estimator=lr, estimatorParamMaps=paramGrid, \<br>                        evaluator=f1_evaluator, numFolds=3)</pre><p>Now our next task is to select the best model that is created from both of these passed parameter values in Grid. Once done, we shall use that best model to work on test set and let out its performance metrices.</p><pre>lrModel = lr_cv.fit(train)<br>bestModel = lrModel.bestModel</pre><pre>results_final = bestModel.transform(test)</pre><pre>evaluator = MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;)</pre><pre>print(&#39;Test set metrics:&#39;)<br>print(&#39;Accuracy: {}&#39;.format(evaluator.evaluate(results_final, {evaluator.metricName: &quot;accuracy&quot;})))<br>print(&#39;F-1 Score:{}&#39;.format(evaluator.evaluate(results_final, {evaluator.metricName: &quot;f1&quot;})))</pre><pre><strong>Test set metrics:<br>Accuracy: 0.8125<br>F-1 Score:0.782204020848846</strong></pre><p>We observe that <em>f-1</em> score slightly reduced on test set from <em>0.79 to 0.78</em> while the <em>accuracy </em>increased. I am not much happy with increase <em>accuracy</em> as this could be misleading due to unbalanced dataset with far less number of churners as compared to the non-churners. But, I am satisfied with the thought that <em>f-1 score</em> was not hurt much. <em>Therefore, as this is a small sample data from the large cluster of 12 GB, I shall surely go ahead in trying this model in one of my branches through git in real life data science</em> to see how it is working.</p><ul><li><strong>Feature Importance in LogR</strong>:</li></ul><p>Feature importance is easy to discern in <em>Regression models</em> as all we have to see is at the <em>Beta(s). </em>Thus, we shall pull out the coefficients and see the ones with larger magnitude (<strong><em>we shall take abs() or absolute values of coefficients for the purpose ease of understanding here</em></strong>) for rendering exactly who these undercover knights are, that dominate our output. <em>I hope we do not encounter where only couple of them dominate entirely while rest lay back seeing the castle burn</em>. hehehe!!</p><p>We shall use bar graph for this observation as exact values are not much of interest right now for us. We are tired after reading such huge article and coding too, right?</p><pre>feat_imp = abs(bestModel.coefficients.values)<br>cols = [&quot;lifetime&quot;, &quot;TotalSongs&quot;, &quot;Thumbsup&quot;, &#39;ThumbsDown&#39;, &#39;PlaylistAdd&#39;,&#39;FriendAdd&#39;,&#39;ListeningTime&#39;,&#39;AvgSongsPlay&#39;, \<br>        &#39;Gender&#39;, &#39;NumofArtists&#39;]<br>y_pos = np.arange(len(cols))<br> <br>plt.pyplot.barh(y_pos, feat_imp, align=&#39;center&#39;)<br>plt.pyplot.yticks(y_pos,cols, rotation = 45)<br>plt.pyplot.xlabel(&#39;Importance Score&#39;)<br>plt.pyplot.title(&#39;Feature Importances&#39;);<br>plt.pyplot.tight_layout()</pre><pre>plt.pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*RkU9tm6viyrJOH87H89hkg.png" /></figure><h3>Conclusion:</h3><h4>Actions on dataset:</h4><p>1.) Dropped rows with no userId.</p><p>2.) converted timestamp to a human readable format.</p><p>3.) converted categorical and other non-numeric columns to numeric using dummy variables or other methods.</p><h4>Modelling actions:</h4><p>1.) Feature engineering yielded 10 features.</p><p>2.) 2 models were used, Gradient Boosted Tree and Logistic Regression in which the later won.</p><p>3.) For tuning the model, cross validation and grid search were used.</p><h4>Results achieved:</h4><p>1.) 81% accuracy and 78% F1 score on test set.</p><p>2.) Thus, the LogR model performed multiple times better than our baseline models.</p><h4>Feature Importance:</h4><p>As we clearly see that the lifetime is the greatest important feature coupled with thumbs down and friends referred. This makes top 3 important features. We can easily say that the person about to churn did not like the quality of songs either by his/her liking or the audio quality. Such people did not referred friends which was very obvious. Thought the length of using service seems to dominate the behavior to churn, it could be biased. Because, the churned customers used the product for shorter time. Hence we can consider some other transformations to mitigate this bias.</p><h4>Drawbacks and Way forward:</h4><p>1.) We can re-use lot of part of the above code in actual work environment. The notebook sets a crude yet very close mirroring to what one shall encounter in field experience when it comes to not only coding but also in areas of customer churn.</p><p>2.) Although it was a effort to understand the gist of building ML model for customer churn overall, the few points can still be improved within this notebook which are; using multiple models before jumping to final conclusion, SCRUM calls with SMEs to understand the direction and domain perspective on each feature, rigorous test cases to make sure model withstands changing marketing sentiments and styles of customer usage methods, etc.</p><h3>Thank You Note</h3><p>I thank all my readers here, who have read this article. I hope that beginners learnt and people with in depth experience and knowledge of customer churn found areas of criticisms.</p><p>Please leave a response whether both positive or negative as I welcome critics. It helps me grow and seep in the minutest gears of ML. Your response would surely encourage me. I am ready to change myself and groom my understanding if it is a criticism. I would like to learn and help others learn in my journey of data science.</p><p>Thanks once again, Bye bye guys !! Take care and have a good one !! Hope you enjoyed reading!!</p><p>:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85dc64257e0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part III: A Beginner’s step by step guide to build Machine Learning Models of Customer Churn for a…]]></title>
            <link>https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8?source=rss-aad6b6fcd9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/88302bc468c8</guid>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[data-scientist]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaustubh Ursekar]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 17:24:55 GMT</pubDate>
            <atom:updated>2020-01-23T14:13:13.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step III: A Beginner’s step by step guide to build Machine Learning Models of Customer Churn for a Music Company in PySpark.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*KqyEkOC_bT9Kx5PJ0S7usA.jpeg" /></figure><p><em>The Link for the preceding part is here:</em></p><p><a href="https://medium.com/@kaustubh.ursekar/step-ii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-8b6fefc07bba"><em>https://medium.com/@kaustubh.ursekar/step-ii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-8b6fefc07bba</em></a></p><h4>Feature Engineering:</h4><p>Hushhh !! you tired? Atleast I am !! Yet we have to go these last two miles. Well ! I can’t think of any words of motivation than making you realize that, “<strong>if you are reading this article at this line, trust me ! you have came a way into your road of achieving your goal which can be even becoming a data scientist or working in your dream field or company</strong>”.<em> Take a cup of coffee or a break or even a short power nap to get from here ahead till our finish line. Slow and steady wins the race, right !! but don’t worry, a nap is not making you the rabbit of the story, Lol !! So chill, relax,</em><strong><em> you still the stubborn turtle with fiery eyes carrying its goal and dream</em></strong><em>! hehehe </em>!</p><p><strong>Feature engineering</strong> is the process of using domain knowledge of the data to create <strong>features</strong> that make sophisticated machine learning algorithms . For this purpose, one should collaborate with <em>Subject Matter Expert</em>, commonly abbreviated as <em>SME</em> while working in the industry. One must be an expert to come up with right features. Do not worry folks !! even I am not an expert. So beginners can stop nail biting right now. hehehe !</p><p>I came up with these 10 features from my experience and googling. I have tried to keep them as academic as possible, while making sure that you would be able to see considerable closeness to the real life customer churn projects while working as a real-life data scientist in an organisation. This part would surely help you, when you would work on technical requirement that requires feature engineering. <em>Recommender systems, Customer Segmentation and Customer Churning, are some of the major areas of leveraging one’s knowledge on feature engineering</em>.</p><p><strong>You are also soon about to see that why so much comprehension on above EDA mattered</strong>.</p><ul><li><strong>Independent Variables</strong>:</li></ul><p><strong>1.) Time Since Registration</strong>:</p><p>As we have already saw that lifetime from registration had a visualizing difference within our <em>churn (1)</em> and <em>non-churn (0)</em> customers, we shall take this as base of our first feature.</p><p>We shall use the same code as before to create this feature. Note that the time goes is given in milliseconds in <em>registration</em> and <em>ts</em> columns. Hence we shall divide it by <em>1000</em> to get time only in seconds. Then, we know that each hour is made of <em>3600</em> seconds, therefore, we shall divide by <em>3600</em> and then to convert hour to days, we shall divide it by <em>24</em>. Hence, “<em>lifetime/1000/3600/24</em>”. I have used the import statement from above again. <em>describe()</em> provides statistical understanding of this feature or our variable.</p><pre>feat_1 = data \<br>    .select(&#39;userId&#39;,&#39;registration&#39;,&#39;ts&#39;) \<br>    .withColumn(&#39;lifetime&#39;,(data.ts-data.registration)) \<br>    .groupBy(&#39;userId&#39;) \<br>    .agg({&#39;lifetime&#39;:&#39;max&#39;}) \<br>    .withColumnRenamed(&#39;max(lifetime)&#39;,&#39;lifetime&#39;) \<br>    .select(&#39;userId&#39;, (col(&#39;lifetime&#39;)/1000/3600/24).alias(&#39;lifetime&#39;))</pre><pre>feat_1.describe().show()</pre><pre><strong>+-------+------------------+-------------------+<br>|summary|            userId|           lifetime|<br>+-------+------------------+-------------------+<br>|  count|               225|                225|<br>|   mean|65391.013333333336|   79.8456834876543|<br>| stddev|105396.47791907164|  37.66147001861254|<br>|    min|                10|0.31372685185185184|<br>|    max|                99|  256.3776736111111|<br>+-------+------------------+-------------------+</strong></pre><p><strong>2.) Total Songs Listened</strong>:</p><p>We also saw how the total songs played and songs played per session were comparatively different for the two categories of interest. Hence, we shall just use the <em>“count”</em> function for counting songs for each user by applying <em>groupby()</em> on <em>userId</em>.</p><pre>feat_2 = data \<br>    .select(&#39;userID&#39;,&#39;song&#39;) \<br>    .groupBy(&#39;userID&#39;) \<br>    .count() \<br>    .withColumnRenamed(&#39;count&#39;, &#39;total_songs&#39;)</pre><pre>feat_2.describe().show()</pre><pre><strong>+-------+------------------+-----------------+<br>|summary|            userID|      total_songs|<br>+-------+------------------+-----------------+<br>|  count|               225|              225|<br>|   mean|65391.013333333336|          1236.24|<br>| stddev|105396.47791907164|1329.531716432519|<br>|    min|                10|                6|<br>|    max|                99|             9632|<br>+-------+------------------+-----------------+</strong></pre><p><strong>3.) &amp; 4.) Likes and dislikes of user</strong>:</p><p>We saw from <strong>bar graph EDA of page visited by users of both interest categories</strong>, that the churners disliked more than non-churners. On the other hand, <em>non-churners</em> threw more likes than <em>churners</em>. Hence, we shall make the 3rd and 4th feature for <em>count()</em> of <em>thumbs up</em> and <em>thumbs down</em>, respectively.</p><pre>feat_3 = data \<br>    .select(&#39;userID&#39;,&#39;page&#39;) \<br>    .where(data.page == &#39;Thumbs Up&#39;) \<br>    .groupBy(&#39;userID&#39;) \<br>    .count() \<br>    .withColumnRenamed(&#39;count&#39;, &#39;num_thumb_up&#39;)</pre><pre>feat_3.describe().show()</pre><pre>feat_4 = data \<br>    .select(&#39;userID&#39;,&#39;page&#39;) \<br>    .where(data.page == &#39;Thumbs Down&#39;) \<br>    .groupBy(&#39;userID&#39;) \<br>    .count() \<br>    .withColumnRenamed(&#39;count&#39;, &#39;num_thumb_down&#39;)</pre><pre>feat_4.describe().show()</pre><pre><strong>+-------+------------------+-----------------+<br>|summary|            userID|     num_thumb_up|<br>+-------+------------------+-----------------+<br>|  count|               220|              220|<br>|   mean| 66420.27727272727|            57.05|<br>| stddev|106196.51156121881|65.67028650524044|<br>|    min|                10|                1|<br>|    max|                99|              437|<br>+-------+------------------+-----------------+</strong></pre><pre><strong>+-------+------------------+------------------+<br>|summary|            userID|    num_thumb_down|<br>+-------+------------------+------------------+<br>|  count|               203|               203|<br>|   mean| 66066.16256157635|12.541871921182265|<br>| stddev|106108.32569893777|13.198108566983787|<br>|    min|                10|                 1|<br>|    max|                99|                75|<br>+-------+------------------+------------------+</strong></pre><p><strong>5.) Playlist length</strong>:</p><p>We saw in <strong>pages visited EDA</strong> about songs added to the playlist were much greater visually for <em>non-churners</em>, than the ones added by the <em>churners</em>. Thus, we shall <em>count()</em> the number of songs added to playlist (“<em>Add to Playlist</em>” <em>page)</em>. <strong><em>Till now, you must have understood like a crystal clear water, that why we spent so much time and deliberated of EDA. it gave us these key findings, which acted as a draft to our Feature Engineering of these variables</em></strong>.</p><pre>feat_5 = data \<br>    .select(&#39;userID&#39;,&#39;page&#39;) \<br>    .where(data.page == &#39;Add to Playlist&#39;) \<br>    .groupBy(&#39;userID&#39;)\<br>    .count() \<br>    .withColumnRenamed(&#39;count&#39;, &#39;add_to_playlist&#39;)</pre><pre>feat_5.describe().show()</pre><pre><strong>+-------+------------------+-----------------+<br>|summary|            userID|  add_to_playlist|<br>+-------+------------------+-----------------+<br>|  count|               215|              215|<br>|   mean| 66103.63720930232|30.35348837209302|<br>| stddev|106360.47999565038| 32.8520568555997|<br>|    min|                10|                1|<br>|    max|                99|              240|<br>+-------+------------------+-----------------+</strong></pre><p><strong>6.) Referring friends</strong>:</p><p>The <strong>bar graph of pages visited</strong> also revealed how the people who liked our product pushed other individuals within their network to use it. This was very obvious trait and hence would form our 6th feature.</p><pre>feat_6 = data \<br>    .select(&#39;userID&#39;,&#39;page&#39;) \<br>    .where(data.page == &#39;Add Friend&#39;) \<br>    .groupBy(&#39;userID&#39;) \<br>    .count() \<br>    .withColumnRenamed(&#39;count&#39;, &#39;add_friend&#39;)</pre><pre>feat_6.describe().show()</pre><pre><strong>+-------+------------------+------------------+<br>|summary|            userID|        add_friend|<br>+-------+------------------+------------------+<br>|  count|               206|               206|<br>|   mean| 66076.91262135922|20.762135922330096|<br>| stddev|106860.60517425007|20.646779074405007|<br>|    min|                10|                 1|<br>|    max|                99|               143|</strong><br>+-------+------------------+------------------+</pre><p><strong>7.) Listening Longevity</strong>:</p><p>As both categories of interest had varied amount of songs listened per session, we shall also consider how long individuals within these groups listened to our songs. This is important as it can be that the people who churned, made a quick or hasty decision rather than dwelling by listening to songs for longer period of time. Hence we shall pick up the “<em>length</em>” for each <em>userId </em>and <em>sum()</em> it to get the total <em>length (</em><strong>of listening to songs</strong><em>).</em></p><pre>feat_7 = data \<br>    .select(&#39;userID&#39;,&#39;length&#39;) \<br>    .groupBy(&#39;userID&#39;) \<br>    .sum() \<br>    .withColumnRenamed(&#39;sum(length)&#39;, &#39;listen_time&#39;)</pre><pre>feat_7.describe().show()</pre><pre><strong>+-------+------------------+------------------+<br>|summary|            userID|       listen_time|<br>+-------+------------------+------------------+<br>|  count|               225|               225|<br>|   mean|65391.013333333336|252558.32065155543|<br>| stddev|105396.47791907164| 275396.4038847635|<br>|    min|                10|         691.66884|<br>|    max|                99|1991154.9155799907|<br>+-------+------------------+------------------+</strong></pre><p><strong>8.) Songs per Session</strong>:</p><p>Now coming to our exact finding of variation in songs listened in per session by both categories of interest which was starkly different. Please understand that we are just using the code from before and hence, I have avoided the same explanation here.</p><pre>feat_8 = data.where(&#39;page == &quot;NextSong&quot;&#39;) \<br>    .groupby([&#39;userId&#39;, &#39;sessionId&#39;]) \<br>    .count() \<br>    .groupby([&#39;userId&#39;]) \<br>    .agg({&#39;count&#39;:&#39;avg&#39;}) \<br>    .withColumnRenamed(&#39;avg(count)&#39;, &#39;avg_songs_played&#39;)</pre><pre>feat_8.describe().show()</pre><pre><strong>+-------+------------------+-----------------+<br>|summary|            userId| avg_songs_played|<br>+-------+------------------+-----------------+<br>|  count|               225|              225|<br>|   mean|65391.013333333336|70.78971233958933|<br>| stddev|105396.47791907164| 42.6153697543817|<br>|    min|                10|              3.0|<br>|    max|                99|286.6666666666667|<br>+-------+------------------+-----------------+</strong></pre><p><strong>9.) Gender:</strong></p><p>No need to much explain this. At every point of our EDA we encountered how <em>Male</em> and <em>Female</em> <em>Gender</em> influenced the churn variable of ours. <strong>Congratulations !! the girl vs boy approach from play school</strong> worked out here. Hence we shall include it by developing a categorical feature from it.</p><pre>feat_9 = data \<br>    .select(&quot;userId&quot;, &quot;gender&quot;) \<br>    .dropDuplicates() \<br>    .replace([&#39;M&#39;, &#39;F&#39;], [&#39;0&#39;, &#39;1&#39;], &#39;gender&#39;) \<br>    .select(&#39;userId&#39;, col(&#39;gender&#39;).cast(&#39;int&#39;))</pre><pre>feat_9.describe().show()</pre><pre><strong>+-------+------------------+-------------------+<br>|summary|            userId|             gender|<br>+-------+------------------+-------------------+<br>|  count|               225|                225|<br>|   mean|65391.013333333336| 0.4622222222222222|<br>| stddev|105396.47791907165|0.49968243883744773|<br>|    min|                10|                  0|<br>|    max|                99|                  1|<br>+-------+------------------+-------------------+</strong></pre><p><strong>10.) No. of Artists Listened</strong>:</p><p>Remeber how in our numerical EDA we had used top 5 artists by churn to look for pattern? We will use that finding in EDA here as one of feature. We will observe the number of artists a users is listening in both categories or interest.</p><pre>feat_10 = data \<br>    .filter(data.page==&quot;NextSong&quot;) \<br>    .select(&quot;userId&quot;, &quot;artist&quot;) \<br>    .dropDuplicates() \<br>    .groupby(&quot;userId&quot;) \<br>    .count() \<br>    .withColumnRenamed(&quot;count&quot;, &quot;artist_count&quot;)</pre><pre>feat_10.describe().show()</pre><pre><strong>+-------+------------------+-----------------+<br>|summary|            userId|     artist_count|<br>+-------+------------------+-----------------+<br>|  count|               225|              225|<br>|   mean|65391.013333333336|696.3777777777777|<br>| stddev|105396.47791907164|603.9518698630802|<br>|    min|                10|                3|<br>|    max|                99|             3544|<br>+-------+------------------+-----------------+</strong></pre><ul><li><strong>Dependent Variable</strong>:</li></ul><p>We will now have to create a dependent variable from our “<em>churn</em>” column. We will create numeric categories of <em>churn</em> label here as <em>1 = churn</em> and <em>0 = no churn</em>.</p><pre>label = data \<br>    .select(&#39;userId&#39;, col(&#39;churn&#39;).alias(&#39;label&#39;)) \<br>    .dropDuplicates()</pre><pre>label.describe().show()</pre><pre><strong>+-------+------------------+------------------+<br>|summary|            userId|             label|<br>+-------+------------------+------------------+<br>|  count|               225|               225|<br>|   mean|65391.013333333336|0.2311111111111111|<br>| stddev|105396.47791907164|0.4224832108996327|<br>|    min|                10|                 0|<br>|    max|                99|                 1|<br>+-------+------------------+------------------+</strong></pre><ul><li><strong>Model Feeder Dataset</strong>:</li></ul><p>Final part in feature engineering. We will have to create a dataframe out of these features to be fed to our machine learning model as input. We shall simply fill all <em>Null</em>, <em>Nan</em> with 0. This is done for simplicity as we have already come far in working for sophistication. Hence this simplicity won’t affect anything and also we must remember that complication is not always yielding best output from ML models.</p><pre>data = feat_1.join(feat_2,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_3,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_4,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_5,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_6,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_7,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_8,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_9,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(feat_10,&#39;userID&#39;,&#39;outer&#39;) \<br>    .join(label,&#39;userID&#39;,&#39;outer&#39;) \<br>    .drop(&#39;userID&#39;) \<br>    .fillna(0)</pre><pre>data.show(5, vertical=True)</pre><pre><strong>-RECORD 0------------------------------<br> lifetime         | 55.6436574074074   <br> total_songs      | 381                <br> num_thumb_up     | 17                 <br> num_thumb_down   | 5                  <br> add_to_playlist  | 7                  <br> add_friend       | 4                  <br> listen_time      | 66940.89735000003  <br> avg_songs_played | 39.285714285714285 <br> gender           | 1                  <br> artist_count     | 252                <br> label            | 0                  <br>-RECORD 1------------------------------<br> lifetime         | 70.07462962962963  <br> total_songs      | 474                <br> num_thumb_up     | 21                 <br> num_thumb_down   | 6                  <br> add_to_playlist  | 8                  <br> add_friend       | 4                  <br> listen_time      | 94008.87593999993  <br> avg_songs_played | 64.5               <br> gender           | 0                  <br> artist_count     | 339                <br> label            | 0                  <br>-RECORD 2------------------------------<br> lifetime         | 71.31688657407408  <br> total_songs      | 11                 <br> num_thumb_up     | 0                  <br> num_thumb_down   | 0                  <br> add_to_playlist  | 0                  <br> add_friend       | 0                  <br> listen_time      | 2089.1131000000005 <br> avg_songs_played | 8.0                <br> gender           | 0                  <br> artist_count     | 8                  <br> label            | 1                  <br>-RECORD 3------------------------------<br> lifetime         | 131.55591435185184 <br> total_songs      | 4825               <br> num_thumb_up     | 171                <br> num_thumb_down   | 41                 <br> add_to_playlist  | 118                <br> add_friend       | 74                 <br> listen_time      | 1012312.0927899999 <br> avg_songs_played | 145.67857142857142 <br> gender           | 1                  <br> artist_count     | 2232               <br> label            | 0                  <br>-RECORD 4------------------------------<br> lifetime         | 19.455844907407407 <br> total_songs      | 2464               <br> num_thumb_up     | 100                <br> num_thumb_down   | 21                 <br> add_to_playlist  | 52                 <br> add_friend       | 28                 <br> listen_time      | 523275.8428000004  <br> avg_songs_played | 211.1              <br> gender           | 0                  <br> artist_count     | 1385               <br> label            | 1                  <br>only showing top 5 rows</strong></pre><p><strong>Thank you to my readers</strong>:</p><p>If you have made it till here, then I appreciate your patience of reading my article, Please leave your responses below. I would surely appreciate any improvements or criticisms suggested.</p><p>The link for next part is given below:</p><p><a href="https://medium.com/@kaustubh.ursekar/part-iv-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-85dc64257e0d">https://medium.com/@kaustubh.ursekar/part-iv-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-85dc64257e0d</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88302bc468c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step II: A Beginner’s step by step guide to build Machine Learning Models of Customer Churn for a…]]></title>
            <link>https://medium.com/@kaustubh.ursekar/step-ii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-8b6fefc07bba?source=rss-aad6b6fcd9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b6fefc07bba</guid>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kaustubh Ursekar]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 17:19:46 GMT</pubDate>
            <atom:updated>2020-02-07T21:52:13.389Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step II: A Beginner’s step by step guide to build Machine Learning Models of Customer Churn for a Music Company in PySpark.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LbTyOcvDhsTRYO-M9lfhAw.jpeg" /></figure><p><em>The Link for preceding part is here:</em></p><p><a href="https://medium.com/@kaustubh.ursekar/predicting-customer-churn-for-a-music-company-1b71111b0483"><em>https://medium.com/@kaustubh.ursekar/predicting-customer-churn-for-a-music-company-1b71111b0483</em></a></p><h3>Exploratory Data Analysis:</h3><p><em>People who are skimming or are quick readers, can skip the coming blocks of texts and jump to </em><strong><em>Numerical EDA</em></strong><em> encountered down from here</em>.</p><p>Knock Knock !! you still there? wow !! if you made it till here from this exhaustive jog in previous part, give yourself a pat. You are already passed the towns from far, that belong to data engineers, data validators, data authenticators, etc. The cities and towns where guys who give you clean and genuine data stay, lol !! Though, note that you have got barely any glimpse. In reality, these tasks are way harder at times than one could imagine. But we would focus on the topic of our article for now and cut the visibility outside its scope.</p><p>Now, I am going to tell something to my starters or beginner style readers here, <strong>EDA is always not about some magical graphics and charts. In fact, most of clients of yours wont even understand them at first go</strong>. Numbers and <em>Table view</em> are in fact popular in various domains. Take for example healthcare, a domain that I work in. I had gone through my 4 healthcare clients. to my surprise !! all of them did not preferred charts and graphs. They liked simply lists, number columns or simply said table view formats and pivot tables.</p><p>So along with a different perspective I shall proceed with my approach for <strong>EDA here, that consists of 3 sections</strong>. <strong>Thus, do not forget to rest after each section while you start another. This shall relax your brain and help it to grasp quickly in shorter period of time. Otherwise, you would loose interest</strong>.</p><p><strong>EDA is important. Because, it will help us understand the landscape on which strong foundation is built for our features to be fed to model in modelling section</strong>. Hence, expect it to be tiresome a little.</p><p>The 3 sections are:</p><ol><li>) mainly numbers or numerical EDA,</li><li>) time Analysis,</li><li>) customer activity analysis or graphical representations.</li></ol><p><em>Note: GRAPHS ONLY WHERE NEEDED &gt;:. haha!!</em></p><h4><strong>I) Numerical EDA</strong>:</h4><p>We will first pull unique records by <em>userId</em>. Then, we shall <em>groupby userId</em> and apply aggregation and math operators to pull out some numbers, that would help us understand behaviors inside our dataset.</p><ul><li><strong>Churn rate within female and males category</strong>:</li></ul><p>Let’s start with our playschool competition like approaches, GIRLS vs BOYS !! Hurray !! :)</p><pre># A way to convert list to dataframe</pre><pre>stat_df = spark.createDataFrame(data.dropDuplicates([‘userId’]).collect())</pre><pre>stat_df1 = stat_df[[&#39;gender&#39;, &#39;churn&#39;]]</pre><pre>print(&#39;The avg churn rate of females is:&#39;, stat_df1.groupby([&#39;gender&#39;]).mean().collect()[0][1]*100)<br>print(&#39;The avg churn rate of males is:&#39;, stat_df1.groupby([&#39;gender&#39;]).mean().collect()[1][1]*100)</pre><pre><strong>The avg churn rate of females is: 19.230769230769234<br>The avg churn rate of males is: 26.446280991735538</strong></pre><p>Hmm !! the proportions of females tend to cancel less than Males. Well our play school approach got us something here to keep in mind.</p><ul><li><strong>Churn for top 5 artists category</strong>:</li></ul><p>As this is a music data, we can surely have this curiosity to know which are top 3, 5 or 10 artists whom majority of our customers left us. ( Each fan base crossing fingers for “<em>not mine</em>”, right? hehe !!. Lets take top 5.</p><p>We shall need to see for each artists with the number of churners and then, arrange descending and keep limit as top 5. Hence, <em>groupby(artists)</em> <em>and sum()</em> the <em>churn</em> column entries as they are just 1 and 0, giving us for whom the majority of our customers left as more 1s added will give more sum.</p><pre># Viewing top 5 cancellations by artist<br>stat_df1 = stat_df[[‘artist’, ‘churn’]]<br>stat_df1.groupBy([‘artist’]).sum().orderBy(‘sum(churn)’, ascending = False).collect()[:5]</pre><pre><strong>[Row(artist=None, sum(churn)=27),<br> Row(artist=&#39;Orenda Fink&#39;, sum(churn)=1),<br> Row(artist=&#39;P!nk&#39;, sum(churn)=1),<br> Row(artist=&#39;P.O.D.&#39;, sum(churn)=1),<br> Row(artist=&#39;Tasavallan Presidentti&#39;, sum(churn)=1)]</strong></pre><p>Thus the fans can cheer here as maximum churners are for artists with no name mentioned in data i.e. ‘None’.</p><ul><li><strong>Churn for “paid” and “free” category</strong>:</li></ul><p>Umm !! what can we think of something else to be curious about our data. Thinking from business perspective, money will do. Hence, let us proceed ahead with the fundamental part of money for a service, which is the number of churns for <em>free</em> subscription and those for <em>paid</em> ones. But here, we would like to see the proportion of people within these groups who got churned rather than pulling out just numbers. The reason is that, if we just pull out the numbers, we do not know how much is the whole part of it and we can possibly be misguided.</p><p>Therefore, lets go with mean(). Because, <em>1s</em> and <em>0s</em> summation divided by their total count will give us the proportion. In other words, ignore the multiplication of 100 as it is just for the purpose of ease of reading the output, acting as math scaler here.</p><pre>stat_df1 = stat_df[[‘level’, ‘churn’]]<br>print(‘proportion of users that chruned from free subscirption’, stat_df1.groupBy([‘level’]).mean().collect()[0][1]*100)<br>print(‘proportion of users that chruned from paid subscirption’,stat_df1.groupBy([‘level’]).mean().collect()[1][1]*100)</pre><pre><strong>proportion of users that chruned from free subscirption 24.858757062146893<br>proportion of users that chruned from paid subscirption 16.666666666666664</strong></pre><p>Clearly !! people of free subscription tend to drop the service more. Hush !! at-least paid ones are not the ones who go away. So this can be a positive aspect as we can be happy that once entire access to all features of our product or service are given, the customers don’t wish to leave. Hence, facilities provided for paid ones is better can be assumed. Hence, we can start by directing our product and sales team to share some of these properties for free customers for certain time after “<em>cancellation</em>” or give them more trial times to enjoy our entire product features and services for free of cost, to change their mind to drop. Maybe, even make an effort to make them a paid customer by offering them discounts or coupons.</p><ul><li><strong>Churn for top 10 states category</strong>:</li></ul><p>We can now proceed ahead with looking for something else. How about the usual state rivalry within the country, huh? We can see churners for top 10 off 50 states giving us also an insight to verify what is going wrong if some of them showed much difference than the rest. But to do this, we would need the <em>split()</em> function. Because, the address consists something like this “<em>bla bla, state”</em>. Hence, we will apply <em>getitem(1) </em>after<em> split()</em>. This will fetch us the state as 1st position after the split is done. <em>withColumn</em> is used to create a new column in the dataframe and this seems the most comfortable way to work while conducting such coding operations in pyspark.</p><pre>stat_df1 = stat_df[[‘location’, ‘churn’]]</pre><pre>stat_df1 = stat_df1.withColumn(‘state’, split(stat_df[‘location’], ‘,’).getItem(1))<br>stat_df1 = stat_df1.drop(‘location’)</pre><pre>print(“Viewing top 10 states to churn:\n”)<br>stat_df1.groupBy([‘state’]).sum().filter(“sum(churn)&gt; 0”).orderBy(‘sum(churn)’, ascending = False).show(10)</pre><pre><strong>Viewing top 10 states to churn:</strong></pre><pre><strong>+---------+----------+<br>|    state|sum(churn)|<br>+---------+----------+<br>|       CA|         6|<br>| NY-NJ-PA|         5|<br>|       MI|         3|<br>|       TX|         3|<br>|       FL|         3|<br>|       MS|         2|<br>|       OH|         2|<br>|       AL|         2|<br>|       WA|         2|<br>|       AZ|         2|<br>+---------+----------+<br>only showing top 10 rows</strong></pre><p>We can surely check with the local service outlets in these states to see: what’s wrong in our service or impact of local competitors or unsuitable product features like color, interface, etc.</p><h4><strong>II) Time Analysis</strong>:</h4><p>We should also see, which duration of the day, in hours, the user got churn, or which day of the month. We shall also dwell in week days to ensure if there is any particular week day users are churning. This might help us understand the behavior and drop advance emails or give some happy hour services in those time periods to keep users happy. We can also check for other external factors like; our competitor offering different product feature, some classy services, different consumer lifestyle or other factors out in the market unknown to us that might propel our customer to churn in this particular hour, weekday, or day of the month.</p><p><strong>Here we must understand that a graph makes more sense than numbers to understand the behavior of user in time. </strong>Numbers are almost impossible for human brain to compare as greater or smaller and draw a trend of increasing or descending when given in unsorted huge chunks. Even a series of about less than 100 numbers takes a scrolling of our eyeballs back and forth. Hence, chart with bars would make a lot more sense to see this trend.</p><p>Hence, we shall now define a function and here is where; <em>from pyspark.sql.functions import UserDefinedFunction as udf</em> comes into play. This would helps us define our own function. Our <strong>date data is in ISO timestamp with milliseconds</strong>. Hence we need to use <em>fromtimestamp</em> attribute from <em>datetime</em> as <em>datetime.datetime.fromtimestamp(givenISOtimestampseries/1000)</em>. We divide by 1000 to remove the millisecond part as we are only interested in hour, day of week and month here. Hence here is where our <em>import datetime</em> helps us.</p><p>User defined functions to get hour, day, month, and weekday of cancellation:</p><pre>get_hour = udf(lambda x: datetime.datetime.fromtimestamp(x / 1000.0).hour)<br>get_day = udf(lambda x: datetime.datetime.fromtimestamp(x / 1000.0).day)<br>get_month = udf(lambda x: datetime.datetime.fromtimestamp(x / 1000.0).month)</pre><pre>get_weekday = udf(lambda x: datetime.datetime.fromtimestamp(x / 1000.0).strftime(‘%w’))</pre><p>Proceeding from here to plot will take;</p><ol><li>) extracting the desired time frame from ts column like hours, days, weekdays, etc.</li><li>) applying above three functions to convert datetime in expected human readable format.</li><li>) restructuring it to existing dataframe to be usable for plotting in <em>matplotlib</em> after converting in <em>pandas dataframe</em>.</li></ol><p>Hence, we need a dictionary first, to pass these above three functions one by one over the entire “<em>ts</em>” column. This action would attach three columns to dataframe at the same time, which could be named after the function’s key. Then convert them to <em>pandas</em> as shown:</p><pre># Adding columns to the dataframe<br>funcs = {‘hour’:get_hour, ‘day’:get_day, ‘month’:get_month, ‘week_day’:get_weekday}<br>for label, func in funcs.items():<br> data = data.withColumn(label, func(data.ts))<br> print(f’Column {label} added successfully.’)</pre><pre># to help in better plotting and visuals<br>dfp = data.toPandas()</pre><pre><strong>Column hour added successfully.<br>Column day added successfully.<br>Column month added successfully.<br>Column week_day added successfully.</strong></pre><p>We shall now define a function that allows us to group our churners by all three time columns called; hour of the day, day of the month and weekday. Otherwise, we will have to write code again and again for all three and it would be tedious. We need to improve our coding style everyday to be expert coder. After <em>groupby</em> on particular column for <em>subsetted churners</em>, we should be counting <em>userId </em>as filter.</p><p>Ex: <em>churners.groupby(SelectedColumn).count_our_userIds</em>. and same for <em>non-churners</em> of when <em>churn = 0</em>. After this, we would try to make our <em>indexes</em> as <em>integers</em> for this newly generated <em>series</em> if possible or else leave it as it is. Trying to make such indexing is beneficial for ease of future indexing or change of business or technical requirement purposes. But, neither is necessary at this point in our learning process. Hence, a <em>try and except</em> block would do here. We shall also provide user an option to <em>normalize</em> their <em>series</em> by giving a <em>Boolean normalize</em> <em>parameter</em> in our <em>function</em>. We shall simply use our academic <em>percentage</em> calculation <em>for normalization</em> if at all needed as it is anyways, just a plot to see the trend at the end.</p><pre>def get_series(col, churn, normalize=False):</pre><pre> ser1 = dfp[dfp.churn == churn].groupby([col])[‘userId’].count()<br> <br> try:<br>     ser1.index = ser1.index.astype(int)<br> except:<br>     pass</pre><pre>if normalize:<br>     ser1=ser1/ser1.sum()*100<br> <br> return ser1.sort_index()</pre><p>But we need to plot for all three duration. Therefore, another function needs to be declared which carries;</p><ol><li>) the above one in its belly for both churners(<em>churn = 1</em>) and non-churners(<em>churn = 0</em>) is needed.</li><li>) the function that takes the column on which to <em>groupby</em> our <em>churn</em> column data,</li><li>) the <em>normalize Boolean</em> of above function.</li><li>) any <em>title</em> or <em>rotation</em> in plot if user wishes at all, just for visual analytics convenience.</li></ol><pre>def draw_time(col, normalize=True, figsize=(16,4), title=None, label_rotation=0):<br> <br> df_time = pd.DataFrame({‘Cancelled’: get_series(col, 1, normalize),<br>                      ‘Active users’:get_series(col, 0, normalize)})<br> <br> ax = df_time.plot(kind=’bar’, figsize=figsize);<br> ax.set_ylabel(‘Percent of users’)<br> <br> if title is None:<br>     title = col<br> <br> ax.set_ylabel(f’Percent of users’)<br> ax.set_xticklabels(ax.get_xticklabels(), rotation=label_rotation)<br> ax.set_title(f’Percent of users took action per {title}’) <br> <br> return ax</pre><p>Time to draw without anymore redundant verbosity.</p><ul><li><strong>Churn and Non-churn by hour of the day</strong>:</li></ul><pre>draw_time(‘hour’, title=’hour of the day’);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nONhB93ucN23PtjvITyGbQ.png" /></figure><ul><li><strong>Churn and Non-churn by day of month</strong>:</li></ul><pre>draw_time(‘day’, title=’day of the month’);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*cf8i8o5Us8b-x_eptzJKdA.png" /></figure><ul><li><strong>Churn and Non-Churn by weekday of week</strong>:</li></ul><pre>ax = draw_time(‘week_day’, title=’week day’)<br>ax.set_xticklabels([‘Mon’, ‘Tue’, ‘Wed’, ‘Thu’, ‘Fri’, ‘Sat’, ‘Sun’], rotation=0);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pIDL0Eweng-phye4wlSMg.png" /></figure><h4><strong>III) Graphical EDA</strong>:</h4><p>There is a famous term in customer churning called <em>Customer Lifetime Value </em>or its acronym as <em>CLV</em>. It helps us know the future net profit of a particular customer till the time our relationship is with this customer. <strong>Marketing Project Managers and Marketing Presidents are interested in these figures</strong>. For the purpose of coming up with this figure, we should be able to predict the time this customer is gonna stay with us or at-least understand when is he/she going to churn to mitigate their chances to do so and increase the profit.</p><p>Such analysis is more sophisticated than presented here. But, for now the focus of this article is to bridge the gap between academic learning and industrial requirements. Hence, we have to come up with such EDA that gives us these marks or trends when customer can churn. Above time analysis is one of its part. So lets dive into some more <em>EDA, to look deep inside the behavior of a customer who has churned and the one who isn’t in their lifetime.</em></p><ul><li><strong>Lifetime since registration</strong>:</li></ul><p>Let us start by seeing; when are the customers churning from their registration time. Are they churning quickly after sometime from the day of registration or they do after much longer period of stay. For how much time are they using our service?</p><p>Therefore, we will have to subtract <em>ts</em> column for user from <em>registration</em> to find the lifetime or the duration. we will make another column called <em>lifetime</em>. Then we would need the <em>max value</em> from this column. But, we need this for a particular user for both the group of churners and non-churners. Hence we would need to <em>groupby</em> these two columns called <em>userId</em> and <em>churn</em>. Do not forget to convert the <em>pyspark</em> <em>dataframe</em> to <em>pandas</em> <em>dataframe</em> at the end for purpose of visualization using <em>matplotlib</em>. For some reason I was getting an error at this line. Hence, importing these sql functions make the bug go away and discipline these lines of code.</p><pre>from pyspark.sql.functions import sum as Fsum, col, split, mean, first, lit</pre><pre>stat_df = data.select(‘userId’,’registration’,’ts’,’churn’) \<br> .withColumn(‘lifetime’,(data.ts-data.registration)) \<br> .groupBy(‘userId’,’churn’).agg({‘lifetime’:’max’}) \<br> .withColumnRenamed(‘max(lifetime)’,’lifetime’) \<br> .select(‘userId’, ‘churn’, (col(‘lifetime’)/1000/3600/24).alias(‘lifetime’)).toPandas()</pre><p>Visualizing using <em>matplotlib </em>remains same as before. Create an object called ax to customize and save the <em>canvas on which we gotta draw and what we are drawing. </em>Then just play with each attribute and feature for customizing as we want. The fancy line of code here for <em>yticklabels</em>; <em>[item.get_text() for item in ax.get_yticklabels()] </em>is nothing fancy<em>, </em>it just fetches the yticklabels which are 1 and 0 from our given churn column and replaces it in our next lines where labels as churn and non-churn are assigned in <em>labels = [‘non-churners’,’churners’] </em>and replaced in its following line; <em>ax.set_yticklabels(labels)</em>.</p><pre>ax =stat_df.boxplot(column=’lifetime’, by=’churn’, figsize=(5,5), vert = False)#kind=’box’, ));<br>ax.set_xlabel(‘Days from registration before churning’)<br>labels = [item.get_text() for item in ax.get_yticklabels()]<br>labels = [‘non-churners’,’churners’]<br>ax.set_yticklabels(labels)<br>ax.get_figure().suptitle(“”)<br>ax.set_title(‘Lifetime of customers’)<br>ax.set_ylabel(‘customer type’);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*4lwPtqNG2xHVWS0gvOU-sQ.png" /></figure><p>This, gives us a stark visual that churners had much shorter lifetime than the non-churners and hence their activity would be way less than the non-churners. <strong>This is a beneficial insight as we can send emails, calls or even provide some offers and extra features to people who cancelled. This can help us deliberate their cancellation confirmation</strong> and may even workout for customer retention, if odds are in our favour. <strong>A detail market survey is needed though at the end to create a huge impact from any insight and make it more roboust by different other evidences to support it</strong>. Nevertheless, this is also a drawback in modelling as this will come as <strong>bias in our models where churners had shorter lifetime. Some normalization or sampling tweaks can be done to mitigate this bias in our models</strong>.</p><ul><li><strong>Songs listened by Churners and Non-Churners by Gender</strong>:</li></ul><p>We have to take songs liked (<em>ThumbsUp</em>)as well as songs played(<em>NextSong</em>) by user for knowing the songs listened by these categories. xticks are just for purpose arranging the visualization appropriately and prevent overlapping of labels on x-axis. Hence, beginners must avoid dwelling on why these xticks values were taken. They were just trial and error to prevent overlapping of labels.</p><pre>stat_df = data.where(‘page == “NextSong” OR page == “Thumbs Up”’).groupby([‘userId’, ‘churn’, ‘gender’, ‘page’]).count().toPandas()<br>stat_df = stat_df.pivot_table(index=[‘userId’,’churn’,’gender’], values=’count’, columns=’page’).reset_index()</pre><pre>fig, ax = plt.pyplot.subplots()</pre><pre>ax = plt.pyplot.violinplot(dataset=[stat_df[(stat_df.churn == 0) &amp; (stat_df.gender == &#39;M&#39;)][&quot;NextSong&quot;].values,<br>                                    stat_df[(stat_df.churn == 0) &amp; (stat_df.gender == &#39;F&#39;)][&quot;NextSong&quot;].values,<br>                                    stat_df[(stat_df.churn == 1) &amp; (stat_df.gender == &#39;M&#39;)][&quot;NextSong&quot;].values,<br>                                    stat_df[(stat_df.churn == 1) &amp; (stat_df.gender == &#39;F&#39;)][&quot;NextSong&quot;].values<br>                                   ])</pre><pre>plt.pyplot.xticks([1,2.1,3.1,4],[&#39;Non-Churn Males&#39;,&#39;Non-Churn Females&#39;,&#39;Churn Males&#39;,&#39;Churn Females&#39;])<br>plt.pyplot.xlabel(&#39;Classes&#39;)<br>plt.pyplot.ylabel(&#39;Lifetime songs listened&#39;)<br>plt.pyplot.title(&quot;Customer lifetime songs listened did/n&#39;t vary a lot&quot;)</pre><pre>plt.pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*KlOUmgo1Cfxd1dwvKy9UxA.png" /></figure><p>Thus, for same genders; songs listened did not vary much for both churners and non-churners. Exception is of some females who listened a lot more music than all three categories above. For not we can ignore this outlier and focus on stronger trends.</p><ul><li><strong>Songs listened per session</strong>:</li></ul><p>We would need here “<em>NextSong”</em> <em>page</em> and must <em>count()</em> it for each user within both <em>churn (1)</em> and <em>non-churn (0)</em> category of <em>churn</em> colum for both <em>gender</em>(s) along with user’s number of sessions by using <em>groupby</em> over them and then averaging<em>(avg())</em> off numer of songs(<em>count() of “NextSong”</em>).</p><p>Thus code should be something like; <em>bla bla page ==”NextSong”.groupby([‘churn’, ’userId’, ’sessionId’, ’gender’]).count().groupby(bla bla remaining other columns). aggregate(bla avg(bla)).bla bla</em></p><pre>stat_df = data.where(&#39;page == &quot;NextSong&quot;&#39;).groupby([&#39;churn&#39;, &#39;userId&#39;, &#39;sessionId&#39;,&#39;gender&#39;]).count()\<br>    .groupby([&#39;churn&#39;, &#39;userId&#39;, &#39;gender&#39;]).agg({&#39;count&#39;:&#39;avg&#39;})\<br>    .withColumnRenamed(&#39;avg(count)&#39;, &#39;avg_songs_played&#39;)\<br>    .toPandas()</pre><pre>fig, ax = plt.pyplot.subplots()<br>ax = plt.pyplot.violinplot(dataset=[stat_df[(stat_df.churn == 0) &amp; (stat_df.gender == &#39;M&#39;)][&quot;avg_songs_played&quot;].values,<br>                                    stat_df[(stat_df.churn == 0) &amp; (stat_df.gender == &#39;F&#39;)][&quot;avg_songs_played&quot;].values,<br>                                    stat_df[(stat_df.churn == 1) &amp; (stat_df.gender == &#39;M&#39;)][&quot;avg_songs_played&quot;].values,<br>                                    stat_df[(stat_df.churn == 1) &amp; (stat_df.gender == &#39;F&#39;)][&quot;avg_songs_played&quot;].values,<br>                                    ])</pre><pre>plt.pyplot.xticks([1,2.1,3.1,4],[&#39;Non-Churn Males&#39;,&#39;Non-Churn Females&#39;,&#39;Churn Males&#39;,&#39;Churn Females&#39;])<br>plt.pyplot.xlabel(&#39;Classes&#39;)<br>plt.pyplot.ylabel(&#39;Average songs played per session&#39;)<br>plt.pyplot.title(&quot;Customers playing music per session&quot;)</pre><pre>plt.pyplot.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*MGzHTDuJt3tjEAyTm76Olw.png" /></figure><p>Both males category for Churn and Non-Churn seem to have played more song per session. Hence, maybe males are following a trend of testing the app for some reasons like whether to buy or remain on subscription or explore all feature at once, or follow some schedule of listening music, etc. This can be another insight useful for our marketing department. So let us keep this in our backyard for now.</p><ul><li><strong>Pages visited by Churners and Non-Churners</strong>:</li></ul><p>Last but not the least. Here we will see all the pages both our Churning and Non-churning users visited and the number of their visits to see whether we get any pattern or strong insights. To tell my readers something, I know in advance that it will reveal some obvious yet interesting behaviour for both categories. Because, the usage of both categories will be and should be different to bear different results. This is very common in customer churning analysis for various domains. A particular variable that reveals all for the data scientists to get the story in depth or atleast a lion’s stake of it. Here its the “page” column.</p><p>We are <em>subsetting two dataframes</em> for both <em>churn == 1</em> and <em>churn == 0</em> and then <em>grouping by page column by dropping records for</em> “<em>NextSong</em>” as it would totally dominate our graph and would not even have any interesting information rather than number of songs listened which we have already covered in above two sections of this Graphical EDA.</p><p>First line of code for both <em>users_1</em> and <em>users_0</em> pulls record for respective category (<em>churn == 1</em> and <em>churn == 0</em>)and then subsets and creates dataframe only with users and pages visited(<em>[[‘userId’,’page’]]</em>). Then it groups the page(s) categories(<em>groupBy([‘page’])</em>) and counts users (<em>count(‘userId’))</em>) in each (<em>one user can occur multiple time within one group of category here but its not something that should worry us, so ignore !!</em>). Then we drop the records or entire group created for category “NextSong” and pull records for the rest and save it in <em>users_((1) or (0)) </em>using; <em>.filter(data[‘page’] != ‘NextSong’).</em></p><p>Second line of code for both <em>users_1</em> and <em>users_0</em> selects grouped <em>page</em> column and counted users column<em>; users_1.select(f.col(‘page’), <br> (f.col(‘count(userId)’).</em> Then divides this later column by total number of records; <em>/users_1.select(Fsum(‘count(userId)’)).</em> It is done to perform the averaging and scaling as well which helps understand proportion in each page visited within each category of churn and non-churn.</p><pre># Creating records of Churned users<br>users_1 = data[data[&#39;churn&#39;] == 1][[&#39;userId&#39;,&#39;page&#39;]].groupBy([&#39;page&#39;]).agg(<br>    count(&#39;userId&#39;)).filter(data[&#39;page&#39;] != &#39;NextSong&#39;)</pre><pre>users_1 = users_1.select(f.col(&#39;page&#39;), <br>                         (f.col(&#39;count(userId)&#39;)/users_1.select(Fsum(&#39;count(userId)&#39;)).collect()[0][0])*100)</pre><pre>users_1 = users_1.withColumnRenamed(&quot;((count(userId) / 8470) * 100)&quot;, &quot;%churn&quot;)</pre><pre># Creating records for Active Users<br>users_0 = data[data[&#39;churn&#39;] == 0][[&#39;userId&#39;,&#39;page&#39;]].groupBy([&#39;page&#39;]).agg(<br>    count(&#39;userId&#39;)).filter(data[&#39;page&#39;] != &#39;NextSong&#39;)</pre><pre>users_0 = users_0.select(f.col(&#39;page&#39;), <br>                         (f.col(&#39;count(userId)&#39;)/users_0.select(Fsum(&#39;count(userId)&#39;)).collect()[0][0])*100)</pre><pre>users_0 = users_0.withColumnRenamed(&quot;((count(userId) / 41576) * 100)&quot;, &quot;%nonchurn&quot;)</pre><pre># Plotting percentage of churned users besides active users<br>stat_df = users_1.join(users_0, &quot;page&quot;,&#39;left_outer&#39;)<br>stat_df = stat_df.toPandas()<br>stat_df = stat_df.set_index(stat_df.columns[0])</pre><pre>ax = stat_df.plot(kind=&#39;barh&#39;, figsize=(10,14));<br>ax.set_xlabel(&#39;Percent of event occurence (%)&#39;)<br>ax.set_title(&#39;Percent of event occurence for churned and nonchurned users&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*MvWTAZCRUnEL9eL3-IqKpg.png" /></figure><p>The stark differences between thumbs up for churners and non-churned users shows that churners were heavily disappointed with songs that they liked or probably even the audio quality of them.This is also supported with the bar of “Add friend” and “Add to Playlist” which is much higher for non-churners as compared to churners showing the likeness of non-churners being much higher than the users that churned.</p><p>The above explanation is also supplemented by seeing the “Thumbs down” bar higher for users who churned as compared for the ones that did not churned. The churners “Roll Advertisement” much larger as compared to ones that did not cancel. This too supports the claim that churners were highly dissapointed with song quality or collection and we should focus on feedback from them to improve the drawbacks.</p><p><strong>Thank you to my readers</strong>:</p><p>If you have made it till here, then I appreciate your patience of reading my article, Please leave your responses below. I would surely appreciate any improvements or criticisms suggested.</p><p>The link for next part is given below:</p><p><a href="https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8">https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b6fefc07bba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Customer Churn for a Music Company]]></title>
            <link>https://medium.com/@kaustubh.ursekar/predicting-customer-churn-for-a-music-company-1b71111b0483?source=rss-aad6b6fcd9ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b71111b0483</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kaustubh Ursekar]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 16:58:08 GMT</pubDate>
            <atom:updated>2020-02-07T20:18:16.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step I: A Beginner’s step by step guide to build Machine Learning Models of Customer Churn for a Music Company in <strong>PySpark.</strong></h3><h3><strong>Preface</strong>:</h3><p>“<strong>All I want is my customer back</strong>” is increasingly becoming a dominant attitude in business meetings these days. From CEOs of companies to Project managers, everyone wishes to know parameters like customer satisfaction, customer retention, etc. These metrics sustains the business models in the modern world and data science is a bloating technology that can be leveraged for this purpose. Thus, nobody wishes to stay behind or miss this opportunity to increase their market footprint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*LbTyOcvDhsTRYO-M9lfhAw.jpeg" /></figure><h3><strong>Introduction:</strong></h3><p>I shall discuss an example of music company data to predict customer churn. This post is intended for people who are brand new to coding in data science field or the ones, who are unaware of technical coding aspects of customer churning.</p><p>Below are the mentioned features of this project:</p><ol><li>) Python 3.x will be used along with Jupyter Notebook.</li><li>) A sample of 128mb from BigData of 12gb is used to work in Pyspark</li><li>) One can setup this spark cluster on AWS or IBM CLOUD with mediocre modification of code.</li><li>) Step by Step guide from importing libraries to hyper parameter tuning.</li><li>) Two models : <strong>Gradient Boosted Tree</strong> and <strong>Logistic Regression</strong> shall be used to predict the churning customers</li><li>) Link to GitHub repository for entire notebook: <a href="https://github.com/ursekar/ML-Model-of-Customer-Churn/blob/master/Sparkify.ipynb">https://github.com/ursekar/ML-Model-of-Customer-Churn/blob/master/Sparkify.ipynb</a></li></ol><h3><strong>The Project</strong>:</h3><p><strong>I have divided my blog post in 4 parts and I have given the link below to all 4 parts of this blog post</strong>. Because, it would be too long for one to grasp everything in a single read or post. I have went in detail throughout my voyage and steered it through each sets of this oceanic topic. <em>The 4 humongous waves are (Parts and Links to those Parts)</em>:</p><p><strong>Part I</strong>: Understanding Dataset &amp; Data Wrangling; “<em>You are here !”</em>.</p><p><strong>Part II</strong>: EDA or Exploratory Data Analysis;</p><p><a href="https://medium.com/@kaustubh.ursekar/step-ii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-8b6fefc07bba"><em>https://medium.com/@kaustubh.ursekar/step-ii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-8b6fefc07bba</em></a></p><p><strong>Part III</strong>: Feature Engineering;</p><p><a href="https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8"><em>https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8</em></a></p><p><strong>Part IV</strong>: Modelling &amp; Hyperparameter Tuning;</p><p><a href="https://medium.com/@kaustubh.ursekar/part-iv-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-85dc64257e0d"><em>https://medium.com/@kaustubh.ursekar/part-iv-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-85dc64257e0d</em></a></p><h4>Data Sources:</h4><p>I have used data provided by Udacity. There are 3 versions of the dataset as the data provided is 12 GB, which is very large. These 3 versions are: a small cluster of 128 MB, a medium size of data of about 6 GB and complete data of 12 GB.</p><p>The deployment can be performed using IBM Cloud or AWS as one desires. For the simplicity of this blog. I shall go with the small cluster of 128 MB provided to us. Do not worry, this code can be re-used with mediocre to no change on both cloud types.</p><p><strong>The 3 types of same dataset available are</strong>:</p><ol><li>) <strong>12 GB Dataset</strong>: You can use the below code line for importing data in your spark session on AWS.</li></ol><p>Full Sparkify Dataset: s3n://udacity-dsnd/sparkify/sparkify_event_data.json</p><p>2.) <strong>6 GB Dataset</strong>: You can download the data from below link</p><p><a href="https://video.udacity-data.com/topher/2018/December/5c1d6681_medium-sparkify-event-data/medium-sparkify-event-data.json">https://video.udacity-data.com/topher/2018/December/5c1d6681_medium-sparkify-event-data/medium-sparkify-event-data.json</a></p><p>3.) <strong>128 MB Small Cluster Dataset</strong>: You can download the data from my Repository below. I have uploaded zipped version of the data. Hence, do not forget to unzip and extract the 128 MB data.</p><p><a href="https://github.com/ursekar/BigData-PySpark">https://github.com/ursekar/BigData-PySpark</a></p><h4><strong>Importing Libraries and Data Introduction</strong>:</h4><p>The Project is done in PySpark along with Pandas and MatplotLib which is used for visualizations. To perform count, sum, groupby, sorting, and other mathematical and logical tweaks, as well as for defining our own functions we shall need <em>functions </em>library of SQL from <em>pyspark.sql.functions</em>. You will soon see this library to prove useful in data exploration, data munging and wrangling. Secondly, we shall need library of <em>ml </em>from <em>pyspark </em>for machine learning and mending of variables. We would need to import <em>feature, evaluation, classification, tuning</em>, etc. Here is all you need to import.</p><pre>from pyspark.sql import SparkSession<br>from pyspark.sql.window import Window<br>from pyspark.sql.types import IntegerType<br>from pyspark.sql.functions import isnan, count, when, col, desc, col, sort_array, asc, avg<br>from pyspark.sql.functions import sum as Fsum, col, split, mean, first, lit<br>from pyspark.sql.functions import UserDefinedFunction as udf<br>from pyspark.sql.functions import broadcast</pre><pre>from pyspark.ml.feature import StandardScaler, VectorAssembler<br>from pyspark.ml.evaluation import MulticlassClassificationEvaluator<br>from pyspark.ml.classification import GBTClassifier,LinearSVC, LogisticRegression<br>from pyspark.ml.tuning import CrossValidator, ParamGridBuilder</pre><pre>import pandas as pd<br>import numpy as np<br>import pyspark.sql.functions as f<br>import datetime<br>import matplotlib as plt</pre><p>Now let us import our data. We need to create a spark session for this purpose. I have given app name as: <em>“Spark SQL Quiz”. </em>One can give anything else if he she desires to. Once done, now I import my json file named <em>mini_sparkify_event_data.json.</em></p><pre># create a Spark session<br>spark = SparkSession \<br>    .builder \<br>    .appName(&quot;Spark SQL Quiz&quot;) \<br>    .getOrCreate()</pre><pre>data = spark.read.json(&quot;mini_sparkify_event_data.json&quot;)</pre><p>Viewing schema, simply means that we are trying to see columns in our data using <em>printSchema()</em> attribute on our dataset as shown.</p><pre>data.printSchema()<br><br><strong>root<br> |-- artist: string (nullable = true)<br> |-- auth: string (nullable = true)<br> |-- firstName: string (nullable = true)<br> |-- gender: string (nullable = true)<br> |-- itemInSession: long (nullable = true)<br> |-- lastName: string (nullable = true)<br> |-- length: double (nullable = true)<br> |-- level: string (nullable = true)<br> |-- location: string (nullable = true)<br> |-- method: string (nullable = true)<br> |-- page: string (nullable = true)<br> |-- registration: long (nullable = true)<br> |-- sessionId: long (nullable = true)<br> |-- song: string (nullable = true)<br> |-- status: long (nullable = true)<br> |-- ts: long (nullable = true)<br> |-- userAgent: string (nullable = true)<br> |-- userId: string (nullable = true)</strong></pre><p>Let us see records in our data-frame too. Observe here, that Spark data-frames are generally ones with many columns and they also give us data very much unaligned when attribute <em>show()</em> is thrown after them. Hence, we shall use some parameters with <em>show() </em>attribute and produce the first 5 records of dataframe without truncating them.</p><pre>data.show(vertical = True, n=5, truncate=False)</pre><pre><strong>-RECORD 0-----------------------------------------------------------<br> artist        | Martha Tilston                                                                                                  <br> auth          | Logged In                                                                                                       <br> firstName     | Colin                                                                                                           <br> gender        | M                                                                                                               <br> itemInSession | 50                                                                                                              <br> lastName      | Freeman                                                                                                         <br> length        | 277.89016                                                                                                       <br> level         | paid                                                                                                            <br> location      | Bakersfield, CA                                                                                                 <br> method        | PUT                                                                                                             <br> page          | NextSong                                                                                                        <br> registration  | 1538173362000                                                                                                   <br> sessionId     | 29                                                                                                              <br> song          | Rockpools                                                                                                       <br> status        | 200                                                                                                             <br> ts            | 1538352117000                                                                                                   <br> userAgent     | Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0                                        <br> userId        | 30                                                                                                              <br>-RECORD 1-----------------------------------------------------------<br> artist        | Five Iron Frenzy                                                                                                <br> auth          | Logged In                                                                                                       <br> firstName     | Micah                                                                                                           <br> gender        | M                                                                                                               <br> itemInSession | 79                                                                                                              <br> lastName      | Long                                                                                                            <br> length        | 236.09424                                                                                                       <br> level         | free                                                                                                            <br> location      | Boston-Cambridge-Newton, MA-NH                                                                                  <br> method        | PUT                                                                                                             <br> page          | NextSong                                                                                                        <br> registration  | 1538331630000                                                                                                   <br> sessionId     | 8                                                                                                               <br> song          | Canada                                                                                                          <br> status        | 200                                                                                                             <br> ts            | 1538352180000                                                                                                   <br> userAgent     | &quot;Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36&quot; <br> userId        | 9                                                                                                               <br>-RECORD 2-----------------------------------------------------------<br> artist        | Adam Lambert                                                                                                    <br> auth          | Logged In                                                                                                       <br> firstName     | Colin                                                                                                           <br> gender        | M                                                                                                               <br> itemInSession | 51                                                                                                              <br> lastName      | Freeman                                                                                                         <br> length        | 282.8273                                                                                                        <br> level         | paid                                                                                                            <br> location      | Bakersfield, CA                                                                                                 <br> method        | PUT                                                                                                             <br> page          | NextSong                                                                                                        <br> registration  | 1538173362000                                                                                                   <br> sessionId     | 29                                                                                                              <br> song          | Time For Miracles                                                                                               <br> status        | 200                                                                                                             <br> ts            | 1538352394000                                                                                                   <br> userAgent     | Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0                                        <br> userId        | 30                                                                                                              <br>-RECORD 3-----------------------------------------------------------<br> artist        | Enigma                                                                                                          <br> auth          | Logged In                                                                                                       <br> firstName     | Micah                                                                                                           <br> gender        | M                                                                                                               <br> itemInSession | 80                                                                                                              <br> lastName      | Long                                                                                                            <br> length        | 262.71302                                                                                                       <br> level         | free                                                                                                            <br> location      | Boston-Cambridge-Newton, MA-NH                                                                                  <br> method        | PUT                                                                                                             <br> page          | NextSong                                                                                                        <br> registration  | 1538331630000                                                                                                   <br> sessionId     | 8                                                                                                               <br> song          | Knocking On Forbidden Doors                                                                                     <br> status        | 200                                                                                                             <br> ts            | 1538352416000                                                                                                   <br> userAgent     | &quot;Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.103 Safari/537.36&quot; <br> userId        | 9                                                                                                               <br>-RECORD 4-----------------------------------------------------------<br> artist        | Daft Punk                                                                                                       <br> auth          | Logged In                                                                                                       <br> firstName     | Colin                                                                                                           <br> gender        | M                                                                                                               <br> itemInSession | 52                                                                                                              <br> lastName      | Freeman                                                                                                         <br> length        | 223.60771                                                                                                       <br> level         | paid                                                                                                            <br> location      | Bakersfield, CA                                                                                                 <br> method        | PUT                                                                                                             <br> page          | NextSong                                                                                                        <br> registration  | 1538173362000                                                                                                   <br> sessionId     | 29                                                                                                              <br> song          | Harder Better Faster Stronger                                                                                   <br> status        | 200                                                                                                             <br> ts            | 1538352676000                                                                                                   <br> userAgent     | Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0                                        <br> userId        | 30</strong></pre><pre><strong>only showing top 5 rows</strong></pre><p>I shall discuss the types of columns and how we would be using or dropping them in coming parts.</p><h4>Data Cleaning and Wrangling:</h4><p>Now comes our time to get hands dirty in this project. The most important yet tedious part of any data science project after machine learning could be data exploration. So I will jump right into it without any fancy quotes or inspirational idioms.</p><p>I am complete noob (amateur or new-be). I hope some of you guys reading this article are like me and the ones who are expert, please feel free to criticize me in your responses below.</p><p>Thus, I start with viewing the null or nan entries in each column of my data by using <em>is.nan()</em>. But this gives only boolean output and hence I need a math operator like <em>count()</em> to know exactly how many are null entries in each column of data as <strong><em>count(when(isnan(c), c))bla bla</em></strong> .</p><p>Also, I would need a <em>for </em>loop as I will be passing each column to my <em>is.nan()</em> one at a time like <strong><em>bla for c in data.columns</em></strong><em>. </em>All these would come together to make my entire function in one line of code as:</p><pre>data.select([count(when(isnan(c), c)).alias(c) for c in data.columns]).show(vertical = True, Truncate = False)</pre><pre><strong>-RECORD 0------------<br> artist        | 0   <br> auth          | 0   <br> firstName     | 0   <br> gender        | 0   <br> itemInSession | 0   <br> lastName      | 0   <br> length        | 0   <br> level         | 0   <br> location      | 0   <br> method        | 0   <br> page          | 0   <br> registration  | 0   <br> sessionId     | 0   <br> song          | 0   <br> status        | 0   <br> ts            | 0   <br> userAgent     | 0   <br> userId        | 0</strong></pre><p>Thus we do not have any <em>null</em> or <em>nan</em> entries in our data. But is it really true or are we deceived? Well, we would see that later. For now, this much would do to proceed ahead for deciding which column will act as “<em>churn” </em>or simply put “dependent variable” in our ML models. We see that the user goes out completely once they confirm their cancellation of subscription of a product or service. Hence, we need to look for such a page under the <em>page</em> column to tell us whether user has cancelled out or not.</p><pre>data.select(“page”).distinct().show(truncate = False)</pre><pre><strong>+-------------------------+<br>|page                     |<br>+-------------------------+<br>|Cancel                   |<br>|Submit Downgrade         |<br>|Thumbs Down              |<br>|Home                     |<br>|Downgrade                |<br>|Roll Advert              |<br>|Logout                   |<br>|Save Settings            |<br>|Cancellation Confirmation|<br>|About                    |<br>|Submit Registration      |<br>|Settings                 |<br>|Login                    |<br>|Register                 |<br>|Add to Playlist          |<br>|Add Friend               |<br>|NextSong                 |<br>|Thumbs Up                |<br>|Help                     |<br>|Upgrade                  |<br>+-------------------------+</strong></pre><p>From all these, we see that we have “<em>Cancellation Confirmation”</em> page that guarantees or assures us the cancellation of the user for this particular music service. Hence we would take this particular page as our label of interest. But we cannot be using this label as it is. We would need binary approach of 1 and 0 to get us it in the language ML models would understand. Therefore, we can simply write a flag function with an <em>if..else..</em> condition to indicate match to “<em>Cancellation Confirmation</em>” as 1 and others as 0.</p><pre># Define a flag function<br>flag_cancelation_event = udf(lambda x: 1 if x == &quot;Cancellation Confirmation&quot; else 0, IntegerType())</pre><p>But, here is one problem. The <em>userId</em> column will have multiple entries for an user. Because, the user would have liked, disliked and changed songs or done other activity causing him/her to visit more than one pages, such as “<em>Thumbs up</em>”, “<em>Thumbs down</em>”, “<em>NextSong</em>”, etc. Therefore, there would be more than one <em>userId</em> records or rows for a particular user who has churned and One would want to be sure that all of them give us 1 value in the page column. Thus, we would need here something like SQL, that partition’s records of our users by their unique ids and yields us the dataset of our interest. This can be achieved by importing <em>Window </em>from<em> sql.window. </em>We would save these 1s and 0s in seperate column called <em>churn</em>, by adding it to our dataset.</p><pre># Define a flag function<br>flag_cancelation_event = udf(lambda x: 1 if x == “Cancellation Confirmation” else 0, IntegerType())</pre><pre># apply to the dataframe<br>data = data.withColumn(“churn”, flag_cancelation_event(“page”))</pre><pre>#Define window bounds<br>windowval = Window.partitionBy(“userId”).rangeBetween(Window.unboundedPreceding, Window.unboundedFollowing)</pre><pre># Applying the window<br>data = data.withColumn(“churn”, Fsum(“churn”).over(windowval))</pre><pre>print(‘The total number of churners are:’, data.agg(Fsum(“churn”)).collect()[0][0])</pre><pre><strong>The total number of churners are: 44864</strong></pre><p>But the above are total number of records of these churners. To find the number of unique churners, we would need <em>distinct()</em>. We have used <em>Fsum()</em> which is nothing but as I call it “F<em>ancy sum()</em>” of PySpark working similarly as our <em>sum()</em> in python. Hence it would be our friend here, in PySpark environment.</p><p>Therefore, we select the <em>userId</em> and <em>churn</em> column and aggregate with <em>Fsum()</em> and apply <em>distinct()</em> to get our number of unique churned users.</p><pre>data.select(‘userId’, ‘churn’).distinct().agg(Fsum(“churn”)).collect()[0][0]</pre><pre><strong>52</strong></pre><p>Now, recollect that before we had only went through <em>Null</em> and <em>Nan</em> values for each column in our dataset, but we did not find any. Hence, to make sure that there really are not any, we should go on looking for even blank “” entries in each column of our dataset. Therefore, we shall define a function here that can do this job for us, no matter how many future columns get created in this dataset. The another reason for defining a function is, it would be easy for us to re-use this code while creating the .<em>py</em> files for producing an application of this code. So here we go.</p><p>Logic is to filter out records that are Nan, Null or Blank “” and count them. This can be easily done with <em>filter </em>attribute of the dataframe in pyspark. But we also wish to go over each column and we know that each column of dataframe comes out as either series or list. hence we would just introduce a <em>for </em>loop here to do our job of going through every column of our dataframe.</p><pre>def missing_recs(df, col):</pre><pre>return df.filter((isnan(df[col])) | (df[col].isNull()) | (df[col] == “”)).count()</pre><pre>print(“\nColumns in data are:\n”,data.columns)</pre><pre>print(“\n[missing values]\n”)<br>for col in data.columns:<br> missing_count = missing_recs(data, col)<br> if missing_count &gt; 0:<br> print(“{}: {}”.format(col, missing_count))</pre><pre><strong>Columns in data are:<br> [&#39;artist&#39;, &#39;auth&#39;, &#39;firstName&#39;, &#39;gender&#39;, &#39;itemInSession&#39;, &#39;lastName&#39;, &#39;length&#39;, &#39;level&#39;, &#39;location&#39;, &#39;method&#39;, &#39;page&#39;, &#39;registration&#39;, &#39;sessionId&#39;, &#39;song&#39;, &#39;status&#39;, &#39;ts&#39;, &#39;userAgent&#39;, &#39;userId&#39;, &#39;churn&#39;]<br><br>[missing values]<br><br>artist: 58392<br>firstName: 8346<br>gender: 8346<br>lastName: 8346<br>length: 58392<br>location: 8346<br>registration: 8346<br>song: 58392<br>userAgent: 8346<br>userId: 8346</strong></pre><p>Well !! this is a surprise now. Here we have caught lot of missing entries in our data. <strong>So are we suppose to bite our nails for them and scratch are heads for it</strong>? Not at all !! simply think by taking a step back and seeing overall. This is a music company and every user must be registered to enjoy either <em>free</em> or <em>paid</em> service.</p><p>Here the <em>userId</em> is acting something like primary key or Unique column within our data. Something we can say as, “a base point to keep our analysis on”. Therefore, let us drop blank records from dataframe where the entry for <em>userId</em> is missing and get only the genuine or authentic part of our data to establish our analysis upon.</p><p>For now, do not worry about blank entries of other columns as you are going to see how the industrial requirements differ from academic teaching in later modelling parts and know approach of <strong>“Feature Engineering”</strong> that is used most of times for highly sophisticated models. Thereby, we are touching the base of it here too, so stay on !</p><pre>print(‘Total number of rows in data are:’, data.count())<br>print(‘Length of data after dropping blank userId:’, data[data[‘userId’] != ‘’].count())<br>data = data[data[‘userId’] != ‘’]</pre><pre><strong>Total number of rows in data are: 286500<br>Length of data after dropping blank userId: 278154</strong></pre><p>Now its time to dive into the Exploratory Data Analysis. Simply acronymed as EDA.</p><h4><strong>Thank you to my readers</strong>:</h4><p>If you have made it till here, then I appreciate your patience of reading my article, Please leave your responses below. I would surely appreciate any improvements or criticisms suggested.</p><p>The link for next part is given below:</p><p><a href="https://medium.com/@kaustubh.ursekar/step-ii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-8b6fefc07bba">https://medium.com/@kaustubh.ursekar/part-iii-a-beginners-step-by-step-guide-to-build-machine-learning-models-of-customer-churn-for-a-88302bc468c8</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b71111b0483" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>