<?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 Francesco Di Salvo on Medium]]></title>
        <description><![CDATA[Stories by Francesco Di Salvo on Medium]]></description>
        <link>https://medium.com/@francesco.disalvo?source=rss-1b06b26db7e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Q33AAaH6pg1hDC16</url>
            <title>Stories by Francesco Di Salvo on Medium</title>
            <link>https://medium.com/@francesco.disalvo?source=rss-1b06b26db7e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:51:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@francesco.disalvo/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[The bias-variance tradeoff: an illustrated guide]]></title>
            <link>https://medium.com/@francesco.disalvo/the-bias-variance-tradeoff-an-illustrated-guide-6c79214b0c2b?source=rss-1b06b26db7e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c79214b0c2b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[bias-variance-tradeoff]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Francesco Di Salvo]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 17:43:36 GMT</pubDate>
            <atom:updated>2023-01-09T16:26:20.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Learning curve" src="https://cdn-images-1.medium.com/max/1024/1*8nIJ2w5nRrdJQuLhtZ4L7g.png" /><figcaption>Image from <a href="https://illustrated-machine-learning.github.io/">illustrated-machine-learning.github.io</a></figcaption></figure><p>This article clarifies the idea behind the very well-known <strong>bias-variance tradeoff</strong>. Even though you have probably heard it many times and in different contexts, it may still cause some confusion.</p><p>This fundamental tradeoff helps you understand the <strong>balance between simplicity and complexity</strong> in your models and as a consequence, it guides you toward building better, more accurate models.</p><p>Finally, to help you better understand and remember this topic, this article will also include graphical illustrations!</p><h3>Main idea</h3><p>The <strong>variance</strong> reflects the variability of the predictions whereas the <strong>bias</strong><br>is the difference between the forecast and the true values (error). Ideally, while building a good Machine Learning model, we hope to reach a low bias (error) and a low variance, in order to well generalize.</p><p>However, this rarely happens, and this is why we need to rely on this “trade-off”. What makes this topic so hot, is its strong relationship with two famous phenomena in the literature: <strong>overfitting </strong>and<strong> underfitting.</strong></p><p>It’s important to find a balance between these two types of error in order to build a good model</p><figure><img alt="Illustration about the bias-variance trade off and underfitting-overfitting" src="https://cdn-images-1.medium.com/max/1024/1*9tdEK2xcNnLIGPX2W25UCQ.png" /><figcaption>Image from <a href="https://illustrated-machine-learning.github.io/">illustrated-machine-learning.github.io</a></figcaption></figure><h3>Overfitting</h3><p>In simple terms, overfitting happens when the model works really well in training but poorly on unseen data, therefore, it <strong>fails to generalize</strong>.</p><p>Based on what we observed above, this means that the model is highly sensitive to little fluctuations in the training set. Hence, the model suffers from <strong>high variance.</strong></p><p>Some of the <strong>most common causes</strong> are:</p><ul><li>the model is too complex and it is not able to generalize enough on unseen data</li><li>there are too many features</li><li>there is not enough regularization (which may help to reduce the model complexity</li></ul><p>Obviously, there is no absolute <strong>solution</strong> to solve overfitting, but based on the problem and the model, we can:</p><ul><li>try simpler models</li><li>try to reduce the degree of the regression (if applicable)</li><li>try linear kernels (if applicable)</li><li>try reducing layers/units (if applicable)</li></ul><figure><img alt="Illustration about overfitting" src="https://cdn-images-1.medium.com/max/1024/1*iuaiZxR7GxzHUVsQFV3_NQ.png" /><figcaption>Image from <a href="https://illustrated-machine-learning.github.io/">illustrated-machine-learning.github.io</a></figcaption></figure><h3><strong>Underfitting</strong></h3><p>Underfitting, on the other hand, happens when the model <strong>doesn’t learn well from the training set</strong>, hence, there is a <strong>high bias</strong>.</p><p>The most common <strong>causes</strong> are:</p><ul><li>the model is too simple for the data</li><li>the features are not informative enough</li><li>you regularize too much (hence, the model becomes too simple)</li></ul><p>A few <strong>solutions</strong> are:</p><ul><li>try more complex models</li><li>select those features with a higher predictive power</li><li>add more training data (if possible..)</li><li>reduce regularization</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbHYRc5mhc9MmlS05ByM1Q.png" /><figcaption>Image from <a href="https://illustrated-machine-learning.github.io/">illustrated-machine-learning.github.io</a></figcaption></figure><h3>Tradeoff</h3><p>As we already mentioned, it is not always possible to have a very low bias and a very low variance, therefore, we need to find a good compromise between the two.</p><p>The overall goal is to reach the so-called <strong>zone of solution</strong>, an optimal zone that balances these two holy metrics.</p><p>Having the picture below as a reference, if we are on the left side, we should carefully move to the right by <strong>increasing the model complexity</strong> (reduce bias). On the other hand, if we seek to move leftwards, we have to <strong>simplify the model</strong> and reduce the variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RVleobFV6MlG_Gu-j99mIg.png" /><figcaption>Image from <a href="https://illustrated-machine-learning.github.io/">illustrated-machine-learning.github.io</a></figcaption></figure><h3>Conclusion</h3><p>In this article, we went through the bias-variance tradeoff, which is crucial for building effective models. I hope the article was clear enough and I hope the illustration may help you remember later on!</p><p>Cheers,<br>Francesco</p><h3>References</h3><ul><li>Machine Learning Engineering, Andriy Burkov</li><li><a href="https://illustrated-machine-learning.github.io/">https://illustrated-machine-learning.github.io/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c79214b0c2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K Nearest Neighbors — Explanation and Implementation]]></title>
            <link>https://medium.com/@francesco.disalvo/k-nearest-neighbors-explanation-and-implementation-438f0ca5dbf4?source=rss-1b06b26db7e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/438f0ca5dbf4</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Francesco Di Salvo]]></dc:creator>
            <pubDate>Sat, 04 Dec 2021 20:55:15 GMT</pubDate>
            <atom:updated>2021-12-06T17:57:56.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>K Nearest Neighbors — Explanation and Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5PPLugodwDJ61gXIMPrUg.jpeg" /><figcaption><a href="https://www.pexels.com/it-it/@michael-tuszynski-1134777?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Michael Tuszynski</a> from <a href="https://www.pexels.com/it-it/foto/vista-aerea-del-villaggio-di-casa-2255938/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><h3>Introduction</h3><p>K Nearest Neighbors is a <strong>supervised learning algorithm</strong> based on the assumption that the points in the neighborhood (i.e. closest points) belong to the same class.</p><p>Therefore, given a positive integer <em>k</em> and a test observation, KNN identifies the the <em>k</em> closest points and then, it can make inferences based on these closest targets.</p><p>Notice that it can be used for both <em>classification </em>and <em>regression </em>problems. In particular, for a <strong>classification problem</strong>, it estimates the conditional probability for class <em>j</em> as the fraction of points in the neighborhood whose target value is equal to <em>j</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*bDj_igOmRSCJZBlVFnomcQ.png" /></figure><p>where N0 represents the neighborhood of the given observation. It classifies the observation with the class having the highest conditional probability. In shorts, it considers the majority class in the neighborhood!</p><p>On the other hand, in a <strong>regression</strong> <strong>problem</strong>, the output will be just the average of the <em>k</em> closest targets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*agiOQIFIEChMjYW9ajcLJA.png" /><figcaption><a href="https://it.wikipedia.org/wiki/K-nearest_neighbors">https://it.wikipedia.org/wiki/K-nearest_neighbors</a></figcaption></figure><h3>How to choose the proper value of <em>k</em></h3><p>The choice of <em>k </em>is always critical, in fact we have to pay attention at two different scenarios:</p><ul><li><em>small k : </em>since you are very close to the observation, you will have a low bias, but you may be affected by a strong variance due to the presence of some outliers</li><li><em>large k : </em>if you enlarge your neighborhood you will be more robust to the outliers (low variance) but you will end up with an higher bias because you will probably consider points that are not so close.</li></ul><blockquote>The <a href="https://towardsdatascience.com/understanding-the-bias-variance-tradeoff-165e6942b229">bias-variance tradeoff</a> is always behind the corner!</blockquote><p>Ok great, but how can we select it? Unfortunately there isn’t an absolute answer but we have to try different values.</p><p>A common practice is to plot the reference error metric for different values of <em>k. </em>By doing so, you can see with your own eyes how your model behaves and what can be a good trade off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*3f724GE1dWZYlXoAoehoeA.png" /><figcaption><a href="https://towardsdatascience.com/how-to-find-the-optimal-value-of-k-in-knn-35d936e554eb">https://towardsdatascience.com/how-to-find-the-optimal-value-of-k-in-knn-35d936e554eb</a></figcaption></figure><h3>Distance metrics</h3><p>In order to quantify how much an observation <em>x </em>is close to <em>y, </em>we need to define a proper distance metric. The most common ones are:</p><ul><li><strong>manhattan</strong><em> : </em>the distance between two points is the sum of the absolute differences of their coordinates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*J2FEAb8eIrmMqE57GyH8nA.png" /></figure><ul><li><strong>euclidean </strong>: it is probably the most used one and it is defined as the square root of the sum of the squares of the differences of the coordinates</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*ZuNPtyyqkiwFkY71yiJ4og.png" /></figure><ul><li><strong>chebyshev </strong>: it is the maximum absolute difference between all the coordinates. It is also called <em>supremum distance</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*1Y5RtCu-4ZzfoNZWxB3nmg.png" /></figure><h3>Implementation</h3><p>To sum up, the naive algorithm is quite straightforward:</p><ol><li>For all the test observations, compute the distances between them and all the training ones</li><li>Consider only the <em>k </em>closest points and maintain their targets</li><li>If it is a classification problem, take the majority class, otherwise, take the average of the closest targets.</li></ol><p>The complete implementation can be found <a href="https://github.com/leadthefuture/ML-and-DataScience-preparation/tree/main/Machine%20Learning/ML%20algorithms%20from%20scratch">here</a>. First, I’d like to report the skeleton of the class, with all the methods that we need to implement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9562ded582bde6b63dc11ac08d88af2b/href">https://medium.com/media/9562ded582bde6b63dc11ac08d88af2b/href</a></iframe><p>The <strong>__init__</strong> method will be used for defining the number of neighbors, the chosen metric and an auxiliary flag for understanding if we’re dealing with a regression or classification problem. Now we will incrementally enrich the code until the end!</p><p>For the sake of brevity here I have reported only the euclidean distance, but on the github repository you will find all the implementations.</p><p>Moreover, since we can choose from different metrics, it is important to check if we are considering a “valid” one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/152bc7c2e6e2d80064e0207ba7427f4c/href">https://medium.com/media/152bc7c2e6e2d80064e0207ba7427f4c/href</a></iframe><p>Then, we must be able to compute the distance, therefore let us add two other methods: <strong>compute_distance() </strong><em>and </em><strong>euclidean_distance(). </strong>The first one will be used to call the proper distance method based on the selected one, while the second one (and also the ones that I haven’t reported) will be in charge to return the actual distance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eeaa7825511b9883d6d67f5c665fbf3/href">https://medium.com/media/7eeaa7825511b9883d6d67f5c665fbf3/href</a></iframe><p>Here the fun begins! We have defined all the contour methods but now we need to define the pure <strong>fit_predict()</strong> method. Recall that in this case we are performing a <em>brute force approach</em>, but there are way more efficient solutions.</p><p>So, for each test point, we have to compute (and save) all the distances with the training points. Then, we sort them and we take just the <em>k </em>closest ones (i.e. the ones for which we have the lowest distance).</p><p>After that, we memorize just their class and finally we can make our prediction as the mean or the majority class, for a regression or classification problem, respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8335322a7da5ae815f51e71944ec06c4/href">https://medium.com/media/8335322a7da5ae815f51e71944ec06c4/href</a></iframe><p>Finally, for the sake of completeness, I have compared the performances of this algorithm with ScikitLearn’s implementation on the <a href="https://archive.ics.uci.edu/ml/datasets/iris">Iris Dataset</a> and the performances are equal!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83f7f1e5d65b9a481c797824c515d8dd/href">https://medium.com/media/83f7f1e5d65b9a481c797824c515d8dd/href</a></iframe><h3>Conclusions</h3><p>This algorithm is quite simple but is extremely powerful whenever we have a moderate number of features and samples. It has been quite fun and challenging and I hope you have understood all the hidden passages!</p><p>For any comments, doubts or feedbacks, feel free to reach me out on <a href="https://www.linkedin.com/in/francescodisalvo-pa/">LinkedIn</a>, I would be more than happy to answer! :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=438f0ca5dbf4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decision Tree and Random Forest — PT 1]]></title>
            <link>https://medium.com/@francesco.disalvo/decision-tree-and-random-forest-pt-1-729b74db1756?source=rss-1b06b26db7e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/729b74db1756</guid>
            <dc:creator><![CDATA[Francesco Di Salvo]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 15:02:07 GMT</pubDate>
            <atom:updated>2021-10-03T15:21:52.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Decision Tree and Random Forest — PT 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WQ-gju_7P0HMPHlY7YvhgQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tbzr?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arnaud Mesureur</a> on <a href="https://unsplash.com/s/photos/trees?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Tree based algorithms are probably the most used algorithms in both classification and regression problems. In fact, if you see a couple of Kaggle notebooks, it is quite easy to understand that most of the people blindly try <strong>Random Forest </strong>as a first trial.</p><p>Today I would like to go deeper in this topic and try to explain what are their main advantages and disadvantages.</p><p>Even though there are several tree based algorithms, most of the times we refer to <strong>Decision Tree and Random Forest.</strong></p><h3>Decision Tree</h3><p><strong>Decision tree</strong> is a <strong>supervised learning</strong> algorithm that predicts the new labels by <strong>recursively splitting</strong> the predictor space into <strong>non overlapping</strong> distinct regions. For every observation that falls into any region we make the same prediction, which is the <strong>majority class</strong> in that region (for classification) or the <strong>mean</strong> of the response value (for regression).</p><p>Since considering every possible partition is computationally infeasible (<strong>NP- hard problem</strong>), the tree is constructed with a <strong>greedy top down approach</strong>, known as recursive binary splitting.</p><p>It is top-down because it begins at the top of the tree and then it successively splits the predictor space; each split is indicated via two new branches further down on the tree. Then, it is greedy because at each step of the tree-building process, the best split is made at that particular step, rather than looking ahead and picking a split that will lead to a better tree in some future step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftQSZ5YQiLu5B3u6pV-aHg.jpeg" /><figcaption>Regression Binary Splitting (<a href="https://tex.stackexchange.com/questions/526560/plotting-regression-tree-and-partitions">Source</a>)</figcaption></figure><p>In order to select the best split to make for classification problems, we consider the split that minimize something. Here we have two main alternatives, the <strong>Gini Index </strong>and the<strong> Entropy.</strong></p><p>The Gini Index is a measure of impurity and in particular it measures the variances across the classes. It is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*YoIz-1KOrjQWt9X_iux3rw.png" /></figure><p>where j is the current class evaluated and p_j is the probability (percentage) of class j. If we have one single class in the current partition its value will be 0 (the minimum) but if we have an equally distributed number of samples, we will have a Gini index equal to 1-(1/#classes).</p><p>On the other hand, the Entropy measures the so called “information gain”, defined as the disorder of the features with the current target. It is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*0QsBHlMvYnvRVZ6_MbePkw.png" /></figure><blockquote>In regression problems, we aim to minimize the RSS (Residual Sum of Squares)</blockquote><p>The main <strong>advantage</strong> of a decision tree is that it is fairly <strong>interpretable</strong>. The expanded decision tree can be easily explained if it is not too big. The problem is not only the interpretability, but huge trees could also have some redundant sub trees. Therefore, there are some techniques that allow to <strong>compress </strong>the dimensions, obtaining a less complex and less redundant tree. It can be pruned after the whole generation of the tree (<strong>post-pruning</strong>), replacing the less informative subtrees with leaves. However, the most efficient way to do that is to prune it before it grows on its entirety (<strong>pre-pruning</strong>) because it simplifies it step by step, and not in the end. The pruning can be performed for different reasons, for example we may decide to prune it if it overcomes a given threshold for the depth or for the Gini/Entropy.</p><p>If we come up with a non-enormous tree, it may be also understood by non-experts. However, the <strong>disadvantages </strong>overcome the benefits and this is the reason why decision trees are barely used. In particular, the performances are not always optimal but most importantly, they are strongly affected by <strong>noise</strong> and <strong>outliers</strong>.</p><p>These limitations have brought to light a more advanced tree-based algorithm, that is <strong>Random Forest</strong>, an ensemble method that combines multiple decision trees (that is why it is called “forest”) with the <strong>bagging</strong> technique, obtaining a more accurate and robust model.</p><h3>Random Forest</h3><p>The idea of <strong>bagging</strong> is to make prediction on <strong>N</strong> <strong>bootstrapped</strong> copies of the training set (i.e. sampled with replacement). In order to decorellate the trees, <strong>feature bagging</strong> is the best option. In particular, each time a split in a tree is considered, a fixed number of features (typically √p) is randomly chosen.</p><blockquote>p is the number of features of the given dataset</blockquote><p>The final prediction will be given by a <strong>majority voting scheme</strong> of all the estimators (or the average, in regression tasks).</p><p>This is why this algorithm is fairly <strong>robust</strong> to noise and <strong>outliers</strong> and will have much <strong>less variance</strong> rather than a single decision tree. It is robust to noise and outliers because the “impact” of these data points will be spread over all estimators and therefore their impact will decrease as the number of estimators increases. Then, it has a less variance because if we consider n observations with variance σ^2, the variance of the sample mean (over all estimators) will be exactly σ^2/n .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4u3B0vnppoahIbm8zz7PdQ.jpeg" /><figcaption>Random Forest (<a href="https://www.tibco.com/reference-center/what-is-a-random-forest">Source</a>)</figcaption></figure><p>On average, each bagged tree uses two third of the observation, therefore the remaining one third can be used to fit the given tree in order to evaluate its performances. This error is called <strong>out of bag error</strong> and sometimes it can be used for “stopping” the training procedure.</p><p>The million-dollar question<strong> </strong>is: <strong>how many trees do I need? </strong>I faced the same problem during my first trials. Intuitively, the higher is the number of estimators, the better will be the results BUT the improvements is not linear, therefore up to a certain point the computational complexity introduced will not be justified by its benefits.</p><p>When I was looking for the same answer I have found <a href="https://www.researchgate.net/publication/230766603_How_Many_Trees_in_a_Random_Forest">this</a> paper that conducted an analysis on 29 different datasets and showed that “from 128 trees there is no more significant difference between the forests using 256, 512, 1024, 2048 and 4096 trees”.</p><p>Since we talked about the advantages we have to mention probably the main drawback : the <strong>computational cost. </strong>If we have limited resources, this algorithm may not be the perfect choice, especially if we have a large number of features and chosen estimators.</p><h3>Conclusions</h3><p>Today we went a bit deeper on the theory behind Decision Tree and Random Forest. Assuming that we have to select one of these two algorithms, we could say in a couple of lines that Decision Tree could be a valid option if we need to explain our model to non-experts or if we want to understand a bit what is going on inside our model. But, if we care only about the overall performances and we do not have any particular computational limitations, Random Forest should be preferred.</p><p>This was just the first part and soon or later I will post the second one, from which we will go through the implementation of both algorithms!</p><p>Thanks for reading the whole post and I hope it is all clear. If you still have some doubts or if you wanna just drop me a message, I would be more than happy to read it! Feel free to contact me on <a href="https://www.linkedin.com/in/francescodisalvo-pa/">LinkedIn</a> :)</p><h3><strong>References and Further Readings</strong></h3><ul><li><a href="https://en.wikipedia.org/wiki/Recursive_partitioning">https://en.wikipedia.org/wiki/Recursive_partitioning</a></li><li><a href="https://quantdare.com/decision-trees-gini-vs-entropy/">https://quantdare.com/decision-trees-gini-vs-entropy/</a></li><li><a href="https://quantdare.com/what-is-the-difference-between-bagging-and-boosting/">https://quantdare.com/what-is-the-difference-between-bagging-and-boosting/</a></li><li><a href="https://www.researchgate.net/publication/230766603_How_Many_Trees_in_a_Random_Forest">https://www.researchgate.net/publication/230766603_How_Many_Trees_in_a_Random_Forest</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=729b74db1756" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast API — How to build a grocery list]]></title>
            <link>https://medium.com/@francesco.disalvo/fast-api-how-to-build-a-grocery-list-ee51d65f5bf2?source=rss-1b06b26db7e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee51d65f5bf2</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Francesco Di Salvo]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 16:59:09 GMT</pubDate>
            <atom:updated>2021-09-15T06:16:08.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fast API — How to build a grocery list</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baa5EEsT49ciN34X-HqCRg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mrsmaria?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maria Lin Kim</a> on <a href="https://unsplash.com/s/photos/grocery?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I recently approached Fast API and I realized that is an extremely useful, powerful, and easy-to-use web framework. Compared to Flask, it is much faster because it is built over Asynchronous Server Gateway Interface (ASGI) instead of Web Server Gateway Interface (WSGI). You can read something more about it in the following medium article: “<a href="https://medium.com/analytics-vidhya/difference-between-wsgi-and-asgi-807158ed1d4c">Difference between WSGI and ASGI?</a>”.</p><p>Today I explain a simple way for implementing a grocery list with FastAPI. Obviously, once you understand the basics of this framework, “the sky’s the limit!”</p><p>First, we should start mentioning the CRUD operations, that are:</p><ul><li>CREATE: create a new item</li><li>READ: retrieve all our items</li><li>UPDATE: update the quantity of a given item that we need to buy</li><li>DELETE: delete a given item</li></ul><blockquote>The code of this tutorial can be found in <a href="https://github.com/francescodisalvo05/fastapi-grocery-list">this</a> repository.</blockquote><h3>Structure</h3><p>This is the structure that I have used on my repository:</p><p>↳ app : __init__.py | app.py<br>↳test.py : __init__.py | test_main.py<br>main.py</p><h3>GET, POST, PUT, DELETE</h3><p>The foundations of the requests that took place on the web lie in Hypertext Transfer Protocol (HTTP). It manages all the communications between <strong>clients </strong>(the ones that request a resource) and <strong>servers </strong>(the ones that own the resources).</p><p>Two of the most common HTTP methods are <strong>GET </strong>and <strong>POST. </strong>The major difference among them is that GET is used for <strong>requesting</strong> data to the server whereas POST is used for <strong>sending</strong> data to the server.</p><p>If you want to know something more, I suggest you have a look at <a href="https://www.w3schools.com/tags/ref_httpmethods.asp">W3Schools</a>. This website has been a bible for me while I was in high school and I was learning the Web Development stack.</p><p>Moreover, we also have PUT and DELETE. PUT is used for updating an instance on the server whereas DELETE is used, as you may imagine, for deleting an existing item.</p><h3><strong>API and JSON</strong></h3><p>An Application Programming Interface (API) is a software that allows the communication between two applications. JavaScript Object Notation (JSON), on the other hand, is a text format based on “key-value” pairs separated by commas. Here’s an example:</p><pre>{<br>    &quot;name&quot; : &quot;Francesco&quot;,<br>    &quot;surname&quot; : &quot;Di Salvo&quot;,<br>    &quot;interests&quot; : [&quot;AI&quot;,&quot;Data Science&quot;,&quot;Finance&quot;]</pre><pre>}</pre><p>The reason why I am mentioning them both together is that JSON is commonly used for communication among applications through APIs. The main advantage of using JSON is that it is easily parsed by the machines and interpreted by us!</p><h3>Requirements</h3><p>To facilitate you, I uploaded the requirements <a href="https://github.com/francescodisalvo05/fastapi-grocery-list/blob/main/requirements.txt">here</a>. Therefore, once you have created your own virtual environment, you can simply install them with:</p><pre>pip install -r requirements.txt</pre><h3>main.py</h3><p>Here we define our <strong>uvicorn</strong> server, which will run on localhost on port 8000. Notice that the option “reload=True” means that we are in debugging mode, Pay attention that <strong>it must be turned to False</strong> in production! It means that every time we change something on our code the server will be restarted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59dbda33391587b75018a1499b3cf493/href">https://medium.com/media/59dbda33391587b75018a1499b3cf493/href</a></iframe><h3><strong>app.py — CREATE</strong></h3><p>Here the magic begins. First, we need to define our FastAPI application and then, we can start implementing our routes. For the sake of simplicity, we will not use any persistent memory but we will just use a list of dictionaries as our basket items.</p><p>As we mentioned before, since we want to send data to the server we need to use a POST method. Now, we need to define an input dictionary, that will be sent from the client.</p><p>From the input dictionary, we need the key-value pairs for the <strong>item</strong> and <strong>qty </strong>(quantity). Therefore, assuming the input keys are correct, we have two scenarios:</p><ol><li>The item already exists: we raise a 400 error</li><li>The item does not exist: we add it to our list, and we send a 201 status code</li></ol><blockquote>For the status code you can also check <a href="https://fastapi.tiangolo.com/tutorial/response-status-code/">this</a> resource.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f7a9801cb7a14ddae939a2301d7ceaa/href">https://medium.com/media/6f7a9801cb7a14ddae939a2301d7ceaa/href</a></iframe><h3><strong>app.py — READ</strong></h3><p>Now, we want to define a route for reading all our inserted items. We do not need to send data on the network. Therefore, we can use a GET method. So, the associated method will simply return our list of dictionaries under the key data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79ac37e70fea25bb3c55eb1e80dcbe2f/href">https://medium.com/media/79ac37e70fea25bb3c55eb1e80dcbe2f/href</a></iframe><h3>app.py — UPDATE</h3><p>The third operation is UPDATE, for which we update the quantity of a given item already present on our current list. Recall from before that to update an instance we use the PUT method.</p><p>Here we have the opposite situation of CREATE. We should raise an error if the item is not present on our list (because we cannot update it) and we can proceed otherwise.</p><p>Instead of using a body, now we use two items that will be given through the URL. We are waiting for “item_name” and “item_quantity”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/687c8b20a04f50a22f3aeddb1eae98cd/href">https://medium.com/media/687c8b20a04f50a22f3aeddb1eae98cd/href</a></iframe><h3>app.py — DELETE</h3><p>Finally, according to the CRUD paradigm we have to take care of the last operation, DELETE. Its corresponding method is DELETE, and we proceed as before. Now, instead of giving both “item_name” and “item_quantity” we give just “item_name”.</p><p>However, to mess up everything a little bit, let’s see a different way for retrieving the item to delete. In particular, we may also give it in a parametric way through the route.</p><p>For example, we may delete the item “water” by simply using the following request:</p><pre>/delete/water</pre><p>Therefore, we use the name of the parameter inside the braces, and it can be used inside the method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d6ea362be0c48d8be87cf01cc49ba1d/href">https://medium.com/media/7d6ea362be0c48d8be87cf01cc49ba1d/href</a></iframe><h3>Testing</h3><p>Once we defined all these operations we may want to test them. There are several ways to do that and probably the most common way is through Postman. Alternatively, FastAPI provides a very intuitive GUI from the route /docs. Otherwise, we can always use our old friend <strong>pytest.</strong></p><p>To define methods recognized as tests, we have to call the python file with “test_fileToTest.py”, so we define our “test_main.py”. Then, each method will be called with “test_stuffToTest()”.</p><p>For example, I want to test the creation of an item. We have two possibilities: the item already exists or not. Therefore, it is a common practice to test all the possible scenarios.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ed51949cd4f1319943a7163f2ced614/href">https://medium.com/media/6ed51949cd4f1319943a7163f2ced614/href</a></iframe><p>You can check all the tests that I have already performed <a href="https://github.com/francescodisalvo05/fastapi-grocery-list/blob/main/test/test_main.py">here</a>. To run all the tests, you need to run:</p><pre>pytest</pre><p>Since I have performed 8 tests, this would be my result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*NeES_3fayXb0emQZTMas7w.png" /></figure><h3>Conclusions</h3><p>Today we have seen how to build a simple local server that can be used for a lot of (more useful) use cases. Recently, I needed to build it for a coding interview, and to be honest, it was quite fun!</p><p>I hope everything is clear, and if not, feel free to reach out on <a href="https://www.linkedin.com/in/francescodisalvo-pa/">LinkedIn</a>. I would be more than happy to hear your feedback!</p><h3><strong>References</strong></h3><ul><li>Available code: <a href="https://github.com/francescodisalvo05/fastapi-grocery-list">https://github.com/francescodisalvo05/fastapi-grocery-list</a></li><li>GET and POST: <a href="https://www.w3schools.com/tags/ref_httpmethods.asp">https://www.w3schools.com/tags/ref_httpmethods.asp</a></li><li>APIs: <a href="https://www.redhat.com/en/topics/api/what-are-application-programming-interfaces">https://www.redhat.com/en/topics/api/what-are-application-programming-interfaces</a></li><li>Status code: <a href="https://fastapi.tiangolo.com/tutorial/response-status-code/">https://fastapi.tiangolo.com/tutorial/response-status-code/</a></li><li>Postman: <a href="https://www.postman.com/">https://www.postman.com</a></li></ul><blockquote><strong>Artificialis</strong>:<a href="https://discord.gg/AHeJaCvK3K"> Discord community server</a> , full of AI enthusiasts and professionals</blockquote><blockquote><a href="https://sendfox.com/artificialis"><strong>Our newsletter</strong></a>, weekly updates on our work, news in the world of AI, tutorials and more!</blockquote><p><a href="https://sendfox.com/artificialis">Artificialis Digest</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee51d65f5bf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Curse of dimensionality]]></title>
            <link>https://medium.com/geekculture/curse-of-dimensionality-e97ba916cb8f?source=rss-1b06b26db7e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e97ba916cb8f</guid>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Francesco Di Salvo]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 09:32:52 GMT</pubDate>
            <atom:updated>2021-09-07T15:12:22.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7h4CnnoLPr_U6iLTbL-EA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sigmund</a> on <a href="https://unsplash.com/s/photos/glasses-3d?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>If you have already gathered a bit of experience in Data Science and Machine Learning you’ve probably heard someone worried about the scary “<strong>curse of dimensionality</strong>”. If not, don’t panic, I will try to clarify it as much as I can!</p><p>Most of the time, the definition of the curse of dimensionality is strictly related to the <strong>sparsity </strong>of the data. In fact, <em>as the dimensionality increases, the volume of the space drastically increases as well, and the data becomes more and more sparse.</em></p><p>A consequence of the sparsity of the dataset is that our machine learning algorithms will need way more data in order to <strong>generalize</strong>! However, it is not always so easy to gather labeled data. Therefore, it is way more efficient to tackle this problem from the beginning instead of looking for new data.</p><h3>From another perspective</h3><p>During my course of Mathematics in Machine Learning, the professor gave us a practical representation of this phenomenon that I have seen only in a few online resources.</p><p>Let us consider a 2D feature space, represented by a <strong>unit square</strong>, and consider also a <strong>circle inscribed on this square</strong>. As you may see, most of the data points lie within the circle whereas the sparse data are on the corners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*NDMF-KQjcgRoi7qD46_X2Q.jpeg" /></figure><p>If we increase the dimension of the feature space by 1, we obtain a <strong>unit cube </strong>and again a <strong>sphere inscribed.</strong> Intuitively, more points than before are sparse (i.e. are on the corners).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*gJMIBBqpC5YLDTGuMi-fuQ.jpeg" /></figure><blockquote>Please, close one eye and imagine that this cube has all the sides of the same length!</blockquote><p>Now, if we continue for a while, we will end up in a very high dimensional space. What happens? Well, the volume of the hypercube will be always one, whereas the volume of the hypersphere (also called n-ball, with n dimensions) will exponentially decrease. Therefore, always more and more points will lie on the corners!</p><p>Are you still confused? Let’s try it mathematically. In <strong>two dimensions</strong>, given a unit square, its surface will be equal to 1 whreas the inscribed circle will have an area equal to 0.785</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*mUx5R0-Xo76DwqTwYib5tQ.gif" /></figure><p>With <strong>three dimensions</strong>, we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*ivLZTF44GWmOY73u_1d3UA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*QqWolf7Hxk3Zh9z9pYFAMA.jpeg" /></figure><p>Finally, with <strong>n dimensions</strong>, we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*M4QuTe4FA8cghjd-NcVFTQ.gif" /></figure><blockquote>See <a href="https://en.wikipedia.org/wiki/Volume_of_an_n-ball">wikipedia</a> for the volume of the “n-ball”</blockquote><p>Hopefully now, you should be able to “see” and understand the relationship between the number of dimensions and the sparsity of the data!</p><h3>What about the distance metrics?</h3><p>Well, some distance metrics may be strongly affected by this phenomenon. In particular the euclidean distance will slowly lose its relevance as the number of dimensions increases.</p><p>Why? Well, first, recall the definition of the euclidean distance with <em>d </em>dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/1*vwxdS9QFlzGXfe3vGGO7-g.gif" /></figure><p>As you can imagine, if you start adding new dimensions, this sum will increases as well. Therefore, for a sufficiently large number of dimensions the ratio among the nearest and the farthest point approaches 1. Hence, it doesn’t make any sense to speak about “K” nearest points (e.g. in KNN, LOF and so on).</p><h3><strong>Conclusions</strong></h3><p>To sum up, we have tried to give a more formal explanation to the <strong>curse of dimensionality</strong>, a very argued and underestimated topic in Machine Learning.</p><p>Whenever we have a very high number of features, we have several options that can be taken into account, for example:</p><ul><li>Remove highly <a href="https://en.wikipedia.org/wiki/Pearson_correlation_coefficient">correlated </a>or non correlated features</li><li>Group similar features</li><li>Use <a href="https://en.wikipedia.org/wiki/Principal_component_analysis">Principal Components Analysis</a> and similar techniques</li></ul><h3>References</h3><ul><li>Curse of dimensionality : <a href="https://en.wikipedia.org/wiki/Curse_of_dimensionality">Wikipedia</a></li><li>The course of dimensionality : <a href="https://mathematical-coffees.github.io/slides/mc08-delon.pdf">Julie Delon</a>,</li><li>The curse of dimensionality : <a href="https://towardsdatascience.com/the-curse-of-dimensionality-50dc6e49aa1e">Tony YiU</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e97ba916cb8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/curse-of-dimensionality-e97ba916cb8f">Curse of dimensionality</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>