<?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 Linn Larsdotter Ohlsson on Medium]]></title>
        <description><![CDATA[Stories by Linn Larsdotter Ohlsson on Medium]]></description>
        <link>https://medium.com/@linn.ohlsson?source=rss-2bf26c285c18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*h_f43jUCqoq_-EcQiKPtmg.jpeg</url>
            <title>Stories by Linn Larsdotter Ohlsson on Medium</title>
            <link>https://medium.com/@linn.ohlsson?source=rss-2bf26c285c18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:42:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@linn.ohlsson/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[What should you focus on as an aspiring data scientist?]]></title>
            <link>https://medium.com/@linn.ohlsson/what-should-you-focus-on-as-an-aspiring-data-scientist-cfae11b70d88?source=rss-2bf26c285c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfae11b70d88</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-scientist]]></category>
            <dc:creator><![CDATA[Linn Larsdotter Ohlsson]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 12:38:38 GMT</pubDate>
            <atom:updated>2020-01-21T12:38:38.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5qZSUJsXR_Ov1jsIqMuXpg.jpeg" /><figcaption>Image via <a href="https://pixabay.com/sv/">Pixabay</a></figcaption></figure><p>Trying to enter the data science field can be overwhelming. It is broad, inter-disciplinary and largely undefined — so how do you know what you should focus on in becoming a data scientist? To try and give an answer to some of the questions on what would be useful when preparing to enter the industry, I have used responses from data scientists active in the industry from Kaggle’s yearly <a href="https://www.kaggle.com/c/kaggle-survey-2019">DS &amp; ML survey</a> from 2019.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*GZrTyTz0OKMbxnO5Trhcew.png" /><figcaption>Image via <a href="https://en.wikipedia.org/wiki/Kaggle">Wikipedia</a></figcaption></figure><p>The survey data includes 19 717 respondents from 171 countries and territories having various data-related titles, such as software engineers, analysts, data engineers, and of course, data scientists. It’s an industry-wide survey that aims to present a comprehensive view of the state of data science and machine learning and includes 34 questions, such as:</p><blockquote>“Who/what are your favorite media sources that report on data science topics?”</blockquote><blockquote>“What is the primary tool that you use at work or school to analyze data?”</blockquote><blockquote>“For how many years have you used machine learning methods?”</blockquote><h3>What education or learning platforms should I focus on in becoming a Data Scientist?</h3><p>The first step in the journey of becoming a data scientist is probably choosing some form of education or courses to further your knowledge. But how do you know what kind of education you need or where to look for relevant courses? To answer this question, a good start is to look at what data scientists active in the industry have done. Two questions from the survey cover this:</p><blockquote>“What is the highest level of formal education that you have attained or plan to attain within the next 2 years?”</blockquote><blockquote>“On which platforms have you begun or completed data science courses?”</blockquote><p>Here we can see the highest level of formal education that the data scientists in the study have attained or plan to attain within 2 years. More than 50% of the respondents have a master’s degree and combined, 92% of the respondents have some form of university degree, ranging from bachelor’s degrees to doctoral degrees. Only 0.6% have no formal education past high school.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*zOVDKKZUn3Oi-1j1vOX8BQ.png" /></figure><p>Below we can see the different learning platforms where respondents working as data scientists have begun or completed data science courses on. A majority of them, 23%, have used Coursera’s data science courses. An equal share, around 11%, have studied university courses resulting in a university degree, used Udemy’s and DataCamp’s courses respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*TAgM3mEjCw2RGI_2S3aNiQ.png" /></figure><p>This data can give us an indication of what education level is needed in the industry and what learning platforms would be the best to use in advancing your data science knowledge as an aspiring data scientist. Based on this, I would recommend data scientists-to-be to get a master’s degree and focus on furthering your knowledge with the help of Coursera’s data science courses.</p><p>It would also be interesting to explore what impact education levels and learning platforms might have on compensation, and what programming language data scientists that are comfortable with specific programming languages recommend to learn first.</p><h3>How do different education levels and learning platforms relate to compensation?</h3><p>Here we can see a graph of the relative impact each education level and learning platform seem to have on compensation, to explore if different educations and courses lead to higher compensation. The data in the graph has been scaled and the bars represent the relative impact on compensation compared to the other options, so the values on the x-axis don’t mean much in terms of their actual value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*0LyIngACFTHW3SYv_cNgPQ.png" /></figure><p>The highest positive impact on yearly compensation appears to be having a doctoral degree and taking data science courses on fast.ai’s learning platform. This means that the respondents with the highest yearly compensation in the survey reported having attained or planning to attain a doctoral degree within 2 years, and having begun or completed data science courses via fast.ai.</p><p>In contrast, having some college/university studies without earning a bachelor’s degree has the most negative impact on compensation, meaning that respondents with the lowest yearly compensation have attained this level of education.</p><p>Interestingly, having a bachelor’s degree as the highest level of education has a negative impact on compensation, suggesting it is worth spending the extra years and resources on getting a master’s degree and especially a doctoral degree to be successful in terms of compensation in the data science industry.</p><h3>What programming language should I learn?</h3><p>There is the forever going battle of which programming language is the best for data science. Isn’t it best to ask what actual data scientists think? To explore which programming language to focus on in becoming a data scientist, I used a survey question that identifies this very well:</p><blockquote>“What programming language would you recommend an aspiring data scientist to learn first?”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*fXzpu5mk3cZVsOZo7Inrrg.png" /></figure><p>From the graph above, the answer is pretty clear. Almost 80% of all respondents recommend learning Python first.</p><h3>What biases might respondents have in recommending which programming language to learn?</h3><p>Related to the question above, it would be interesting to explore if there is bias in recommending a programming language to learn to aspiring data scientists. Are regular users of a programming language more inclined to recommend it than those that don’t use it often?</p><p>In order to take a closer look at this, I divided the data into two groups for each recommended programming language, those that recommend it and use it regularly and those that recommend it but don’t use it on a regular basis. I then calculated the percental difference between the group that uses the programming language and the group that doesn’t, to see if users of a programming language are proportionally more inclined to recommend it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*uBhl9gMtdbBT8DXYliocmQ.png" /></figure><p>We can see the result of this in the above graph. Regular users of Python are 95% more likely to recommend learning it to aspiring data scientists compared to those that don’t use it regularly. There is also a lot of bias in recommending to learn R and SQL, regular users of these programming languages are 86% and 80% more inclined to recommend it, respectively.</p><p>The opposite is true for C and Java, regular users of these programming languages are less inclined to recommend learning them compared to respondents that don’t use them.</p><h3>Conclusion</h3><p>In this article, we took a look at what to focus on when preparing to enter the data science industry by using survey data from Kaggle’s yearly DS &amp; ML survey for 2019. Some findings:</p><ol><li>It is worth spending the extra time and resources on getting a university degree. In terms of getting the highest compensation, focus on getting a doctoral degree. It is also worth taking data science courses to further your knowledge and increase your compensation. Choose courses from learning platforms fast.ai and Coursera, they seem to have the greatest positive impact on compensation.</li><li>Focus on learning Python first when it comes to the various programming languages used for data science. We found that regular users of Python are much more inclined to recommend it compared to data scientists that don’t use it. C and Java seem like less important programming languages to focus on initially, regular users of these are less inclined to recommend them as a first programming language to learn compared to those that don’t use them.</li></ol><p>I hope these findings will help you with guidance on what path to take to become a successful data scientist!</p><p>To get more technical details on how the analysis was conducted, visit my <a href="https://github.com/LinnPinnFinn/-Write-a-Data-Science-Blog-Post">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfae11b70d88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Customer Churn with Apache Spark’s PySpark API]]></title>
            <link>https://medium.com/@linn.ohlsson/predicting-customer-churn-with-apache-sparks-pyspark-api-9c941af67a59?source=rss-2bf26c285c18------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c941af67a59</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[sparkml]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Linn Larsdotter Ohlsson]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 16:04:14 GMT</pubDate>
            <atom:updated>2020-01-16T16:04:14.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5gnKkNLLLrEw0-yTzc4Ew.png" /><figcaption>Image via <a href="https://itnext.io/how-to-create-a-simple-etl-job-locally-with-pyspark-postgresql-and-docker-ea53cd43311d">itnext.io</a></figcaption></figure><p><a href="https://blog.hubspot.com/service/what-is-customer-churn">Customer Churn</a> is one of the most important metrics for businesses to evaluate. It is the percentage of customers that stopped using your company’s product or service during a certain time frame. This is important to keep track of because it costs more to acquire new customers than it does to retain existing customers. In this article, we will go through how to manipulate a big dataset to engineer relevant features for predicting customer churn and build and evaluate machine learning models using Apache Spark’s <a href="https://spark.apache.org/docs/latest/api/python/index.html">PySpark API</a> and <a href="https://spark.apache.org/docs/2.2.0/api/python/pyspark.ml.html">PySpark ML Package</a>.</p><p>Two accompanying Jupyter notebooks to this article can be found <a href="https://github.com/LinnPinnFinn/Sparkify">here</a>. The ‘<em>sparkify_mini</em>’ notebook in the repository contains the initial analysis conducted on a subset of the data and you can check this out if you want more information on the data processing steps taken on the bigger dataset, which you can find in the ‘<em>sparkify_medium</em>’ notebook.</p><p>The dataset comes in the form of a JSON file that contains 543 705 samples of event log data for October-December 2018 for a fictional music streaming platform called Sparkify, similar to companies like Spotify and Pandora. The data has been provided by <a href="https://www.udacity.com/">Udacity</a> as part of a Data Science Nanodegree course. For this project, the notebook has been run in a spark environment directly on the IBM Watson Studio platform. To find out more about how to do this, visit IBM Watson Studio’s <a href="https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/spark-envs.html">documentation</a> or read <a href="https://medium.com/ibm-watson/ibm-watson-studio-spark-environments-generally-available-f3dda78d3668">this article</a> with more information on IBM Watson Studio’s Spark Environments.</p><h3>Defining churn</h3><p>Before building our prediction model, we need to define when a customer has churned and translate this into a <em>target variable</em> (the variable whose values are to be modeled and predicted by other variables) that can be used in a machine learning model.</p><p>In our case, we can do this rather easily, in other cases, this depends on the business and can vary greatly. In our dataset, there is a variable called ‘<em>page</em>’, showing which platform page the event is linked to. Here we have an option called ‘<em>Cancellation Confirmation</em>’, which refers to the company’s confirmation of a customer’s inquiry to cancel their account. Using this page event as our churn definition means that a customer has churned only when they have completely stopped using the service and canceled their account. This page event applies the same way to customers on both free and paid subscription plans, which makes this information easy to recode into our model target variable.</p><p>Here is some example code showing how we have defined and set up a binary output variable, ‘<em>churn</em>’, where 1 means that the user has churned and 0 means that the user is still active, and applied this to every row linked to the user (same ‘<em>userId</em>’):</p><pre># create &#39;churn&#39; and set 1 (churned) or 0 (active) for all rows</pre><pre># churn = 1 if column &#39;page&#39; = ‘Cancellation Confirmation’, else 0<br>df = df.withColumn(‘churn’, when(col(‘page’) == ‘Cancellation Confirmation’, 1).otherwise(0))</pre><pre># get userId’s where churn = 1<br>churned_users = df.select(‘userId’).where(col(‘churn’) == 1).groupby(‘userId’).count()</pre><pre># get values from ‘userId’ column and store as list<br>churned_users = [row[‘userId’] for row in churned_users.collect()]</pre><pre># set column ‘churn’ as 1 for all rows for a churned user<br>df = df.withColumn(‘churn’, when((df.userId).isin(churned_users), 1).otherwise(0))</pre><h3>Exploring the data</h3><p>Before we begin with selecting features to use and setting up our models, we should have a look at the data. When we load the dataset as a dataframe, it has the following structure, showing the column names and their data types:</p><pre>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)</pre><p>The 543 705 rows of event logs in the dataset belong to a total of 448 unique users, where 99 of them are churned users and 349 are active users. There are a few columns where data is missing, and they are related to columns containing user information and columns tied to a specific event type, namely events where a song was played.</p><p>Columns in the dataset with NaNs and Nulls:</p><pre>|artist|firstName|gender|lastName|length|location|registration|song||userAgent|<br>+------+----+---------+------+-------------+--------+------+-----+--<br>|110828|15700|15700|15700|110828|15700|15700|110828|15700|</pre><p>Columns in the dataset with empty strings:</p><pre>|userId|<br>+------+----+---------+------+-------------+--------+------+-----+--|15700|</pre><p>We can see that the columns ‘<em>artist</em>’, ‘<em>length</em>’ and ‘<em>song</em>’ have the same number of missing values. When looking more in-depth at the data, these columns only have data when the page event is related to playing a song (column ‘<em>page</em>’ == ‘<em>NextSong</em>’).</p><p>Columns ‘<em>firstName</em>’, ‘<em>gender</em>’, ‘<em>lastName</em>’, ‘<em>location</em>’, ‘<em>registration</em>’, ‘<em>userAgent</em>’ and ‘<em>userId</em>’ have the same number of missing values, and these columns contain information about a user. Missing user data in these columns is linked to column ‘<em>auth</em>’ having the value of ‘<em>Logged Out</em>’ or ‘<em>Guest</em>’. This means we do not have an identified user for these events and we should not include those events in our analysis, which is user-specific.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*xcDhmdq4NiFC1RH_Hz4KOg.png" /></figure><p>Above we can see the number of event types as proportions for each user group. Active users are illustrated in blue and churned users in orange. More than 80% of all events refer to playing songs (‘<em>NextSong</em>’) for both user groups. The average number of songs played per active user is 999 songs and per churned user it is 852 songs. Comparatively more active users have given thumbs ups and more churned users have received ads. There is also a small but noticeable difference in the number of friends added. On average, active users have added 19 friends, compared to churned users that have added 16 friends. It is hard to see from this graph, but there is also a difference in the number of home page visits (‘<em>Home</em>’), churned users have visited the home page 38 times on average and active users have visited the home page 44 times on average. The average number of total events for active users is 1216 events and for churned users it is 1047 events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*4ofP2zsj40DB8bB-qZlbeA.png" /></figure><p>The graph above shows the average session length in hours per user, split into churned and active users. For churned users, the average session length is 8.72 hours, and for active users it is 8.54 hours, so churned users spend slightly more time on the platform each time, but the difference is negligible. The average number of total sessions for active users is 14 sessions and for churned users it is 12 sessions. Not a great difference there either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*SlRBfgeGo-Cx-q2xJY045A.png" /></figure><p>Above we can see the number of days registered on the platform per user group. There is quite a big difference, active users have, on average, been registered on the platform for 87 days, meanwhile churned users have been registered for 68 days.</p><p>We have also calculated the number of unique artists and unique songs played per user, based on the frequency of each unique text string in the columns ‘<em>artist</em>’ and ‘<em>song</em>’ respectively. For churned users, the average number of unique artists played is 593 and for unique songs it is 757. Active users have, on average, played 678 unique artists and 879 unique songs.</p><p>If we look at the distribution of churned and active users when it comes to the subscription plan they are on, 48% of churned users are on a paid plan and 52% are on a free plan. For active users, 46% are on a paid plan and 54% are on a free plan, so this does not differ much between the user groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*oKntr7h50p047M3dG7y5NA.png" /></figure><p>In terms of the gender distribution for the user groups, there is not much of a difference. 55% of churned users are male and 45% are female. For active users, 56% are male and 44% are female.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GSSnqmYKxp_xwJozRbGBA.png" /></figure><p>Looking at the different states where the users are located, California (CA) is the most common for both user groups. Churned users are shown in orange and active users are shown in blue in the graph above, which illustrates the proportions of each user group across the states. The location distribution is a bit different between the groups, for example, Texas (TX) is more common for active users and Kentucky (KY) is more common for churned users.</p><h3>Feature engineering and selection</h3><p>Before we can set up our models, we need to decide on which columns (input features) to train the models on. Columns of interest would be those that showed differences between churned and active users.</p><p>Firstly, before we select which features to use in modeling, we need to engineer some new ones to understand our data. Based on our analysis and finding columns with differences across the user groups, we have recoded the frequency per user when it comes to number of events, number of sessions, average session length, number of days registered on the platform, number of songs, unique artists and unique songs played, thumbs ups given, added friends and home page visits, and finally, number of ads received, into new variables. We have done this to be able to use this information as input features when modeling, but restructuring the data to only contain one row per user instead of per event, since we are interested in user-specific behaviors.</p><p>We have also recoded some other columns. For example, we needed to change the Unix timestamps to a more human-readable format to calculate the average session length, and the original location variable had both the metropolitan area and the state in the same column so we split these into two separate columns. To see how all this has been done, check out the accompanying notebooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaMZ98ZcEI560KdDRyAzrA.png" /></figure><p>Here is a correlation matrix of all numerical columns, including the new ones we have recoded. We have also included ‘<em>gender</em>’, which we have recoded from a categorical to a binary numerical column, to be able to calculate its correlation to other columns. The correlation matrix shows that the total number of songs played (‘<em>total_song</em>’) has a perfectly positive correlation with the total number of events per user (‘<em>total_events</em>’) and the total number of unique songs played (‘<em>unique_songs</em>’). No columns appear to have a high correlation with our target variable ‘<em>churn</em>’.</p><p><a href="https://en.wikipedia.org/wiki/Feature_selection">Feature selection</a> is the process of selecting a subset of relevant features to use in building our model. We do this, among others, to enhance the model’s ability to generalize by reducing the risk of overfitting, shorten the training times and to simplify the model and make it easier to interpret. Based on our analysis, interesting columns that show differences between churned and active users, and that are good input feature candidates, are:</p><ul><li>number of days registered on the platform (‘<em>days_registered</em>’)</li><li>number of events (‘<em>total_events</em>’)</li><li>number of unique artists played (‘<em>unique_artists</em>’)</li><li>number of unique songs played (‘<em>unique_songs</em>’)</li><li>number of thumbs ups given (‘<em>total_thumbsup</em>’)</li><li>number of home page visits (‘<em>total_home</em>’)</li><li>number of friends added (‘<em>total_addfriend</em>’)</li><li>number of ads received (‘<em>total_rolladvert</em>’)</li><li>the location of users (‘<em>state</em>’)</li></ul><p>There were also differences between the user groups when it comes to the number of songs played (‘<em>total_songs</em>’), but as we could see in the correlation matrix, this column was perfectly correlated to other ones. Following the notion of <a href="https://en.wikipedia.org/wiki/Feature_selection#Correlation_feature_selection">Correlation Feature Selection</a> (CFS), good input features should not be highly correlated to each other, and we will remove this feature with the highest correlations to minimize this problem a bit, even though many of the other features still are highly correlated to each other.</p><p>To be able to use our columns of interest in modeling, we need to transform them into a format the works in a machine learning model. Our state column consists of nominal categorical values with no notion or sense of order amongst them. In general, machine learning models cannot handle this kind of data and we need to recode each state option to its own binary column, indicating if that state is selected for the row (code 1), which is called <em>one hot encoding</em>.</p><p>We should also apply some form of <a href="https://en.wikipedia.org/wiki/Feature_scaling">feature scaling</a> to our numerical columns. The range of values across our columns varies widely, and in many machine learning models, objective functions will not work properly without normalizing these. Normalizing these means that each feature contributes proportionately to the model and not based on the different ranges of values in each column, which would mean that a column with higher values would be more important to the model than a column with low values. The <em>MinMaxScaler</em> is a good feature scaling method for our data, it gives each input feature a value range of 0–1, but still <a href="https://towardsdatascience.com/scale-standardize-or-normalize-with-scikit-learn-6ccc7d176a02">preserves the shape of the original distribution</a>.</p><p>We can set up a data pipeline to transform the columns into useful input features. Here is some example code on how to do that:</p><pre># create a data pipeline</pre><pre># list of numerical columns<br>numerical_cols = [‘days_registered’,<br>                  ‘total_events’,<br>                  ‘unique_artists’,<br>                  ‘unique_songs’,<br>                  ‘total_thumbsup’,<br>                  ‘total_home’,<br>                  ‘total_addfriend’,<br>                  ‘total_rolladvert’]</pre><pre># convert sting column to index column<br>indexer = StringIndexer(inputCol=’state’, outputCol=’stateIndex’, handleInvalid=’skip’)<br>inputs = [indexer.getOutputCol()]</pre><pre># one hot encode categorical columns to numerical vector columns<br>encoder = OneHotEncoderEstimator(inputCols=inputs, outputCols=[‘stateVec’], handleInvalid=’keep’)</pre><pre># transform numerical columns to a single vector column<br>num_assembler = VectorAssembler(inputCols=numerical_cols, outputCol=’num_features’)</pre><pre># apply scaler (MinMax scaler preserves original data distribution)<br>scaler = MinMaxScaler(inputCol=’num_features’,            outputCol=’scaled_features’)</pre><pre># transform all create vector columns into one vector column<br>assembler = VectorAssembler(inputCols=[‘stateVec’, ‘scaled_features’], outputCol=’features’)</pre><pre># create pipeline with above steps<br>data_pipeline = Pipeline(stages=[indexer, encoder, num_assembler, scaler, assembler])</pre><pre># fit pipeline and transform dataframe<br>df = data_pipeline.fit(df).transform(df)</pre><p>All columns of interest have been recoded into numerical features, scaled uniformly, converted into one vector. This new vector is the input data we will use to train our models.</p><h3>Modeling and hyperparameter tuning</h3><p>We are dealing with a binary classification problem (if a user belongs to the class ‘<em>churn</em>’ or not) and to start exploring which models are suitable, we will instantiate and train multiple models from the Spark ML Package that work on classification problems. This is a good way to understand what kind of model works best with our data and to get baseline performance results as well, how each model performs on the data without any hyperparameter tuning.</p><p>Before training our model, we need to split our dataset into separate training, validation and test datasets. This is so that we have some data to train on and some unseen data left to test the model with. This is very straightforward and here is some example code for doing that:</p><pre># split data into train, validation and test sets<br>train, validation_test = df_ml.randomSplit([0.7, 0.3], seed = 4)<br>validation, test = validation_test.randomSplit([0.5, 0.5], seed = 4)</pre><p>The selected models to test come from Spark ML’s <a href="https://spark.apache.org/docs/latest/api/python/pyspark.ml.html#module-pyspark.ml.classification">classification module</a> and are suitable for binary classification:</p><ul><li>Naive Bayes Classifier</li><li>Logistic Regression</li><li>Linear Support Vector Classifier</li><li>Random Forest Classifier</li><li>Decision Tree Classifier</li></ul><p>Naive Bayes is a simple and straightforward model that could be a good baseline model to compare more complex models to. Logistic Regression and Linear Support Vector Classifier assume a linear relationship between the data, meanwhile the Random Forest and Decision Tree models can be applied to non-linear relationships as well. These models could be good to compare to each other to see how well they fit our data and whether it appears to have a linear or non-linear relationship.</p><p>Instantiating and training a model without any hyperparameter specifications (and timing how long this takes) is simple:</p><pre># instantiate and train naive bayes<br>start = time()<br>nb = NaiveBayes(featuresCol=’features’, labelCol=’churn’)<br>nb_model = nb.fit(train)<br>end = time()</pre><pre>print(‘Total training time for naive bayes: {} seconds’.format(<br>end — start))</pre><p>After instantiating and training all our models, we will test them on the validation set (the test set is reserved for the final model evaluation, after any hyperparameter tuning). Our dataset has imbalanced classes, there are only 22% churned users, which means that evaluating our model performance with a metric such as accuracy is not a good idea. The accuracy could be high because the model predicts well on the majority class (active users), but that would not be a good model for us since our goal is to predict on the minority class (churned users). Using the F1 score as our performance metric is a better option, it is the harmonic mean of precision and recall. Precision and recall calculations do not make use of the true negatives, they are only concerned with the correct prediction of the minority class.</p><p>Another performance evaluation metric that is suitable is the <em>area under the precision-recall curve</em>. Precision-recall curves are <a href="https://machinelearningmastery.com/roc-curves-and-precision-recall-curves-for-classification-in-python/">more informative</a> than the <em>receiver operating characteristic curve</em> (ROC) when evaluating binary classifiers on an imbalanced dataset, and a precision-recall curve is a plot of the precision and the recall for different thresholds. The <em>area under the curve</em> (AUC) can be used as a summary of the model skill. Area under the PR curve will typically show larger differences than area under the ROC curve when comparing classifiers trained on imbalanced data.</p><p>We can set up a for loop that makes a prediction on the validation set, prints out the F1 score and the area under the PR curve score for each baseline model:</p><pre># make baseline model predictions</pre><pre># create lists with the models and their respective names<br>models = [nb_model, <br>          lr_model, <br>          svc_model, <br>          rf_model, <br>          dt_model]</pre><pre>model_names = [‘naive bayes’, <br>               ‘logistic regression’, <br>               ‘linear svc’, <br>               ‘random forest’, <br>               ‘decision tree’]</pre><pre># for all models, make prediction, calculate f1 and area under the PR scores and display results<br>for i in range(len(models)):<br>    model = models[i]<br>    model_name = model_names[i]<br>    <br>    # predict on validation set<br>    validation_prediction = model.transform(validation)<br> <br>    # use MulticlassClassificationEvaluator to get f1 scores<br>    evaluator1 = MulticlassClassificationEvaluator(labelCol=’churn’)<br> <br>    # use BinaryClassificationEvaluator to get area under PR <br>    evaluator2 = BinaryClassificationEvaluator(<br>                 rawPredictionCol=’prediction’, labelCol=’churn’)</pre><pre>    # make evaluation and print f1 and area under PR score per model<br>    print(‘F1 score for {} on validation set:{}’.format(<br>          (model_name), <br>          (evaluator1.evaluate(<br>             validation_prediction, {evaluator1.metricName:’f1&#39;}))))<br> <br>    print(‘Area under PR for {} on validation set: {}’.format(<br>          (model_name), <br>          (evaluator2.evaluate(<br>     validation_prediction {evaluator2.metricName:’areaUnderPR’}))))</pre><p>Our baseline model results are:</p><pre>F1 score for naive bayes: 0.6561085972850679<br>Area under PR for naive bayes: 0.11538461538461539<br><br>F1 score for logistic regression: 0.6412698412698414<br>Area under PR for logistic regression: 0.19515669515669515<br><br>F1 score for linear svc: 0.6911421911421912<br>Area under PR for linear svc: 0.2877492877492877<br><br>F1 score for random forest: 0.7078593048742302<br>Area under PR for random forest: 0.3803418803418803<br><br>F1 score for decision tree: 0.6726137377341661<br>Area under PR for decision tree: 0.27692307692307694</pre><p>The Random Forest model has the best baseline results on the validation set in terms of both the F1 score of 71% and the area under PR score of 38%. Let us continue with the best performing baseline model and try tuning some of its hyperparameters to see if we can improve it further.</p><p>To test different variations of a hyperparameter, we can set up a parameter grid with all hyperparameters and options to test, and us this to cross-validate (<em>CrossValidator</em> in Spark ML) over a specific number of folds. <a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)">Cross-validation</a> is a technique where you partition the data and test the model multiple times (over <em>k</em> folds) and averages the results of each test to get a more accurate estimate of model prediction performance. The <em>CrossValidator</em> returns the model with the best results. Here is some example code showing how to set this up:</p><pre># tune hyperparameters with ParamGridBuilder and CrossValidator</pre><pre># build paramGrid with hyperparameters to tune<br>paramGrid = (ParamGridBuilder()<br>            .addGrid(rf.impurity,[‘entropy’, ‘gini’]) #default: gini<br>            .addGrid(rf.maxDepth, [5, 10, 15]) #default: 5<br>            .build())</pre><pre># add paramGrid to CrossValidator<br>crossval = CrossValidator(estimator = rf,<br>   estimatorParamMaps = paramGrid,<br>   evaluator = MulticlassClassificationEvaluator(labelCol=’churn’),<br>               numFolds = 3)</pre><pre># fit cv model and train it<br>start = time()<br>cv_rf = crossval.fit(train)<br>end = time()</pre><pre>print(‘Total training time for hyperparameter tuning on random forest model: {} seconds’.format(end — start))</pre><p>You can find a description of which hyperparameters that exist for you model by running <em>your_model.explainParams(). </em>The hyperparameters we have chosen here to test in tuning the random forest model are ‘<em>impurity</em>’ and ‘<em>maxDepth</em>’. The ‘<em>impurity</em>’ parameter with ‘<em>entropy</em>’ and ‘<em>gini</em>’ refers to which criterion to be used for information gain calculation, and ‘<em>maxDepth</em>’ refers to the maximum depth of the tree.</p><p>Let us test the tuned model on the validation set (only for comparing with the baseline results) and on the test set (the actual performance evaluation). We can also test the baseline Random Forest model on the test set to be able to compare the final performance of both models:</p><pre># use MulticlassClassificationEvaluator to get f1 scores<br>evaluator = MulticlassClassificationEvaluator(labelCol=’churn’)</pre><pre># predict on validation set<br>validation_prediction_rf = cv_rf.transform(validation)</pre><pre># make evaluation and print f1-score<br>print(‘F1 score for tuned random forest model on validation set: {}’.format(evaluator.evaluate(<br> validation_prediction_rf, {evaluator.metricName:’f1&#39;})))</pre><pre># predict on test set<br>test_prediction_rf = cv_rf.transform(test)</pre><pre># make evaluation and print f1-score<br>print(&#39;F1 score for tuned random forest model on test set: {}&#39;.format(evaluator.evaluate(<br>    test_prediction_rf, {evaluator.metricName:&#39;f1&#39;})))</pre><pre># test baseline random forest model on test set</pre><pre># predict on test set<br>test_prediction_rf_baseline = rf_model.transform(test)</pre><pre># make evaluation and print f1-score<br>print(&#39;F1 score for baseline random forest model on test set: {}&#39;.format(evaluator.evaluate(<br>            test_prediction_rf_baseline, {evaluator.metricName:&#39;f1&#39;})))</pre><p>And the results for the tuned Random Forest model and the baseline Random Forest model are:</p><pre>F1 score for tuned random forest model on validation set: 0.7316997518610423</pre><pre>F1 score for tuned random forest model on test set: 0.6981718035860776</pre><pre>F1 score for baseline random forest model on test set: 0.6619917263646455</pre><p>The tuned Random Forest model performs the best with an F1 score of 73% on the validation set and an F1 score of 70% on the test set. Compared to the baseline model without any hyperparameter tuning, we managed to improve our F1 score on the final test set with 4% by tuning it.</p><p>We can get the hyperparameters for the best tuned model from the <em>CrossValidator</em> by running <em>your_model.bestModel.extractParamMap()</em>. In our case, the best option for ‘<em>impurity</em>’ is ‘<em>entropy</em>’ and for ‘<em>maxDepth</em>’ it is 10.</p><h3>Model feature importance</h3><p>To understand our tuned model better, we can look at how important each feature is to the model in predicting customer churn. We can extract the input vectors and their feature importance score from the model’s metadata, and map this to the actual feature name. We can also calculate the cumulative feature importance score of a feature and the features before, to get a sense of their combined importance. Here is a function that does this and returns a Pandas dataframe with the results:</p><pre># function to extract feature importance score and name for model, convert to pandas dataframe and add column with cumulative score</pre><pre>def extract_feature_imp(featureImp, dataset, featuresCol):<br>    <br>    # dictionary to replace vector name with feature name<br>    feat_name_dict = {<br>    ‘scaled_features_0’: ‘days_registered’,<br>    ‘scaled_features_1’: ‘total_events’,<br>    ‘scaled_features_2’: ‘unique_artists’,<br>    ‘scaled_features_3’: ‘unique_songs’,<br>    ‘scaled_features_4’: ‘total_thumbsup’,<br>    ‘scaled_features_5’: ‘total_home’,<br>    ‘scaled_features_6’: ‘total_addfriend’,<br>    ‘scaled_features_7’: ‘total_rolladvert’,<br>    ‘stateVec_ CA’: ‘state: CA’,<br>    ‘stateVec_ TX’: ‘state: TX’,<br>    ‘stateVec_ NY’: ‘state: NY’,<br>    ‘stateVec_ IL’: ‘state: IL’,<br>    ‘stateVec_ FL’: ‘state: FL’,<br>    ‘stateVec_ PA’: ‘state: PA’,<br>    ‘stateVec_ NC’: ‘state: NC’,<br>    ‘stateVec_ GA’: ‘state: GA’,<br>    ‘stateVec_ OH’: ‘state: OH’,<br>    ‘stateVec_ MI’: ‘state: MI’,<br>    ‘stateVec_ AZ’: ‘state: AZ’,<br>    ‘stateVec_ IN’: ‘state: IN’,<br>    ‘stateVec_ WA’: ‘state: WA’,<br>    ‘stateVec_ CT’: ‘state: CT’,<br>    ‘stateVec_ AL’: ‘state: AL’,<br>    ‘stateVec_ MN’: ‘state: MN’,<br>    ‘stateVec_ VA’: ‘state: VA’,<br>    ‘stateVec_ TN’: ‘state: TN’,<br>    ‘stateVec_ MO’: ‘state: MO’,<br>    ‘stateVec_ MA’: ‘state: MA’,<br>    ‘stateVec_ WI’: ‘state: WI’,<br>    ‘stateVec_ DC’: ‘state: DC’,<br>    ‘stateVec_ OR’: ‘state: OR’,<br>    ‘stateVec_ CO’: ‘state: CO’,<br>    ‘stateVec_ KY’: ‘state: KY’,<br>    ‘stateVec_ RI’: ‘state: RI’,<br>    ‘stateVec_ MS’: ‘state: MS’,<br>    ‘stateVec_ LA’: ‘state: LA’,<br>    ‘stateVec_ SC’: ‘state: SC’,<br>    ‘stateVec_ UT’: ‘state: UT’,<br>    ‘stateVec_ MD’: ‘state: MD’,<br>    ‘stateVec_ NH’: ‘state: NH’,<br>    ‘stateVec_ NM’: ‘state: NM’,<br>    ‘stateVec_ IA’: ‘state: IA’,<br>    ‘stateVec_ NJ’: ‘state: NJ’,<br>    ‘stateVec_ OK’: ‘state: OK’,<br>    ‘stateVec_ KS’: ‘state: KS’,<br>    ‘stateVec_ NV’: ‘state: NV’,<br>    ‘stateVec_ MT’: ‘state: MT’,<br>    ‘stateVec_ WV’: ‘state: WV’,<br>    ‘stateVec_ AK’: ‘state: AK’,<br>    ‘stateVec_ SD’: ‘state: SD’,<br>    ‘stateVec_ NE’: ‘state: NE’,<br>    ‘stateVec_ AR’: ‘state: AR’,<br>    ‘stateVec_ ND’: ‘state: ND’,<br>    ‘stateVec_ ME’: ‘state: ME’,<br>    ‘stateVec_ VT’: ‘state: VT’,<br>    ‘stateVec_ HI’: ‘state: HI’,<br>    ‘stateVec_ ID’: ‘state: ID’}<br> <br>    list_extract = []<br> <br>    for i in dataset.schema[featuresCol].metadata[“ml_attr”]<br>    [“attrs”]:<br>        list_extract = list_extract + <br>        dataset.schema[featuresCol].metadata[“ml_attr”][“attrs”][i]<br> <br>    # create pandas dataframe with index and feature vector name <br>    # from metadata<br>    df = pd.DataFrame(list_extract)</pre><pre>    # add column with feature importance score<br>    df[‘score’] = df[‘idx’].apply(lambda x: featureImp[x])<br>    df = df.sort_values(‘score’, ascending = False)<br> <br>    # add column with cumulative feature importance score<br>    df[‘cumulative_score’] = df[‘score’].cumsum()<br> <br>    # replace feature vector name with feature name<br>    df[‘name’] = df[‘name’].map(feat_name_dict)<br> <br>    return df</pre><p>Running the function above on our best tuned random forest model, we get these feature importance results, show the feature importance in descending order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*Y4mta2aqYXzm2rpz-xX4fQ.png" /></figure><p>We can plot these feature importance scores together with the cumulative score by running this plot script:</p><pre># plot feature score and cumulative score for most important <br># features</pre><pre># keep only top 15 most important features for plotting<br>df_feat_imp_rf_15 = df_feat_imp_rf.head(15)</pre><pre>ind = np.arange(len(df_feat_imp_rf_15[‘name’]))</pre><pre>fig = plt.figure(figsize = (15,10))<br>plt.bar(ind, df_feat_imp_rf_15[‘score’], label=’Feature score’)<br>plt.plot(ind, df_feat_imp_rf_15[‘cumulative_score’], label=’Cumulative score’)<br>plt.title(‘Most important features for tuned random forest model’)<br>plt.legend(loc=’upper left’)<br>plt.ylabel(‘Score’)<br>plt.yticks(np.arange(0, 1.1, step=0.1))<br>plt.xlabel(‘Feature’)<br>plt.xticks(ind, df_feat_imp_rf_15[‘name’], rotation=90)<br>plt.show()</pre><p>We then get this plot with the feature importance results for our tuned Random Forest model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*SE_t85J2SvYD0qWSIWfeCQ.png" /></figure><p>Above we can see the top 15 most important features for the tuned Random Forest model in predicting churn. The score is the weight of the feature, and the higher the weight the more important the feature is to the model. The weight of a feature indicates its predictive power. The cumulative score shows the total predictive power of a feature and its previous features. The most important features are ‘<em>days_registered</em>’, ‘<em>total_rolladvert</em>’ and ‘<em>unigue_songs</em>’, which have a weight of 20%, 12%, and 10% respectively. This means that the most important user behaviors to this model in predicting customer churn are the number of days a user has been registered on the platform, the number of ads they have received and the number of unique songs they listen to.</p><p>The first 45 most important features have a cumulative weight of 1, which means they add up to a predictive power of 100%. All features displayed after this do not add any useful information to the model, and we could simplify the model by removing these and still get the same model performance. However, this would not make sense in our case, since all these features belong to the same variable, ‘<em>state</em>’, and it would not make sense to remove only some state options from that variable.</p><p>Based on this tuned random forest model, it could be wise for the company to set up an alert system to communicate with a user after a certain number of days to minimize the risk of them canceling their account, look more into finding an optimum number of ads a user can tolerate and build the platform to increase a user’s exposure to new songs and artists to improve their experience and keep them on as customers for longer.</p><h3>Further model improvements</h3><p>There are many ways to further improve this churn prediction model. For starters, the initial analysis in this project was based on a subset of the data which had a slightly different data distribution across the columns. Looking at the graph of the number of event page types for the total dataset in the data analysis section of this article, there are other input features that would have been interesting to add to the modeling to see how they would affect the performance. For example, there seems to be a difference between churned and active users when it comes to the number of songs added to playlists (‘<em>Add to Playlist</em>’) and the number of thumbs down given (‘<em>Thumbs Down</em>’). There are also other types of input features we could have created to test in modeling. We could have performed some more statistically sound dimensionality reduction or feature selection in the pre-processing, such as conducting a <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">Principal component analysis</a> (PCA) or applied a <a href="https://www.analyticsvidhya.com/blog/2018/08/dimensionality-reduction-techniques-python/">Low variance or High correlation filter</a> on the input features, to remove unnecessary features or reduce them but still allowing them to convey enough information about the data.</p><p>Due to our dataset being imbalanced between the classes, we could have benefited from using a bigger dataset or maybe <a href="https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis">over- and undersampling</a> of churned and active user groups to get a more even distribution of examples to train on. We could also have used more model performance tools, such as bias-variance plots that visualize how the model’s train performance compares to its test performance, to simultaneously minimize the bias and variance, <a href="https://towardsdatascience.com/understanding-the-bias-variance-tradeoff-165e6942b229">two sources of error that prevent models from generalizing beyond the training set</a>.</p><p>We could also have removed outliers from the dataset to see if this would improve model performance. Though, in our case, that would have left us with even fewer examples to train on and would probably only be suitable if we had access to more data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c941af67a59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>