<?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 Oleksandr Yatsenko on Medium]]></title>
        <description><![CDATA[Stories by Oleksandr Yatsenko on Medium]]></description>
        <link>https://medium.com/@oleksandr_49102?source=rss-15984b855758------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wrgsIiLgmANhPVnavT4nmg.jpeg</url>
            <title>Stories by Oleksandr Yatsenko on Medium</title>
            <link>https://medium.com/@oleksandr_49102?source=rss-15984b855758------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:50:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oleksandr_49102/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 user churn with PySpark]]></title>
            <link>https://medium.com/@oleksandr_49102/predicting-user-churn-with-pyspark-4bdbed544cfc?source=rss-15984b855758------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bdbed544cfc</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pyspark]]></category>
            <category><![CDATA[churn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Oleksandr Yatsenko]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 12:26:12 GMT</pubDate>
            <atom:updated>2023-02-05T10:59:12.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Multiple gold fish jumping out of a fish bowl" src="https://cdn-images-1.medium.com/max/1024/1*QTkIqX09lAw5RcskD0SONw.png" /><figcaption>Image is generated by DALL-E</figcaption></figure><h4>Framing the problem</h4><p>Imagine you are newly hired data scientist for an audio streaming start up called Sparkify. One of the first tasks for you in this kind of business would be predicting user churn. The company is very interested in preventing users from leaving its platform and would like to identify those users before the churn happens and potentially providing them with some sort of incentive to stay.</p><p>Let’s outline the key questions you would like to answer for this project:</p><ul><li><em>Can we predict the churn by looking into users activity ?</em></li></ul><p>Please refer to <a href="https://github.com/Olek-ua/Sparkify_Project">my git repository</a> for all the CRISP-DM steps you will see in this article.</p><h4>Strategy to solve the problem</h4><p>Predicting the churn falls into a ML classification problem, where we would attempt to predict a binary outcome (active vs churned) by looking into user characteristic and platform activity (features). We will follow a standard CRISP-DM methodology, namely:</p><ul><li><strong>Business Understanding — </strong>this what we covered in Framing the problem section</li><li><strong>Data Understanding</strong> — we will investigate all the features and target variables from the data we have. The key idea is to shortlist the most valuable feature and potentially engineer some new, also we may need to define which users do we actually consider to be churned</li><li><strong>Modelling </strong>— since we are talking about the binary classification many models can solve this problem. I will primarily focus on three models: <strong>logistic regression, decision trees and random forest classifiers </strong>the first is highly descriptive with very good accuracy while the second and third can find non obvious patterns and non linear relationship in data.</li><li><strong>Evaluation — </strong>we will pick the model based on the metrics which is better answers the question outlined in the Framing the problem section.</li></ul><p>As you could have guessed from the title today we are not going to use Scikit-learn but rather PySpark because this framework was specifically designed to work with the big data which you are very likely to face when you are dealing with the <strong>user events data</strong>. PySpark also allows us to follow standard CRISP-DM steps discussed above.</p><h4>Metrics</h4><p>It should be mentioned that we will judge our model primarily on the <strong>Recall</strong> metric as it’s more important to spot users who are about to churn than users who would be wrongly classified as churned which would still be acceptable to some degree.</p><h4><strong>Fictional data overview</strong></h4><p>Let’s take a look what we have, as you can see the data represents a json file with the following schema:</p><pre>user_log.printSchema()<br><br>Output: <br>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>To make it more visual let’s also look into the data frame itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*4mFiMrf4p4qEnZbr2voVsg.png" /></figure><p>As we can see this is an event log level data where each row represents an event like <em>NextSong </em>and the rest of the columns is just a set of parameters related to it.</p><p>Let’s a take a closer look to find what kind of features can be useful for our model. In my opinion only three such features have really valuable information for churn prediction those are:</p><ul><li><strong>level</strong></li><li><strong>page</strong> (event name)</li><li><strong>ts </strong>(timestamp).</li></ul><p>You may be tempted also to use artist name or song or even <strong>firstName</strong> and <strong>lastName</strong> of user (remember they are fictional anyway), as for me I find these kind of information not useful as <strong>artist/song</strong> preference is a subject of taste and alone is not likely to produce any valuable input for our model. However if you will take an extra step and will be able to classify an artist or song you can generate a new set of features such as genre. Most likely you will need to use third party service for this. Then I assume this newly created feature may be relevant. As for our case I will stick only to the above mentioned four feature.</p><h4>Exploratory data analysis</h4><p>If we take a closer look into our events there are couple that could mean churn such as <strong>Downgrade, Cancellation_Confirmation </strong>and <strong>Cancel, </strong>let’s see what those are. Basically Downgrade would mean that a user downgrades from paid but would continue to use platform on free tier, while Cancellation_Confirmation and Cancel are basically duplicated events and mean that users have removed their accounts from our services. Therefore <strong>Cancellation_Confirmation </strong>would be our primary target variable.</p><p>Another thing you need to consider is the time aspect since you are predicting a churn you would want to predict it some time before it happens and potentially prevent it. Since we are dealing with the fictional data it has some constraints like you don’t have enough of historical observations you also don’t know user activation date. Nevertheless there is something you can squeeze out from the data we have, you can establish epochs from the user activity by looking into their downgrade history. Every time user submits downgrade a new phase starts.</p><figure><img alt="Every time user submit downgrade we count new epoch" src="https://cdn-images-1.medium.com/max/924/1*2bqjMPEQQ21AqK8Q7MqoSw.png" /><figcaption>Every time user submits downgrade we count a new phase</figcaption></figure><p>Now that we have <strong>phase </strong>column in place let’s see what’s the difference between active and cancelled users by phase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*eEn_tl2QMWyF0bbTWNSwUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*zv44FuNTGGOhsDlVzRUVIA.png" /></figure><p>Simply by looking in this two bar charts above you can notice that none of cancelled users have any activity beyond the phase 0 meaning they’ve never attempted to downgrade. This is a very strong predictor on its own but we should also consider the case where users never cancelled and never downgraded — meaning that they would stay on a free tier or upgraded. Let’s compare active vs cancelled users in phase 0 to see if there is an obvious patterns in user behaviour.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*7qezIKA8ANV-duf7bSsITQ.png" /></figure><p>Indeed on average an active user who never downgraded (max_phase == 0) tends to listen more song, adding friends more frequently and rolling less ads in comparison to the churned users. There is also one more interesting observation we can make, it’s that some of the cancelled users have actually upgraded to the premium version but instead of downgrading later to the free version they preferred to cancel their account. Potentially we should investigate and prevent this kind of behaviour.</p><h4>Feature engineering</h4><p>Here we will aim to build a sparse matrix of unique combinations of phase, level and page — these will be our feature set. The idea behind this kind of approach is to spot changes in user activity over the time and let a model to find a pattern.</p><p>After all the data transformation steps these would be the look of the sparse matrix before feeding it into the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EF6cKzVu7IkixbeVaBylIw.png" /><figcaption>Sparse matrix of unique features</figcaption></figure><p>where the first label corresponds to the phase, the second label corresponds to the subscription type and the third is the name of the event.</p><h4>Modelling</h4><p>Our modelling steps follow the standard process of train-test split and building ML pipeline.</p><pre># Importing all the necessary pyspark and sklearn methods for ML <br>from pyspark.ml.feature import Normalizer, RegexTokenizer, StandardScaler, VectorAssembler, StringIndexer<br>from pyspark.sql.functions import col<br>from pyspark.ml.evaluation import MulticlassClassificationEvaluator<br>from sklearn.metrics import confusion_matrix<br>from pyspark.ml.classification import DecisionTreeClassifier, LogisticRegression, RandomForestClassifier<br>from pyspark.ml.tuning import CrossValidator, ParamGridBuilder<br>from pyspark.ml import Pipeline</pre><p><strong>Train-test split</strong></p><pre># Train / test split - it&#39;s worth to use 70/30 % split because the have only 225 unique users.<br>train, test = features_df.randomSplit([0.7, 0.3], seed = 42)</pre><p>I’ve selected the split of 0.7 train / 0.3 test. Let’s verify that we have a stratified user split by looking into the amount of the target variables labels are present in each of the sets:</p><pre>train - cancelled users:  13<br>test - cancelled users:  8</pre><p>The above split looks fair to me, although the total number of cancelled users can seem a bit low (only 21 cancelled users in our dataset). It may be the case that a model won’t perform well detecting users who are about to churn (True Positive in our case), however it will probably perform well with detecting users who are planning to stay with us (True Negative).</p><p><strong>Building a ML pipeline</strong></p><p>Our ML pipeline will include the following steps:</p><ul><li><strong>assembler</strong> — for converting features into vectors</li><li><strong>scaler / scaler2 </strong>— for normalising and standardising our data, this is quite important transformation step because values in our features can have quite high variance and we need to keep under control in order to improve the model quality.</li><li><strong>indexer</strong> — for assigning features and labels</li><li><strong>dtc / lr / rfc — </strong>these are decision tree , logistic regression and random forest classifiers</li></ul><pre># We are going to test three models: Decicion Trees, Logistic Regression and Random Forest<br># Logistic regression is particularly sensitive to variations in features<br># therefore we will normalise and standtartise our features<br><br>assembler = VectorAssembler(inputCols=features_list, outputCol=&quot;NumFeatures&quot;)<br>scaler = Normalizer(inputCol=&quot;NumFeatures&quot;, outputCol=&quot;ScaledNumFeatures&quot;)<br>scaler2 = StandardScaler(inputCol=&quot;NumFeatures&quot;, outputCol=&quot;features&quot;, withStd=True)<br>indexer = StringIndexer(inputCol = &quot;0_free_Cancellation Confirmation&quot;, outputCol = &quot;label&quot;)<br><br><br>dtc = DecisionTreeClassifier()<br>lr = LogisticRegression(maxIter=10, regParam=0.0, elasticNetParam=0)<br>rfc = RandomForestClassifier()<br><br>evaluator=MulticlassClassificationEvaluator(predictionCol=&quot;prediction&quot;)</pre><p><strong>Decision Trees: hyperparameter tuning and cross validation</strong></p><p>For decision trees I’ve tested only a single <strong>maxDepth</strong> hyperparameter which corresponds to the node depth in decision trees, I’ve tested several combinations and found that this depth combination [10, 12, 14] suits best for our data (based on accuracy). Since we have relatively few data points <strong>numFolds=5 </strong>parameter in CrossValidator should be sufficient to reach good accuracy for all of the models discussed in this article.</p><pre>dtc_pipeline = Pipeline(stages=[assembler, scaler, scaler2, indexer, dtc])<br><br>paramGrid = ParamGridBuilder()\<br>        .addGrid(dtc.maxDepth, [10, 12, 14])\<br>        .build()<br><br>crossval = CrossValidator(estimator = dtc_pipeline,<br>                          estimatorParamMaps = paramGrid,<br>                          evaluator = MulticlassClassificationEvaluator(),<br>                          numFolds = 5)<br><br>cv_DTC_Model = crossval.fit(train)<br>dtc_pred = cv_DTC_Model.transform(test)<br><br>acc = evaluator.evaluate(dtc_pred)<br>print(&quot;Decision Tree Prediction Accuracy: &quot;, acc)</pre><pre>Decision Tree Prediction Accuracy:  0.8626148854671918</pre><pre>y_pred=dtc_pred.select(&quot;prediction&quot;).collect()<br>y_orig=dtc_pred.select(&quot;label&quot;).collect()<br><br>cm = confusion_matrix(y_orig, y_pred)<br>print(&quot;DT Confusion Matrix:&quot;)<br>print(cm)</pre><pre>DT Confusion Matrix:<br>[[64  6]<br> [ 5  3]]</pre><p><strong>Random Forest: hyperparameter tuning and cross validation</strong></p><p>For random forest I’ve decided to go “all in” and tested several hyperparameters. My goal was to find the best combinations of trees and their depth, bootstrap (sampling) and impurity measures.</p><p>Random forest is essentially a more complex version of decision trees models and I was wondering if extra complexity can do a better job.</p><pre>rfc_pipeline = Pipeline(stages=[assembler, scaler, scaler2, indexer, rfc])<br><br>paramGrid = ParamGridBuilder()\<br>        .addGrid(rfc.maxDepth, [5, 6, 8])\<br>        .addGrid(rfc.numTrees, [20, 30, 40])\<br>        .addGrid(rfc.bootstrap, [True, False])\<br>        .addGrid(rfc.impurity, [&#39;gini&#39;, &#39;entropy&#39;])\<br>        .build()<br><br>crossval = CrossValidator(estimator = rfc_pipeline,<br>                          estimatorParamMaps = paramGrid,<br>                          evaluator = MulticlassClassificationEvaluator(),<br>                          numFolds = 5)<br>cv_RFC_Model = crossval.fit(train)<br>rfc_pred = cv_RFC_Model.transform(test)<br>acc = evaluator.evaluate(rfc_pred)<br>print(&quot;Random Forest Prediction Accuracy: &quot;, acc)</pre><pre>Random Forest Prediction Accuracy:  0.848925848925849</pre><pre>y_pred=rfc_pred.select(&quot;prediction&quot;).collect()<br>y_orig=rfc_pred.select(&quot;label&quot;).collect()<br><br>cm = confusion_matrix(y_orig, y_pred)<br>print(&quot;RFC Confusion Matrix:&quot;)<br>print(cm)</pre><pre>RFC Confusion Matrix:<br>[[70  0]<br> [ 8  0]]</pre><p><strong>Logistic Regression: hyperparameter tuning and cross validation</strong></p><p>In logistic regression I’ve only tested <strong>regParam </strong>which corresponds to L2 regularization (Ridge regression) and should serve as penalty term to the loss function, in simple terms how much should we penalise our model to avoid overfitting.</p><pre>lr_pipeline = Pipeline(stages=[assembler, scaler, scaler2, indexer, lr])<br><br>paramGrid = ParamGridBuilder()\<br>        .addGrid(lr.regParam, [0.0, 0.2, 0.5, 0.8])\<br>        .build()<br><br>crossval = CrossValidator(estimator = lr_pipeline,<br>                          estimatorParamMaps = paramGrid,<br>                          evaluator = MulticlassClassificationEvaluator(),<br>                          numFolds = 5)<br><br>cv_LR_Model = crossval.fit(train)<br>lr_pred = cv_LR_Model.transform(test)<br><br>print(&quot;Logistic Regression Accuracy: &quot;, \<br>      lr_pred.filter(lr_pred.label == lr_pred.prediction).count() / lr_pred.count())</pre><pre>Decision Tree Prediction Accuracy:  0.8589743589743589</pre><pre>y_pred=lr_pred.select(&quot;prediction&quot;).collect()<br>y_orig=lr_pred.select(&quot;label&quot;).collect()<br><br>cm = confusion_matrix(y_orig, y_pred)<br>print(&quot;LR Confusion Matrix:&quot;)<br>print(cm)</pre><pre>LR Confusion Matrix:<br>[[65  5]<br> [ 6  2]]</pre><p><strong>Some complications that I came across</strong></p><p><strong>Train / test split: </strong>all of the models are extremely sensitive to the split ratio, I’ve found that keeping split 0.7 vs 0.3 provides the best results, otherwise regardless of increasing or decreasing the test size we lose the quality of the model.</p><p><strong>Random forests hyperparameters: </strong>due to the high number of random forest hyperparameters it takes significant amount of time to train the model. Unfortunately looking through the vast set of hyperparameters has not had any positive effect on the model.</p><p><strong>Interesting observations and intermediate results</strong></p><p>While tuning hyperparameters I’ve found that <strong>maxDepth </strong>parameter for Decision Trees should be higher than 8 which translates having more than 8 nodes, only then the model can have higher than 0.25 of recall. Also I’ve found that Logistic Regression improves from 0 to 0.25 when <strong>regParam </strong>is on the higher end (close to 1), if regParam is too low the model underfits and classifies all users as active.</p><h4>Results</h4><p>Let’s look into the results of the models discussed above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*y0DsJgWaRvTTKZOfHPCy1g.png" /><figcaption>Model results comparison</figcaption></figure><p>The results for all of the classification models are unsatisfactory; despite the fact that in all cases the quality of the model would be around 85% (this is due to the fact that majority of observations do not cancel their subscription) but sadly in all cases we will miss most of churned users. These are quite concerning results, however as we’ve discussed earlier this can be due to the small amount of churned users available to us in the dataset. Therefore we can announce <strong>a winner model which is Decision Trees in our case.</strong></p><p>You may be surprised that random forest precison and recall results are N/A, this is due to the fact that model is terribly underfitting the data by classifying everyone as active users.</p><h4>Final thoughts &amp; Improvements</h4><p>Unfortunately with 21 churned user in our data is not enough to build a robust model. Therefore primarily we should aim to expand with our dataset. As we know the full dataset exceeds 12 GB and we should consider to use a full capability of PySpark which was designed to be used on big data in cloud computing systems like AWS and GCP.</p><h4>Git</h4><p>You can check my git repository <a href="https://github.com/Olek-ua/Sparkify_Project">here</a>.</p><h4><strong>Useful Sources</strong></h4><ul><li>CRISP-DM: Udacity, Data Science Nano Degree ( <a href="https://www.udacity.com/course/data-scientist-nanodegree--nd025">https://www.udacity.com/course/data-scientist-nanodegree--nd025</a>)</li><li>The full dataset available at: s3n://udacity-dsnd/sparkify/sparkify_event_data.json</li><li>L1 and L2 regularization:<strong> </strong><a href="https://towardsdatascience.com/l1-and-l2-regularization-methods-ce25e7fc831c">https://towardsdatascience.com/l1-and-l2-regularization-methods-ce25e7fc831c</a> (Article by Anuja Nagpal)</li><li>Decision Lines and Hyperplanes: Data Science for Business (O’Reilly, 2013, F.Provost &amp; T.Fawcett p.69)</li><li>Class Probability Estimation and Logistic “Regression”: Data Science for Business (O’Reilly, 2013, F.Provost &amp; T.Fawcett p.96)</li><li>Spark Logistic Regression Hyperparameters: <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.classification.LogisticRegression.html">https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.classification.LogisticRegression.html</a></li><li>Spark Decision Trees: <a href="https://spark.apache.org/docs/1.5.2/ml-decision-tree.html">https://spark.apache.org/docs/1.5.2/ml-decision-tree.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bdbed544cfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use the power of Machine Learning to predict AirBnB prices in Seattle]]></title>
            <link>https://medium.com/@oleksandr_49102/use-the-power-of-machine-learning-to-predict-airbnb-prices-in-seattle-bc9a781fd370?source=rss-15984b855758------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc9a781fd370</guid>
            <category><![CDATA[crisp-dm]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Oleksandr Yatsenko]]></dc:creator>
            <pubDate>Wed, 06 Oct 2021 08:02:33 GMT</pubDate>
            <atom:updated>2021-10-06T08:02:33.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-5OI3HLAAeZKMKbO7_w-4A.jpeg" /><figcaption><a href="https://www.pexels.com/photo/architecture-buildings-business-city-336512/">Seattle at Night</a> — photo by <a href="https://www.pexels.com/@snapwire">Snapwire</a></figcaption></figure><h4>Framing the problem</h4><p>Suppose you are working for an estate development company and you want to find a reliable way to predict a certain property letting price. This is quite important as you want to make an informed investment decision. You also might want to have an insight on what are the most expensive areas in your town as well as how the rent prices behave in the town.</p><p>Traditionally estate companies would have a group of experts who can provide estimations based on their market knowledge, but this is costly and time-consuming as well as the estimates are not always great. So can we beat the base line — a humane expertise prediction with ML algorithm?</p><p>Before we deep dive into Exploratory Data Analysis let’s clearly outline the questions we look to answer:</p><ol><li><em>What is the busiest time of the year for Seattle?</em></li><li><em>What are the most expensive neighbourhoods?</em></li><li><em>Can we predict the price of a property based on its features and name the most important features?</em></li></ol><h4>Know your data</h4><p><em>Seattle Airbnb Open Data</em> comes directly from<a href="https://www.kaggle.com/airbnb/seattle/data"> Kaggle</a>, this is a very well known data set. It consists of three files: calendar, listings, reviews. We will ignore reviews data as these are purely text reviews and would require natural language processing (NLP) which is outside of the scope of our exercise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c31f03882ec05735b35bd0ff13a1d889/href">https://medium.com/media/c31f03882ec05735b35bd0ff13a1d889/href</a></iframe><p>Some of the numeric variables are presented in a string format, we would need to fix this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*LTsfESOTzUb8tgyxy_rU3w.png" /><figcaption>%-string instead of float</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*bY8gtRMv3eSjeSLDQ2nm2A.png" /><figcaption>$-string instead of float</figcaption></figure><p>Let’s clean this data in order to further explore it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecca55765c1fd223b5a506d1390f8354/href">https://medium.com/media/ecca55765c1fd223b5a506d1390f8354/href</a></iframe><h4>Exploratory Data Analysis</h4><p>First thing first let’s look into correlations matrix of numeric variables, this will help us to uncover predictors that may cause a multicollinearity at the future modelling stage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00e63bf28cf88c1a7f443637e0c4d7ec/href">https://medium.com/media/00e63bf28cf88c1a7f443637e0c4d7ec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*EIPmEUxrl14NokuDopbkZw.png" /><figcaption>Correlations heat map</figcaption></figure><p>From what we see above there are quite a few highly correlated numeric variables. Particularly among host, property size, availability and reviews related parameters. This makes complete sense as for instance square feet is very likely to be correlated with the number of rooms and bathrooms in a property. In the following step of data cleaning we will keep only one out of many highly correlated variables.</p><p>Now we’ve approached the business questions section:</p><p><strong>What is the busiest time of the year for Seattle?</strong></p><p>In order to answer the first question we don’t really need to build a sophisticated model but rather we can take a closer look into calendar data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/037f2d518a6499f7616560a6056b96bb/href">https://medium.com/media/037f2d518a6499f7616560a6056b96bb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*o_q6DfnL24a94MLrGKNrKQ.png" /><figcaption>We’ve added a numeric month column</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f28d7815af583d6c7aab1cb93c0aa27/href">https://medium.com/media/6f28d7815af583d6c7aab1cb93c0aa27/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*CY044QOsvEUHQFOdVaggBA.png" /><figcaption>Number of days booked per month</figcaption></figure><p>We can see that there are a high number of days booked in January, August and September. But what about the percentage of used capacity of all of the properties listed for Seattle on AirBnB that year?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f63acc9fb336ab0216cb6406e55851f4/href">https://medium.com/media/f63acc9fb336ab0216cb6406e55851f4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*TGuqfsOg4F53X9aPmiEr2w.png" /><figcaption>Percentage of booked properties by month</figcaption></figure><p>Used capacity looks quite similar to the number of days booked. Hence we can certainly conclude that the busiest time of the year is January, August and September.</p><p><strong>What are the most expensive neighbourhoods ?</strong></p><p>As with the busiest time question we don’t really need to build a model we will simply do minor data manipulations</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa6c9516c6862f57495687635469fc55/href">https://medium.com/media/aa6c9516c6862f57495687635469fc55/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*sVJYQ14fWd7cYXbdmAn1_g.png" /><figcaption>Top 20 of the most expensive neighbourhood groups</figcaption></figure><p>As we could see the most expensive neighbourhood groups are Magnolia, Queen Anne, Downtown and West Seattle. For price prediction we will primarily focus on neighbourhood groups rather individual neighbourhoods as these will provide less noise for our model.</p><p>Before we answer our main question we need to complete the data cleaning step.</p><h4>Data Cleaning</h4><p>As you have probably have already realised there are too many attributes in listings data set, most of them won’t add any value to the model, for instance host_id, host_picture_url, thumbnail_url etc. Let’s get rid of these and some other less useful attributes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b7cb68684a5e88443dafd47e8fa3192/href">https://medium.com/media/8b7cb68684a5e88443dafd47e8fa3192/href</a></iframe><p>Now we can proceed to the cleaning of numerical and categorical variables, due to their nature we would need to process them separately. We will assemble several helper functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fa080f80e8c6de12e57bf6b9ca60ac6/href">https://medium.com/media/9fa080f80e8c6de12e57bf6b9ca60ac6/href</a></iframe><p>Let’s combine previous functions in the main data cleaning function, where we will make some final preparations before we can feed data into a model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1fecea86721af938a1cbd5e34395135/href">https://medium.com/media/b1fecea86721af938a1cbd5e34395135/href</a></iframe><h4>Data Modelling</h4><p>We’ve finally approached the most fun step we’ve been waiting for so long — data modelling!</p><p>The first model we are going to use in this step is linear regression. This is completely reasonable since we are aiming to predict a continuous variable — property price. Before running the model let’s apply feature scaling to our data, as this will help us to improve the quality of the model by balancing attributes that lay on different scales.</p><p>Also at this step we will split data into test and control groups.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18bfc841f66a84ba1bee6e06c65cc832/href">https://medium.com/media/18bfc841f66a84ba1bee6e06c65cc832/href</a></iframe><h4>Linear regression</h4><p>Let’s run our first regression model. In order to assess the quality of our model we will primarily look into r-squared coefficient.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a4f8434a4998b6763603dbea6e757ec/href">https://medium.com/media/2a4f8434a4998b6763603dbea6e757ec/href</a></iframe><p>The result we get for linear regression is not bad with <strong>r-squared (R²)= 0.59</strong>, but it demonstrates that linear regression is under fitting. This is likely to happen due to the fact that there is more complex a non-linear relationship between variables. Therefore let’s use more complex model.</p><h4><strong>Random Forest</strong></h4><p>Random forest regressor model is a great candidate to uncover hidden patterns inside of the continuous data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aef726293bfac6b824c628dbc186edea/href">https://medium.com/media/aef726293bfac6b824c628dbc186edea/href</a></iframe><p>The result we get for <strong>random forest regressor is amazing R² = 0.98. </strong>Random Forest clearly wins Linear regression with high R².</p><p>Now that we can select our winning model, let’s find out what are the strongest attributes for our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30caae1678da8bedf8be3415bd85aac/href">https://medium.com/media/a30caae1678da8bedf8be3415bd85aac/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*Z9sDJHtC8zrShZX5D9MF9w.png" /><figcaption>Feature importance chart</figcaption></figure><p>As we can see, the cleaning fee is a good indicator of a property price in Seattle. However this can be <em>chicken and egg</em> issue where the cleaning fee can be a consequence of a property price and not the other way around. More sceptic readers would prefer it to be removed from the predictors list and this would be completely legit.</p><p>The rest of the features are matching well with the common sense — number of rooms, beds, month of the year, minimum stay as well as location are the features that determines rental price of the property.</p><p>Such a high predictive power of our model also indicates that the AirBnB market in Seattle is very developed and every feature or lack of such adds / decreases the value of the property proportionally and that the market has a general consensus of a value for this feature.</p><h4>Summary &amp; final thoughts</h4><p>On completion of Seattle AirBnB booking analysis we could clearly find the busiest time of the year — January, July and August. With the most expensive neighbourhoods being Magnolia, Queen Anne and Downtown.</p><p>We could also predict the price of a property based on its features. In particular, we’ve found that Random Forest is probably one of the best kinds of model to predict continuous price metrics based on numerical and one-hot encoded categorical features. The strongest indicators of booking prices are cleaning fee, number of bathrooms and beds followed by minimum number of nights, room type and number of reviews. It should be mentioned that although an individual neighbourhood features (one-hot encoded) scored relatively low individually, they are truly one of the key feature if looked combined.</p><h4>Git</h4><p>You can find my <a href="https://github.com/Olek-ua/Seattle_Project">comlete jupyter file on github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc9a781fd370" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>