<?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 Badr MOUFAD on Medium]]></title>
        <description><![CDATA[Stories by Badr MOUFAD on Medium]]></description>
        <link>https://medium.com/@badr-moufad?source=rss-1e68b6587f47------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CfKEeWy3jLlOwtcQ2LYSuw.jpeg</url>
            <title>Stories by Badr MOUFAD on Medium</title>
            <link>https://medium.com/@badr-moufad?source=rss-1e68b6587f47------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:38:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@badr-moufad/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[Leveraging linear regression for feature selection of categorical and continuous variables]]></title>
            <link>https://medium.com/data-science/beyond-linear-regression-467a7fc3bafb?source=rss-1e68b6587f47------2</link>
            <guid isPermaLink="false">https://medium.com/p/467a7fc3bafb</guid>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[categorical-variable]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <dc:creator><![CDATA[Badr MOUFAD]]></dc:creator>
            <pubDate>Fri, 29 Jul 2022 22:00:10 GMT</pubDate>
            <atom:updated>2022-10-15T22:35:15.459Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to use Group Lasso to select the top K most relevant features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*t9Dt46Yifi6s6hi8lEBJRg.png" /><figcaption>[generated thanks to <a href="https://www.craiyon.com/">https://www.craiyon.com/</a>]</figcaption></figure><p>Linear regression is among the primary/entry-level Machine Learning (ML) models. It owes that to its…</p><ul><li><strong>Simplicity</strong>: It models a given response <em>y </em>as a linear combination of some variables <em>x_1, …, x_p</em></li><li><strong>Interpretability</strong>: The coefficient associated with variable <em>x_j </em>hints at its relationship with the response <em>y</em></li><li><strong>Trainability</strong>: It doesn&#39;t require a lot of hyperparameter tuning during training.</li></ul><p>It’s not even wrong to say that it’s the synonym of the <a href="https://en.wikipedia.org/wiki/%22Hello,_World!%22_program">“Hello world” program</a> for Data scientists. Despite being basic, linear regression still has some other pretty interesting properties to unfold …</p><h3>Penalized linear regression for feature selection</h3><p>Finding the linear regression coefficients <em>β_1, …, β_p </em>involves finding the “best” linear combination of variables that approaches the response. Said differently, finding the coefficients that minimize the <a href="https://en.wikipedia.org/wiki/Mean_squared_error#:~:text=If%20a%20vector,is%20computed%20as">mean squared error (MSE)</a>.</p><p>It’s possible to endow the regression coefficients with some extra properties by considering the MSE plus an additional penalty term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*leuRNHGbdAOkHVSNSwkKwA.png" /><figcaption>The penalized objective function to be minimized. [illustration by author]</figcaption></figure><p>It’s similar to implicitly saying to the model: <strong>retain as much data fidelity as possible while taking into account the penalty term with intensity <em>α</em></strong><em>. </em>It happens that with a particular choice of the penalty term, we can provide linear regression with a feature selection property.</p><h4>Lasso feature selection works well until you consider categorical variables</h4><p>When we set the penalty term as the <a href="https://en.wikipedia.org/wiki/Norm_(mathematics)#:~:text=The%20name%20relates,of%20the%20columns">L1-norm </a>— the sum of the absolute values of the regression coefficients — we get a solution with few non-zero coefficients. This is known in the literature as the <a href="https://en.wikipedia.org/wiki/Lasso_(statistics)">Lasso model</a> and its resulting solution enjoys a feature selection property as <strong>the (few) non-zero coefficients indicate the most relevant features to the model, and therefore the features to select.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*KnHFKwghiG3jiO7mXDRWuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*z7jmcBt6rusIf7jpRh-6eg.png" /><figcaption><strong>Top)</strong> Lasso&#39;s objective function to be minimized. <strong>Bottom)</strong> The resulting solution after fitting a Lasso model. [illustration by author]</figcaption></figure><p>It is very frequent to encounter categorical variables — for example, a variable color that takes “red,” “white,” and “blue” as values. These must be encoded beforehand in a numerical form to be used in a regression model. And to do so, we often resort to using <a href="https://en.wikipedia.org/wiki/One-hot#Comparison_with_other_encoding_methods:~:text=important%20than%20%27laugh%27.-,Machine%20learning%20and%20statistics,-%5Bedit%5D">one-hot encoding</a> — exploding a variable into its dummy values — to avoid implicitly enforcing an order between the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*YEw0VspWxOpJDReH7saivQ.png" /><figcaption>The result after applying one-hot encoding to a variable color that takes “red”, “white”, and “blue” as values. [illustration by author]</figcaption></figure><p>Applying Lasso in this specific case is not appropriate as a feature selection technic since it treats the variables independently and hence ignores any relationship between them, in our case, it disregards the fact that the dummy variables, taken as a whole, represent the same categorical variable.</p><p>For instance, if Lasso selected <em>color_red </em>among<em> color_white </em>and<em> color_blue</em>, then it doesn&#39;t say much about the relevance of the “color” variable.</p><h4>Group Lasso for a mixture of continuous/categorical feature selection</h4><p>Ideally, we need a penalty that considers the dummies of a categorical variable as a whole, in other terms, a penalty that incorporates the underlying “group structure” between the dummies when dealing with categorical variables.</p><p>This can be achieved by extending Lasso by slightly altering its penalty to handle groups of variables. To do so, we rearrange the regression coefficients that belong to the same group in vectors. Then, we consider the sum of their <a href="https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm:~:text=of%20its%20norm.-,Euclidean%20norm,-%5Bedit%5D">L2-norm</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*47cdwy6A7Be5d58GCVW6-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*UlApEKtbmKNNtRmstfq05A.png" /><figcaption><strong>Top)</strong> Group Lasso objective function to be minimized. <strong>Bottom)</strong> The resulting solution after fitting a Group Lasso model. [illustration by author]</figcaption></figure><p>The resulting model is known in the literature as <a href="https://en.wikipedia.org/wiki/Proximal_gradient_methods_for_learning#Group_lasso:~:text=few%20such%20methods.-,Group%20lasso,-%5Bedit%5D">Group Lasso</a>. It is worth mentioning that by considering the above penalty we obtained a model that:</p><ul><li><strong>has a group-wise feature selection property.</strong> The variables of a group are either all selected (assigned non-zero coefficients) or expelled (assigned zero coefficients).</li><li><strong>treats equally the variables of a group.</strong> We are using the L2-norm which is known to be isotropic and hence won’t privilege any of the variables of a group — in our case, the dummies of a categorical variable.</li><li><strong>handles a mixture of single and group variables.</strong> The L2-norm in a one-dimensional space is the absolute value. Therefore, Group Lasso reduces to Lasso if the groups consist of one variable.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*wrgg1Ho-E0HNbasOAMmYdA.png" /><figcaption>L2-norm in one-dimensional space is the absolute value. [illustration by author]</figcaption></figure><p>Based on that, we can use Group Lasso to perform feature selection of a mixture of continuous/categorical variables. <strong>Continuous variables will be considered as groups with one variable and categorical ones will be treated as groups of dummies.</strong></p><h3>Fitting Group Lasso model using celer</h3><p><a href="https://en.wikipedia.org/wiki/Scikit-learn">scikit-learn</a> is one of the famous python packages that are behind the prevalence of ML nowadays. Its user-friendly API and comprehensive documentation lowered the barriers to entry to the ML field and enabled non-practitioners to benefit from it without trouble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*7N8w06MjrHVXBrNCEyg4dQ.png" /><figcaption>[meme by author]</figcaption></figure><p>Unfortunately, Group Lasso is missing from scikit-learn implementation. Yet, that’s not surprising at all, as countless are today&#39;s ML models, let alone when you consider their variants!</p><p>Likely, there are several initiatives that aim at keeping ML accessible to the general public by standardizing the implementation of ML models and aligning them with scikit-learn API.</p><h4>celer: a scikit-learn API conform package for Lasso-like models</h4><p><a href="https://mathurinm.github.io/celer/"><strong>celer</strong></a><strong> </strong>is a python package that embraces the <a href="https://jmlr.csail.mit.edu/papers/v12/pedregosa11a.html#:~:text=This%20package%20focuses%20on%20bringing%20machine%20learning%20to%20non%2Dspecialists%20using%20a%20general%2Dpurpose%20high%2Dlevel%20language.%20Emphasis%20is%20put%20on%20ease%20of%20use%2C%20performance%2C%20documentation%2C%20and%20API%20consistency.">scikit-learn vision</a> and provides models that are entirely designed under scikit-learn API and thereby integrate well with it — can be used with Pipelines, and GridSearchCV among others. Hence, fitting one of <strong>celer</strong>&#39;s models is as straightforward as doing the same for scikit-learn.</p><p>Also, <strong>celer </strong>is specially designed to handle Lasso-like models such as Lasso and Group Lasso. Therefore, it features a tailored implementation that enables it to fit these types of models quickly — <strong>up to 100 times faster than scikit-learn </strong>— and efficiently on large datasets.</p><h4>Getting started with celer Group Lasso</h4><p>After installing <strong>celer </strong>via pip, you can easily fit a Group Lasso model as shown in the snippet below. Here, a toy dataset with one continuous variable and two categorical variables is considered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc956dd70419372d01d12f21d8c260a4/href">https://medium.com/media/fc956dd70419372d01d12f21d8c260a4/href</a></iframe><p>We have successfully fitted a Group Lasso and henceforth all that remains is to inspect the resulting solution — non-zero coefficients — to decide on the variables to select.</p><p>Ideally in feature selection, we are rather interested in answering the question: <strong>what are the top <em>K&#39;s </em>most relevant features? </strong>Therefore we can’t claim that we 100% answered this question as the non-zero coefficients — variables to select — depends on the intensity of the penalty <em>α </em>and hence we don’t have full control over them.</p><h3>Controlling the number of selected features via the penalty intensity</h3><p>The more we increase <em>α </em>from 0 — pure linear regression — the more variables are filtered out — assigned zero coefficients. Ultimately, for a “large enough” <em>α </em>we get a zero solution — all coefficients are zeros.</p><p>This means that the more a variable “survives” being expelled by a high <em>α,</em> the more it shows its importance to the model. Therefore, we can rely on the penalty intensity to score the variables.</p><p>Interestingly, given a response and a collection of variables, we can show that <a href="https://arxiv.org/pdf/1602.06225.pdf">there exists an <em>α_max</em></a><em> </em>above which the zero solution is the only solution that trades off data fidelity and the penalty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*X0BP5yUTayxEMEPsPLrD-A.png" /><figcaption>Group Lasso <em>on the toy dataset over a </em>grid (0, <em>α_max]. Notice that above α_max all coefficients are zeros. </em>[Illustration by author]</figcaption></figure><p>This implies that every variable would have a finite score between 0 and <em>α_max. </em>Additionally, since we have an explicit formula of <em>α_max, </em>we can further normalize the scores by <em>α_max </em>to obtain scores between 0 and 1 instead.</p><p>To sum up the approach, we first generate a grid of <em>α </em>between 0<em> </em>and <em>α_max. </em>Then, we fit Group Lasso on each of those<em> α </em>and track when the variables are assigned zero coefficients — it will be their corresponding score<em>. </em>Finally, we normalize these scores and thereafter rank the variables according to them.</p><p>All the above steps, except the last one, are meticulously handled by <a href="https://mathurinm.github.io/celer/generated/celer.celer_path.html">celer_path </a>— the building block of celer models.</p><p>Back to the original question: <strong>what are the top <em>K&#39;s </em>most relevant features?</strong> All that remains is to <strong>sort descendingly the features according to their scores and select the top <em>K</em> ones.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*pJr_H9UuOsETYDbvRzZ-4A.png" /><figcaption>The resulting scores of features of the toy dataset using the considered approach. [Illustration by author]</figcaption></figure><h3>Recap and conclusion</h3><p>Linear regression remains undoubtedly one of the simplest and easy-to-understand models which coupled with well-chosen penalties yields more interpretable results.</p><p>In this article, we extended linear regression to perform feature selection of a mixture of continuous/categorical variables using the Group Lasso model.</p><p>In the end, we used <strong>celer </strong>to fit Group Lasso as well as relied on its core solver — <em>celer_path — </em>to control the number of selected features.</p><p>I made a detailed GitHub repository where I applied the introduced feature selection technic to a real dataset. You can check the source code in <a href="https://github.com/Badr-MOUFAD/beyond-OLS-med-supp-material">this link</a>, and leverage the developed python utils to apply it to your own use case.</p><p><strong>useful links:</strong></p><ul><li><strong>example on real datasets:</strong> <a href="https://github.com/Badr-MOUFAD/beyond-OLS-med-supp-material">https://github.com/Badr-MOUFAD/beyond-OLS-med-supp-material</a></li><li><strong>celer documentation:</strong> <a href="https://mathurinm.github.io/celer/">https://mathurinm.github.io/celer/</a></li><li><strong>celer GitHub repository:</strong> <a href="https://github.com/mathurinm/celer">https://github.com/mathurinm/celer</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467a7fc3bafb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/beyond-linear-regression-467a7fc3bafb">Leveraging linear regression for feature selection of categorical and continuous variables</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s time to structure your data science project]]></title>
            <link>https://medium.com/data-science/its-time-to-structure-your-data-science-project-1fa064fbe46?source=rss-1e68b6587f47------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fa064fbe46</guid>
            <category><![CDATA[project-structure]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cookie-cutters]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Badr MOUFAD]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 22:39:09 GMT</pubDate>
            <atom:updated>2021-11-15T15:02:16.616Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple template to structure your data science project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3x4FtZy22IDBRogYBe9DOw.jpeg" /><figcaption>[Illustration by author]</figcaption></figure><h3>Why notebooks are so popular within the data science community?</h3><p>When you dive into the field of data science, you quickly notice that <a href="https://en.wikipedia.org/wiki/Notebook_interface">Notebooks</a> are the communally used tool to work on and share data science projects.</p><p>To some extent, it is a well-justified and nicely-founded choice. Notebooks bring together code, graphics, and text in a single-fast interactive “ecosystem”.</p><p><em>let’s take a step back,</em></p><p>To run a python line of code, I could say there is nothing fast than executing it directly into the console. However, this becomes inconvenient at the moment you have to run multiple lines of code. Just imagine how awkward and impractical it will be to define a function in a console.</p><p>On the other hand, python scripts are a convenient way to create and execute long code. Yet, it is also impractical in the context of data science because it simply does not scale well. Indeed, whenever you want to write a piece of code you will have to create a python file. So, take a while to think about the number of notebook cells created in one data science project. Certainly, it will give you an idea of how many python files you will create and how it will be challenging to ensure their order of execution.</p><p><strong>In short, Notebooks provide a way to run python code as fast as it will be in a console while giving the ability to write snippets of code. Consequently, they extend the console-based behavior and add interactivity to the mix.</strong></p><p>Personally, I find that these are the core features that enabled Notebooks to gain such tremendous popularity among the data science community.</p><h3>The “One notebook structure” works well until …</h3><p>As a data science student, I used to submit my assignments and mini data science projects in a form of a notebook. Besides the advantages I mentioned above, it was convenient to structure my work in a single notebook since I was able to embed graphics and <a href="https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html">inject markdowns</a> to write text/equations, and therefore elaborate further my reasoning.</p><p>It was until I got involved in a research internship that I realized the limits of this “<strong>one notebook structure</strong>”. In particular, I noticed that this method doesn’t scale well when projects get bigger and bigger.</p><p>The moment I started fetching, cleaning, and exploring the data, the number of cells exploded exponentially, and I got quickly overwhelmed by the huge number of variables. Also, when trying new approaches, I noticed that I was constantly writing repetitive code. In the end, to avoid ambiguity between variables and that some notebook cells do not influence others, I toggled into comments some (many) parts of the code. Honestly, I usually ended up shutting down the <a href="https://jupyter.readthedocs.io/en/latest/projects/kernels.html">notebook kernel</a> and restarting the environment.</p><p><strong>In short, it was impractical to code an entire project in one single notebook where one fetches, explores, and cleans the data then setups, trains, and evaluates models.</strong></p><p>It will be even a nightmare if one wanted to spot a bug or decided to change something in a terribly long and extremally chaotic notebook full of blocks of code toggled into comments.</p><p>From this unfortunate experience, I released that the “one notebook structure” is not the choice to opt for when dealing with big projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXUKbTFPhN7TdXj1GXwpqw.png" /><figcaption>[meme by author]</figcaption></figure><h3>Google it before taking action</h3><p>I believe that Data Science is at the interface between software programming and applied mathematics (probability, statistics, optimization, …). When working on data science projects, I often realize that I am coding more than anything else. Cleaning the data requires code, understating data require making visualizations which at its turn requires code, …</p><p>And as I coded, I developed the so-called “google it” reflex. So, whenever I forget/doubt something or get stuck on an error, I simply google it.</p><blockquote>“Some say a software engineer is just a professional google searcher”, <a href="https://thedailytechie.com/how-to-google-it-like-a-senior-software-engineer/">Fireship, how to “google it” like a senior software engineer.</a></blockquote><p>Personally, it is one of the best lifesaving habits to develop that will release you from loading your brain with detailed packages’ documentations<strong>. It is better to learn how to google things efficiently rather than remember them by heart.</strong></p><p>Following that, I browsed the internet to look for a solution to my problem, particularly a project structure to use in order to organize and thereby be able to scale up my work. Obviously, I found what I was seeking. I found a cookie-cutter template project: “<a href="https://drivendata.github.io/cookiecutter-data-science/">cookiecutter data-science</a>”. It is a cookie-cutter template that aims to provide a standardized data science project structure.</p><h3>The Motivation behind a standard project structure</h3><p>I do admit that my unfortunate experience showed me how desperately I needed a project structure. Yet, after scrutinizing the template <a href="https://drivendata.github.io/cookiecutter-data-science/">description</a> and its <a href="https://github.com/drivendata/cookiecutter-data-science">GitHub repository</a>, I was more convinced about the importance of standard structure and aware of the advantages it offers for both “you and others”.</p><p>On one hand, it enables an efficient organization of thoughts and code and hence speeds up the workflow. So, you won’t get lost in the “middle of the road” or stand speechless in front of a notebook wondering “What the hell was I thinking”.</p><p>On the other hand, it ensures code shareability and reproducibility. So, others will be able to jump quickly and directly to parts of code they are interested in. And more importantly, they won’t get into trouble while re-executing your code.</p><p>At once, I thought I solved my problem and all I needed is to adopt this project structure. However, it was not easy as I thought. Indeed, <strong>it was so difficult to get familiar with the project structure which contained some files and folders that I totally ignored their purpose —especially for a beginner like I was.</strong></p><p>In the hope of adapting this project structure to my use case, I spent hours of reflection as well as experimentation to understand this structure and adjust it according to my needs. In the end, I resolved to the following structure: “<strong>Simple DS project</strong>”</p><h3>The “Simple DS project” structure</h3><p>In this section, I will detail every component of the “<strong>Simple DS project</strong>” structure. Also, I will emphasize the purpose as well as the motivation behind each one of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*mOe8Z_Bj6ytz5soKJw9Hvg.png" /><figcaption>“Simple DS project” structure[Illustration by author]</figcaption></figure><h4>The “data” folder</h4><p>A fundamental objective of data science is to derive insights from data. Therefore, it is an essential ingredient.</p><p>The purpose of this folder is to gather all the project raw data. On the other hand, it will also serve as a “bucket” where one saves its preprocessed data to avoid repeating the same operations on it every time.</p><h4>The “notebooks_exploration_cleaning” folder</h4><p>This folder will contain all notebooks related to exploration-cleaning of the data. But <em>why mix exploration and cleaning in one folder and not split them into separate folders?</em></p><p>In every project I have worked on, I have never been able to explore the data independently from cleaning it (or vis-versa). Indeed, it was during the exploration phase when I resolved how to treat the data. For instance, it is after visualizing the proportions of missing values in the data columns that I decide how to handle them (e.g. remove them, or replace them by the median, …).</p><p>Finally, after exploring-cleaning your data, make sure to save it in the <strong>“data” folder</strong> so that to use it later when building models.</p><h4>The “notebooks_models” folder</h4><p>As its name suggests, this folder is dedicated to notebooks where one builds, trains, and evaluates its models. I highly recommend putting each model in a single notebook.</p><p>A typical structure of this folder would be, <em>model_1.</em><a href="https://fileinfo.com/extension/ipynb#:~:text=An%20IPYNB%20file%20is%20a,and%20analyze%20data%20using%20Python.&amp;text=IPYNB%20notebooks%20are%20plain%20text,easy%20to%20share%20with%20others."><em>ipynb</em></a>, <em>model_2.ipynb</em>, … or if you want to give meaningful names to your files there is nothing better than naming them by the name of the model, for example, <em>linear_regression.ipynb</em>, <em>lasso.ipynb</em>, <em>ridge.ipynb</em>, <em>elasticNet.ipynb</em></p><h4>The “py_scripts” folder</h4><p><em>Let’s imagine the following (recurrent) situation,</em></p><p>In <em>exploration_1.ipynb</em> you wrote a code to visualize a data column. Later, while trying another approach, you needed the same code in <em>exploration_2.ipynb</em> to make a similar visualization, so you copy-pasted that code to reuse it. In <em>exploration_3.ipynb</em>, you needed this visualization another time, so you copy-pasted that thing again, …</p><p>One major drawback when working simultaneously with multiple notebooks is writing repetitive code. The main purpose of the <strong>“py_script” folder</strong> is to overcome such a problem. Indeed, it will serve as a python package where you put all the repetitive code. So, whenever you notice that you are copy-pasting a code multiple times, just rewrite it as a function, put it into a python module, and voilà! Whenever you need it, you will import it directly, the same as you are importing a usual python module.</p><h4>The “README.md” file</h4><p>The <strong>README.</strong><a href="https://fileinfo.com/extension/md"><strong>md</strong></a> is a markdown file meant to describe your project. It is here where you will set the context of the project, mention its purpose, and state the guidelines to reproduce its findings.</p><p>When browsing projects, I always glance first at their README before diving deeper into their content. Therefore, always keep in mind that this file is at the forefront of your project.</p><h4>The “.gitignore” file</h4><p>When working on a big project, it becomes mandatory to use <a href="https://en.wikipedia.org/wiki/Version_control">version control</a> software, especially if the project has more than one contributor. <a href="https://en.wikipedia.org/wiki/Git">Git</a> combined with <a href="https://en.wikipedia.org/wiki/GitHub">GitHub</a> are one of these that enable easy and efficient management of projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*NN7IklDC6F-Kljn6KgAhHw.png" /><figcaption>Troubles when not using version control [meme by author]</figcaption></figure><p>In particular, the <strong>“.gitignore” file</strong> contains the name of all files and folders that should not be tracked by Git and hence won’t be synchronized with your GitHub repository. Typically, it contains the name of cache and build folders. Besides, you may include in it the <strong>“data” folder</strong> especially if you are using large datasets that exceed 100MB.</p><p>Aside from that, if you are not familiar with Git and GitHub (and frankly you shouldn’t), consider spending a while to learn about them. Certainly, it will make an inflection point to your programming life.</p><h4>The “environment.yml” file</h4><p>The use of third-party packages such as <em>numpy, scikit-learn</em> is omnipresent in data science. So, <em>how can you tell others about the dependencies they are required to install to run your code?</em></p><p>The <strong>“environment.yml”</strong> is meant to answer this question in the sense that it contains all the python packages that your Jupyter kernel needs to run code or notebooks.</p><p>In addition to that, this file is easy to create and use. To export your <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/environments.html">conda environment</a> just <strong>cd</strong> to your project directory using the anaconda prompt and run the following command:</p><pre>conda env export &gt; environment.yml</pre><p>By adding this file to your project, you ensure that others won’t find trouble executing your code, and more importantly, you guarantee the reproducibility of your findings. Indeed, others will only run the following command to replicate your conda project environment</p><pre>conda env create -f environment.yml</pre><p>connect to it and thereafter run the code.</p><h3>Getting Started with “Simple DS project”</h3><h4>Generate the project structure</h4><p>It is easy to get started with <strong>“Simple DS project”</strong> structure. All you need to do is to install <a href="https://cookiecutter.readthedocs.io/en/1.7.2/">cookiecutters</a> — a python package that creates projects from template projects — by running</p><pre>pip install cookiecutter</pre><p>Afterward, execute the command below and follow the prompt to create/set the project and its name</p><pre>cookiecutter https://github.com/Badr-MOUFAD/cookiecutter-simple-DS-project.git</pre><p>With that being achieved, the <strong>“Simple DS project” </strong>structure will be generated on your local machine and will be ready to start working…</p><h4>Note on Integrated Development Environment (IDE)</h4><p>When working with this project structure, you will notice that you are constantly moving from one notebook to another, from a notebook to a python file, … which I find a bit restrictive.</p><p><a href="https://en.wikipedia.org/wiki/Integrated_development_environment">IDE</a>s are tools that alleviate such a restriction in the sense that they enable juggling easily between the project directories and files. In fact, you have all the visibility on the project through the directory tree shown in the sidebar. In addition, you can modify files while staying in the same environment.</p><p>In my case, I use <a href="https://code.visualstudio.com/">VS code</a> combined with <a href="https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter">Jupyter extension</a>.</p><h3>Recap and conclusion</h3><p>“Simple DS project” is a template inspired by “cookiecutter data science”. It provides an entry-level structure to organize your work when dealing with a “bit bigger project”.</p><p>Also, it is not a structure to be literally followed. You can adjust it and refine it based on your needs. Honestly, I constantly alter it according to the project I am involved in by adding/removing files and folders.</p><p><strong>Remember, the way you organize your work keeps evolving as you work on projects.</strong> In my case, I noticed that I recently started to converge more and more to the initial structure — “cookiecutter data science”. When I rethink what prevented me from directly adopting it, I find out that it was not the complexity of the structure itself, but rather my unfamiliarity with working with a project where I manipulate multiple folders and files with different extensions (python, notebooks, markdowns, …). <strong>I trust that “Simple DS project” template will make this transition smooth for you.</strong></p><p>Finally,<strong> to view a live version of the template</strong>, you can visit its <a href="https://github.com/Badr-MOUFAD/cookiecutter-simple-DS-project">GitHub repository</a>. There, you will also find the source code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fa064fbe46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/its-time-to-structure-your-data-science-project-1fa064fbe46">It’s time to structure your data science project</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deriving the inverse transform sampling method from first principles]]></title>
            <link>https://medium.com/data-science/an-insight-on-generating-samples-from-a-custom-probability-density-function-d0a06c290c54?source=rss-1e68b6587f47------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0a06c290c54</guid>
            <category><![CDATA[scratch-programming]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[distribution]]></category>
            <dc:creator><![CDATA[Badr MOUFAD]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 23:21:59 GMT</pubDate>
            <atom:updated>2021-06-04T12:35:03.643Z</atom:updated>
            <content:encoded><![CDATA[<h4>Insights on generating samples from a custom probability density function</h4><h4><strong>Quick note:</strong></h4><p>In this article, I provide insights on generating samples from a <strong>custom probability density function</strong> using the <strong>inverse transform sampling</strong> method.</p><p>Almost every programming language enables its users to generate random numbers. But <strong>what about generating numbers that follow a certain probability distribution?</strong> This question was the main trigger of my determination to read about this topic.</p><p>When dealing with abstract concepts, namely math and programming, often the challenge is to picture those concepts in mind. In light of that, and throughout this article, I will be constantly illustrating my ideas using either <strong>diagrams</strong> or <strong>animations</strong>.</p><p>In the end, what I will try to achieve is to build — <strong>from scratch</strong> — a tool that enables sampling from a custom probability density function.</p><h3>Probability density functions are easy to construct yet not trivial to sample from</h3><p>In probability and statistics, precisely when describing continuous random variables, we often come across the concept of a probability density function. It is a powerful tool that characterizes a random variable as it gives the probabilities/frequencies of occurs of the values taken by the random variable.</p><p>As an illustration (<em>see figure below</em>), If we consider a random variable <strong><em>Y</em></strong> described by the density function <strong><em>f,</em></strong> then if we generate a total of 100 independent samples, ideally 24 of the samples would fall between 1–2, 40 between 2–3, 16 between 3–4, and so forth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*iV1HKbqwbJeqLxQr9yaIAQ.png" /><figcaption>Illustration of a probability density function [illustration by author]</figcaption></figure><p>It happens that there is a huge family of probability density functions that range from the most communally used ones (uniform, normal, exponential, …) to the most unseen ones. Indeed, if you want to construct your own density function, just take an integrable function, normalize it by its integral, et Voilà!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KxDAKH3Pzh2nUlDB6HgbnA.png" /><figcaption>Examples of distributions: in the 1st row 3 usual distributions whereas in the second row 3 unusual ones [illustration by author]</figcaption></figure><p>Numerically speaking, generating samples from a uniform distribution is quite straightforward in the sense that it is equivalent to generating random numbers. And obviously, almost every programming language has a <a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator">pseudorandom number generator</a> such as <a href="https://docs.python.org/3/library/random.html">random.random()</a> for Python and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a> for JavaScript.</p><p>However, doing the same thing for a custom distribution function is not trivial and needs some consideration.</p><p>This frustration of being restricted to only sampling from a uniform distribution yet having the ease to construct density functions was the trigger of my determination.</p><p>I do admit that after making some research on the internet, I discovered pre-existing tools that enable doing that (Python: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.html">scipy.stats.rv_continuous</a>). Still, it was not sufficient to satisfy my curiosity.</p><p>What I will try to achieve in this article is to uncover what lies under the hood by <strong>building from scratch — using uniform distribution — a tool that enables sampling from a custom density function</strong>.</p><h3>Finding a link between a uniform and custom distribution</h3><p>Suppose that I constructed a custom density function <strong><em>f</em></strong>. My objective now is to generate samples from it by leveraging a uniform distribution. The basic idea I thought about is to find a mapping between a uniform and the desired density function. In other words, I will generate samples from a uniform distribution and map those numbers with their corresponding peers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*ZJKIKCRrD7LG5mLlMiZOKQ.png" /><figcaption><em>The schema followed to generate samples from a custom density </em>[illustration by author]</figcaption></figure><p>With this in mind, what remains is to construct the mapping function between uniform and the custom density, said differently reveals what the above cogs are actually doing.</p><p>A hint to building this mapping can be derived from <a href="https://mathworld.wolfram.com/MeasureTheory.html">measure theory</a>. In short, measure theory is a generalization of the concept of length, area, and volume. Except that in the context of probability theory — <a href="https://en.wikipedia.org/wiki/Measure_(mathematics)#:~:text=Probability%20theory%20considers%20measures%20that,naturally%20from%2C%20a%20dynamical%20system.">which is a special case</a> — we are measuring probabilities instead. Density probably functions — more precisely “<strong><em>f dx</em></strong>” — can be perceived as measures and their integration has a direct link with probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*IUpYy-cL0k9BPCDKyPCmWw.png" /><figcaption>Interpretation of the area under the curve of the density function as a probability [illustration by author]</figcaption></figure><p>In both cases uniform and custom density, we are measuring probabilities which are interpreted as the area under the curve. Therefore, <strong>to find the mapping, we only need to find a link between the areas under the curve of both uniform and custom density.</strong></p><p>To do so, we firstly sample a number from a uniform. Then measure the area delimited by it. Finally, we find the corresponding number that delimits the same area under the curve of the custom distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*PpaRRp9jCvzyhdzzrPjRtQ.png" /><figcaption>A detailed schema of the process followed to sample from a custom density [illustration by author]</figcaption></figure><p>Putting that into an equation, we need to solve for every sampled number <strong><em>x</em></strong><em> </em>from the uniform distribution the following equation to find its corresponding peer in the custom density function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*45Yiy_Y9Azb2CBhkphstLQ.png" /></figure><p>Where the <strong><em>F </em></strong>subscript <strong><em>X</em></strong> (respectively <strong><em>F</em></strong> subscript <strong><em>Y</em></strong>) denotes the area under the curve delimited by <strong><em>x</em></strong> (respectively <strong><em>y</em></strong>) of the density function. In literature, <strong><em>F</em></strong> is called <a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function">cumulative distribution function</a>. It measures the probability that the random variable will fall in the left-hand interval delimited by the specified bound which is exactly in our case the area under the curve delimited by the specified bound.</p><h3>Implementation of the mapping process between a uniform and a custom distribution</h3><p>Now, we have all the theoretical material to map a generated sample from a uniform to its peer sample in the custom density. What remains is to build a program to solve the above equation.</p><p>For the sake of simplicity, we will sample from a uniform distribution between 0–1. Therefore, the area under the curve for every sampled number will be exactly equal to the number itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*hSWGUrzEz2Dw0pJ1xcW-eg.png" /></figure><p>On the other hand, computing the area under the curve of the custom density for a given <strong><em>y</em></strong> is straightforward as we have an explicit expression of the density function. In fact, we are the ones who inputted this expression. We compute this area by computing an integral. To achieve that, we can use Python: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html#scipy.integrate.quad">scipy.intergrate.quad</a>. Therefore, the final look of the equation that must be solved is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*-1zFDwloCGGt-SDYCrCYZw.png" /></figure><p>Solving this problem is equivalent to finding the roots of the above nonlinear equation. To do so, we might use again a solver. For instance Python: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html">scipy.optimize.fsolve</a>.</p><p>However, <strong>how do we ensure that this equation has a solution? And if so, how do we pick up the right one if it has too many?</strong></p><p>The cumulative distribution function measures a probability. Hence, it is a quantity between 0–1. Since the sampled number from the uniform distribution is also a quantity that lies between 0–1, we are guaranteed that the equation has <strong>at least one solution</strong>.</p><p>On the other hand, the cumulative distribution function is a monotonically increasing function. So, we are sure that whenever there is a solution <strong>it must be unique</strong>.</p><p>Based on this reasoning, we can solve the equation using a solver without worries. The core idea behind nonlinear solvers is to build a sequence that converges to the desired solution. Usually, this sequence is defined through a recursion formula, in other terms, the value of the sequence in a given stage relies on the values computed in the previous ones. Therefore, the choice of the starting point of the solver is a critical element in the sense that chosen an inappropriate one might yield a wrong solution, and in the worst-case yield a sequence that does not converge at all.</p><p>To avoid such a problem, we need to find a way to choose conveniently the starting point. To do so, we can use again one of the properties of the cumulative distribution function, namely its monotony.</p><p>We can — at the moment we build the density function — create an array of tuples <em>(see illustration below)</em>. Consequently, the elements of the array are sorted in increasing order. Based on that, suppose we sampled a number <strong><em>x</em></strong> from the uniform distribution. We can use a slightly modified version of <a href="https://en.wikipedia.org/wiki/Binary_search_algorithm#:~:text=In%20computer%20science%2C%20binary%20search,middle%20element%20of%20the%20array.">binary search</a> to find the two closest elements to it. The ‘<strong><em>y</em></strong>’s that correspond to these two elements will define an interval where our solution is most likely to be. Hence, we can choose as a starting point the midpoint of this interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*hpLkHDryOBwao5gKDtWSpw.png" /><figcaption>Illustration of the way of choosing a suitable starting point [illustration by author]</figcaption></figure><p>Now, we have all the ingredients to find the mapping of a given sampled number from a uniform.</p><h3>Testing the mapping process on examples</h3><p>After coding the previous ideas, I started testing the mapping process gradually<em> (see figure below)</em>.</p><p>I have started with a special case where the custom density that I want to sample from is a uniform distribution. Based on that, the mapping process should ideally give values that are exactly the same as the ones generated from the uniform distribution. Indeed, in this case, I am using a uniform to generate samples from a uniform.</p><p>The second test I have opted for is to generate samples from a usual distribution, in my case I have chosen a normal distribution. Visually, I was expecting to see the same delimited area for both curves. For instance, whenever we get a number on the right side of the square (uniform), the mapped number must be also on the right side of the bell (normal).</p><p>The last test was to test the process on an unusual distribution. Frankly, I was genuinely creative in imaging the most unusual density function I have ever come across :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*ZwHbg5XmlKj6f1ZKrppcHA.png" /></figure><p>I have gathered all the previous tests in animations where on the left side I put the uniform distribution from which I sample. Besides, I represented the sampled number using a red dot. On the right side, I put the densities that I am trying to sample from. Similarly, I represented the mapped number using a red dot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*zfn61YDsAvX2clFT00y9ow.gif" /><figcaption>Test of the mapping process on a uniform [illustration by author]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*TDwBfWXpbKwWE_GWAj7M8A.gif" /><figcaption>Test of the mapping on a normal distribution [illustration by author]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*nBBYffck9Y_ToMv1chMi5Q.gif" /><figcaption>Test of the mapping process on a custom distribution [illustration by author]</figcaption></figure><p>After making sure that the mapping process gives accurate results, it was time to test the whole process in which the target is to generate samples from a given density function. So I considered a custom density function, I generated a large sample from a uniform, then I mapped those samples with their corresponding peers. Finally, I represented the result using a histogram. My expectation was that the bars of the histogram should get close to the curve of the density function as the number of samples grows.</p><p>Another time, I made an animation where I represent the evolution of the histogram bars length as I increase the number of samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*S8yoHSZmDt_zJkLCE7wqew.gif" /><figcaption>Testing the whole process on a custom density function [illustration by author]</figcaption></figure><h3>Conclusion</h3><p>Throughout this article, I described how we can leverage uniform distribution to generate samples from a custom density function. Precisely, I built a tool that enables doing that. Firstly, I explained the process of implementing it. lastly, I have tested it on several distributions ranging from the communally used ones to the most unfamiliar ones.</p><p>Referring to literature, the method described in this article is called<a href="https://en.wikipedia.org/wiki/Inverse_transform_sampling"> Inverse transform sampling</a>. There are other methods used to achieve the same goal. <a href="http://web.mit.edu/urban_or_book/www/book/chapter7/7.1.3.html">Check this article for further reading</a>.</p><p>When writing this article, I deliberately avoided putting any piece of code though I was adopting a numerical perspective. In fact, I wanted the article to be accessible for both programmers and non-programmers. However, if you are curious about how things were actually implemented, you can check <a href="https://github.com/Badr-MOUFAD/distributions-from-scratch">my GitHub repository</a>. There, I uploaded details about the code.</p><p>Last but not least, I can say that I have successively reached my objective. So, to celebrate such an achievement and to satisfy my ego there was nothing better than imagining all sort of density functions and sampling from them</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gyiN8goSV81g3rajgQS0jg.png" /><figcaption>examples of distribution generated using the built tools [illustration by author]</figcaption></figure><blockquote>Rendezvous: “Insight on pseudonumber generators”</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a06c290c54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/an-insight-on-generating-samples-from-a-custom-probability-density-function-d0a06c290c54">Deriving the inverse transform sampling method from first principles</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>