<?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 Antoinette Tang on Medium]]></title>
        <description><![CDATA[Stories by Antoinette Tang on Medium]]></description>
        <link>https://medium.com/@anntangyj?source=rss-d14c32a06a4f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o_4rv-zWfQ5WhQbaivf-Aw.jpeg</url>
            <title>Stories by Antoinette Tang on Medium</title>
            <link>https://medium.com/@anntangyj?source=rss-d14c32a06a4f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 05:23:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anntangyj/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[KNN From Scratch: Curiosity, Satisfaction, And A Distinct Lack of Cats]]></title>
            <link>https://python.plainenglish.io/knn-from-scratch-curiosity-satisfaction-and-a-distinct-lack-of-cats-0185b0e62ceb?source=rss-d14c32a06a4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0185b0e62ceb</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[k-nearest-neighbors]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[curiosity]]></category>
            <category><![CDATA[k-nearest-neighbours]]></category>
            <dc:creator><![CDATA[Antoinette Tang]]></dc:creator>
            <pubDate>Thu, 09 May 2024 08:11:51 GMT</pubDate>
            <atom:updated>2024-05-13T00:44:55.514Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Science is a vast field that keeps growing. With so much to learn and advancement and innovation at every turn, it’s easy to feel overwhelmed or lost. That’s why today’s article is sponsored by Satisfying Curiosities! (Resurrection spells sold separately.)</p><p>Curiosity is like a lighthouse — it gives you direction, a sense of purpose, and a destination. Faced with a veritable mountain of knowledge to acquire, having a question you really want to answer gives you a good place to start.</p><p>For me, I’ve always been curious about how the mechanics of machine-learning techniques translated into code. What kind of thinking goes into the process of coding one? What codes does that lead to? Then, right on the heels of these thoughts: “Can I code one myself?”</p><p>Lighthouse found! Land ahoy!</p><p>Although you can code pretty much any machine-learning technique from scratch, I chose the K-Nearest Neighbours (KNN) algorithm for its simplicity. The core idea is easy to grasp: you take a point, calculate its distance to every point in the training dataset, and find the k-nearest points (aka, its neighbours) for some value of k.</p><p>For classification, you would determine which category most of the neighbours were in, then classify the point into that category. For regression, you would average the target values (for e.g., height) of the neighbours and assign this average value to the point.</p><p>Ta-dah! The basics of KNN! Simple, right?</p><p>Now, let’s look at how the mechanics of a simple KNN classification algorithm translate into code.</p><p>First we import our packages:</p><pre>import numpy as np<br>from collections import Counter</pre><p>Then, we put our coding hats on!</p><p>KNN is a machine-learning algorithm, so we want it to be able to do a few things, like fit data and make predictions. We also want to be able to call it multiple times, with varying numbers of neighbours and different distance metrics. So, we create a class, call it KNN, and initialise variables k and p.</p><pre>class KNN:<br>    <br>    #initialise variables<br>    def __init__(self, k = 5, p = 2):<br>        self.k = k<br>        self.p = p<br>        assert k &gt;= 1 and type(k) == int, &quot;k must be an integer in the range [1, inf)&quot;<br>        assert p &gt; 0 and (type(p) == int or type(p) == float), &quot;p must be an integer or a float in the range (0, inf)&quot;</pre><p>Initialising k and p allows us to use the KNN algorithm with different values of k and p when we call it later. Here, k refers to the number of neighbours we want the algorithm to use for classification, and p is used to choose the distance metric. We then add assert statements to limit input values for k and p.</p><p>We need at least 1 nearest neighbour for KNN, so k must be more than or equal to 1. k must be an integer for a more technical reason: we use k for slicing later on, and slice indices must be integers.</p><p>For p, we use p as a divisor later, so it must be more than zero. As it can take on values such as 0.75 or 1.5, p can be either a float or an integer, though it should be noted that Minkowski distance is not a metric when p is less than 1.</p><pre>  #compute distance metrics<br>    def distance_metric(self, x1, x2):<br>        &quot;&quot;&quot;<br>         Compute distance between two datapoints using Minkowski formula<br><br>         If p = 1, Manhattan distance is obtained<br><br>         If p = 2, Euclidean distance is obtained<br><br>         Else, Minkowski distance is obtained<br><br>         Returns distance as a float<br>         &quot;&quot;&quot;<br>        return np.sum(np.abs(x1 - x2)**self.p)**(1/self.p)</pre><p>For the distance metric, the Minkowski distance formula was chosen for its flexibility. This formula generalises the Manhattan and Euclidean distance formulae, as p = 1 would give you the Manhattan distance formula and p = 2 would give you the Euclidean distance formula. Other values of p would give you the Minkowski distance formula. Neat!</p><pre>def fit(self, x, y):<br>        &quot;&quot;&quot;<br>        Fit the model, with training data as x and target values as y<br>        &quot;&quot;&quot;<br>        self.x_train = x<br>        self.y_train = y</pre><p>The fit method allows us to store our training data, which the algorithm uses to classify datapoints later.</p><pre>def predict(self, X):<br>        &quot;&quot;&quot;<br>        Predict class labels for provided data, where X is data used for prediction<br><br>        Returns predicted class labels as an array-like object<br>        &quot;&quot;&quot;<br>        predicted_labels = [self.predict_for_one(x) for x in X]<br>        return np.array(predicted_labels)</pre><p>When you give the predict method a dataset of points as input, it instructs the algorithm to classify each datapoint by calling the predict_for_one method shown below. It stores all predictions in a list and returns them in a NumPy array because we’re going to use scikit-learn’s accuracy_score function to compare these predictions to the actual values later.</p><pre> def predict_for_one(self, x):<br>        &quot;&quot;&quot;<br>        Predict class label for a single sample, x<br>        <br>        Returns predicted class label as an int<br>        &quot;&quot;&quot;<br>        #compute distances between x and all datapoints in training set<br>        distances = [self.distance_metric(x, x_train) for x_train in self.x_train]<br><br>        #sort by distance and return indices of first k neighbours<br>        k_indices = np.argsort(distances)[:self.k]<br>        #extract labels of k-nearest neighbours<br>        k_nearest_labels = [self.y_train[i] for i in k_indices]<br>        #return the most common class label as prediction<br>        most_common = Counter(k_nearest_labels).most_common(1)<br>        return most_common[0][0]</pre><p>Here’s where most of the action happens!</p><p>The predict_for_one method is what allows the algorithm to classify each point: it computes the distances between the query point and every point in the training dataset using the distance_metric method, then sorts points according to their distance from the query point.</p><p>Then, it takes the indices of the first (and thus, nearest) k points and uses them to extract the labels associated with these points. The query point is then classified under the most common label.</p><p>Behold! A KNN classification algorithm, coded from scratch!</p><p>Now, we need to check its performance. To evaluate it, I decided to compare its accuracy scores with those of scikit-learn’s KNN classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgkyt8Fp0CeycENEgTGgwQ.png" /><figcaption>Comparison of Accuracy Scores between From-Scratch KNN Algorithm and Sklearn KNN Classifier</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57Yh5SpSOAhfoFnd_adYWg.png" /><figcaption>Average Accuracy Scores for each KNN Classifier</figcaption></figure><p>Great news! The algorithm is highly accurate, with average accuracy scores ranging from 93.57% to 95.09%.</p><p>It is, however, slightly less accurate than scikit-learn’s KNN classifier. Using Euclidean and Minkowski distances to classify points, the algorithm is on average 0.35% less accurate. Meanwhile, the algorithm is on average 1.52% less accurate when it classifies points using Manhattan distance.</p><p>What causes this gap in performance? After studying the Manhattan distance graph, I suspected a possible pattern. By comparing accuracy scores for each k value individually, I found that the algorithm was less accurate than scikit-learn’s KNN classifier when the value of k was even.</p><p>Why even values of k specifically? Even values of k expose the KNN algorithm to the possibility of ties in voting. For example, if there were 4 neighbours and 2 categories, each category could have 2 neighbours, resulting in a tie as both categories would be equally common. It‘s possible that the classifiers handled these ties differently, resulting in different classification decisions and thus differences in accuracy scores. Situations like these are why it’s advisable to use odd values of k with KNN!</p><p>Following your curiosity usually leads to new experiences and takeaways, and this time was no exception.</p><p>The coolest part of this project was definitely seeing and understanding how pieces of code come together to form a functional algorithm. Experiencing the thought processes that go into coding one from scratch was interesting as well. I gained a better understanding of classes and methods in Python, plus extra confidence coding functions.</p><p>I’m glad I decided to challenge myself by trying something new and can’t wait to see where my curiosity will lead me next. Thanks for reading!</p><p><strong>Bibliography</strong></p><p>One of the beauties of Data Science (and, well, the internet) is the wealth of learning resources available right at your fingertips. If you want to learn something, chances are there’s already an article or tutorial out there just waiting to teach you! For this project, I couldn’t have done it without the help of the following resources:</p><ol><li>Scikit-learn Nearest Neighbours<br><a href="https://scikit-learn.org/stable/modules/neighbors.html#neighbors">https://scikit-learn.org/stable/modules/neighbors.html#neighbors</a></li><li>Scikit-learn KNeighboursClassifier<br><a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html">https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html</a></li><li>The Math Behind K-Nearest Neighbours by <a href="https://medium.com/u/c24a3d106811">Cristian Leo</a><br><a href="https://towardsdatascience.com/the-math-behind-knn-3d34050efb71">https://towardsdatascience.com/the-math-behind-knn-3d34050efb71</a></li></ol><p>For my code in full, see here:</p><p><a href="https://github.com/antoinettetangyj/knn_classifier_from_scratch/blob/401801983806c5b7d7e7eb173b01a6815d178ffb/KNN%20Classifier%20from%20scratch.ipynb">knn_classifier_from_scratch/KNN Classifier from scratch.ipynb at 401801983806c5b7d7e7eb173b01a6815d178ffb · antoinettetangyj/knn_classifier_from_scratch</a></p><p>Finally, as a reward for scrolling this far, here’s one (1) cat!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaRgLZOf5lVbVukbYKtJFA.jpeg" /><figcaption>An Incurious Stray, circa. Jan 2024</figcaption></figure><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0185b0e62ceb" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/knn-from-scratch-curiosity-satisfaction-and-a-distinct-lack-of-cats-0185b0e62ceb">KNN From Scratch: Curiosity, Satisfaction, And A Distinct Lack of Cats</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Egads! My Interest!]]></title>
            <link>https://medium.com/@anntangyj/egads-my-interest-03d35dda9057?source=rss-d14c32a06a4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/03d35dda9057</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[calculator]]></category>
            <category><![CDATA[interest-rates]]></category>
            <dc:creator><![CDATA[Antoinette Tang]]></dc:creator>
            <pubDate>Sun, 14 Apr 2024 17:20:57 GMT</pubDate>
            <atom:updated>2024-04-14T17:20:57.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*SwCoRMiHP1tEnTWVC968lw.jpeg" /></figure><p>On 1 April 2024, UOB announced that interest rates for their flagship savings account, the UOB One Account, would be… revised (read: cut).</p><p>If you have a UOB One Account, were thinking of getting a UOB One Account, or are just someone who banks their money, the words “revised interest rates” would automatically fill you with a vague sense of dread. Perhaps you panic a little, as you visualise your prospective interest flying off into the ether. Plans would have to be made to maintain (or better yet, increase) your annual interest and safeguard against future interest revisions, and for that you would need more information.</p><p>Firstly, what do the revised interest rates mean?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*pJK5Tnks5Z5C_UXD9eTJHQ.png" /></figure><p>Using data provided by UOB, I compared effective interest rates between the old and new schemes. Previously, maintaining an account balance of $100,000 would net you an effective annual interest rate of 5%. With the revised interest rates, this would only get you a 3.38% interest — a 1.62% decrease! To top it off, adding an additional $50,000 to your account will only net you a 4% interest (the max amount of interest you can earn under the new scheme).</p><p>Goodbye, 5%. You will be dearly missed.</p><p>Okay, you say, then what do the revised interest rates mean for me specifically?</p><p>Well, with the data provided, I also created a <a href="https://docs.google.com/spreadsheets/d/1kF6j9bXYlQ5bPFDHHrE8lVopXCMY3qnzJYJJwO484IM/edit?usp=sharing">calculator</a> using Excel! Now that we know the difference in percentage interest gained per year, you might want to see what that means for you and your UOB One Account.</p><p>I used my calculator and found out that you would now have to maintain an account balance of $133,700 (hehe) to obtain around the same amount of raw interest per year. Is depositing that extra $33,700 worth it? You decide!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*XqmedzXHLy2Ajqf67TqeHg.png" /></figure><p>Now that you know what the revised interest rates mean, what can you do about it?</p><p>For those who want more consistent interest rates, consider Singapore Savings Bonds (SSBs)! Fully backed by the Singapore government, SSBs guarantee you an interest of about 3% for the next 10 years, with increasing interest the longer you invest. This is one way to safeguard your investments against interest cuts. Better still, your investment amount is guaranteed, and you can choose to exit at any time without penalties and regain your capital in full. For this reason, SSBs are quite possibly one of the safest investments you can make! (Disclaimer: This is not meant as financial advice! Please do your own research!)</p><p>Of course, there are many alternatives to SSBs that you can explore. It all depends on your personal financial goals! To that end, I hope this article has been helpful in some way. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03d35dda9057" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>