<?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 Sami BEN BRAHIM on Medium]]></title>
        <description><![CDATA[Stories by Sami BEN BRAHIM on Medium]]></description>
        <link>https://medium.com/@sami.benbrahim?source=rss-45a2159770be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q_lYjxQOHV9JYTX2xJ60ZA.jpeg</url>
            <title>Stories by Sami BEN BRAHIM on Medium</title>
            <link>https://medium.com/@sami.benbrahim?source=rss-45a2159770be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:43:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sami.benbrahim/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[World Cup Memories: Zidane, and The Tunisian Old Man.]]></title>
            <link>https://medium.com/@sami.benbrahim/zidane-and-the-tunisian-old-man-12cd3c0f0c26?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/12cd3c0f0c26</guid>
            <category><![CDATA[life]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[soccer]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Sun, 10 May 2026 03:19:17 GMT</pubDate>
            <atom:updated>2026-05-17T22:57:23.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3l-F15ZBrJLUV46jBk8Nsg.jpeg" /><figcaption>Zidane and Ronaldo, before the kick-off of France-Brazil, FIFA World Cup QF 2006</figcaption></figure><p>It’s been a long time since my last Medium story. I’m back to writing, but this time not to talk about machine learning.</p><p>A few hours ago, I was in my neighborhood’s football (soccer) pitch spending some time with my ball. The ball, 450 grams, unites people, creates joy, smiles, memories, lifetime friends. As the FIFA World Cup is near the start, in this story, I will share with you my three most memorable world cup moments.</p><h3>Zidane, the new Napoleon</h3><p>The first iconic image that comes to my mind is Zidane’s two headers against Brazil in the 1998 FIFA World cup final. My dear father used to watch the replay of that final a lot. He made me love Zizou (Zidane’s Nickname). Zidane was a pure artist, very calm, and smart. He could eliminate a whole defence line with just a ball control. Zidane played a pivotal role in France’s historic first World Cup victory in 1998.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*y4a0NEXXmwWBPEasSnxJyg.jpeg" /><figcaption>One of Zidane’s two winning headers against Brazil in the 1998 FIFA World Cup Final</figcaption></figure><h3>“Oh Zineddine !”</h3><p>It was the 110th minute of the 2006 FIFA World cup final Italy VS France. All my family was gathered in front of the TV watching the historic final. “Baba, chbih Zidane?”, I said to my father (in Tunisian dialect, it means “Dad, what’s wrong with Zidane?”). No one understood what had happened. Everyone was focused on the game; the players, the referees, the fans, then suddenly something very unexpected happened. The referee stopped the game and went to check the Italian defender lying on the ground and holding his chest. Nobody saw anything, even the referee and his assistants. What happened? The camera showed Gigi Buffon (the Italian goalkeeper), who apparently saw something, angry and asking the referees to recheck the video. Then, the images on TV switched to a replay; Zidane headbutting Materazzi! “<em>Oh Zineddine, Oh Zineddine, Pas ça, pas ça. Oh non, pas ça! Pas aujourd’hui, pas maintenant, pas après tout ce que tu as fait!! Ayyyyyyyyy yaaa yaaaa yaaaay</em>”. This was the iconic commentary from Thierry Gilardi, just after seeing the replay of the headbutt. In French, it means “<em>Oh Zineddine, Oh Zineddine, not this, not this. Oh no, not this! Not today, not now, not after everything you’ve done!! Ayyyyyyyyy yaaa yaaaa yaaaay</em>”. Everybody was shocked! How come? How could Zizou, the soft and gentle guy, do that? And actually, that incident marked the first (unofficial) use of the VAR (video assistant referee), because the red card decision against Zidane was taken after seeing the video outside the pitch. Also, that was the last game of Zidane as a professional footballer. Zidane later admitted the mistake that probably cost his national team the World cup, although Italy totally deserved that trophy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*Vu76TOI_oeuxiN6XugChHw.jpeg" /><figcaption>Gigi Buffon, the Italian goalkeeper, trying to cheer up his former Juventus teammate Zidane after the incident.</figcaption></figure><h3>The Tunisian old man</h3><p>It was around 9–10pm in Monastir, Tunisia. The 2014 FIFA World cup semi-final between Brazil and Germany was ongoing. All coffeeshops were full. I was unable to watch the first half, and had no idea about the score. So, I went straight to the closet coffeeshop. I remember the game was probably in the 60th minute. I took one step inside and looked up at the screen. “Oh My God!”, I said to myself. I removed my glasses, looked up again at the screen, put my glasses back on. “Is that 6–0 or 0–0?”, I asked the closet person to me. “6–0!”, he replied. I could not believe it. I started looking strangely at the people around me, and I saw an old man sitting in the middle, smiling at me; a wise, pained smile. That man probably had witnessed all Brazil’s five World cup wins. That was a shocking night for all football fans, not only Brazilian people.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_J3AxwqqevQVDgfyf29cg.jpeg" /><figcaption>The night when the Brazilian national team forgot how to defend.</figcaption></figure><p>And you my friend, what’s your best World cup memory? Tell me in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12cd3c0f0c26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLxtend for a smarter interpretation of your classifier]]></title>
            <link>https://medium.com/@sami.benbrahim/mlxtend-for-a-smarter-interpretation-of-your-classifier-d5e3b8c8f252?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5e3b8c8f252</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sklearn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 09:19:21 GMT</pubDate>
            <atom:updated>2023-06-14T09:27:06.204Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*lHNB_K8ElD109dST.png" /><figcaption>source: <a href="https://rasbt.github.io/mlxtend/">mlxtend (rasbt.github.io)</a></figcaption></figure><p>“We have to add some regularization to avoid overfitting”.</p><p>This sentence is often used by ML bloggers and Youtubers to justify the regularization of neural network layers. But only few do explain the logic of regularization. In this blog I’m trying to give an intuitive justification of the importance of regularization (L2).</p><h3>Intuition</h3><p>Overfitting in simple terms is a “blind learning” of the training data. As we see in the figure below the overfitted model follows rigorously the boundary that separates the two classes. Two issues are observed:</p><ul><li>The proposed model is highly non-linear (complex). As a result the computation of weights is more expensive.</li><li>No guarantee that the model will generalize on unseen data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YZ5kRrNFbW42uemB.png" /><figcaption>source: <a href="https://www.superannotate.com/blog/overfitting-and-underfitting-in-machine-learning">Overfitting and underfitting in machine learning | SuperAnnotate</a></figcaption></figure><p>As a result in order to avoid this problem we add a penalty term to our cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*NxnpGSZ4N1jQV_eU3s6Atg.png" /><figcaption>source: <a href="https://medium.com/analytics-vidhya/l1-vs-l2-regularization-which-is-better-d01068e6658c">L1 vs L2 Regularization: The intuitive difference | by Dhaval Taunk | Analytics Vidhya | Medium</a></figcaption></figure><p>We know that machine learning is all about minimizing the above cost function. By adding the regularization term (λ) we aim to minimize the loss function and also keep the weights as small as possible. <strong>But why is that?</strong></p><p>Let’s take the example of a neural network layer with an activation function “tanh”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*QuYSBevZrET9Z5iw.png" /><figcaption>source: <a href="https://www.medcalc.org/manual/tanh-function.php">TANH function calculator and graph (medcalc.org)</a></figcaption></figure><p>Looking back at the penalized cost function:</p><p>If λ is high then the optimization algorithm will try to shrink the weights w_j in order to minimize the cost function. So w_j will get close to 0.</p><p>As a result:</p><p><strong>z_j</strong>=sum(i=1 to n) w_ij*x_i+b_j will get <strong>closer to 0.</strong></p><p>By observing the tanh curve above we clearly understand that the tanh is locally <strong>linear </strong>for values close to 0.</p><p>Thus:</p><p><strong>tanh(z) behaves linearly around z_j.</strong></p><p>Consequently regularization reduces the non-linearity of our model.</p><p>The same principle applies if we use sigmoid or relu functions as well !</p><h3>Implementation</h3><h4>Problem:</h4><p>classification of iris dataset.</p><h4>Model:</h4><p>A shallow neural network with 1 hidden layer.</p><h4>Process:</h4><p><em>1-Install “mlxtend” and import the necessary packages:</em></p><p>“mlxtend” is a very useful Python library that is used to <strong>visualize the decision boundary of a classifier.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a45521daa19b379d0316cbaa234d607/href">https://medium.com/media/6a45521daa19b379d0316cbaa234d607/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa8e848dcb92e0c43e58a62aaceae818/href">https://medium.com/media/aa8e848dcb92e0c43e58a62aaceae818/href</a></iframe><p><em>2-Read and visualize the data :</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a067f2f61b9d97113a84cddc315c99c/href">https://medium.com/media/0a067f2f61b9d97113a84cddc315c99c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*4qp-shiu43e4z0YgQd5kCA.png" /><figcaption>overview on iris data</figcaption></figure><p>Iris dataset comprises 4 features : sepal_length, sepal_width, petal_length, petal_width. The target is the type of iris: Setosa, Virginica or Versicolour.</p><p>This dataset is usually used in ML tutorials due to its simplicity, low size and balance : every class is represented exactly by 50 samples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b666a527715228a7b7e43deab444f4f4/href">https://medium.com/media/b666a527715228a7b7e43deab444f4f4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*IhqIoiEjOOHuOEt8P58iaQ.png" /><figcaption>balanced classes</figcaption></figure><p><em>Remark:</em></p><p><em>“mlxtend” does only accept a classifier with 2 explanatory variables. So first we have to choose the variables to be used as features of our model.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bce7f9fd70ab77ca5f662e4c6748aab3/href">https://medium.com/media/bce7f9fd70ab77ca5f662e4c6748aab3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*qsCxIrIorLY3TTteKt3NXA.png" /><figcaption>pairwise visualization</figcaption></figure><p>The choice of the features is done after observing the above gaph. We just chose the pair of features that simplifies the separation of the three classes. We can remark that in all the scatter plots that include “petal_length” the classes can be separated more easily.</p><p><strong>As a result we choose (petal_length, sepal_length) as our features.</strong></p><p><strong><em>3-Feature matrix Scaling:</em></strong></p><p>Normalizing our 2D-feature matrix fastens the convergence of the cost function to its minimum value. I advise you to fit your model with both the non-scaled feature matrix and the scaled feature matrix and you’ll certainly notice the difference ;)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d2ffc5aa0363f6449ecd6d79008e559/href">https://medium.com/media/9d2ffc5aa0363f6449ecd6d79008e559/href</a></iframe><p><strong><em>4-Target Encoding:</em></strong></p><p>Our target variable is categorical, composed of 3 distinct strings “verginica”, “setosa”, “versicolour”. So obviously these strings have to be transformed into <strong>integer classes.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c563b736db6b68ed329515792c8e6b5/href">https://medium.com/media/1c563b736db6b68ed329515792c8e6b5/href</a></iframe><p><strong><em>5-Splitting the data and performing Onehot encoding:</em></strong></p><p>The data is splitted into training and test data. Subsequently we generate two vectors <em>y_train_onehot </em>and <em>y_test_onehot</em> which represent the onehot encoding of <em>y_train</em> and <em>y_test</em> respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf9e2b64780dff9bd7bb33af5ab90785/href">https://medium.com/media/cf9e2b64780dff9bd7bb33af5ab90785/href</a></iframe><p><strong><em>6-Build the model and fit it to Iris data:</em></strong></p><p>A dense neural network with a single hidden layer is built. There are no theoretical rules about the choice of hyperparameters’ values (number of epochs, number of neurons,…), so a trial-and-error process is needed in order to find the best model. Personally I fit the model maybe 100 times trying different values in order to achieve the best performance and also <strong>see the effect of variation of the hyperparameters’ values on the model’s cost function curve and accuracy curve.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cb555036cb863119bd0e597ab3c9cd7/href">https://medium.com/media/7cb555036cb863119bd0e597ab3c9cd7/href</a></iframe><p>I share with you some rules/tips about the design of your neural network model:</p><ul><li>The number of input units = 2 = number of features.</li><li>The number of output units=3=number of Iris classes.</li><li>The choice of the activation function, initial weights, the value of lambda, the number of neurons, is done with <strong>trial and error</strong>.</li><li>I used “CheckPoint” class from Keras to save the best achieved model during training.</li></ul><p>We observe the results obtained without regularization (lambda=0) and with regularization (lambda=0.7)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*qMmG4ZWzTYyaPcDUomP_IQ.jpeg" /><figcaption>without regularization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*Y3Cj9Inr_DPxwjQBXsndWg.jpeg" /><figcaption>with regularization</figcaption></figure><p>We remark that the addition of a penalty term makes the loss function <strong>smoother</strong> with largely <strong>higher values</strong>, similarly the model’s accuracy curve becomes <strong>more stable. </strong>But in terms of convergence and performance both models give satisfactory results with a <strong>validation accuracy around 0.95.</strong></p><p><strong><em>7-”mlxtend” for decision boundary visualization:</em></strong></p><p>To see the effect of regularization more concretaly we use mlxtend to visualize our classifier’s decision boundary for both cases (with/without regularization).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b0111b004d6c4d0592a34e8121636c/href">https://medium.com/media/62b0111b004d6c4d0592a34e8121636c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*vfQbK7SPeMQjbNGZjNiqHw.jpeg" /><figcaption>the decision boundary (without regularization)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*D6Sta6l_bP2TaPGB9fyzBA.jpeg" /><figcaption>the decision boundary (with regularization)</figcaption></figure><p>We remark that the non-regularized decision boundary is <strong>less linear</strong> that the regularized decision boundary.</p><p><strong>I recommend using mlxtend to better explain your classifier.</strong></p><p>One drawback is that mlxtend can only explain models in <strong>2D-feature space.</strong> But generally we face multi-dimensional problems that are difficult to visualize. So in this case what tools do you advise me to use to<strong> increase my model’s explainability</strong> ? :)</p><h3>References</h3><ul><li><a href="https://stackoverflow.com/questions/75960845/plot-decision-regions-typeerror-axis-got-an-unexpected-keyword-argument-y-mi">https://stackoverflow.com/questions/75960845/plot-decision-regions-typeerror-axis-got-an-unexpected-keyword-argument-y-mi</a></li><li><a href="https://rasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/">https://rasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/</a></li><li><a href="https://github.com/ibtissammakdoun/Introduction-au-deep-learning/blob/main/code%20Iris%20Deep%20Learning%20Classification.ipynb">https://github.com/ibtissammakdoun/Introduction-au-deep-learning/blob/main/code%20Iris%20Deep%20Learning%20Classification.ipynb</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5e3b8c8f252" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The intuition behind Logistic Regression loss function]]></title>
            <link>https://medium.com/@sami.benbrahim/the-intuition-behind-logistic-regression-loss-function-64390260ed81?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/64390260ed81</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[pattern-recognition]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 00:36:52 GMT</pubDate>
            <atom:updated>2023-04-02T00:36:52.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fv48BIaRr4Ov0s9L" /><figcaption>Photo by <a href="https://unsplash.com/@fromwhereiseethings?utm_source=medium&amp;utm_medium=referral">Noelle Guirola</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever thought why we choose cross-entropy as the loss function for a logistic regression problem? Why not choose the average mean squared error for example ?</p><p>The answer is very simple and intuitive!</p><h3>Cross-entropy loss function:</h3><p>Cross-entropy loss is defined as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*ZqDo79LHHs14WoQO.png" /><figcaption>source: <a href="https://androidkt.com/choose-cross-entropy-loss-function-in-keras/">How to choose cross-entropy loss function in Keras? — Knowledge Transfer (androidkt.com)</a></figcaption></figure><p>where the output size is the number of unique classes. For example: for a cat-dog image classification problem the number of classes is 2= the output size.</p><p>Now one may ask whether we can use mean squared error (MSE) function as our loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*B-KEhIZbjrlVkfWC" /><figcaption>source: <a href="https://www.freecodecamp.org/news/machine-learning-mean-squared-error-regression-line-c7dde9a26b93/">Machine learning: an introduction to mean squared error and regression lines (freecodecamp.org)</a></figcaption></figure><p>The answer is NO !</p><h3>Simple explanation:</h3><p>To simplify things let’s take the case of binary classification.</p><h4>First reason: intuitive function:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jf_a9NfZvwI2yPvm.png" /><figcaption>Binary cross entropy function denoted by “L”. Source: <a href="https://subscription.packtpub.com/book/big-data-and-business-intelligence/9781789132212/3/ch03lvl1sec30/understanding-categorical-cross-entropy-loss">Understanding categorical cross entropy loss | TensorFlow Machine Learning Projects (packtpub.com)</a></figcaption></figure><p>For a binary classification problem we have two possible outputs:</p><ul><li><strong>y_i = 0:</strong> then <strong>L = — log(1-p_i).</strong> The objective is to minimize L, equivalent to maximize log(1-p_i), equivalent to minimize p_i. <strong>So p_i should be as close to 0 as possible.</strong></li><li><strong>y_i = 1:</strong> then <strong>L = -log(p_i)</strong>. We have to minimize L, equivalent to maximize log(p_i). So <strong>p_i should be as close to 1 as possible.</strong></li></ul><p><strong>Conclusion: the choice of cross-entropy is intuitive!</strong></p><h4>2nd reason: convexity!</h4><p>Convexity of the loss function makes the minimization problem simpler and increases the chance of convergence to the optimal solution (optimal parameters of our sigmoid function).</p><p>And it is proved by simple calculus that <strong>the binary cross entropy function is convex with respect to the parameters of the sigmoid function.</strong></p><p>Contrary to the cross entropy, <strong>mean squared error function is NOT convex</strong> with respect to the parameters of the sigmoid. So the search of the minimum is usually complicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0oLgiEuWo781xCYX.jpg" /><figcaption>Left: example of convex function. Right: example of non-convex function</figcaption></figure><h3>References:</h3><p><em>The content is inspired from the Deep learning course of Andrew Ng on Coursera. I highly recommend it to improve your DL intuition!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64390260ed81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A comparative study of Logistic Regression and Naive Bayes]]></title>
            <link>https://medium.com/@sami.benbrahim/naive-bayes-and-logistic-regression-are-linear-classifiers-characterized-by-their-efficiency-and-d8de47e7b390?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8de47e7b390</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 22:01:22 GMT</pubDate>
            <atom:updated>2022-12-15T22:31:28.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8wXMew615pLH95r8" /><figcaption>Photo by <a href="https://unsplash.com/@chw98?utm_source=medium&amp;utm_medium=referral">Wiem Chatti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Naive Bayes and logistic regression are linear classifiers characterized by their efficiency and ease of interpretation. Naive Bayes is an example of <strong>generative learning</strong> algorithm and logistic regression represents an example of <strong>discriminative learning</strong> algorithm. After reading [1] I was excited to verify its results on other datasets. Scroll down to see which results I am talking about !</p><p>In [1] A. Ng and M. Jordan implemented naive Bayes and logistic regression models and tested them on 15 different datasets : 7 with discrete input variables and 8 with continuous inputs. For each dataset they varied the number of training examples and for each number of training examples they averaged the generalization error over 1000 train/test splits. The two following results were highlighted by the authors:</p><ul><li><em>Naive bayes achieves its (higher) asymptotic error remarkably faster than logistic regression.</em></li><li><em>In 66% of the experiments logistic regression achieves a higher prediction accuracy as the number of training examples increases.</em></li></ul><p>In this blog we will apply Naive Bayes and logistic regression on two simple classification problems and we will compare our results to [1].</p><p>Let’s start by the first classification problem !</p><h3>1-Iris dataset:</h3><p>We will use the famous iris dataset from sklearn to train a logistic regression classifier and a Gaussian naive Bayes classifier. First let’s load the required libraries and the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a49070412b5225cacb22a9765312305e/href">https://medium.com/media/a49070412b5225cacb22a9765312305e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4822bb4ec87a5ac644da51c8391d15/href">https://medium.com/media/3d4822bb4ec87a5ac644da51c8391d15/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*B5DFe8FO414nwFQKxMOm0Q.png" /><figcaption>iris dataset (screenshot from author)</figcaption></figure><p>The iris dataset is composed of 150 rows and 5 columns. The columns include:</p><ul><li><strong>4 predictor variables</strong> which are roughly on the same scale (see the descriptive statistics below). Thus scaling the input matrix is not required.</li><li><strong>A target :</strong> a categorical variable which contains 3 balanced classes (0,1,2).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*4W5zgV8fUQZwAexLDHG0ig.png" /><figcaption>descriptive statistics (screenshot from author)</figcaption></figure><p>We follow basically the same methodology of [1] : we measure the training accuracy score of both algorithms and we see the effect of the variation of size of training data on the models’ training performance. In each experiment the training accuracy score is averaged over 1000 randomly selected training datasets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f021e05b1147e738df8de5704407dbc/href">https://medium.com/media/2f021e05b1147e738df8de5704407dbc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdf69b30895d865bf7bb6265646cfe62/href">https://medium.com/media/bdf69b30895d865bf7bb6265646cfe62/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*PlSqe4lnbp04UsYNnjW09w.png" /><figcaption>training accuracy (source: author)</figcaption></figure><p>The figure above shows that with relatively small training datasets naive Bayes performs better than logistic regression. But as the size of training data increases logistic regression overtakes naive Bayes. This result confirms a major conclusion drawn in [1].</p><p>Let’s carry on with the second classification problem!</p><h3>2– Heart disease prediction :</h3><h4>Data description</h4><p><a href="https://www.kaggle.com/datasets/dileep070/heart-disease-prediction-using-logistic-regression">The dataset</a> used in heart disease prediction problem is taken from Kaggle. It is composed of 4238 rows and 16 columns. The columns are a combination of categorical and numerical variables :</p><p><strong>-15 Predictor variables :</strong> the variables that impact a person’s risk of coronary heart disease. These variables can be classified into four families :</p><ul><li><em>Demographic variables : </em>age, sex, education</li><li><em>Behavioral :</em> smoker/non smoker, number of cigarettes per day</li><li><em>Medical history :</em> blood pressure medication, prevalent stroke, prevalent hypertension, diabetes</li><li><em>Current medical :</em> total cholestoral level, systolic blood pressure, diastolic blood pressure, BMI, heart rate</li></ul><p><strong>-Target variable :</strong> 10-year risk of coronary heart disease CHD (0/1)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf79f43917c4fded04ba71ea049a12d1/href">https://medium.com/media/cf79f43917c4fded04ba71ea049a12d1/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*u8v06GlIdl2JtArQB4qH7A.png" /><figcaption>columns (source: author)</figcaption></figure><h4>Data preprocessing :</h4><p>First we verify the missing values in each column.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2d0140bc74ba7af81664808f429d7f6/href">https://medium.com/media/a2d0140bc74ba7af81664808f429d7f6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*Li9X3yMPniS-QOCRJYYUIA.png" /><figcaption>number of NaNs per column (source: author)</figcaption></figure><p>So the first preprocessing step is to remove the rows with NaN value(s).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec17439925ac60447748e99c8c79800b/href">https://medium.com/media/ec17439925ac60447748e99c8c79800b/href</a></iframe><p>Second we remark that « education » variable is a categorical variable with 4 unique values : 1,2,3,4. But as no description is given about this variable we decide to remove it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/050ee0f81275e5fbc3c64834e86dbc24/href">https://medium.com/media/050ee0f81275e5fbc3c64834e86dbc24/href</a></iframe><p>Third we look at the target variable which is binary. We plot the barplot of both target classes and we conclude that the classes are imbalanced (see the barplot below).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd4e90d889a8d1878ee28bc8c3368c5c/href">https://medium.com/media/cd4e90d889a8d1878ee28bc8c3368c5c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*WWHqx8EbzRqZUHCND5JOuQ.png" /><figcaption>number of observations per class</figcaption></figure><p>In order to solve this issue we extract 500 rows corresponding to class 0 and 500 rows corresponding to class 1. Once concatenated together and shuffled these rows will constitute the data that we will use in the modelling part.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/240626885e1199362edf39e1c25dea0b/href">https://medium.com/media/240626885e1199362edf39e1c25dea0b/href</a></iframe><h4>Data modelling :</h4><p>As we have seen earlier the dataset contains a lot of variables. In order to decrease the complexity of our models and select only the most significant predictor variables we implement a <strong>logit model,</strong> and the variables with a p-value &gt;0.05 are removed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72a9c4433b6493bcf7268fe1af4f8520/href">https://medium.com/media/72a9c4433b6493bcf7268fe1af4f8520/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*OiAo_bhRzQUXfromCOV8zA.png" /><figcaption>summary of the logit (source: author)</figcaption></figure><p>As a result we remove the following variables : currentSmoker, BPMeds, prevalentStroke, totChol, sysBP, BMI, glucose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc7cae625d833b49dd346813f5e0de1a/href">https://medium.com/media/bc7cae625d833b49dd346813f5e0de1a/href</a></iframe><h4>Reminder : interpretation of the p-value in regression analysis :</h4><p>The p-value corresponding to variable <strong>x</strong> in a regression model represents the probability of having zero correlation between <strong>x</strong> and the target variable <strong>y </strong>at the population level. The zero correlation represents the null hypothesis<strong> (H_0).</strong> So if :</p><p>· <strong>p-value &lt;= 0.05 :</strong> we reject H_0 and we can conclude that x is statistically significant and might be a worthwhile addition to our regression model.</p><p>· <strong>p-value&gt;0.05 :</strong> we fail to reject H_0. Then <strong>x</strong> should not be considered in our model.</p><p>Now that our data is ready we are going to make two experiments :</p><p>1- In the first experiment we only use discrete variables as our predictor variables.</p><p>2- In the second experiment we only use continuous variables as our predictor variables.</p><p>The seperation between discrete and continuous variables is justified by the fact that the type of Naive Bayes classifier is dependant on the type of input variables :</p><p>1- Discrete input variables : we build a categorical Naive Bayes.</p><p>2- Continuous input variables : we build a Gaussian Naive Bayes.</p><h4>*discrete input variables :</h4><p>We repeat the same procedure that was executed in problem 1. We plot the accuracy of the models versus the number of training samples. Interestingly we remark that the two models perform roughly the same with a slight superiority for Naive Bayes. This result was also observed in some experiments run by the authors in [1].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*XL3YBS6OprxM0JpOS2tXHg.png" /><figcaption>training accuracy (source: author)</figcaption></figure><h4>*Continuous input variables:</h4><p>In this case the continuous variables are not on the same scale. As a result we will scale our data using <strong>StandardScaler</strong> from sklearn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e4b8236da9120dd024095d5c23f630/href">https://medium.com/media/56e4b8236da9120dd024095d5c23f630/href</a></iframe><p>Once our data is scaled we implement our models. Following the same methodology we plot the curve of the training accuracy score versus the number of training samples. Again we see that the performance of logistic regression and Gaussian naive Bayes are almost the same with a slight superiority for Naive Bayes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*suIKtIvLe_obluMLSvYiAQ.png" /></figure><h3>Conclusion</h3><p>The three experiments we have run confirm few of the conclusions drawn in [1]:</p><ul><li>Naive Bayes tends to achieve its (higher) asymptotic error faster than logistic regression.</li><li>As the size of training sample increases logistic regression usually overtakes Naive Bayes.</li></ul><p>Also as shown in [2] the performance of logistic regression and Naive Bayes classifiers highly depends on the data : in some cases naive Bayes might performs better than logistic regression and in other cases logistic regression overtakes Naive Bayes.</p><h3>References</h3><p>[1]: A. Y. Ng &amp; M. I. Jordan, On Discriminative VS Generative classifiers: A comparison of logistic regression and naive Bayes, 2001</p><p>[2]: Tsangaratos, Paraskevas and Ioanna Ilia. “Comparison of a logistic regression and Naïve Bayes classifier in landslide susceptibility assessments: The influence of models complexity and training dataset size.” <em>Catena</em> 145 (2016): 164–179.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8de47e7b390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient descent from scratch: An overview of GD variants]]></title>
            <link>https://medium.com/@sami.benbrahim/gradient-descent-from-scratch-an-overview-of-gd-variants-f558da269a5f?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/f558da269a5f</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[multiple-linearregression]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 21:26:52 GMT</pubDate>
            <atom:updated>2022-11-21T21:26:52.782Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nD2HiDdcsdrhuA0G" /><figcaption>Photo by <a href="https://unsplash.com/@claudiotesta?utm_source=medium&amp;utm_medium=referral">Claudio Testa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Gradient descent (GD) is the most famous optimization technique used to train machine learning (ML) models. Any ML practitioner has certainly come across GD while making his first steps in ML. In this article we will discover the three variants of GD and we will compare their results in terms of accuracy, computation cost and loss function variability. Are you ready ? Let’s go familia !</em></p><h3>Data</h3><p>We use this <a href="https://www.kaggle.com/datasets/ashydv/advertising-dataset">dataset</a> which contains information about advertising and sales. An overview of the dataset is shown in the figure below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42c0b60bf832388ef77889716de6bb13/href">https://medium.com/media/42c0b60bf832388ef77889716de6bb13/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*9k7yaljYDqePMsBMnny1hQ.png" /><figcaption>an overview of the dataset, source: author</figcaption></figure><p>In this article we will apply gradient descent in order to implement a <strong><em>multiple linear regression</em></strong> model from scratch. The model takes as <strong>input</strong> the advertising variables (tv, radio, newspaper) and <strong>output</strong>s the sales.</p><p>First it is quite remarkable that the features are not on the same scale. Thus it is necessary to scale our data in order to help our gradient descent algorithm converge faster. Therefore we use <strong><em>MinMax scaler</em></strong> defined below. This scaler maintains all the values in the interval [0,1].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd9730f3b9a2901c1913c64a6fc81fa4/href">https://medium.com/media/fd9730f3b9a2901c1913c64a6fc81fa4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*4cMCGp07JZ_QFLD04UbVvg.png" /><figcaption>Min-Max scaler, source: <a href="https://stackoverflow.com/questions/62178888/can-someone-explain-to-me-how-minmaxscaler-works">python — Can someone explain to me how MinMaxScaler() works? — Stack Overflow</a></figcaption></figure><p>There exist three variants of gradient descent : <strong>batch gradient descent (BGD), mini-batch gradient descent (MBGD) and stochastic gradient descent (SGD).</strong></p><h3>An overview of the three variants of GD</h3><p>In machine learning we usually use the following terms while describing the training process:</p><p><strong><em>1- Iteration : </em></strong>during a single iteration we compute the cost function and we update the weights of the model.</p><p><strong><em>2- Epoch :</em></strong> once the model has been trained on <strong>ALL the training examples</strong> we say that an epoch is finished.</p><h4>The three variants:</h4><p><strong><em>1- BGD : </em></strong>in BGD all the training examples are used to train the model during a single iteration.</p><p>Thus in batch gradient descent <strong>1 epoch = 1 iteration.</strong></p><p><strong><em>2-MBGD :</em></strong> in MBGD we divide the training dataset into <strong>M mini-batches</strong> of equal size. Then we train our model <strong>M times per epoch </strong>using a different mini-batch in every iteration.</p><p>In MBGD<strong> 1 epoch = M iterations</strong>, <strong>M &lt; N, where N is the number of training examples.</strong></p><p><strong><em>3-SGD :</em></strong> in SGD we first shuffle the training data. Then we use every single observation separately to train our model.</p><p>in SGD <strong>1 epoch = N iterations</strong></p><h4>Steps of GD:</h4><p>Suppose we start a new epoch. The training over this epoch is done through these two steps :</p><p><strong><em>1- computation of the cost function :</em></strong> in our example we chose to use Mean squared error as our cost function. The advantage of this function is that it is <strong>differentiable</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*jivskGq8c9vtlljE-aZIGQ.png" /><figcaption>computation of the loss function, souce: <a href="https://mccormickml.com/2014/03/04/gradient-descent-derivation/">Gradient Descent Derivation · Chris McCormick (mccormickml.com)</a></figcaption></figure><p>The value of <strong>m </strong>(in the formula above)<strong> </strong>depends on the GD variant that we are implementing:</p><ul><li>if <strong>variant = BGD:</strong> then m = size of the training data</li><li>if <strong>variant = MBGD: </strong>then m= mini-batch size and the loss function is computed: <strong>int(N/m) times per epoch</strong> if N is a multiple of m, <strong>int(N/m) + 1 / epoch</strong> if not. (int(x) = integer part of x)</li><li>if <strong>variant = SGD: </strong>then m=1 and the loss function is computed N times / epoch.</li></ul><p><strong><em>2- Weights’ update :</em></strong> in every iteration we update the weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*VQVw3cttElI1rTsuvwUgyw.png" /><figcaption>weight’s update, source: <a href="https://www.geeksforgeeks.org/difference-between-batch-gradient-descent-and-stochastic-gradient-descent/">Difference between Batch Gradient Descent and Stochastic Gradient Descent — GeeksforGeeks</a></figcaption></figure><p>where: α is the learning rate, i.e. the step size, as shown in the figure below. The step size tells how far the weight has to move against the gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*b4bbJv5QyUvZEiCESHizAQ.png" /><figcaption>souce: <a href="https://towardsdatascience.com/batch-mini-batch-stochastic-gradient-descent-7a62ecba642a">Batch, Mini Batch &amp; Stochastic Gradient Descent | by Sushant Patrikar | Towards Data Science</a></figcaption></figure><p>The algorithm ensures that the weight is moving against the gradient:</p><ul><li>if the loss function is increasing the weight decreases.</li><li>if the loss function is decreasing the weight increases.</li></ul><p><strong>And we repeat this update process until a stop condition (either convergence or achieving the maximum number of iterations)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*gkOEH1BDJu5igitWxTs0KA.png" /><figcaption>souce: <a href="https://medium.com/analytics-vidhya/vectorized-implementation-of-gradient-descent-in-linear-regression-12a10ea37210">Vectorized Implementation of Gradient Descent in Linear Regression | by Vishesh Khandelwal | Analytics Vidhya | Medium</a></figcaption></figure><h3>Application</h3><p>Now we apply the three variants of gradient descent in order to build the linear regression model for our advertising problem. Just before starting the learning process we initialize:</p><ul><li>the <strong><em>model parameters</em></strong>: the weights.</li><li>the <strong><em>hyperparameters </em></strong>: number of epochs, learning rate α, error tolerance threshold ε (if the loss function achieves a value below ε we stop the gradient descent).</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/376633b8219d18be1e73ce92f93b9063/href">https://medium.com/media/376633b8219d18be1e73ce92f93b9063/href</a></iframe><p>Then we implement gradient descent as described earlier using the three methods: BGD, MBGD, SGD.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/686c287dd679c2ea47322c10b1d3251c/href">https://medium.com/media/686c287dd679c2ea47322c10b1d3251c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1626cbbf43cb631b1e688e852b80a8d/href">https://medium.com/media/f1626cbbf43cb631b1e688e852b80a8d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b83914d6db439604051edb3f45c1a500/href">https://medium.com/media/b83914d6db439604051edb3f45c1a500/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2638cf3e54b5add269ed89a0a7028037/href">https://medium.com/media/2638cf3e54b5add269ed89a0a7028037/href</a></iframe><p>The loss functions of the different variants are visualized in the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Ox0UyhTcFyESTfydKdWcbw.png" /><figcaption>loss function of every variant, source: author</figcaption></figure><h4>Interpretation:</h4><p>Comparing the results of the three methods we remark that the <strong>variation of SGD’s loss function</strong> is very high relatively to MBGD and BGD. The loss function of BGD is the smoothest one. The high variability of SGD loss function is explained by the randomness of the training examples, contrary to MBGD and BGD where the computation of the loss function is done by averaging over a set of training examples.</p><p>Also by computing the <strong>CPU time</strong> for each method we noticed that the highest CPU time is for BGD (0.68 seconds) followed by MBGD (0.08 s) then SGD (0.008 s). This is also intuitive because for BGD in every iteration to compute the loss function we use all the training data, whereas in MBGD we only use a subset of the data and in SGD only a single observation is used for the computation of the loss function.</p><p>Finally when tested on a seperate test dataset the different models provide the following RMSE (root mean squared error) values :</p><p>· BGD : 9.63</p><p>· SGD : 6.85</p><p>· MBGD : 6.79</p><h4>Note :</h4><p><em>The obtained results (curves &amp; CPU time) may differ from one experience to another because of the random initialization of the weights.</em></p><h3>Conclusion</h3><p>If we want to make a <strong>trade-off between CPU time and accuracy</strong> MBGD is the best choice. That’s why MBGD is considered as the most used GD algorithm in deep learning for example [1].</p><h3>References</h3><p>[1]: <a href="https://machinelearningmastery.com/gentle-introduction-mini-batch-gradient-descent-configure-batch-size/">A Gentle Introduction to Mini-Batch Gradient Descent and How to Configure Batch Size — MachineLearningMastery.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f558da269a5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Paris real estate data analysis (part II)]]></title>
            <link>https://medium.com/@sami.benbrahim/paris-real-estate-data-analysis-part-ii-c95eda1861c1?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/c95eda1861c1</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 18:56:36 GMT</pubDate>
            <atom:updated>2022-10-31T19:25:32.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1cKJH--WlMXRndxy" /><figcaption>Photo by <a href="https://unsplash.com/@uncertainthink?utm_source=medium&amp;utm_medium=referral">J Shim</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In our previous story we explored a real estate dataset relative to Paris, 10th borough (10e arrondissement). We went through some basic steps including data visualization, cleaning and feature selection. For a better understanding of this story please consider checking out <a href="https://medium.com/@sami.benbrahim/analysis-of-paris-real-estate-data-part-i-9361e609ab26">Part I</a>.</p><h3>Feature Engineering: Clustering</h3><p>Undoubtedly the geographical position of a building is a key factor of its value in the market. Thus we decide to cluster the buildings by their geographical position and price.</p><p>When it comes to <a href="https://www.geeksforgeeks.org/difference-between-hierarchical-and-non-hierarchical-clustering/#:~:text=Non%20Hierarchical%20Clustering%3A%20Non%20Hierarchical,or%20minimize%20some%20evaluation%20criteria.">non-hierarchical clustering</a>, a key step is to choose the right number of clusters. The choice of number of clusters can be done using various methods such as the <a href="https://en.wikipedia.org/wiki/Elbow_method_(clustering)#:~:text=In%20cluster%20analysis%2C%20the%20elbow,number%20of%20clusters%20to%20use.">elbow method</a>.</p><p>In our case study we choose to implement K-Means clustering algorithm and we use the elbow method to determine the optimal number of clusters by following these steps:</p><p>1- We cluster the data points with a number of clusters k varying from 1 to 10.</p><p>2- We plot the curve that represents <em>the within-cluster sum of squares: </em>the squared distance of the data points to their cluster’s centroid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61374bf5e0c94f6d39e4e0cc48fe6d1d/href">https://medium.com/media/61374bf5e0c94f6d39e4e0cc48fe6d1d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*26qcPQYQcDQpSFzp1b9YLw.png" /><figcaption>within-cluster sum of squares in function of K</figcaption></figure><p>As shown in the figure above starting from <strong>k=4 </strong>there is no significant variation of the within-cluster sum of squares. Thus we choose <strong>k=4</strong> as our number of clusters. k=4 is called the <strong>elbow</strong> (remember the human elbow shape !).</p><p>So we perform our clustering and we plot the resulting repartition of the clusters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34312f439a9722da9dd1a0c5c0ff4f07/href">https://medium.com/media/34312f439a9722da9dd1a0c5c0ff4f07/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*zwGVe2vwUIvTS8qLVVK7_A.png" /><figcaption>visualization of clusters</figcaption></figure><p>We plot the boxplot of real estate price values for each cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/462b7d9688d602545c02b3b4e6ba9592/href">https://medium.com/media/462b7d9688d602545c02b3b4e6ba9592/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*vI4A5IXM9q1giEHTkSkTLA.png" /><figcaption>Boxplot of real estate price values of each cluster</figcaption></figure><p>The clusters 0, 1, 2 are close to each other in terms of buildings’ price but differ with respect to buildings’ location.</p><p>Cluster 3 clearly represents a group of luxurious buildings or strategic ‘commercial, industrial or assimilated’ buildings. The buildings relative to cluster 3 are basically located in the same area as cluster 1 buildings.</p><h3>Correlation analysis</h3><p>In order to identify the most important features in predicting real estate price we compute three different correlation metrics.</p><h4>Pearson correlation coefficient r:</h4><p>is the measure of linear correlation between two sets of data. <strong>r ∈ [-1,1] </strong>and it is calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*9vbQ5VSx8vl6r9Vt.JPG" /><figcaption>source: <a href="https://www.analyticsvidhya.com/blog/2021/01/beginners-guide-to-pearsons-correlation-coefficient/">Pearson’s Correlation Coefficient — A Beginners Guide (analyticsvidhya.com)</a></figcaption></figure><ul><li><strong>r(X,Y)=1 :</strong> X = a.Y, where a&gt;0.</li><li><strong>r(X,Y)=-1 :</strong> X = a.Y, where a&lt;0.</li><li><strong>r(X,Y)=0:</strong> X and Y are not linearly correlated (but <strong>NOT independent!!</strong>).</li></ul><p>The Pearson correlation matrix of our data is shown in the figure below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9338b020c868d859495a1a733cb54ebc/href">https://medium.com/media/9338b020c868d859495a1a733cb54ebc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*X40hFvurzIkU5REWCqm-fQ.png" /><figcaption>Pearson correlation matrix</figcaption></figure><p>A relatively high correlation is observed between valeur_fonciere (price) and both features « cluster » &amp; « surface_reelle_bati » (area).</p><p>Here we emphasize the importance of <strong>feature engineering</strong>: “cluster” is the 2nd most correlated feature with our target “price”.</p><h4>Spearman correlation coefficient ρ:</h4><p>Spearman correlation coefficient is a non-parametric measure of rank-correlation between two variables. It assesses how well a relationship between two variables can be described with a monotonic function.</p><p><strong>ρ ∈ [-1,1] </strong>and it is calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*Pp-4FTiy9lXFCsOd.png" /><figcaption>source: <a href="https://www.postnetwork.co/correlation/">Correlation in Statistics — Hub and Network of Posts (postnetwork.co)</a></figcaption></figure><p>The example shown below facilitates the understanding of the previous formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*gmUHtCiNlKjqFF7M.png" /><figcaption>source: <a href="https://stats.stackexchange.com/questions/449497/spearmans-rank-correlation-coefficient-calculation">Spearman’s rank correlation coefficient calculation — Cross Validated (stackexchange.com)</a></figcaption></figure><p>Additionally we underline that Pearson correlation and Spearman correlation are different, e.g. a high Pearson correlation does not induce a high Spearman correlation.</p><p>After computing Spearman’s correlation matrix we remarked that “area” and “number of rooms” are the most correlated variables with the target “price”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d30ccd5d1b2fa24cbfcc46e91c7566a6/href">https://medium.com/media/d30ccd5d1b2fa24cbfcc46e91c7566a6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxcS7cvcsNDVV8eRjZUcwA.png" /><figcaption>Spearman’s correlation matrix</figcaption></figure><h4>Mutual information</h4><p>Mutual Information between two random variables X and Y, denoted by <strong>I(X,Y)</strong> is a measure of the quantity of uncertainty explained from X given Y (or the inverse). It is calculated as follows :</p><h3><strong>I(X,Y)=H(X)-H(X|Y)</strong></h3><p>where:</p><ul><li><strong>H(X) </strong>represents the <strong>entropy</strong> of X (the measure of uncertainty of X).</li><li><strong>H(X|Y) </strong>represents the entropy of X given Y, i.e. the amount of uncertainty of X that Y can not explain.</li></ul><p><strong><em>Properties of mutual information:</em></strong></p><ul><li>I(X,Y)&gt;0</li><li>I(X,Y)=I(Y,X) : <strong>symetric </strong>measure.</li><li>I(X,Y)=0 : means that X and Y are<strong> independent.</strong></li></ul><p>The computation of the mutual information between real estate price variable and the predictor variables proves that real estate price is mostly explained by the following features : <strong>area, number of rooms and cluster.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87769bccefc7d37f253d32cc38b47411/href">https://medium.com/media/87769bccefc7d37f253d32cc38b47411/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*AkeZCG2Qp8CGDbWulVyyAw.png" /><figcaption>Mutual information between the price and the different predictor variables</figcaption></figure><p><strong><em>Remark:</em></strong></p><p><em>Mutual Information (MI) is a univariate metric, i.e. a variable can have a low MI but at the same time it can have an important weight in predicting the target when joined with other features.</em></p><h3>Summary</h3><p>In both parts of real estate data analysis series we have seen an example of data analysis workflow. Specifically in this article we showed that the location, the area and the number of rooms are the most important features in terms of explanation of uncertainty (via Mutual information) and correlation (via Spearman and Pearson) with our target “building’s price”.</p><p>Dear Reader, do not hesitate to correct me in some point or suggest any improvement/idea. Cheers :D ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c95eda1861c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of Paris real-estate data (Part I)]]></title>
            <link>https://medium.com/@sami.benbrahim/analysis-of-paris-real-estate-data-part-i-9361e609ab26?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/9361e609ab26</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[real-estate]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 20:19:22 GMT</pubDate>
            <atom:updated>2022-10-26T20:19:22.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wlFF6UlOiIWD1qzg" /><figcaption>Photo by <a href="https://unsplash.com/@mihail_ribkin?utm_source=medium&amp;utm_medium=referral">Mihail Ribkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Accurate real estate price prediction is important for all the parties included in the real estate sector such as property owners, investors, banks,… In this article we will work on real-world data extracted from <a href="https://app.dvf.etalab.gouv.fr/">DVF</a>. The data is relative to Paris, 10th borough (« 10e arrondissement). We will analyse the data in order to draw insights that will facilitate real-estate price prediction.</p><h3>Data overview:</h3><p>The data contain different characteristics of the buildings such as the area, number of rooms, latitude, longitude,… It is composed of 16601 rows (observations) and 41 columns (variables).</p><p><em>Note:</em></p><p><em>In this article we will refer to the different columns by their original french names.</em></p><p>In order to reduce the problem’s complexity we only keep the most relevant variables with <strong>low number of missing values</strong>:</p><ul><li><strong>‘lot_surface_carrez’ (5 columns)</strong>: ‘surface carrez’ of a building (measured in m²) is calculated as follows:</li></ul><h4>surface carrez= total floor area — area occupied by walls, partitions, frames&amp; stairs.</h4><p>Also every part in a building with <strong>height less than 1.80 m</strong> is not considered in the previous formula [1].</p><ul><li><strong>‘Code_type_local’ :</strong> a numeric categorical variable that indicates the type of a building.</li><li><strong>‘Type local’ :</strong> a string variable that indicates the type of a building.</li><li><strong>‘surface_reelle_bati’ (m²) : </strong>area of the building.</li><li><strong>‘Nombre pieces principales’ :</strong> number of rooms.</li><li><strong>longitude</strong></li><li><strong>latitude</strong></li></ul><p><em>Remark about ‘lot_surface_carrez’:</em></p><p>‘lot_surface_carrez’ columns contain a considerable number of missing values (<strong>NaN</strong>) for a simple reason. Let me explain it through the example described in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*JM9vw0rENipPO6wcWUKIKg.png" /><figcaption><a href="https://www1.nyc.gov/site/planning/zoning/glossary.page">https://www1.nyc.gov/site/planning/zoning/glossary.page</a></figcaption></figure><ul><li>if a building is situated on lot 1 then we have <strong>lot1_surface_carrez=a &gt; 0 <em>and</em> lot2_surface_carrez=lot3_surface_carrez= lot4_surface_carrez=NaN.</strong></li><li>If a property consists of two adjacent buildings situated on lots 1 &amp; 2, then we have <strong>lot1_surface_carrez=a&gt;0 &amp; lot2_surface_carrez=b&gt;0 &amp; lot3_surface_carrez= lot4_surface_carrez=NaN.</strong></li><li>If a building is not situated on any of the four lots then <strong>lot1_surface_carrez=lot2_surface_carrez=lot3_surface_carrez= lot4_surface_carrez=NaN.</strong></li></ul><p>And as we are interested in the total lot area, then for every property we <strong>add up the five lot area columns</strong> and we assign the results to a new column <em>“total_lots_surface_carrez”.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e1830102763d4877dff278c139e570f/href">https://medium.com/media/1e1830102763d4877dff278c139e570f/href</a></iframe><p>By observing our dataset we notice the presence of missing values in some columns as shown in the figure below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/402f9f4ff39a3f5e31f9dde2fb431ced/href">https://medium.com/media/402f9f4ff39a3f5e31f9dde2fb431ced/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*4-GcBZeuuHQ9X7OOaHBVFA.png" /><figcaption>number of missing values per column</figcaption></figure><p>For simplicity we just delete the rows with missing values to obtain a dataset with 12836 rows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b14ec0967df4a0904c4ddd3eb3e69e16/href">https://medium.com/media/b14ec0967df4a0904c4ddd3eb3e69e16/href</a></iframe><h3>Remove the redundant features</h3><p>While engineering our features we should always be aware of the importance of removing <a href="https://www.geeksforgeeks.org/redundancy-and-correlation-in-data-mining/">redundant features</a> because they are just a repetition of other attributes that already exist in the data.</p><p>While examining our dataset’s attributes we notice the presence of two attributes related to the buildings’ area and two other attributes related to the buildings’ type. In the following paragraph we will analyse these features in order to verify whether they are redundant or not.</p><h4>Comparison between “<em>total_lots_surface_carrez</em>” and “<em>surface_reelle_bati</em>”:</h4><p>We compare the two features <em>‘total_lots_surface_carrez’ </em>and <em>‘surface_reelle_bati’ </em>because both of them represent area features.</p><p>By plotting the statistics of both variables we notice a significant difference in terms of <strong>mean, standard deviation and quartiles.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6fcdba7b699e85054b663d65f7390b2/href">https://medium.com/media/a6fcdba7b699e85054b663d65f7390b2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*zkZHxiM9ZIxdbsiWW15SDA.png" /><figcaption>descriptive statistics of ‘total_lots_surface_carrez’</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*WQc3hT0U2Sc_CCu2brxiJg.png" /><figcaption>descriptive statistics of ‘surface_reelle_bati’</figcaption></figure><p>For <em>‘total_lots_surface_carrez’</em> we remark that the first 25% percentiles are <strong>all null</strong>. In fact these zeros may be caused by:</p><ul><li>the buildings corresponding to the first 25% percentiles are not built on any of the lots 1…5.</li><li><strong>Error:</strong> as we know, data is always prone to errors.</li><li>Unavailability of the exact lot area value.</li></ul><p>To verify the redundancy of <em>‘total_lots_surface_carrez’ and “</em>surface_reelle_bati<em>” we delete the rows containing </em><strong><em>null values of ‘total_lots_surface_carrez’. </em></strong>Then w<em>e compare the descriptive statistics of </em>‘total_lots_surface_carrez’<strong><em> </em></strong><em>to the descriptive statistics of “</em>surface_reelle_bati<em>”.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/703205876686454095995e846df420b2/href">https://medium.com/media/703205876686454095995e846df420b2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*nTkjjMDPDttTunK8jJjrfA.png" /><figcaption>new descriptive statistics of “total_lots_surface_carrez”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*BNgMC5bUivQMm90pt-iPcA.png" /><figcaption>new descriptive statistics of “surface_reelle_bati”</figcaption></figure><p>Now we find that both variables have almost similar statistics and their histograms are overlapping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec8be0cae76d3e836bb09927d4082ef2/href">https://medium.com/media/ec8be0cae76d3e836bb09927d4082ef2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*AuHX77dVlVi_cg7XbcGa6A.png" /><figcaption>histograms</figcaption></figure><p>As a result we delete the rows corresponding to <strong><em>total_lots_surface_carrez=0</em>.</strong> Now the resulting dataset has 7710 rows. And as we saw that “surface_reelle_bati” and “total_lots_surface_carrez” are redundant features, we decide to <strong>remove « total_lots_surface_carrez » and keep the variable « surface_reelle_bati ».</strong></p><h4>Comparison between “code_type_local” and “type_local”:</h4><ul><li><strong>Code_type_local :</strong> the unique values of this column are the following : ‘2’, ’4’, ’1’, 2, 4. Obviously ‘2’ &amp; ‘4’ refer to 2 &amp; 4 respectively. Hence we convert the column’s type to integer and we obtain three unique classes of properties: <strong>1,2,4.</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e545dc7ff26451d7aa190161de56941/href">https://medium.com/media/9e545dc7ff26451d7aa190161de56941/href</a></iframe><ul><li><strong>Type_local :</strong> similarly to ‘code_type_local’ this column contains three uniques classes :</li></ul><p>o ‘<em>Appartement’ :</em> apartment.</p><p>o ‘<em>Maison’ : house.</em></p><p>o <em>‘Local industriel. commercial ou assimilé’</em>: industrial, commercial or assimilated building.</p><p>With three simple code lines we verify the correspondance between code_type_local and type_local :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04350a343c63ca0af4f878d6ac91f4a5/href">https://medium.com/media/04350a343c63ca0af4f878d6ac91f4a5/href</a></iframe><p>o ‘<em>Appartement’ :</em> corresponds to class 2</p><p>o ‘<em>Maison’ : </em>class 1</p><p>o <em>‘Local industriel. commercial ou assimilé’</em>: class 4</p><p>Once again to prevent data redundancy we remove <em>‘type_local’</em> column and we keep <em>‘code_type_local’ </em>as a categorical variable that will be used for our prediction of real estate price.</p><p>Interestingly we notice that a single observation corresponds to class 1. Thus in order to prevent the issue of <a href="https://machinelearningmastery.com/what-is-imbalanced-classification/">class imbalance</a> we remove this observation. Therefore two ‘code_type _local’ classes are now available, as shown in the bar plot below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/970dbd8a526b12fa32ff6e75f53ac0dd/href">https://medium.com/media/970dbd8a526b12fa32ff6e75f53ac0dd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*nSCZP2trsn-fqx06IAr87Q.png" /><figcaption>occurence of each building class</figcaption></figure><p>Apartments (class 2) are 9 times more present in the dataset than commercial, industrial and assimilated buildings (class 4) : we have a 1:9 class imbalance problem which can be classified as a <strong>slight class imbalanc</strong>e problem according to [2]. We note that a slight class imbalance problem is often not a concern [2].</p><h3>Data cleaning</h3><p>We continue exploring the remaining features.</p><ul><li><strong>Surface_reelle_bati : </strong>The descriptive statistics are shown below.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea8b9a8d1d3b51b532c69e37165f2b7/href">https://medium.com/media/bea8b9a8d1d3b51b532c69e37165f2b7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*UNqtQ5ZZmj0nH92CD5KWng.png" /><figcaption>descriptive statistics of ‘surface_reelle_bati’</figcaption></figure><p>We remark that the minimum building area is equal to 2m² which seems to be an <strong>outlier</strong>. For verification we generate the descriptive statistics of the data sample “S1”: S1 contains all the values below or equal to 25m².</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71d7fba16cb28b61cc4d22f5da3b66e3/href">https://medium.com/media/71d7fba16cb28b61cc4d22f5da3b66e3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*tcpPsDzTHTgzykJAMckXow.png" /><figcaption>descriptive statistics of S1</figcaption></figure><p>When we select the buildings with an area comprised between 2m² and 13m² we obtain the following results :</p><p>o The number of rooms in these buildings is either 0,1 or 2.</p><p>o The buildings are from two classes: 2 (apartment) and 4 (industrial, commercial and assimilated building).</p><p><strong>As a result we can conclude that the buildings with an area between 2 and 13 may correspond to garages, rooms in student residences, …</strong></p><p>Then we remark that only 23% of the sample S1 values are below 9m² and the remaining 77% are between 9 and 25. Thus to reduce the effect of extreme values (outliers) we use a technique called « <a href="https://en.wikipedia.org/wiki/Winsorizing">winsorization/clipping </a>».</p><p>We apply the winsorization technique by replacing all <em>‘surface_reelle_bati’</em> values which are below 9m² by 9m². Once done we obtain the following histogram.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6dd3fe1da67c6d59ff44418c34661c3/href">https://medium.com/media/c6dd3fe1da67c6d59ff44418c34661c3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*jhnhfjSHUGa67k3A8bgfPw.png" /><figcaption>‘surface_reelle_bati’ distribution after cleaning the left part</figcaption></figure><p>Visually we remark that <em>‘surface_reelle_bati’ </em>distribution is highly spread on the right tail due to outliers. Thus we have also to winsorize the upper tail of the data.</p><p>We notice that only 30 observations out of 7709 have an area above 300m² and all of these correspond to class 4 buildings (industrial, commercial and assimilated) with 0 number of rooms. Thus to reduce the effect of these outliers we replace all the values above 300m² by 300m². Finally we obtain the following histogram.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8c27b634bf63f5ceaecee1a14f6f1ea/href">https://medium.com/media/f8c27b634bf63f5ceaecee1a14f6f1ea/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*hGxLzddv3yy68nXzLzzUaA.png" /><figcaption>‘surface_reelle_bati’ after winsorizing the right tail</figcaption></figure><ul><li><strong>Number of rooms : </strong>The following barplot represents the occurrence of each number of rooms’ class in descending order.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9e502b5d46a7d82a7a69a95da7e86ef/href">https://medium.com/media/e9e502b5d46a7d82a7a69a95da7e86ef/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*xn3HzdSQzaxtour5aAeD0w.png" /></figure><p>Again, to avoid the problem of class imbalance we remove the classes with significantly low number of observations, i.e. classes from 6 to 10.</p><p>After that we group the buildings by their <strong>number of rooms</strong> and we compute the median and mean of buildings’ area for each group. Both computations are visualized in the figures below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/804e96f04440e6f2d2c0ff414325414f/href">https://medium.com/media/804e96f04440e6f2d2c0ff414325414f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*TYzTLggWmL-A6ILDsv3G-w.png" /><figcaption>area median value for each group</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7de4c54e3644d77fcd37920b3fb2d346/href">https://medium.com/media/7de4c54e3644d77fcd37920b3fb2d346/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*vhAUBybAMO8LjRyVP93vcg.png" /><figcaption>area mean value for each group</figcaption></figure><p>Considering classes from 1 to 5 we remark there is <strong>a positive correlation between number of rooms and area</strong>. Class 0 buildings have relatively high area values because <strong>all class 0 buildings are either assimilated, industrial or commercial buildings</strong>. In fact for buildings with <em>area&gt;50m²</em> and <em>number of rooms</em>=0 we find that <strong>425 out of 427</strong> buildings are classified as commercial, industrial or assimilated buildings.</p><ul><li><strong>‘Valeur fonciere’ : </strong>the distribution of buildings’ price is highly spread due to outliers.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd3e62a7688042d389b5d35c87f594d/href">https://medium.com/media/1cd3e62a7688042d389b5d35c87f594d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*aChhDdI_0JSOvGWmhpyWcA.png" /><figcaption>distribution of buildings’ price (valeur_fonciere)</figcaption></figure><p>So similarly to ‘surface_reelle_bati’ we winsorize ‘valeur_fonciere’ by setting 10000 and 0.3*10⁷ as minimum and maximum threshold values respectively. The resulting distribution is shown in the figure below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6f909d58dcfa17cf1ce1cb9a058809b/href">https://medium.com/media/d6f909d58dcfa17cf1ce1cb9a058809b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*at6XHcjFfg6yHzc6GkqWYg.png" /></figure><p><em>Remark :</em></p><h4>As far as we know when applying winsorization there is no exact rule on how to choose the threshold percentile. It is usually chosen by trial and error.</h4><ul><li><strong>‘Date_mutation’ :</strong> this feature represents the purchase date of a property. The available purchases in the dataset date from 2017 to 2021. The first thing to do is to transform this column from ‘object’ dtype to ‘datetime’ dtype using <em>‘to_datetime’</em> function from pandas.</li></ul><p>As we can see in the barplot below the dataset is balanced in terms of year of purchase, i.e. the number of properties purchased every year is almost stable. And this is important in order to see whether there is a correlation between time and real estate price.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13db018b466360d35f4d43bbb2472f34/href">https://medium.com/media/13db018b466360d35f4d43bbb2472f34/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*JkDGdKSpq3fx2RDf-NiWdg.png" /><figcaption>number of buildings’ purchases per year</figcaption></figure><h3>Conclusion</h3><p>In this article we performed data exploration and cleaning of a subset of Paris real-estate data. In the next story we will apply feature engineering and correlation analysis in order to decide which variables we will use to predict the real estate price.</p><p>Stay tuned ;) ❤ And do not hesitate to ask a question or criticize my work.</p><h3>References:</h3><p>[1]: <a href="https://www.journaldunet.fr/patrimoine/guide-de-l-immobilier/1202245-loi-carrez-qu-est-ce-que-c-est-et-comment-la-calculer/">Loi Carrez : qu’est-ce que c’est et comment la calculer ? (journaldunet.fr)</a></p><p>[2]: <a href="https://machinelearningmastery.com/what-is-imbalanced-classification/">A Gentle Introduction to Imbalanced Classification (machinelearningmastery.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9361e609ab26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Game, Set and Math”, Naive Bayes]]></title>
            <link>https://medium.com/@sami.benbrahim/game-set-and-math-naive-bayes-28a16b35538e?source=rss-45a2159770be------2</link>
            <guid isPermaLink="false">https://medium.com/p/28a16b35538e</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tennis]]></category>
            <category><![CDATA[naive-bayes]]></category>
            <dc:creator><![CDATA[Sami BEN BRAHIM]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 18:07:14 GMT</pubDate>
            <atom:updated>2022-10-06T18:13:42.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ko9v_ISkdMZSxACp" /><figcaption>Photo by <a href="https://unsplash.com/@zombience?utm_source=medium&amp;utm_medium=referral">Ryan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Exploring the mathematics behind the magical Naive Bayes and applying it on a small tennis dataset.</h4><h3>1-Naive Bayes theory</h3><p>Naive Bayes classifier is a supervised probabilistic learning algorithm that is based on Bayes theorem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*fwtTuZThiyX-5y9AX22HYg.png" /></figure><p>where A and B are random events.</p><p>“Naive” term comes from the naive assumption: Given the target variable the predictive variables are independent from each other , i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D7FKrHxpMtu-5Nuk.png" /></figure><p>where:</p><ul><li>“n” is the number of features.</li><li>“y” is the class variable (target variable).</li><li>“x_1,…,x_n” are the features.</li></ul><p>Using Naive Bayes theorem we have the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*whCvBswjegKGS_eE.png" /></figure><p>where:</p><ul><li>P(y|x_1,…,x_n) is the class posterior probability.</li><li>P(x_1,…,x_n|y) is the likelihood.</li><li>P(y) is the class probability (the frequency of class y)</li><li>P(x_1,…,x_n) is the predictor’s prior probability</li></ul><p>Using the conditional Naive Independence relationship we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qyYmrwpoi00NN7ko.png" /></figure><p>where:</p><ul><li>P(x_i|y) follows a certain distribution depending on the Naive Bayes classifier type, e.g. if we deal with a Gaussian Naive Bayes classifier then:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S_EMvlOitYXyUmjH.png" /></figure><p>Once P(y) and P(x_i|y) are estimated we can estimate the class variable y using Maximum A Posteriori :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Wx656tPnqY4r6b3u.png" /></figure><h4>Pros and cons of Naive Bayes:</h4><ul><li><strong>(+):</strong> Compared to sophisticated supervised learning algorithms Naive Bayes is fast thanks to the conditional independence assumption of the data features. The latter condition enables a one-dimensional estimation of every parameter’s distribution, which alleviates potential problems related to the “curse of dimensionality”.</li><li><strong>(-):</strong> The conditional independence assumption rarely holds in real life because features are usually correlated to some degree with each other. But this problem can be overcome using for instance <strong>Augmented Naive Bayes </strong>structure [2]. Additionally it was proven in [2] that despite strong dependencies between the predictive variables Naive Bayes can still show high classification accuracy under the condition that these dependencies cancel out each other.</li></ul><h3>2- A simple implementation of Naive Bayes</h3><p>I wish to play a tennis game with my beloved player Roger Federer in an outdoor tennis court, but would the weather allow us to play?</p><p>To answer the question I decided to implement a Naive Bayes classification algorithm that tells us whether we can play or not. Therefore for our implementation we use a small <a href="https://www.kaggle.com/datasets/pranavpandey2511/tennis-weather">dataset</a> found in Kaggle.</p><h4>Data exploration</h4><p>We start importing the required libraries:</p><ul><li><strong>pandas:</strong> to read and process the dataset.</li><li><strong>numpy: </strong>to apply mathematical operations on arrays.</li><li><strong>sklearn:</strong> to process our data, train our Naive Bayes classifier and test its performance.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b36e2c28a4543a97fe1bc7ead051e37/href">https://medium.com/media/8b36e2c28a4543a97fe1bc7ead051e37/href</a></iframe><p>We read our dataset using pandas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f5533dcef88f5f4d6f5dc4af15e0e2/href">https://medium.com/media/a7f5533dcef88f5f4d6f5dc4af15e0e2/href</a></iframe><p>The dataset first rows appear as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*U3hvFYfUfox8tnetWMa_Iw.png" /></figure><p>The dataset contains 14 rows and 5 categorical columns. Precisely we have 4 predictor variables:</p><ul><li><strong>outlook:</strong> describes the weather state. It has 3 different categories: rainy, sunny, overcast.</li><li><strong>temp: </strong>describes the temperature state: hot, mild or cool.</li><li><strong>humidity: </strong>tells us whether the humidity is high or normal.</li><li><strong>windy: </strong>a Boolean variable which tells us if the weather is windy or not.</li></ul><p>And our <strong>target variable</strong> is “<strong>play</strong>”: a Boolean variable which represents the decision to take, whether to play tennis (“yes”) or stay at home (“no”).</p><h4>The dataset is very small!</h4><p>A question may be asked: “Can we obtain an efficient classifier with only 14 data samples?”</p><p>Interestingly a major advantage of Naive Bayes is its ability to converge quickly to its asymptotic error [3], i.e. it can perform well with few observations.</p><h4>One-hot encoding</h4><p>We have seen that all our dataset columns are text variables. And as Naive Bayes classifier cannot work on text, our data columns need to be encoded. <strong>One-hot encoding</strong> is among the most popular methods of encoding categorical variables.</p><p>A one-hot encoder identifies the unique categories of a column, then builds a binary column for each category, as shown in the example below.</p><p><em>“outlook”</em> column contains 3 unique categories: rainy, sunny, overcast, as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*yvE35ID4uCOKOZVzgl27uQ.png" /></figure><p>By applying a one-hot encoder the column is transformed into 3 binary columns, as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*ueEc3NCSmnUa0IkXZv7W3A.png" /></figure><p>Similarly we apply one-hot encoding on “temperature” column as it contains 3 distinct categories. For the remaining variables “humidity”, “windy” and “play” we just binarize them because each column contains two single classes.</p><p>For one-hot encoding we use “get_dummies” function from pandas and for binarization we use “preprocessing.LabelEncoder()” function from sklearn, as shown in the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e452185d7182b25381861fe5bc533c59/href">https://medium.com/media/e452185d7182b25381861fe5bc533c59/href</a></iframe><p>We concatenate the new numerical columns and we remark that all the resulting columns are binary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08bf801132c9040c95ee144d6cea5604/href">https://medium.com/media/08bf801132c9040c95ee144d6cea5604/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*wOP6jttQBl3ppPESh4a6qg.png" /></figure><h4><strong>Training our model</strong></h4><p>We define our input matrix <strong>X</strong> and our target <strong>y</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7f1ef961772c82ce5ddffc400371015/href">https://medium.com/media/f7f1ef961772c82ce5ddffc400371015/href</a></iframe><p>We choose to train our Naive Bayes classifier on 60% of the data. The remaining 40% is for test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0ec19faf9060e13fa34d1a7f0edcdd4/href">https://medium.com/media/c0ec19faf9060e13fa34d1a7f0edcdd4/href</a></iframe><p>As all the variables are binary we choose to apply Bernoulli Naive Bayes. The assumption of Bernoulli naive Bayes is that every variable follows a Bernoulli distribution, i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4bc5B6TKALWiPdjA.png" /></figure><p>where: <strong>n</strong> is the number of features.</p><p>Thus <strong>y </strong>is estimated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kgFACDePPPi6LzpW.png" /></figure><p>Coming back to our code we define our Bernoulli Naive Bayes classifier and then we train it on the training sample.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a91ea2906508e0d0599f4ac85839f970/href">https://medium.com/media/a91ea2906508e0d0599f4ac85839f970/href</a></iframe><p>Furthermore our model’s quality is tested based on three metrics: <strong>accuracy, recall and precision. </strong>The figure below illustrates the formulas of the considered metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/0*CdBNvXl9iD6RXt1D.png" /><figcaption>source: <a href="https://towardsdatascience.com/precision-and-recall-made-simple-afb5e098970f">https://towardsdatascience.com/precision-and-recall-made-simple-afb5e098970f</a></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eacfc549fd065de84afa7b41cfbc0482/href">https://medium.com/media/eacfc549fd065de84afa7b41cfbc0482/href</a></iframe><ul><li>The model’s accuracy = (TP+TN) /(TP+FP+FN+TN) = <strong>0.66, </strong>which means that 4 observations out of 6 are classified correctly.</li><li>The model’s precision = <strong>0.8</strong>, which means that if our model predicts class 1 (“we can play tennis!”) then we are 80% confident that the model’s decision is correct.</li><li>The model’s recall = <strong>0.8</strong>, which means that 80% of the real positive classes are predicted correctly.</li></ul><p>In summary our Bernoulli Naive Bayes classifier shows a good performance in classifying positive labels. We cannot judge its performance on classifying negative labels because the test data contain one single negative label out of 6 labels. But provided a larger dataset we must verify the classifier’s performance in predicting the negative class (“we cannot play tennis!”) in order to not miss any single tennis game ;)</p><p>Finally I was inspired to implement the algorithm on a tennis dataset after I had heard about the retirement of my beloved player Roger Federer. The career ends, but the legacy remains. Thank you for many years of pure magic! ❤</p><h3>References:</h3><p>[1]: <a href="https://scikit-learn.org/stable/modules/naive_bayes.html">https://scikit-learn.org/stable/modules/naive_bayes.html</a></p><p>[2]: H. Zhang, <a href="http://www.cs.unb.ca/~hzhang/publications/FLAIRS04ZhangH.pdf">The Optimality of Naive Bayes</a> (2004), Proceedings of the Seventeenth International Florida Artificial Intelligence Research Society Conference, FLAIRS 2004. 2.</p><p>[3]: A. Ng and M. Jordan, <a href="https://papers.nips.cc/paper/2001/file/7b7a53e239400a13bd6be6c91c4f6c4e-Paper.pdf">On Discriminative vs. Generative classifiers: A comparison of logistic regression and naive Bayes</a> (2001), Advances in Neural Information Processing Systems 14 (NIPS 2001).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28a16b35538e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>