<?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 Lucca Gomes on Medium]]></title>
        <description><![CDATA[Stories by Lucca Gomes on Medium]]></description>
        <link>https://medium.com/@luccagomes?source=rss-4eb354633264------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*L6iJvp3WttrV8FAE.</url>
            <title>Stories by Lucca Gomes on Medium</title>
            <link>https://medium.com/@luccagomes?source=rss-4eb354633264------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:41:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luccagomes/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[MLflow 101: My Quickstart]]></title>
            <link>https://medium.com/@luccagomes/mlflow-101-how-i-did-it-f451e787d916?source=rss-4eb354633264------2</link>
            <guid isPermaLink="false">https://medium.com/p/f451e787d916</guid>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Lucca Gomes]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 11:54:10 GMT</pubDate>
            <atom:updated>2023-10-12T13:33:02.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RjnDQB2IFfTGaKJX" /><figcaption>Photo by <a href="https://unsplash.com/@solenfeyissa?utm_source=medium&amp;utm_medium=referral">Solen Feyissa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A gentle introduction to MLFlow and its applications with Hyperparameter tuning</h4><h3>Projects, experiments &amp; Spreadsheets</h3><p>If you’ve been working with Data Science I’m sure that at some point you needed to try a lot of different things to solve a problem. At the same time, you also needed to keep track of the performance of what you tried to do.</p><p>Probably at some point you, like me, fired up an Excel spreadsheet and tried to manually keep track of things. This often results in chaotic organization both in the project folder as well as the spreadsheet itself.</p><p>It is hard to keep track of all possible things that can run differently in an experiement. Preprocessing steps for specific models, the models themselves, the parameters,…</p><p>MLflow comes in to help sort this kind of thing. It is a platform built to organize, facilitate experimentation, streamline and serve models to production. Basically a platform to manage ML lifecycle.</p><h4>A (Brief) Intro to ML Flow</h4><p>As of this writing, MLflow has 5 components in total. For this quick guide I’ll use only a few of the available ones (highlighted below), which are:</p><ul><li><strong>Tracking</strong></li><li><strong>Models</strong></li><li><strong>Model Registry</strong></li><li>Projects</li><li>Recipes</li></ul><p>The <strong>Tracking</strong> module acts pretty much as a logger, but for everything model related: What model is being used, which parameters are configured in the run, outputs (even tabular and images), etc.</p><p>Tracking has many “flavors” — how common ML/AI libraries such as sklearn, Keras, H2O are named — to help store important data and metadata of commonly used libs.</p><p><strong>Models</strong> is a form of wrapping a model after training. It encapsulates a model in such a way the model can be saved, containerized or accessed easily to be ran in other environments or easily called.</p><p><strong>Model Registry </strong>is the logical next step of the <em>Models </em>wrapper. It enables to register models that are useful and will be used in production. By registering the models, we can perform version management to them. This makes it easier to organize and register the production pipeline of a model.</p><p>MLflow tracks, throughout the components, basically 3 things:</p><ol><li>Models: model objects that can be agnostic or belong to a certain flavor of ML/AI library;</li><li>Parameters: Constant values related to the models (e.g. the weights of a Neural Network);</li><li>Artifacts: Every sort of file generated in a run. You can, for instance, save an image (like the plot of a DecisionTree) or a table.</li></ol><p>These objects are tracked in a <em>run </em>level within an <em>experiment. </em>An experiment is a general environment for MLflow to store information. A run happens within an environment. A <em>run</em> is pretty much the name MLflow gives to an algorithm execution.</p><p>To centralize all components and facilitate usage, MLflow has a really intuitive UI that can be easily started from the terminal.</p><p>MLflow can store all its files and artifacts locally. But, you can use a DB such as PostgreSQL to log the artifacts. For my tests I left it saving the data locally. In this case, MLflow generates a <em>mlruns </em>folder in the directory of the project that I supress in the repo using <em>.gitignore.</em></p><h3>A Quick Problem for a Quick Start</h3><p>To try out MLflow in practice I used a basic dataset to solve a straightfoward problem. I’ve used data sourced from Amazon made available in Kaggle to <strong>predict the sales amount </strong>for certain groceries in the UK. You can find the data <a href="https://www.kaggle.com/datasets/dalmacyali1905/amazon-uk-grocery-dataset-unsupervised-learning/data">here</a>.</p><p>The main focus of this test is to understand and use MLflow. So, for this purpose, only basic data cleaning was performed. Let’s get into it.</p><p>First things first, let’s get a sense of the data at hand. We have data for over 6.000 products that contain some features regarding the product itself as well as its performance in the marketplace (e.g. price, sales, revenue, …). See an example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q9XXKboTo8lVoYO2W42nqA.png" /></figure><p>We fetch the raw data and after some cleaning, feature engineering and subsetting we end up with a little over 5.000 products with the following features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-N9981rG5nxMTXABk6lgKw.png" /></figure><p>With this data, we can start running models for the <em>sales </em>column. Keep in mind not all the features in the picture above will be used. I’ll be using a simple Linear Regression as a baseline for comparison with other models (and to help show the power of MLflow down the road).</p><h3>Using MLflow</h3><p>MLflow can be installed as a library in your pip or conda environment. So you can bring up a terminal and run:</p><pre>pip install mlflow<br><br># or, if using Anaconda/Miniconda:<br><br>conda install -c conda-forge mlflow</pre><p>I’ll be using sklearn. I can simply import <em>mlflow </em>to use it in my code. With it imported I can use the following logic to track my models:</p><pre># Other imports #<br>import mlflow<br><br>mlflow.autolog()<br><br>### Data ingestion ###<br>### Sklearn stuff ###<br><br># Baseline Model<br>with mlflow.start_run() as run:<br><br>    lr.fit(X_train, y_train)<br><br>    y_pred = lr.predict(X_test)<br><br>    mse = -1 * mean_squared_error(y_test, y_pred, squared = False)<br>    mae = -1 * mean_absolute_error(y_test, y_pred)<br>    r2 = r2_score(y_test, y_pred)<br><br>    print(&#39;Logging Baseline Linear Regression Results&#39;)<br>    mlflow.log_metrics({&#39;Neg. RMSE&#39;:mse,<br>                        &#39;Neg. MAE&#39;:mae,<br>                        &#39;R2&#39;:r2})</pre><p><strong><em>Note:</em></strong><em> keep in mind that MLflow has .autolog() methods for common flavors, but they work best up to certain versions. Check if your lib version is fully supported by autolog, if you’re going to use it. It won’t break your code necessairly, but it can lead to problems.</em></p><p>I associate the code to my experiment with my <em>mlflow.autolog()</em> call. It automatically identifies I’m using sklearn (but I could use <em>mlflow.sklearn.autolog()</em>).</p><p>Then, I use a context to call <em>mlflow.start_run()</em> to start a run in the experiment. The run in the snippet above is for the baseline LinearRegression().</p><p>If you opt to start a run outside of a context, just make sure you end the run explicitly after.</p><p>By calling <em>.fit(),</em> MLflow automatically identifies the command and logs training metrics. I will also manually log using <em>mlflow.log_metrics(). </em>Within that run the Negative RMSE, Negative MAE and R2 scores are logged. This is done to enable comparison with test performance with other models.</p><p>The reason to use Negative RMSE and MAE and not their positive (and most usual) counterparts is that I want to perform Hyperparameter Tuning with GridSearchCV. To work within the search, these metrics need to be negative.</p><p>For the GridSearch, we use the same block used for the Linear Regression. The only change is to call the Cross Validation object instead of the model when we run <em>.fit()</em> and <em>.predict()</em>. MLflow will automatically handle what happens on the backend and will log the runs apropriately for the CV case.</p><h4>Tracker</h4><p>Now, let’s see how this looks after running in the mlflow UI. To start it just bring up a terminal window in the environment you have it installed and type:</p><pre>mlflow ui</pre><p>This will prompt you with a local IP adress where the UI was served to. You can open it in your browser to find the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r750B3bQAhyDMqi9A9syvQ.png" /><figcaption>Initial screen of MLflow</figcaption></figure><p>After running the models this is what we have. On the left, we have a list with all experiments. In this case we only have one called “Default” (automatic name assigned by MLflow, you can change it).</p><p>Using mlflow with autolog out of the gate will associate the runs to this experiment. You can build different experiments in the ui or through the API within the code.</p><p>On the right, we have a list of all of our runs. Each run gets one of the assigned names. One for the baseline model (ambitious-carp), one for the 3 other models I’ve used, these with Hyperparameter Tuning.</p><p>Notice how the GridSearchCV objects will have a “+” to their left. If we expand, we will have the <strong>5 best performing combinations in the GridSearch! </strong>The top-level run, that encapsulates all the other runs, will be the best estimator. This would be equivalent to a <em>.best_estimator_</em> call within sklearn.</p><p>Now with the models tracked, using the chart tab, we can can visually answer 2 questions:</p><ul><li>Do the models outperform the baseline?</li><li>Which model performed the best?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHZUAYAFHmcTmBiilu7X1A.png" /><figcaption>Example of Metric Graph by Run in MLflow</figcaption></figure><p>Using the Negative MAE as example, we can see one of the strenghts of MLflow. All of our models, even the ones with tuned hyperparameters, can be easily compared side by side for any of the metrics we logged.</p><p>This view enables us to answer both questions above. We do actually outperform de baseline (last deep-red bar), and we see that the second model (name: unequaled-horse) is the one that performs the best. This is true for all 3 metrics we’ve tracked.</p><p>Let’s then take a deeper look into the best model by simply clicking on its name on the list. We will this way access the second component.</p><h4>Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDqn39ZbpeX_1-CrZXMzJQ.png" /><figcaption>Detail of a run</figcaption></figure><p>This is the page that describes a run, that contains a model object. Notice how it has a lot of attributes: The data used to train and evaluate it, the parameters, the metrics tracked and the artifacts.</p><p>The “artifacts” section is what actually holds the model container. MLflow shows us how is the schema for the data used in the model and how we call the model to make predictions, with code snippets. We will do that just in a bit.</p><p>First, I will register the model to see how the <strong>Model Registry </strong>works. We can register a model by simply clicking on the “Register Model” button and giving it a name. After it’s registered, we can access the “Models” tab in the UI.</p><h4>Registry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZdUuwLApqZx3SkDogD4-Q.png" /><figcaption>Details of a registered model</figcaption></figure><p>The initial screen of the registry will be a list of the <strong>registered </strong>models and their names. By clicking on a model, the screen above pops up.</p><p>Notice how a model will have versions. The first version we generate is, naturally, Version 1. To generate a second version of a model, just log a model with the same name it has in the registry.</p><p>We can also add a description and information about who generated it. But what is really interesting here, along with the versioning possibilities, is the “Stage” tag.</p><p>With it, we can assign if a model is in Staging or Production phase. To change it, we simply click on the version we want to edit and select the correspondent stage. Notice how we also have the schema, source run info and also tags we can associate to our model. I’ll put my model on “Staging”.</p><p>It’s also worth to notice that changing the stage will trigger some actions in MLflow. For instance, when we transition a model to “Staging” a prompt shows up asking if you want that other models that get to “Staging” go to “Archived”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-hCvH8cg-uxGo9xiEZ6vg.png" /><figcaption>Trasitioning registered model version to Staging</figcaption></figure><p>With our model registered, we can call it easily to predict on data.</p><h4>Calling a Model</h4><p>To call a model you need to basically pass a URI string to mlflow. There are many options to do so, I chose one that seemed the most clean and intuitive to me. Feel free to check out other options <a href="https://mlflow.org/docs/latest/python_api/mlflow.sklearn.html?highlight=load_model#mlflow.sklearn.load_model">on the docs</a>.</p><p>To call my model to predict on data, I can simply do:</p><pre>model = mlflow.sklearn.load_model(&#39;models:/dt_amz_prices/staging&#39;)<br><br># Given that the data corresponds to the Schema in the model<br>y_pred = model.predict(X)</pre><p>And the trained model will run. That’s it. MLflow enables us to easily compare, share, store and use a lot different models for any given ML problem.</p><p>This has been, of course, a simplified scenario that I used to grasp how its basic functions work. We could, very easily, also serve this registered model as an API. However, this is beyond the scope of this text.</p><h3>Final Thoughts</h3><p>This text is a product of my personal studies to understand MLflow. I’ve used it to solve a quite simple ML problem. This was done as a way to understand how its functionalities help Data Scientists experiment in a more orderly and structured fashion.</p><p>I’ve covered 3 of the 5 components of the tool and tried out how they can be used in a project setting. In my honest opinion, MLflow is something I am strongly considering to adopt as a standard for my own work. This is because of the following reasons:</p><ul><li><strong>Structure</strong>: I can test various models, with various configurations really easily, in a ordered way that I know where what is;</li><li><strong>Easy comparability between runs</strong>: I don’t have to build extra layers of code to keep track and compare all the experiments I run. The chart mode helps a lot for model selection and comparison;</li><li><strong>Replicability</strong>: It’s easy to call any model, not only the registered, without the fuss of opening other files and replicating the code (given the data preprocessing is the same);</li><li><strong>Transparency </strong>: At all times we can look at parameters, features, inputs, outputs and artefacts from every model. If in a team setting you can see who did what;</li><li><strong>UI</strong>: The UI is a major facilitator. It is clean, simple and self explanatory. This helps a lot to navigate problems with many possible solutions.</li></ul><p>I hope this text helped you understand the main strenghts I’ve come to experience using MLflow.</p><h4>Acknowledgements and links</h4><ul><li>For the full code of the project, check out my <a href="https://github.com/bglucca/test_mlflow">Repo on GitHub</a>.</li><li>Check out the <a href="https://mlflow.org/docs/latest/index.html">MLflow docs </a>for further and more in-depth information.</li><li>The data for the project came from <a href="https://www.kaggle.com/datasets/dalmacyali1905/amazon-uk-grocery-dataset-unsupervised-learning/data">this dataset on Kaggle</a>.</li><li>If you liked the text, leave some claps, a comment and feel free to check out my personal page at <a href="https://bglucca.github.io/">Lucca Bevilacqua — Data Scientist (bglucca.github.io)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f451e787d916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You’ve got mail! Machine Learning for Customer Segmentation.]]></title>
            <link>https://medium.com/@luccagomes/youve-got-mail-machine-learning-for-customer-segmentation-2c90d9b9d58d?source=rss-4eb354633264------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c90d9b9d58d</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <dc:creator><![CDATA[Lucca Gomes]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 17:45:49 GMT</pubDate>
            <atom:updated>2025-09-07T13:42:45.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSD7mSCwBL501ZlwzPlk5g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@jontyson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jon Tyson</a> at <a href="https://unsplash.com/pt-br/fotografias/vVSleEYPSGY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Using Data Science to better understand the customers for a mail-order company and predicting their marketing actions’ response.</h4><p><em>Disclaimer: This article and data for the development of the code are part of my submission Udacity’s Data Science Nanodegree program.</em></p><h3>Who should I reach out to? And where are they?</h3><p>These are common questions to every sort of business. Especially B2C companies that reach out directly to consumers. Thankfully, Data Science can help us better pinpoint the niches within possible markets/ population.</p><p>In this specific article, we will be covering data for Arvato-Bertelsmann. The data provided belongs to a mix of german general population demographic data and data from one of the company’s clients: an organics mail-order comapny.</p><p>This is a two-part analysis. The first part will be an unsupervised cluster generation and interpretation of the census data vs current customers. This helps us understand <strong>which characteristics better define our customer base</strong>.</p><p>The second part will be a supervised learning problem to predict responses to marketing actions. This can help us predict <strong>which people have the highest probability of becoming customers after marketing efforts.</strong></p><p>To answer these questions, we have 4 tables:</p><ul><li>2 .csv files with demographic data. One is the general population data, the other is the customer base.</li><li>2 other .csv files with the Mailout information. One is the training data and the other was supposed to be the test data. But for this article, only the training data will be used.</li></ul><p><strong><em>Note: The test data for mailout information was supposed to be used as part of a Kaggle competition entry that no longer exists. This is why only the training data was used, since it has labels for scoring and model evaluation.</em></strong></p><p>There were also 2 auxiliary tables that represented a documentation regarding the available variables and how to interpret the encodings of categorical variables.</p><p>All files use “;” as the separator between values.</p><p>An observation at stage is necessary: Due to terms and conditions of the data, the data cannot be shared and thus will not be found anywhere except within the Udacity Data Science Nanodegree context.</p><p>With all the context set, lets get into the analyses. The methodology is the following: We first do an Exploratory Analysis of the Data and check for its consistency. This way, we can define any preprocessing steps to get the best out of our data.</p><p>Then, we go to the unsupervised stage, where we try to build segments that might help us understand the companies customer base.</p><p>At last, we move to the modelling, where we attempt to build a model to predict wether a person answers to a mailout campaign or not.</p><h3>Initial EDA</h3><p>The general census data contains 891221 rows by 366 columns<strong><em>. </em></strong>The variables are divided into different groups, where each one means a different thing. For instance there is a group regarding automobile ownership information, other blocks regard the surroundings of the respondent.</p><p>The rows represent one respondent’s responses. Each respondent is represented by an anonym ID called “LNR” in the database.</p><h4>Fixing CAMEO_ columns</h4><p>There are 3 columns in the data (<em>CAMEO_DEUG_2015, CAMEO_INTL_2015 and CAMEO_DEU_2015</em>) that raise a warning about mixed types in Data. This happens because the values “X” or “XX” show up on them, when they should be numeric types (<em>int </em>or <em>float</em>). Since there is no description on the documentation of what these values are supposed to be and since they are different to the possible values in the columns, they were replaced as NaNs.</p><h4>Fixing Documentation — Removing undocumented columns</h4><p>Another problem found was that not all columns were in the documentation, on either of the two auxiliary files. This generated 3 scenarios:</p><ul><li>The naming of the column was incorrect, but it was in fact documented (salvageable);</li><li>The column name was self-explanatory enough to be associated to other columns that had similar encodings and names (salvageable);</li><li>The column was, effectively, missing from the documentation (unsalvageable).</li></ul><p>The most critical case would be the last one. When we don’t have a clear meaning to the feature we can’t assure its usefullness. Therefore, columns considered unsalvageable were dropped.</p><p>The steps taken to set the not found columns were:</p><ol><li>Get column names not in the documentation</li><li>A first automatic attempt to match columns by appending common strings to the names</li><li>A second manual verification to see if the names coincide heavily with other columns in the docs and, therefore, we can infer the meaning of the not found columns.</li><li>The columns not found after these two steps, were dropped.</li></ol><p>31 columns were dropped by this process.</p><p>Also, with the documentation now fully representing the data, the files could be used to:</p><ul><li>Correlate the column names to their data types (float, int,…) and variable type (numeric, interval, nominal or binary)</li><li>Correlate the column names to the variable group they belonged to</li><li>Correlate the column names to their respective NaN values that could be encoded differently</li></ul><p>To build these correlations, especially variable type, changes were made manually to the files or new files were created in a format that made fetching the documentation’s information in an easier manner.</p><h4>NaN Handling</h4><p>Given the (now fixed) documentation on the value of the columns, we can extract information from the documentation to replace values that map from “unknown” to NaN.</p><p>By ingesting this information and considering that strings that contain “unknown” in the meaning of the encoding represent NaNs, we can build a dictionary for each column to map its corresponding NaN values using pandas’ .replace() method:</p><pre>df_attributes[[&#39;Attribute&#39;,&#39;Description&#39;]] = df_attributes[[&#39;Attribute&#39;,&#39;Description&#39;]].fillna(method=&#39;ffill&#39;)<br><br># Assuming, from manual inspection from the &#39;Values&#39; Spreadsheet, that NaNs are represented with substrings in Meaning col<br>nan_val_df = df_attributes[df_attributes[&#39;Meaning&#39;].str.contains(&#39;unknown&#39;,regex=True,na  = False)].copy()<br><br>nan_val_df[&#39;Value&#39;] = nan_val_df[&#39;Value&#39;].str.replace(&#39;\s&#39;,&#39;&#39;, regex = True)<br><br>nan_val_df[&#39;Value&#39;] = nan_val_df[&#39;Value&#39;].str.split(&#39;,&#39;)<br><br>nan_val_map = dict(zip(nan_val_df[&#39;Attribute&#39;], nan_val_df[&#39;Value&#39;]))<br><br># Reshaping the dictionary for .replace<br>nested_nan_map = {}<br>for k, v in nan_val_map.items():<br>    nested_nan_map[k] = {int(val):np.nan for val in v}<br><br># Mapping values to NaN<br>census = census.replace(nested_nan_map)</pre><h4>Column Elimination — NaN Proportion</h4><p>After mapping the NaNs to each column, we can check for high incidence of NaNs column-wise.</p><p>Columns with a high percentage of NaN values can be discarted because they probably do not provide any sort of valuable information regarding the general properties of the population, which makes building inferences/ insights around them risky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*wQB_eD9cf8xD4Goowe6Uog.png" /><figcaption>Columns with a proportion of NaNs above the threshold, would be dropped.</figcaption></figure><p>The proportion threshold is a somewhat arbitrary definition. The plot above helps us understand the reasoning to why select 30% as the maximum threshold to drop a column.</p><p>If a threshold of proportion of NaNs ≤ 30% is chosen, we drop 9 columns that do not meet this criterion and manage to retain other columns in which we can impute values. Having in mind that the amount of columns that would be dropped if a 50% threshold was selected is 8 and that the cut for 20% might be too conservative, 30% was deemed as an appropriate cut.</p><h4>Numeric Variables Distributions</h4><p>With unused columns dropped and types appropriately fixed, we can look into some of the distributions to get some insight on the variables.</p><p>Broadly speaking, the numerical variables either needed no transformations or required to be binarized. One variable needed to be dropped.</p><p>In general, numerical variables are left-skewed as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcGGgHvLhwb-MYzffWaZfQ.png" /><figcaption>Box-Plot of numerical distributions’ examples</figcaption></figure><p><em>Note: The fliers (dots beyond whiskers) were ommitted to help the visualization</em></p><p>Two variables needed to be binarized: ANZ_HH_TITEL and ANZ_KINDER. This was because they had, respectively, <strong>86.43% </strong>and <strong>82.05% of zeroes in them</strong>. On top of that, both of them showed a dominance in low discrete values. These aspects makes it really hard to consider these variables as numeric when approaching any problem. Therefore, they were binarized to represent wether or not they had that attribute.</p><p>GEBURTSJAHR was the dropped variable. It had 44.02% of YoB as 0. Therefore, from every 10 answers, 4 wouldn’t have a YoB. Since we also have a variable that represents the age category of the respondents (ALTERSKATEGORIE). This variable was dropped.</p><p>The binarization occurred on the preprocess stage, which will be covered in the coming section.</p><h4>Categorical Variables Distributions</h4><p>Categorical variables were more looked into especially for the interval variables. Some variables presented too many categories that not necessairly were informative, such as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*6RHcaFtOCm0huVhTAK3oog.png" /></figure><p>Taking the example above, the consumption variable for banking shows how the answers gravitate between the 0, 3 and 6 values. Accounting other categories could make the space of options too sparse and the combinations of variables would make it even sparser. Keep in mind that there are 36 columns like the one showed above just for its group.</p><p>So the next step was to identify the columns that showed this sparsity and reduce it by reducing the number of bins. This affected mainly columns from 2 groups:</p><ul><li>125 x 125 Grid columns (case illustrated above): from 7 categories, reduced to 4</li><li>D19 columns in the “Household” group: 3 types of columns were identified which had respectively 10, 7 and 10 groups that were reducet to 3, 4 and 3 possible values</li></ul><p>The specifics of these alterations will be covered below in the “Preprocessing” stage</p><h3>Cleaning the Data — Defining Preprocessing Steps</h3><p>The approach for defining the preprocessing will use as baseline the general population demographic data. This is to ensure that no bias from the customer base or mailout base affect the conclusions or steps taken to clean the data.</p><p>The idea is that cleaning steps that apply to the general population, should apply to its subsets since the same variables are present across all files and that all the files are technically a subset of the general population.</p><h4>Dropping empty rows</h4><p>Rows that are filled with too many NaNs mean that they might be rows with a lot of imputation. What this results is that we will have rows in which a person might be described a lot by general values of the variables (mean, median, mode, etc.). This automatically might deliver bias to our analysis.</p><p>The individuals with highly imputed responses will actually be an “average” (or other imputed value of choice) of all variables. This assumption is not reasonable if most of the data of that response isn’t from that person. We would end up having some “average” indivituals</p><p>The graph below shows a distribution of amount of rows by proportion of data missing in them. Notice how approximately 10% of the data (orange shaded area) has more than half of their information compromised by NaN values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*8Gw1TbcSYquLgh919OYEPQ.png" /><figcaption>Distribution of proportion of NaN values in the data’s rows</figcaption></figure><p>Considering the information the graph displays, rows with more than 30% of its data missing will be discarted.</p><h4>Re-encoding the relevant numerical variables to binary</h4><p>As noted in the ETL, some numerical variables had to be encoded to binary. Using a simple np.where is enough to encode the variables the way we need them to.</p><h4>Fixing Object columns</h4><p>Some columns are in the object format. This is not inherently a problem. But some columns could benefit from not being object :</p><ul><li>The OST_WEST_KZ is actually a binary column</li><li>The CAMEO_DEU_2015 column could be interpreted as an interval variable.</li></ul><p>The fix to OST_WEST_KZ is straightfoward, the column values were mapped to 0 and 1. The CAMEO_DEU_2015 column had 1 integer value mapped to each one of the columns’ possible values. The smaller integer values account for the higher income classifications, the higher account for the lower incomes.</p><h4>Imputations</h4><p>The imputation strategy used was separated in two:</p><ul><li>Mode for any categorical variable (interval, nominal or binary variables)</li><li>Mean for numerical</li></ul><h4>Reencoding D19 Columns</h4><p>As mentioned in the ETL stage, some columns that start with the “D19” prefix could be reencoded after inspecting their distributions to reduce sparsity in the categories. This led to 4 reencodes:</p><ul><li>Columns from the “125 x 125 Grid” that refered to consumption frequency of a group of goods. They were re-encoded into 4 groups: No transactions, consumed within 12 months, consumed within 24 months and Prospects (&gt; 24 months)</li><li>Columns from the “Household” that refered to the actuality of the last transaction: Activity within the last 12 months, activity older than 12 months, no activity</li><li>Columns from the “Household” that refered to the transaction activity in the last months (12 or 24): No transactions, low activity, increased activity, high activity</li><li>Columns from the “Household” that refered to the percentage of transactions made online: 0% online, 100% online, mixed online-offline (values between 0% and 100%)</li></ul><p>All re-encodes were made assigning an int value to each category but always mantaining the logical order of the variable. This was made so that the variables could be interpreted as interval and not simple nominal variables, since they contain an inherent order.</p><p>After the ETL and Preprocessing notebooks, all relevant steps were turned into a .py file so that all steps could be equally applied across all files.</p><h3>Building Customer Segmentation</h3><p>With the data now cleaned and preprocessed, we can start building our segmentation. This part uses the general census data and the consumer census data. The question we want to answer at this stage is:</p><p><strong>Do the possible consumers find themselves in specific segments of the general population?</strong></p><p>In a more technical fashion: Given the existance of clusters in the general public data, can the consumers be found more often in specific clusters?</p><h4>Strategy — Approaching the problem</h4><p>Given the main question at this stage, the approach had to cover (mainly):</p><ol><li>A Dataset with a high amount of features (300+, possibly more after One-hot encoding the nominal variables);</li><li>A Dataset with mixed-typed data (categorical and numerical);</li><li>A Dataset with a high amount of rows (~800.000 on the general population data);</li><li>Establish a comparison between general population and consumers, given the clusters formed around general population data. Consumer data should not “leak” to form the clusters, since we aim to build clusters around the general population and see how the consumer data “fits” into this reality.</li></ol><p>To solve the 1. topic, we would usually go with using a dimensionality reduction method such as PCA. However, given the constraint of the mixed data (topic 2.), <strong>we should not use PCA. </strong>Using PCA directly on a mixed-data context, would not generate mathematically correct (and thus interpretable) results.</p><p>We can look use alternative approaches such as <strong>Factorial Analysis of Mixed Data (FAMD)</strong>. This approach is a form of generalizing Factorial Analysis to a mixed-data setting. The result is similar to PCA. For a more technical and in-depth look into the strategy <a href="https://towardsdatascience.com/famd-how-to-generalize-pca-to-categorical-and-numerical-data-2ddbeb2b9210">this article explains the theory and implementation of the method</a>.</p><p>FAMD outputs something similar to PCA. This covers the first two main points, handling the amount of features and mixed data. Now for the last two, the solution is pretty straightfoward.</p><p>To enable our model to train clusters on the general population and to assign them to the consumer base, we can use clustering methods that will generate centroids. This makes it possible to assign customers to the nearest centroids of the general population. This works because customer data will have the same features as the general population table.</p><p>Considering the output of FAMD is a fully numerical table, we can use the well-known K-Means algorithm. But since we need to process 800k + rows across hundreds of columns (which might make some setups runs a little slow), we can use sklearn’s cluster.MiniBatchKMeans that handles confortably the amount of data to give us the results we need.</p><h4><strong>FAMD</strong></h4><p>To get the data ready for the FAMD, we create a function to basically One-Hot Encode nominal variables, and weigh these variables accordingly. We also use sklearn’s StandardScaler to handle the numerical attributes accordingly. For this work, interval variables will be considered as numerical attributes and will be handled like numericals.</p><p>The FAMD approach used is a manual one (find more about it in the article linked in the previous section). This means that after applying these transformations, we use PCA on the transformed data. The preprocessed data for FAMD, in the end, ends up with 396 features.</p><p>So to select the amount of Components we will have, we define an acceptable threshold for the amount of variance we want to keep and then make the transformations. The graph below shows that for a threshold of 95% of variance, selecting 225 components satisfy this criterion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*ex1QVDV0uw8y-vsTwlxpRQ.png" /></figure><p>Starting from a higher amount of components and following with bigger steps was a deliberate approach to save processing time.</p><h4>Mini Batch K-Means</h4><p>With the transformed data after the FAMD process, we can train the Mini Batch K-Means algorithm and use the elbow method to choose an appropriate amount of clusters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*72zpLQfemmondlclKfeAqQ.png" /></figure><p>From the graph above, we could select k = 14 as a reasonable amount of clusters for our problem.</p><p>With the trained FAMD and K-Means objects trained on the overall census data, we now use them on the customer data to then classify data from both files to clusters.</p><h4>Adjusting Customer Data</h4><p>To use customer data as intended, we run the same preprocessing we did for the general data and then we will simply use the .transform() from the PCA object and .predict() from the model, both fitted on general population data, to use the customer data.</p><p>Neither the PCA or model are re-fitted on customer data to avoid that the customer’s characteristics, which could be differently distributed than the general population and would this way affect the estimates of the cluster centroids or generates Components different from the general population. We want to classify customers <strong>according to</strong> general population groups and <strong>not to consider them jointly</strong>.</p><p>The code to reuse the customer data with the objects trained on general data will look, generally, like this:</p><pre>customers = pd.read_parquet(CUSTOMER_PATH)<br><br># Preprocessing function<br>customers = prep_data_famd(customers, nominal_vars, binary_vars, num_cols)<br><br># Dropping specific columns that aren&#39;t used in clustering<br>X_cust = customers.drop(columns = [&#39;LNR&#39;,&#39;CUSTOMER_GROUP&#39;, &#39;ONLINE_PURCHASE&#39;, &#39;PRODUCT_GROUP&#39;])<br><br># Are there columns that do not match between the frames?<br>na_cols = set(census.columns) - set(customers.columns)<br><br>print(f&#39;Categories not in customer data but are in census: {na_cols}&#39;)<br><br>for col in na_cols:<br>    <br>    X_cust[col] = 0<br><br>assert set(census.columns.drop(&#39;LNR&#39;)) == set(X_cust.columns)<br><br>X_cust = pca.transform(X_cust[census.columns.drop(&#39;LNR&#39;)]) # Order needs to be the same<br><br># Assigning clusters to responses<br>customers[&#39;cluster&#39;] = kmeans_model.predict(X_cust)<br><br>census[&#39;cluster&#39;] = kmeans_model.predict(X)</pre><h4>Results</h4><p>This process gives us the following distribution in each dataset of responses for k = 14 clusters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ufQ9RVysHSoXspjNYevdFA.png" /></figure><p>There are clear differences in some clusters! We can see clusters that clearly contain more customer responses than general population responses. Especially the 1, 6, 8, 9 and 11 clusters are clusters that contain a higher proportion of customers.</p><p>This already gives us an insight: <strong>If we want to find new customers similar to the current customer base, we should target the clusters with a notably larger proportion of responses then the general population. I.e. the clusters mentioned above.</strong></p><p>We can go one step further and dig a little bit deeper on the interpretation of the clusters. We will first understand around which components the cluster is more heavily centered around and then look a little into some of the main variables that compose the component.</p><p>Let’s take the cluster 11 as an example, since it contains the highest overall proportion of customers in it. More specifically, let’s look into the 3 main components of the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*vVeqKEm9J3FQMsblsagqIw.png" /><figcaption>Main components for cluster 11</figcaption></figure><p>The cluster is heavily centered at high values in the 0 component, backed up by other components. Here, only the 3 top components will be shown for brevity and as to draw a concrete example of interpretation of the information. But, this analysis could be extended to how many components we would like and all clusters.</p><p>Let’s look at the top 10 features in each component 0, 3 and 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*UGK7D5pxMMPYB1-LLDd52A.png" /><figcaption>Main features in Component 0</figcaption></figure><p>For component 0 we can draw that it has a heavy weight on Economic Class (<em>CAMEO_DEUG_2015, CAMEO_DEU_2015</em>) and distance to nearest city centre (<em>BALLRAUM</em>). Both indicators are <strong>inversely proportional </strong>to the weight of the component.</p><p>These features are interval variables. They have an interpretation that the bigger their value, the <strong>lower the income</strong> (for <em>CAMEO_… </em>columns) or the <strong>farther from the center</strong> the respondent is (<em>BALLRAUM</em>).</p><p>In, general, this component could refer to:</p><ul><li><strong>indiviual income</strong></li><li><strong>distance to urban centers.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*RoaJ5caiamIGWrtkh8aKmA.png" /><figcaption>Main features in Component 3</figcaption></figure><p>Component 3 seems more balanced in terms of feature impact that component 0. However, a lot of the variables in the component are from the same group (<em>SEMIO_</em>…) and we have a big contribution of the <em>KONSUMNAEHE </em>variable. The component is proportional to this variable. The bigger its value, the further the respondent is from Point of Sale (PoS).</p><p>The <em>SEMIO_ </em>variables refer to the mindset of the respondent. Note that the <em>SEMIO_FAM</em> variable has an opposite signal on the effect than the other <em>SEMIO_ </em>variables. This means in practice that the component grows proportionally to <em>SEMIO_FAM, </em>but grows inversely proportionally to the others.</p><p>The <em>SEMIO </em>variables have highest affinities (stronger mindset) on lower values. So, for this component, the higher the family mindset, more positive is the component. But, the higher the other mindsets, the more negative it is.</p><p>There are also the <em>RELAT_AB </em>and <em>MOBI_REGIO </em>variables, that are about unemployment rates on the surroundings of the respondents and mobility profile of the respondent.</p><p>Therefore, we can say that this component refers to:</p><ul><li><strong>The geographical distance of the respondent to a PoS, and;</strong></li><li><strong>The mindset (affinities) of the respondent, towards some themes.</strong></li><li><strong>And has some relation to the respondents’ surroudings employment rates and their mobility profile</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*-iMZR53UNDYxuuzPQ9oZhg.png" /><figcaption>Main features in Component 1</figcaption></figure><p>Component 1 shows a heavy contribution of the <em>PLZ_HHZ </em>variable, being inversely proportional to it. We can also see that other <em>SEMIO_</em> Features contribute to the component, as well as <em>FINANZ_ </em>and <em>CJT_ </em>variables.</p><p>HHZ is about housing density on the surroundings of the respondents. The higher the variable’s value, more dense is the region.</p><p>The <em>FINANZ_ </em>variables are about how the respondent handles money (finances)</p><p>CJT is about Customer Journey Tipology. This means how the customer behaves regarding advertisement consumption and types of Channels used for purchases.</p><p>Therefore, we can infer that this component is about:</p><ul><li><strong>If the respondent lives in densly populated regions;</strong></li><li><strong>How the respondents handle their finances (some attributes);</strong></li><li><strong>How the respondents see the world (different themes than Component 3)</strong></li><li><strong>And how they consume ads and which channels they use.</strong></li></ul><p>These examples are to illustrate how we could interpret these results towards understanding what is that drives certain clusters. Of course that transformation processes such as FAMD and PCA will add a complexity layer to the interpretation of these informations, since we will have compositions of original features being used.</p><p>However, even so we can grasp to some extent what is that drives the components and, consequently, the clusters.</p><p>After the clustering, we move on the prediction of responses (interaction) to marketing campaigns.</p><h3>Predicting Customer Response</h3><p>At this stage we have a different question then that one posed in the segmentation stage:</p><p><strong>Can we predict better then a naïve approach the customers that might or might not respond to marketing campaigns?</strong></p><p>For this task we will actually use the Test mailout dataset only. This is because its the only dataset that contains labels for predictions.</p><h4>Strategy — Approaching the problem</h4><p>Differently from the segmentation phase, when we were handling with an unsupervised problem, now we have a Supervised Classification Machine Learning problem. This means we have labels that we can match correct predictions to. However, the dataset at hand has its specifities.</p><p>The labels we are trying to predict come from a column named <em>RESPONSE</em>. It is a binary target. 0 stands for no response, where 1 stands for a response by that individual.</p><p>We need to keep in mind that we are dealing with an <strong>unbalaced target. </strong>This means that the response variable is heavily populated by one of the values. This case, 0. The graph belows illustrates the situation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*jMqqZC4jgyKirfVHdN_y-w.png" /></figure><p>In total, after preprocessing, we are left with 435 positive responses versus approx. 34.5k of negative (absence) responses. This means we have about a 1.2% response rate. The remaining 98.8% are people that didn’t respond to the campaign.</p><p>It is important to keep in mind that for such an extreme unbalance <strong>accuracy is not an option for a good metric in this case</strong>. It is a biased metric when we are handling unbalanced datasets.</p><p>In short, it is very easy to get a good result for accuracy in an unbalanced setting, since <strong>it accounts both True Positives (TP) and True Negatives (TN) as successes</strong>. For a more detailed explanation <a href="https://machinelearningmastery.com/failure-of-accuracy-for-imbalanced-class-distributions/"><strong>check this article</strong></a>.</p><p>So we need a strategy that:</p><ol><li>Handles unbalanced data;</li><li>Uses a metric that quantifies effectively the success of the model;</li><li>Performs better than a baseline naïve approach.</li></ol><p>As to topic 1. we have some options. We can use methods that weigh the response variable according to its occurance or we can use artificial sampling methods like SMOTE or Downsampling, both available in imblearn .</p><p>Working always from the least to the most complex, testing with methods that weighed the response variable worked well. So this approach was selected.</p><p>About topic 2. the solution proposed is using the well known <strong>Area Under the Curve for the ROC Operator (ROC-AUC score)</strong>. This will take into consideration the occurance of the Recall (how many relevant instances we classified correctly) versus the False Positive Rate (how often we misclassified an instance as being a respondent, when it wasn’t).</p><p>The third and final topic can only be known for certain known after modelling and comparing results to the test data. So, let’s get into it.</p><h4>Modelling</h4><p>To avoid Data Leakage (i.e. test data being used in training) and thus preventing that the model gets information from data it should not have, sklearn’s Pipeline will be used.</p><p>The approach selected for better handling the data unbalance was hyperparameter tuning. By default, a lot of algorithms have options to handle this kind of problem.</p><p>For the problem at hand, 4 models were used:</p><ul><li>Logistic Regression — Baseline value for comparison (simplest model)</li><li>Decision Tree</li><li>Random Forest</li><li>XGBoost</li></ul><p>For the first 3 models, there is the class_weight parameter that sklearn has available for usage. For XGBoost, the scale_pos_weight was used to achieve a similar effect on the XGBoost API.</p><p>Also, given that the problem had interval variables (categorical variables with an ordinal relationship) they were approached in two different ways: first, using them as numerical variables; second, using them as ordinal variables. For the first case, these variables were handled as numeric. For the second, they were handled by an OneHotEncoder .</p><p>In general, the numerical variables were Standardized because, although not needed by the methods, we would be able to test the models with regularization.</p><p>Also, considering the unbalance, all Cross Validations for results were made with StratifiedKFoldto assure target balance.</p><h4>Results — Test Data</h4><p>We want to first compare what strategy we will use: encode or not the interval variables. This is because variables of this type are the majority of the data. How we use them can impact the results.</p><p>Secondly, we want to see if the models we choose will have results good enough to justify Hyperparameter Tuning. We will compare the results from the other models to Logistic Regression performance.</p><p>To start we split the train and test data. Then, setting up the pipelines with initial versions of the models, we run them <strong>only using the training </strong>data inside cross_validation and evaluate the comparative performance of the models. The results are the following:</p><p><strong>For the interval variables being used as numeric</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eu0Z1gIULJndPntoU52nUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*DcIUw4Z5CF1z8QSdq6JzMQ.png" /></figure><ul><li><strong>For the interval variables being one-hot encoded:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eu0Z1gIULJndPntoU52nUw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*_9wijCDxuKxHi_Rem6-2Mg.png" /></figure><p>On a first glance, the models seem to overfit. However, we must consider we have a heavy unbalance at hand. So, what can actually be happening is that we don’t have enough samples to generalize well to test data. This means that this heavy difference of results could be result of the amount of available information.</p><p>Also, on this first run, the models aren’t with any sort of hyperparameter tuning. This can heavily affect the results. Tree depth or regularization, for instance, are parameters that affect a lot these kinds of models.</p><p>All the models outperform the Logistic Regression on test data.</p><p>Also, the strategy of using interval variables as One Hot Encoded features seem to wield better results. However, the results are only slightly better. So, as a counterproof, we will run both strategies for all models to tune hyperparameters.</p><p>When we run the final models against the test data, we can assess if they actually overfit or yield bad results.</p><h4><strong>Hyperparameter Tuning</strong></h4><p>With the results from before, we will do hyperparameter tuning for the Decision Tree, Random Forest and XGBoost in both cases of usage of the interval variables. The tuning took place with the following parameters:</p><pre>dt_params = {&#39;DT__max_depth&#39;:[2,3,5,6],<br>             &#39;DT__min_samples_split&#39;:[2,5,10],<br>             &#39;DT__min_samples_leaf&#39;:[1,3,5]}<br><br>rf_params = {&#39;RF__n_estimators&#39;:[100,200],<br>             &#39;RF__max_depth&#39;:[2,3,4]}<br><br>xgb_params = {&#39;XGB__n_estimators&#39;:[100,150],<br>              &#39;XGB__max_depth&#39;:[2,3],<br>              &#39;XGB__learning_rate&#39;:[0.1,0.2],<br>              &#39;XGB__alpha&#39;:[0,1,2.5]}</pre><p>For the tuning, only training data was used and the Stratified K-fold cross validation was kept.</p><p><strong>Mean AUC-Score results for the interval variables used as numerical</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*XsHHkugS19xz6OC6R5DeYA.png" /></figure><p><strong>Mean AUC-Score results for the interval variables used as categorical:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*6BuRWY34uyHGvKXHi7Yw7A.png" /></figure><p>From the scores, we get that in general the variables used as categorical (One-Hot Encoded) yielded better results. However, the difference in results are still really close. To assure we don’t discard useful models, they will be tested on the test data to see their generalization power.</p><h4><strong>Final Run: Results on test data</strong></h4><p>Now, running the models with data never seen we can actually assess if there is indeed overfitting taking place or not. If the results on test data never seen is a lot lower than on the training stages, then overfiitting might be a possibility.</p><p><strong>Results for the interval variables used as numerical</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rV_h4fwFSkKyNyhxvMQyfg.png" /></figure><p><strong>Results for the interval variables used as categorical:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NME6oTFfDjLafxCsN3LJ8g.png" /></figure><p>From the results the model that best generalizes to the test data is the <strong>Random Forest with One-Hot Encoded interval variables</strong>. We can also see that the results are similar to those obtained on the predictions over the training data. This points that the difference might not be necessarily overfitting, but actually the model’s capability to generalize well to the data at hand.</p><p>However, the results point to a better performance when comparing any model to a naïve Logistic Regression.</p><h4>Conclusions</h4><p>We can see that <strong>it was possible to predict the respondents using ML approaches successfully</strong>. All models outperformed a naïve Logistic Regression baseline.</p><p>The best model had the following variables as the most important for predicting results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*f-lPk7eMVFA5qqBmHv0QDw.png" /></figure><p>We can notice that informations regarding car ownership (KBA13_…) and some general counts of the households (ANZ_…) appear often.</p><p>From these results, we could potentially <strong>use this model to pinpoint which customers could be targeted by future marketing endeavors</strong>.</p><p>Some improvements could be thought of for future development cycles such as:</p><ul><li>Feature selection, removing highly correlated features to increase perfomance and reduce any redundancies the models might capture.</li><li>Rerunning the clustering with selected features. This might enable us to cluster without recurring to FAMD method and thus making the interpretation of the cluster easier.</li><li>Rerunning the models with more data available: given the unbalance, to improve the models generalization capabilities, using more data would be optimal to achieve substantially better results.</li></ul><h3>Thanks for reading!</h3><p>Here is the <a href="https://github.com/bglucca/ArvatoCustomerSegmentation/tree/main">repo</a> for the project</p><p>If you liked this article, consider leaving a clap and a comment.</p><p>If you have any feedback or just want to get in touch, feel free to leave it in the comments or DM on <a href="https://www.linkedin.com/in/luccabgomes/">LinkedIn</a>.</p><p>To know a litte bit more about me, check out my <a href="https://bglucca.github.io/">page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c90d9b9d58d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making browsing AirBnb easier through Data Science]]></title>
            <link>https://medium.com/@luccagomes/making-browsing-airbnb-easier-through-data-science-bf96e2a72e0c?source=rss-4eb354633264------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf96e2a72e0c</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[airbnb]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Lucca Gomes]]></dc:creator>
            <pubDate>Sat, 12 Nov 2022 18:02:43 GMT</pubDate>
            <atom:updated>2023-10-24T13:22:18.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayCDmfhfvitG0I5DjUQ47A.jpeg" /><figcaption>Rio is a big city. There are a lot of options to look into.</figcaption></figure><p>I consider myself somewhat of a regular traveler. That’s why I often look for places to stay in AirBnb. But, when I fire it up, the options are countless.</p><p>Don’t get me wrong, the filters on the site are great and I always liked it. But as a Data Scientist, I wonder if even with some simple Data Analysis navigating AirBnB could be made easier.</p><p>That’s why I asked myself if I could use Rio de Janeiro’s (my hometown and a popular tourist city) AirBnB data to:</p><ol><li>Find out if I could narrow my search by looking directly into the cheapest zones and cheapest neighbourhoods into each zone.</li><li>Discover natural listing groups (i.e., clusters) based on their declared characteristics so that, if I wanted to, I could look into the group that suited me the most for a trip.</li><li>Find out which are the most (and least) common ammenities I should expect when looking into listings in Rio.</li></ol><p>Let’s get into it.</p><h4>Sometimes I don’t want to spend that much</h4><p>Price is an easy go-to filter. But that isn’t the only factor to take into consideration in a travel. You might wonder about distance to touristical spots, public transportation or even if you are cutting a good deal for that region… Location matters.</p><p>So to get a glimpse of that, we can try check out the prices by neighbourhood and even by city zone and see if they vary and, if so, we can rank them from cheapest to most expensive.</p><p>The data I had at hand didn’t contain city zone information. But we won’t let that stop us. With an easy scrape using Pandas <em>read_html</em> method on this <a href="https://pt.wikipedia.org/wiki/Lista_de_bairros_da_cidade_do_Rio_de_Janeiro">Wikipedia page</a>, we can get the city zone data to populate our table.</p><p>So first let’s take a look into the price distribution for each city zone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzX_jsVH8fCmIQqY3WEFFQ.png" /><figcaption>Note that y-axes are not shared between plots</figcaption></figure><p>We can see that generally price is a right-skewed distribution and that zones have effective differences in their distribution behaviour. For instance the south zone peaks more to the left then the north zone. West zone has a fatter tail.</p><p>This gives us two informations: We can group regions and use a comparison metric since it most probably will wield different results. Given the distribution, the median will be used. This results in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*XLmpnHe4PG9Znc8nYWK5cg.png" /></figure><p>So when looking for a place to stay, listings on the North and Central regions might be more price-friendly.</p><p>We can dig a little bit deeper and even, for each zone, list the neighbourhoods within each region that have the cheapest prices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*MFP0GGD59_03TIxDlaKl7A.png" /></figure><p>This is where some domain knowledge kicks in, though. Especially on the West Zone, the cheapest lisitings are really far away from the downtown or touristical spots.</p><p>But we have considerable price differences even within the cheapest/ expensive regions. So bringing this geographical layer on top of prices (and vice-versa) might facilitate users navigating through listings.</p><h4>But what if I’m looking for something in specific?</h4><p>Maybe location doesn’t matter as much if your priority is to first find listings suitable to your needs. That’s where clustering comes in. We can find natural groups of listings with similar features for someone can look into without the need to filter variable by variable.</p><p>The variables that describe a listing can be interpreted essentially as categorical. It can be argued that something like the amount of bathrooms a listing has is continuous/numerical, but on the sample it was rare to have more than 3 bathrooms in an AirBnb listing, for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*ceR9kl7JY6nf-9cPTgzhyw.png" /><figcaption>Count of listings for the bathroom variable. Note that from 3 bathrooms onward, there are few listings that contain more baths. There are even listings with no bathrooms!</figcaption></figure><p>What we see for bathrooms happens generally for the other variables that describe listings as well.</p><p>This limits our approach to categorical variable clustering methods. For this one, I will be using KModes. But you could use some variation like Gower Distance + Hierarchical Clustering.</p><p>After selecting our desired variables: Room Type, Number of Persons Accomodated, Bathrooms, Bedrooms and minimum accepted nights we can use our methods’ cost-function to set up an elbow-method plot and define our n for our clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*uWuG-qmFwkMcoDGI2OteKg.png" /></figure><p>It looks like n = 8 is a nice enough amount of clusters. The rate in which the cost falls after that slows down heavily. When we run it we get the following clusters (using their centroid as reference):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHeVJ39O3HUx8mUJL6IPsg.png" /><figcaption>Clusters</figcaption></figure><p>Centroids, in this case, are the most-frequent value for each feature.</p><p>It is normal that most clusters are centered around Entire rooms/ apts in Entire Rental Units. These values dominate the dataset, having more than 50% of listing associated to them.</p><p>The biggest differences come from the “size” of the listings and the minimum nights. With size I want to express how many people they accommodate and the amount of bathrooms, bedrooms, etc. that a listing has.</p><p>If users were to search for listings in a city, the clusters could be a good starting point for showing them listings more aligned with their needs.</p><h4>What if I want WiFi in my room?</h4><p>Sometimes you want certain amenities. Sometimes you expect a room to have some basic things. So, it is only natural to try to find out what are the most common and rare amenities in listings. That way, users could know what to expect (or not to) for the listings in the city.</p><p>To start off answering our final question, we look into the the amenities field available in the dataset. It is a somewhat tricky feature. It is a whole string that should’ve been a list. So it is a list contained within a string and a simple <em>.split()</em> won’t cut it.</p><p>With a little bit of RegEx and text cleaning, we get our data to a list format. The only thing left to do is some text cleaning especially for WiFi. Since it’s is an important aspect nowadays, we do some special cleaning for it. WiFi values have multiple values like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*FisnVL1xckUqLvdko1Y6lg.png" /><figcaption>Multiple different forms to write that a listing has WiFi</figcaption></figure><p>With the cleaning handled, we can use the <em>.explode() </em>method to turn our lists into rows and make our analysis easier.</p><p>We get a total of 2788 unique amenities. But, considering each amenity is only listed once per listing, we can use <em>.value_counts()</em> on top of our exploded dataset to get the number of listings each amenity was cited in. This allows us to approach the problem using a Pareto logic. That is, a low number of amenities will show up with high frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*ThrOWQ_CsHQdYrarHGSAqw.png" /></figure><p>We can see that even by making a cut as small as 10% on the proportion of listings an amenity shows up in, we already reduce the amount of amenities from 2788 to 56.</p><p>I chose to work with this this 56 amenities subset. Considering that there might be a lot of amenities that will show up sparsely or are super specific, we cannot simply select the overall least cited amenities. This could lead to unnecessary/ wrong information.</p><p>For instance, it is safe to assume that a refrigerator from a specific brand (which exists on the data) is not an amenity someone would actively look for. Even the least common amenities must be contained in a group within reason.</p><p>With that in mind we get that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*0vlOKkW4r56Xow__wf0JVA.png" /></figure><p>Are the most common amenities, so you can expect them to occur in a lot of the listings. Need WiFi? You’ll probably have it covered. No need to worry about it.</p><p>On the other hand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*c94QGQORrU0hjknHA-3s3Q.png" /></figure><p>Are the least common amenities within that subset. So if for instance a beachfront view is a must for you when coming to Rio, you might only have more niched options available.</p><h4>Conclusions</h4><p>All things considered, all 3 analyses show relatively simple ways data could be incorporated to facilitate decision-making within the platform for the users. If we get back to our starting questions:</p><ol><li>We can narrow our search for cheap listings by adding a geographical layer to our data. This could be even further explored if we incorporated more data like proximity to tourist sights or restaurants concentration , for instance.</li><li>It is possible to segregate listings based on their declared characteristics like amount of beds, rooms, etc. using a relatively simple clustering algorithm. This might be helpful to present to users more focused listing groups in-line with their needs without the need to manually set filters.</li><li>From more than 2000 amenities we can get a subset of 56 significant amenities that could allow a user to catch a glimpse of what they could expect in a lot of the listings or not. That way, expectations can easily be set.</li></ol><p>Naturally, all three paths could be enhanced with more work put into them. But the conclusions show how already on the current state we can create value to an user by answering key-questions and focusing of efficient analysis methods.</p><h4>Acknowledgements</h4><p><em>The full notebook and data can be found on my </em><a href="https://github.com/bglucca/RioAirBnb"><em>GitHub</em></a><em>.</em></p><p><em>Data for AirBnB was collected from </em><a href="http://insideairbnb.com/get-the-data/"><em>Inside AirBnb</em></a><em>.</em></p><p><em>For more references into K-Modes, I recommend visiting </em><a href="https://github.com/nicodv/kmodes"><em>nicodv’s GitHub</em></a><em> that contains not only the implementation of the algorithm but references to the Theory behind it.</em></p><p><em>This work was done as a submission to Udacity’s Data Science Nanodegree Program.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf96e2a72e0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>