<?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 Conor Walsh on Medium]]></title>
        <description><![CDATA[Stories by Conor Walsh on Medium]]></description>
        <link>https://medium.com/@conorwalsh206?source=rss-2fd8f6be5513------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dm2gWcJbwHoPIQGsQVO0Tg.jpeg</url>
            <title>Stories by Conor Walsh on Medium</title>
            <link>https://medium.com/@conorwalsh206?source=rss-2fd8f6be5513------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:18:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@conorwalsh206/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[Machine learning from scratch in C++]]></title>
            <link>https://medium.com/@conorwalsh206/machine-learning-from-scratch-in-c-49f82bbdfbd6?source=rss-2fd8f6be5513------2</link>
            <guid isPermaLink="false">https://medium.com/p/49f82bbdfbd6</guid>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Conor Walsh]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 12:44:52 GMT</pubDate>
            <atom:updated>2026-08-31T12:53:53.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krVxmXPbBgnqWhmjlOLCRg.png" /></figure><p>As a python-native machine learning (ML) engineer, I have long been tempted to dip my toes into C++. After all, it is the backbone of major ML frameworks such as PyTorch. Additionally, I have heard enough stories about its blazing fast speed (and seen enough memes about python’s lack thereof) that I couldn’t help but give it my attention. So why not take the time to implement some fundamental ML algorithms - from scratch - in C++? What could go wrong?</p><p>After deciding that learning a new language (particularly one with the reputation of C++) brings enough complexity in its own right, I cut myself some slack and chose to begin with an implementation of the K-nearest neighbours (KNN) algorithm, one of the simplest (but foundational) ML algorithms.</p><p>My first port of call was the excellent <a href="https://youtu.be/8jLOx1hD3_o?si=TpeczlSw8tNPU-ze">C++ Programming Course — Beginner to Advanced</a>, which gives a really comprehensive introduction to the fundamentals of C++. Nevertheless, after making it about halfway through the tutorial, I felt the urge to begin my implementation.</p><p>As I began this project in order to learn C++, I decided looking for help from the AI Gods was counter-productive. I needed to write the code if I was to learn anything. Therefore, my goal became the following: develop a functional KNN implementation, however ugly, inefficient or fragile it may be, and only then ask ChatGPT, Gemini or Claude how to optimise it. I realised this would actually turn out to be a nice way to learn the advantages of the language, as by first developing a working (but brittle) solution, and then having a coding assistant help me optimise it step-by-step, I would (hopefully) realise my mistakes, uncover my knowledge gaps, and learn how good C++ code should be written. After all, this was the whole point of the project, the satisfaction that comes from actually learning a bit of the language. Obviously, any model could spin up a perfect KNN implementation in a matter of seconds, but there would be no joy in that. If you have ever ordered food in a foreign language abroad, you will know there is a qualitative difference in the feeling of using a language you have actually learned, versus using google translate, even if the result is identical.</p><p>However, this project still needed to get off the ground, so I allowed myself a few exceptions, and asked ChatGPT for help with the following:</p><ol><li>Structuring the project (forgive me, I didn’t have the patience to learn what cmake does, I promise I will one day!)</li><li>Passing data to the model (my brain couldn’t break out of its NumPy array worldview, so I needed a nudge from GenAI to understand how I could use std::vector to get the job done)</li></ol><p>After that, the blame for any poor design choices/implementation lies solely with me (and the stack overflow/cpp-reference pages that guided me).</p><h3>K-Nearest Neighbours</h3><p>So how does the KNN algorithm work? KNN is a supervised learning algorithm (it learns from a set of examples — known as the training data — to understand how outputs are associated with different combinations of inputs, and uses this knowledge to predict the outputs for new data points given their inputs) that can be used for regression or classification problems. In plain English, given a new data point whose value we want to predict, this algorithm’s estimate is the average value of the K most similar points (the nearest neighbours) seen in the training data.</p><p>More formally, for some number K:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*dpHNkjpwh568qF2Lw5hGWQ.png" /></figure><p>For regression problems, the model prediction is this average. For binary classification, (where response values are either 0 or 1), the prediction is the majority vote - 0 if the average is less than 0.5, 1 otherwise.</p><p>To find a point’s K nearest neighbours, we must first have some concept of ‘nearest’. This means choosing a function with which to calculate the distance between points. To keep things as simple as possible, we use the Euclidean distance function. To further simplify our implementation, we assume all input features are numerical, and for classification we only consider the binary case.</p><h3>The Implementation</h3><p>There are only 5 parameters required to implement this simplified KNN model.</p><ul><li>Integer <em>k</em></li><li>Training data feature vector <em>X</em> (<em>X_input</em> below)</li><li>Training data response vector <em>Y</em> (<em>Y_input</em> below)</li><li>Prediction feature vector <em>X</em> (<em>X_predict</em>) for which we wish to generate predictions</li><li>The mode of prediction (either regression or classification)</li></ul><pre>class KNN{<br>    private:<br>        int k;<br>        int n;<br>        int p;<br>        std::vector&lt;double&gt; X;<br>        std::vector&lt;double&gt; y;<br>        std::string mode = &quot;regression&quot;;<br><br>    public:<br>        KNN() = default;<br>        KNN(<br>            const std::vector&lt;double&gt;&amp; X_input,<br>            const std::vector&lt;double&gt;&amp; y_input,<br>            const int k_input,<br>            const std::string mode <br>        );<br><br>        std::vector&lt;double&gt; predict(const std::vector&lt;double&gt;&amp; X_predict) const;        <br>        std::vector&lt;int&gt; get_neighbours(const std::vector&lt;double&gt;&amp; X_predict) const;<br>        int get_size_X_predict(const std::vector&lt;double&gt;&amp; X) const;        <br>};</pre><p>If, like me, you are python-native, you may be confused as to why our input data (which is usually thought of as a dataframe or matrix) is referred to as a vector here — more on that later. The conventional title “training data“ may also be slightly misleading here — this model doesn’t strictly require any <em>fit()</em> step, as no model parameters are ‘learned’. When generating predictions for a new set of data points, we simply find the nearest neighbours from our existing “training” data on the fly and calculate the average responses. Simple!</p><p>In fact, we have very few functions in this class. The user, after initialising the class object, only needs to call <em>.predict()</em>.</p><pre>int main(){<br>    <br>    std::vector&lt;double&gt; X_train {<br>        1.0, 2.0, <br>        2.0, 3.0<br>    };<br>    std::vector&lt;double&gt; y_train {<br>        10.0,<br>        100.0<br>    };    <br>    KNN knn_regressor = KNN(X_train, y_train, 1, &quot;regression&quot;);<br>    std::vector&lt;double&gt; X_predict {<br>        1.0, 1.0, // should find first point as nearest neighbour -&gt; prediction should be 10.0<br>        1.0, 2.0, // should find first point as nearest neighbour -&gt; prediction should be 10.0<br>        4.0, 5.0 // should find second point as nearest neighbour -&gt; prediction should be 100.0<br>    };<br><br>    std::vector&lt;double&gt; y_predict = knn_regressor.predict(X_predict);<br><br>    return 0;<br>}</pre><p>When the model is initialised, we perform several set up and validation steps. We first find the size of the data, and the number of features in each point. The size is the product <em>N</em> x <em>P</em>, where <em>N</em> is the number of points, and <em>P </em>is the number of features. These two numbers are crucial for later, when we need to loop through the data to calculate distances between points.</p><p>As a C++ beginner, this step felt completely alien to me at first. In python, where the input would usually be akin to a pandas dataframe, we know that the number of rows corresponds to the number of data points, and the number of columns corresponds to the number of features. However, in the vectorised world of C++, we are storing all our data in a one-dimensional vector, each data point following the previous one in a single, contiguous block, without the natural separation of living in different rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DDtMyxBOmj6NkycSSDrlw.png" /></figure><p>Therefore, to loop through our data, we need to know where each point starts and ends, and for this, we need the value <em>P</em>. We can find <em>N</em> from the size of our training data response vector <em>Y</em> (as we will have one response value per point), and <em>P</em> by dividing the size of the vector <em>X</em> by <em>N</em>.</p><p>We also need to validate that our input is usable — i.e. that we have valid values of <em>k </em>and <em>N</em>, response values are 1s or 0s if mode is classification, etc.</p><pre>KNN::KNN(<br>    const std::vector&lt;double&gt;&amp; X_input,<br>    const std::vector&lt;double&gt;&amp; y_input,<br>    int k_input, <br>    std::string mode_input<br>){<br>    k = k_input;<br>    X = X_input;<br>    y = y_input;<br>    mode = mode_input;<br>    n = y.size();<br><br>    if (mode != &quot;regression&quot;){<br>        if(mode != &quot;classification&quot;){<br>        throw std::invalid_argument(&quot;Mode must be either &#39;regression&#39; or &#39;classification&#39;.&quot;);<br>        }else{<br>            for(int i{0}; i&lt;n; i++){<br>                if((y[i] != 0) &amp; (y[i] !=1)){<br>                    throw std::invalid_argument(&quot;When mode is classification y must consist of 1s and 0s only.&quot;);<br>                }<br>            }<br>        }<br>    }<br>    if (n &lt;= 0){<br>        throw std::invalid_argument(&quot;n must be a positive integer&quot;);        <br>    }else{<br>        if (X.size() &lt;= 0){<br>            throw std::invalid_argument(&quot;X must contain data&quot;);<br>        }else{<br>            if (X.size() % n &gt; 0){<br>                throw std::invalid_argument(&quot;n must be a positive integer&quot;);               <br>            }else{<br>                p = X.size() / n;<br>            }            <br>        }                <br>    }<br><br>    if (k &gt; n){<br>        k = n;<br>        std::cout &lt;&lt; &quot;k cannot be greater than n. Reassigning k the following value: &quot; &lt;&lt; n &lt;&lt; std::endl;<br>    }<br>}</pre><p>Once the input is validated, our plan is simple, and the pseudo-code is shown below:</p><pre>// Create (empty) &#39;predictions&#39; vector to store predictions for points in X_predict<br>// Loop through X_predict:<br>    // Isolate the elements of the given point (positions (i*p) to ((i+1)*p)-1)<br>    // Create &#39;distances&#39; vector to store distance from this point to each point in X_input (should be n positions)<br>    // loop through X_input:<br>        // Isolate given point in X_input<br>        // Calculate distance between this X_input point and X_predict point<br>        // Store in distances vector<br>    // Find K nearest neighbours of given X_predict point:<br>        // Create (empty) neighbours vector (where we will store neighbours&#39; indices from X_input) of size k<br>        // Loop through distances vector K times:<br>        // On first loop, find smallest distance -&gt; add index to neighbours vector in position 0<br>        // On consecutive loops, find next smallest distance (must include check to ensure not including previous neighbours) etc.        <br>    // Loop through neighbours vector:<br>        // For each neighbour index, get corresponding response from y<br>        // Calculate mean of neighbours&#39; responses and store in ith position of predictions vector<br>    // For classification, round predictions to 0 or 1<br>    // Return predictions</pre><p>As mentioned, this simplified implementation aims to do one thing only: return the correct predictions. There are therefore several caveats to be aware of:</p><ul><li>Doesn’t allow for categorical inputs</li><li>Doesn’t allow for multi-class classification</li><li>Doesn’t return any non-essential info (other quantities of interest not returned include the distances vector, and for classification, the vector of probabilities)</li><li>Tiebreak logic — when choosing which of two or more equidistant points (from the point of interest) to add to the nearest neighbours vector — is simply to keep whichever point comes later in the for loop</li></ul><p>Now let’s break down what is happening under the hood when <em>.predict()</em> is called.</p><p>The first step we take is to find the number of points in the feature vector <em>X_predict</em>, to know how many points we need to loop through and generate predictions for.</p><pre>std::vector&lt;double&gt; KNN::predict(const std::vector&lt;double&gt;&amp; X_predict) const {<br>    // Step 1. validate X_predict size<br>    int n_X_predict = get_size_X_predict(X_predict);</pre><p>Within the helper function:</p><pre>int KNN::get_size_X_predict(const std::vector&lt;double&gt;&amp; X_predict) const {<br>    if (X_predict.size() % p &gt; 0){         <br>        throw std::invalid_argument(&quot;Input not of correct shape. X_predict.size() must be a multiple of p.&quot;);<br>    }else{<br>        int n_X_predict = X_predict.size() / p; <br>        return n_X_predict;<br>    }    <br>}</pre><p>Next, we begin our loop through <em>X_predict</em>, isolating the elements of each point.</p><pre><br>.... (body of KNN::predict continued)<br><br>    // Loop through X_predict   <br>    for (int i {0}; i &lt; n_X_predict; i++){ <br>        // isolate point_i<br>        int start_index = i * p;        <br>        std::vector&lt;double&gt; x_i(p, -1); // fill with -1 as dummy data for now         <br>        for (int j{0}; j &lt; p; j++){<br>            x_i[j] = X_predict[start_index + j];<br>        }</pre><p>Once we have the given point, we find its nearest neighbours from <em>X_input</em>.</p><pre>.... (body of KNN::predict continued)<br><br>        std::vector&lt;int&gt; nearest_neighbours = get_neighbours(x_i);</pre><p>Inside <em>get_neighbours()</em>:</p><pre>std::vector&lt;int&gt; KNN::get_neighbours(const std::vector&lt;double&gt;&amp; x) const {<br>    // Create distances vector to store distance between x and each point in the training data -&gt; will be of size n<br>    std::vector&lt;double&gt; neighbour_distances(n, -1);<br><br>    // Loop through neighbours (training data)<br>    for (int i {0}; i &lt; n; i++){<br>        // Isolate given point<br>        int start_index = i*p;<br>        std::vector&lt;double&gt; neighbour(p, -1);<br>        for (int j{0}; j&lt;p; j++){<br>            neighbour[j] = X[start_index + j];<br>        }<br>        // Calculate distance between the two points<br>        double distance_to_neighbour = calculate_euclidean_distance(x, neighbour);<br>        neighbour_distances[i] = distance_to_neighbour; <br>    }<br><br>    // Create vector to store nearest neighbours -&gt; size k<br>    std::vector&lt;int&gt; nearest_neighbours(k, -1);<br>    <br>    // Loop through distances vector k times to find k nearest neighbours:<br>        // find smallest distance each time (that of next nearest neighbour)<br>        // get corresponding index<br>        // insert the index into nearest_neighbours vector at given position<br>    // Prerequisites -&gt; create placeholders next_smallest_distance, next_nearest_neighbour_index<br>    <br>    // In more detail, loop through distances vector k times:<br>        // Each time, check if neighbour is a valid candidate to be considered next nearest neighbour (not already in nearest_neighbours)<br>        // If so, compare distance to next_smallest_distance<br>        // If smaller, set next_smallest_distance to this distance and next_nearest_index to this neighbour<br>        // At end of loop, add next_nearest_index to nearest_neighbours vector, and invalidate it from the next round of checks (by setting value in neighbour_distances to -1) <br>        // Reset next_smallest_distance to placeholder value<br>    int next_nearest_index {-1}; <br>    double next_smallest_distance {std::numeric_limits&lt;double&gt;::infinity()};<br>    for (int nearest_neighbour_position{0}; nearest_neighbour_position &lt; k; nearest_neighbour_position++){<br>        for (int neighbour_index{0}; neighbour_index &lt; n; neighbour_index++){                <br>            double neighbour_distance = neighbour_distances[neighbour_index];<br>            if (neighbour_distance == -1){ // already in nearest_neighbours<br>                continue;<br>            }else{<br>                if (neighbour_distance &lt;= next_smallest_distance){<br>                    next_smallest_distance = neighbour_distance;<br>                    next_nearest_index = neighbour_index;<br>                }<br>            }<br>        }<br>        nearest_neighbours[nearest_neighbour_position] = next_nearest_index;<br>        neighbour_distances[next_nearest_index] = -1; // invalidate this neighbour from future rounds when checking for next nearest neighbour<br>        next_smallest_distance = std::numeric_limits&lt;double&gt;::infinity();<br>    }<br>    return nearest_neighbours;<br>}</pre><p>Given the nearest neighbours, we calculate their average response and store it in the predictions vector.</p><pre>.... (body of KNN::predict continued)<br><br>        double prediction_i {0};<br>        for (int index{0}; index &lt; k; index++){<br>           prediction_i += y[nearest_neighbours[index]];<br>        }<br>        prediction_i /= k;<br>        predictions[i] = prediction_i;</pre><p>We have now completed our loop through <em>X_predict</em>, and have a prediction for each point. Outside of the for loop, we must now check the mode of prediction, and round these values to 0 or 1 if it is classification.</p><pre>.... (body of KNN::predict continued)<br><br>    if (mode==&quot;classification&quot;){<br>        std::vector&lt;double&gt; predicted_probabilities = predictions;<br>        for (int i{0}; i&lt;n_X_predict; i++){<br>            if (predicted_probabilities[i]&gt;=0.5){<br>                predictions[i] = 1.0;<br>            }else{<br>                predictions[i] = 0.0;<br>            }            <br>        }<br>        return predictions;<br>    }else{<br>        return predictions;<br>    }</pre><p>And there we have it! Nothing fancy, but it gets the job done.</p><p>Now let’s see what tricks, best practices or other optimisations we’re missing by asking an LLM to help us optimise this.</p><h3>The Optimisation</h3><p>In cursor, I gave composer-2.5 fast the following prompt:</p><p><em>Optimise this KNN implementation to leverage C++ best practices. This could involve making the code more robust, efficient or readable. Explain the benefits of each change you make.</em></p><p>The changes it made were plentiful. Below we detail the most impactful:</p><h4>Replace temporary vectors with std::span()</h4><p><em>std::span()</em> is a (previously unknown to me) data type that essentially holds a view of a contiguous slice of an existing array. It stores only two values: a pointer to the first element in the slice of interest, and the number of elements following this.</p><p>This can help us wherever we loop through our data to isolate points of interest. This happens in a couple of places:</p><ul><li>When isolating the given point in <em>X_predict</em> for which we wish to generate a prediction</li><li>When isolating the given point in <em>X_input</em> in order to find its distance to the point in <em>X_predict</em></li></ul><p>In our naive implementation, each time we isolated a point of interest, we created a new vector, allocating <em>P</em> elements of memory, and copied over the <em>P</em> values of the point.</p><p>In the optimised implementation, the win is two-fold: we instead create a span to simply view the point as it already exists, using only two new values in memory, and with zero copying of values.</p><p>As <em>N</em> grows, the savings on allocations and copying here can be enormous.</p><h4>Replace the Euclidean distance with the squared Euclidean distance</h4><p>This tweak has nothing to do with C++, but is a clever optimisation nonetheless. As we are not returning the distances, but only use them to order neighbours by nearness, we can simply use the squared Euclidean distance instead of its square root. As the square root is monotonic, the order of distances will be the same, but we are saved from calculating the square root each time (<em>N</em> times per point in <em>X_predict</em>).</p><h4>Replace repeated linear scans with partial sort</h4><p>To find the <em>k </em>nearest neighbours of a given point once the <em>N</em> distances have been computed, our naive implementation loops through these distances <em>k</em> times, each time selecting the next smallest distance.</p><p>The optimised implementation instead uses the partial sort algorithm, which, as the name suggest, sorts only a part of the full array. More specifically, it selects and sorts only the <em>k</em> smallest elements from all <em>N</em>, without fully sorting the rest.<em> </em>It works as follows:</p><ul><li>Take the first <em>k</em> items and arrange them into a “current best <em>k</em>” set.</li><li>Look through every remaining item.</li><li>If a new item is worse than all current best items, ignore it.</li><li>If it is better, replace the worst item in the current best set.</li><li>When finished, sort just those <em>k</em> selected items.</li></ul><p>The computational complexity of our naive, repeated linear scans approach is <em>O</em>(<em>k.N</em>). Partial sort comes in at <em>O</em>(<em>N</em>.log(<em>k</em>)), which for large <em>N</em> and moderate <em>k</em>, can be a significant improvement.</p><p>In addition to these main optimisations, there were many other improvements made to the readability and robustness of the code. The source code for both naive and optimised implementations is linked below.</p><h3>Conclusion</h3><p>In the fast moving world of ML, where coding by hand seems to be disappearing bit-by-bit, taking the time to implement something from scratch can be seen as futile. However, it is a great way to actually learn (or remind yourself) how ML algorithms work, both in theory, and on the metal itself! Optimising your implementation with an LLM can also be a great to reveal your blindspots, and learn how to get the best out of the language you are working with. If nothing else, it can be an enjoyable and rewarding endeavour — this certainly was for me.</p><p>Full source code is available at <a href="https://github.com/conorwalsh99/ml-from-scratch-cpp">https://github.com/conorwalsh99/ml-from-scratch-cpp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49f82bbdfbd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Calibration]]></title>
            <link>https://medium.com/@conorwalsh206/an-introduction-to-calibration-e5a9f56173af?source=rss-2fd8f6be5513------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5a9f56173af</guid>
            <category><![CDATA[classification-metrics]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[calibration]]></category>
            <dc:creator><![CDATA[Conor Walsh]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 18:55:53 GMT</pubDate>
            <atom:updated>2024-10-28T19:25:53.362Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to evaluating the performance of machine learning classifiers, calibration is the most important measure you’ve probably never heard of. This often overlooked, but crucial aspect of model performance tells us how reliable a classifier’s predictions are. In this article, we’ll define calibration and discuss why it’s so important, before taking an in-depth look at how to measure calibration, with examples in Python. By the end of this article, you’ll be equipped with the necessary tools to robustly evaluate the reliability of your classifiers.</p><h3>What is Calibration?</h3><p>At a high level, calibration is simply a measure of the reliability of a classifier.</p><p>Consider a binary classification problem, where the classifier assigns 100 data points an 80% chance of being positive. Intuitively, we would expect approximately 80 of these points to be positive in reality. If this is the case, the model’s predictions are clearly reliable, and the model is said to be well-calibrated. If exactly 80 positives occur, the model is said to be perfectly calibrated.</p><p>More formally, we say that the probability a classifier assigns to an event should reflect the true frequency of that event [1]. This is the notion of calibration in a nutshell.</p><h3>Why is Calibration Important?</h3><p>Classifiers produce scores that reflect the model’s confidence that a data point belongs to a given class. It is important to remember that these scores are <em>estimates </em>of the underlying probability<em>, </em>and are only reliable if the model is well-calibrated. If this is not the case, these scores should not be assumed to be an accurate reflection of the underlying probability.</p><p>This may seem obvious, but it is often overlooked when it comes to evaluating classifiers. Data scientists very often assume a model’s predictions are reliable, and therefore treat these predictions as probabilities. Depending on the nature of the task, this could be a costly mistake.</p><p>For applications where decisions are made based on the predicted probability of an event occurring, it is critical that the predicted probabilities are reliable<strong>,</strong> i.e. that the model is well-calibrated.</p><h4>A Shift in Mindset</h4><p>Generally speaking, the goal in classification is to correctly predict the true label for each data point. While this is of course always important, for <strong>probabilistic decision-making </strong>applications, we must also concern ourselves with reliably estimating the true probability of each label occurring. If we only care about correctly predicting the true label, a prediction of 55% and 95% are effectively the same thing — they will get us the same result if accuracy is our only metric. However, for applications where the predicted probability informs a decision-making process, these predictions could be vastly different.</p><p>A slight shift in mindset is necessary here — for some applications,<strong> reliably predicting the true probability of a given label occurring is more important than correctly predicting the true label.</strong></p><h3>Probabilistic Decision-Making</h3><p>The following are examples where this is the case:</p><h4>Weather Forecasting</h4><p>People check weather forecasts to make plans for the future. If you are planning a barbecue, you may want to know the percentage chance of rain. The decision of whether or not to cancel your barbecue may be different for forecasts of a 65% chance of rain versus a 95% chance of rain. For each of these predictions, knowing the forecasting model is highly accurate tells you that it will probably rain, and you should cancel your barbecue. However, knowing the model is well-calibrated tells you that in the case of a 65% chance of rain, it will be dry approximately 35% of the time. If you have already bought your supplies, you may decide to risk it and go ahead with your barbecue.</p><h4>Sports Betting</h4><p>The world of sports is unpredictable, and bettors can never be sure of an outcome in advance. Therefore, rather than simply predicting the correct outcome, the aim of sports betting is to place bets that are <em>profitable in expectation. </em>Even if an outcome is unlikely, betting on it may still be profitable in expectation, if the probability of that outcome occurring is greater than the probability implied by the bookmaker’s odds. For instance, if a football team has a 33% chance of winning a particular game, betting on them is profitable in expectation if the odds offered are greater than 2/1. So even if they are likely to lose on this occasion, this is still a good bet, as it should pay off in the long run. Therefore, a sports betting model does not need to predict the correct outcome all the time, but reliably predicting the frequency with which each outcome occurs (a proxy for the underlying probability) is extremely important.</p><h4>Diagnosis of Disease</h4><p>Doctors often need to convey risk information to patients, such as the percentage chance of a disease being present. Providing the patient with a reliable estimate of the true risk allows the patient to plan for their future sensibly. Even if a diagnostic model is highly accurate (i.e. its diagnosis is correct most of the time), if it over- or underestimates the risk, this can cause the patient unnecessary anxiety, or worse, give them a false sense of security.</p><p>The above examples serve to show that there are certain applications where reliably estimating the true probability of a given label occurring can be more important than correctly predicting the true label. This is generally true for probabilistic decision-making applications. If you are using machine learning to estimate the underlying probability of an event occurring, in order to make an informed decision that will have real-world consequences (whether that be financial, personal or otherwise), it is absolutely critical to ensure your model is well-calibrated.</p><h3>Measuring Calibration</h3><p>So how can we tell if a model is well-calibrated? To answer this, let’s look at a formal definition of calibration.</p><p>“A probabilistic classifier is well-calibrated if among test instances receiving<br> a predicted probability vector p, the class distribution is (approximately) p” [2].</p><p>This echoes our earlier statement, that if a classifier assigns 100 data points an 80% chance of being positive, we would expect approximately 80 of them to be positive in reality.</p><p>However it doesn’t bring us much closer to being able to measure calibration. For instance, when dealing with finite data and continuous probabilities, there is no guarantee that any two data points will receive the same prediction vector p. Further, for a multi-class classification problem, even if two vectors have the same predicted probability for a given class, their predictions for the other classes may differ. It is therefore no surprise that several solutions have been proposed.</p><p>For the following definitions, assume we are dealing with a multi-class problem, with K classes. Let X represent the feature space. Let Py represent the probability space, for K dimensions. Denote our classifier as f : X → Py. The classifier produces a prediction vector S, an element of Py.</p><h4>Confidence Calibration</h4><p>A model is said to be confidence calibrated if the underlying probability that the true label is equal to the label predicted by the model, given the model’s score for this label is p, is equal to p. This is the weakest notion of calibration, as for each data point, it only considers the most likely class predicted by the model [3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*pTpbdoSpKF3Os-kw02sjyw.png" /><figcaption>A classifier is said to be confidence calibrated if the above condition is met.</figcaption></figure><h4>Class-Wise Calibration</h4><p>A classifier is class-wise calibrated if the underlying probability that the data point belongs to class i, given the model’s score for this class is p, is equal to p. This is a stronger notion of calibration, where we consider the marginal probabilities. That is, rather than only considering the most likely class, we consider each class in isolation [4].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*RqTwc2EA0Wl-cvJKcmpucg.png" /><figcaption>A classifier is class-wise calibrated if the above is true.</figcaption></figure><h4>Multi-Class Calibration</h4><p>A classifier is multi-class calibrated if the underlying probability that a data point belongs to class i, given the model predicts the score vector S, is S_i (the i^th dimension of S), and this is true for all dimensions i from 1 to K, for a k-class problem. This is the strongest notion of calibration. For each data point we consider the entire vector of predicted probabilities, rather than considering each class in isolation [5].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*EFGxjXFelaRttOMKjDBNgg.png" /><figcaption>A classifier is multi-class calibrated if the above holds.</figcaption></figure><p>We will focus on class-wise calibration, as it is stricter than confidence calibration, and more accessible than multi-class calibration.</p><p>As mentioned previously, for finite data it is impractical (if not impossible) to find instances receiving the exact same prediction vector. Therefore we relax these definitions, and look for instances receiving approximately equal predictions instead. We do this using binning.</p><h4>Calculating the Class-Wise Expected Calibration Error</h4><p>Given a set of prediction vectors, we calculate the class-wise expected calibration error (ECE) by the following steps:</p><p>For each class:</p><ol><li>We split the interval [0, 1] into M equal-width bins such that the j^th bin is given by the interval [j−1/M, j /M).</li><li>We associate each data point with the bin that contains its predicted probability.</li><li>Within each bin, we take the absolute difference between the mean predicted probability (expected rate of occurrence) and the actual rate of occurrence of instances of the given class.</li><li>We then weight this bin’s error by the proportion of the dataset the bin contains.</li><li>Summing these weighted errors together across all bins, we get the error for the given class.</li></ol><p>Taking the average of these errors across all classes, we get the class-wise expected calibration error.</p><p>The above steps can be summarised by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KpCUdIXHZEF6_rGajJWIw.png" /><figcaption>The class-wise expected calibration error (ECE), with each component explained.</figcaption></figure><p>Conventionally, 10 or 20 bins are used. If M=20, the bins will be the intervals [0, 0.05), [0.05, 0.1), …, [0.95, 1]. Since the predicted probabilities within a bin are effectively treated as predictions of the same event, the narrower the bin, the better (assuming sufficient data within each bin), so using 20 bins is preferable.</p><p>Perfect calibration occurs if, within all bins, the expected frequency matches the observed frequency of the given class.</p><h4>A Note on the Class-Wise Expected Calibration Error</h4><p>This error is bounded between 0 and 1, with lower scores representing a more reliable model. A helpful way to conceptualise this error is to think of it as the percentage by which the model’s predicted probability deviates from the true probability, on average.</p><p>This error also has its limitations, most notably that within a bin, errors caused by over- or under-confidence can cancel each other out. Even more worryingly, if a model simply predicts the class distribution for all instances, it will obtain a perfect error of 0, despite being completely redundant [2].</p><h3>Measuring Calibration in Python</h3><p>Let’s take a look at some code examples.</p><h4>Binary Classification</h4><p>First, let’s look at a toy example to see how we can measure the calibration of a set of predictions in the simplest case. Assume we have the following ten predictions, and corresponding true labels.</p><pre>y_pred_proba = [0.04, 0.13, 0.2, 0.33, 0.44, 0.5, 0.61,  0.7, 0.8, 0.93]<br>y_true = [0, 0, 0, 1, 0, 1, 0, 1, 1, 1]</pre><p>We can calculate the class-wise ECE of this set of predictions, as follows [6].</p><pre>from calibra.errors import classwise_ece<br><br>cw_ece = classwise_ece(y_pred=y_pred_proba, y_true=y_true, num_bins=10)<br><br>print(f&quot;Classwise ECE: {cw_ece * 100:.2f}%&quot;)</pre><pre>Classwise ECE: 24.20%</pre><p>This returns a class-wise ECE of 24.2%. This error looks enormous, despite the predictions seeming reasonable (with an accuracy of 80%), but this is simply because the size of the dataset is so small. Let’s look at a more reasonable example, using scikit-learn’s make_classification functionality.</p><pre>from sklearn.datasets import make_classification<br>from sklearn.model_selection import train_test_split<br>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score<br><br># Step 1: Create a synthetic dataset for a classification problem<br>X, y = make_classification(n_samples=10000, n_features=20, n_informative=2, n_redundant=10, random_state=42)<br><br># Step 2: Split the dataset into training and testing sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Step 3: Instantiate the models<br>random_forest = RandomForestClassifier(random_state=42)<br>logistic_regression = LogisticRegression(random_state=42)<br><br># Step 4: Train the models on the training data<br>random_forest.fit(X_train, y_train)<br>logistic_regression.fit(X_train, y_train)<br><br># Step 5: Make predictions on the test set<br>y_pred_rf = random_forest.predict(X_test)<br>y_pred_lr = logistic_regression.predict(X_test)<br><br># Step 6: Evaluate the accuracy of the models on the test set<br>accuracy_rf = accuracy_score(y_test, y_pred_rf)<br>accuracy_lr = accuracy_score(y_test, y_pred_lr)<br><br># Print the accuracies<br>print(f&quot;Random Forest Accuracy: {accuracy_rf * 100:.2f}%&quot;)<br>print(f&quot;Logistic Regression Accuracy: {accuracy_lr * 100:.2f}%&quot;)</pre><pre>Random Forest Accuracy: 94.00%<br>Logistic Regression Accuracy: 88.65%</pre><p>The random forest and logistic regression models perform well, achieving accuracies of 94.00% and 88.65%, respectively. Now let’s measure their calibration.</p><pre>y_pred_proba_rf = random_forest.predict_proba(X_test)<br>y_pred_proba_lr = logistic_regression.predict_proba(X_test)<br><br>cw_ece_rf = classwise_ece(y_pred_proba_rf, y_test, num_bins=20)<br>cw_ece_lr = classwise_ece(y_pred_proba_lr, y_test, num_bins=20)<br><br>print(f&quot;Random Forest Classwise ECE: {cw_ece_rf * 100:.2f}%&quot;)<br>print(f&quot;Logistic Regression Classwise ECE: {cw_ece_lr * 100:.2f}%&quot;)</pre><pre>Random Forest Classwise ECE: 2.15%<br>Logistic Regression Classwise ECE: 3.05%</pre><p>Both models are well-calibrated, achieving class-wise ECE’s of 2.15%<br>and 3.05%, respectively.</p><h4>Multi-Class Classification</h4><p>We can also calculate this error for the multi-class problem.</p><pre>X, y = make_classification(n_samples=10000, n_features=20, n_informative=3, n_classes=3, n_redundant=10, random_state=42)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>random_forest = RandomForestClassifier(random_state=42)<br>logistic_regression = LogisticRegression(random_state=42)<br>random_forest.fit(X_train, y_train)<br>logistic_regression.fit(X_train, y_train)<br><br>y_pred_rf = random_forest.predict(X_test)<br>y_pred_lr = logistic_regression.predict(X_test)<br>y_pred_proba_rf = random_forest.predict_proba(X_test)<br>y_pred_proba_lr = logistic_regression.predict_proba(X_test)<br><br>accuracy_rf = accuracy_score(y_test, y_pred_rf)<br>accuracy_lr = accuracy_score(y_test, y_pred_lr)<br>cw_ece_rf = classwise_ece(y_pred_proba_rf, y_test, num_bins=20)<br>cw_ece_lr = classwise_ece(y_pred_proba_lr, y_test, num_bins=20)<br><br># Print the accuracies<br>print(f&quot;Random Forest Accuracy: {accuracy_rf * 100:.2f}%&quot;)<br>print(f&quot;Logistic Regression Accuracy: {accuracy_lr * 100:.2f}%&quot;)<br><br># print the class-wise ECEs<br>print(f&quot;Random Forest Classwise ECE: {cw_ece_rf * 100:.2f}%&quot;)<br>print(f&quot;Logistic Regression Classwise ECE: {cw_ece_lr * 100:.2f}%&quot;)</pre><pre>Random Forest Accuracy: 93.30%<br>Logistic Regression Accuracy: 74.75%<br>Random Forest Classwise ECE: 2.01%<br>Logistic Regression Classwise ECE: 9.06%</pre><p>Here the random forest once again outperforms the logistic regression model, with an accuracy and class-wise ECE of 93.30% and 2.01% versus 74.75% and 9.06% for the logistic regression model.</p><p>While these class-wise ECE values are the average errors across all the classes, we can also examine the errors for specific classes. This can be useful in some applications, where we may be more interested in a particular class than others.</p><pre>cw_ece_lr, lr_classwise_errors = classwise_ece(y_pred_proba_lr, y_test, num_bins=20, return_classwise_errors=True)<br><br>for label in [0, 1, 2]:<br>    print(f&quot;Class {label} Error: {lr_classwise_errors[label] * 100:.2f}%&quot;)</pre><pre>Class 0 Error: 10.21%<br>Class 1 Error: 9.33%<br>Class 2 Error: 7.65%</pre><p>This returns class-wise errors of 10.21%, 9.33% and 7.65% respectively. Even though the logistic regression model does not appear particularly well-calibrated in general, it is most reliable when it comes to predicting probabilities for the final class.</p><h3>Visualising Calibration</h3><p>As we have seen, we can measure calibration for a given set of predictions, using several different errors. However, there are certain limitations associated with these errors, and they can even be gamed to<br> appear perfect for completely redundant models. Therefore, rather than relying on a single number to tell us how well-calibrated our model is, we can instead visualise this using calibration curves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RZ4K355rq0OcX55eUZ9aKw.png" /><figcaption>A Calibration Curve, showing for each bin, the mean predicted probability (X-axis), versus the fraction of positives (Y-axis).</figcaption></figure><p>Let’s break down what’s happening in the above curve. For each bin, we plot the expected frequency (mean predicted probability) against the actual frequency (fraction of positives, in the binary case). The diagonal line y=x is therefore where expected and actual frequency are equal. In other words, this line represents perfect calibration.</p><p>When the calibration curve lies above this line (y&gt;x), the actual frequency is greater than the expected frequency. For predictions greater than 50%, this represents an under-confident model (as the true frequency is greater than the model predicted). When the calibration curve lies below the diagonal (y&lt;x), the actual frequency is less than the expected frequency. For predictions greater than 50%, this represents an over-confident model (as the model’s expectation exceeds reality). The reverse is true for predictions less than 50%, as shown below [7].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*YsDsmCpSbxPDgVWIEvjUKg.png" /><figcaption>The calibration curve on the left shows an under-confident model, and on the right we see an over-confident model.</figcaption></figure><p>The closer the curve lies to the diagonal, the more well-calibrated the model is. Calibration curves therefore provide an easy means of quickly assessing the reliability of a classifier, at a glance.</p><h3>Visualising Calibration in Python</h3><p>Let’s plot some calibration curves in Python. We will use the predictions generated by the logistic regression model, from the previous example.</p><pre>import matplotlib.pyplot as plt<br>from calibra.plotting import CalibrationCurve<br><br>calibration_curve_lr = CalibrationCurve(y_pred_proba_lr, y_test, num_bins=10)</pre><p>Let’s compare the logistic regression model’s calibration curve for the first class (least well-calibrated) and the final class (most well-calibrated).</p><pre>calibration_curve_lr.plot(class_label=0, label=&#39;Logistic Regression&#39;)<br>plt.title(&#39;Calibration Curve: 1st Class&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*Z3mh7NaFGlBHZ_LttzaxAA.png" /></figure><pre>calibration_curve_lr.plot(class_label=2, label=&#39;Logistic Regression&#39;)<br>plt.title(&#39;Calibration Curve: 3rd Class&#39;)<br>plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*K6p6pcv5rqhBR7nF-_SwUg.png" /></figure><p>Unsurprisingly, a quick glance at these calibration curves tells us what we already know — the logistic regression model is more well-calibrated when it comes to predictions for the final class.</p><h3>Conclusion</h3><p>Calibration is the most important model evaluation measure you’ve probably never heard of. It is a simple, yet powerful measure of the reliability of a classifier. For probabilistic decision-making problems, it is critical that the classifier is well-calibrated. Otherwise, decisions will be informed by unreliable probability estimates. If these decisions have real-world consequences, this could be very costly. Luckily, we can easily measure (and visualise) the calibration of a set of predictions in Python. For probabilistic classification problems, the calibration of the model should always be evaluated, alongside the usual metrics.</p><h3>References</h3><p>[1] <a href="https://proceedings.neurips.cc/paper/2019/file/f8c0c968632845cd133308b1a494967f-Paper.pdf">Kumar, A., Liang, P.S. and Ma, T., 2019. Verified uncertainty calibration. <em>Advances in Neural Information Processing Systems</em>, <em>32</em></a></p><p>[2] <a href="https://proceedings.neurips.cc/paper/2019/file/8ca01ea920679a0fe3728441494041b9-Paper.pdf">Kull, M., Perello Nieto, M., Kängsepp, M., Silva Filho, T., Song, H. and Flach, P., 2019. Beyond temperature scaling: Obtaining well-calibrated multi-class probabilities with dirichlet calibration. <em>Advances in neural information processing systems</em>, <em>32</em>.</a></p><p>[3] <a href="http://proceedings.mlr.press/v70/guo17a.html">Guo, C., Pleiss, G., Sun, Y. and Weinberger, K.Q., 2017, July. On calibration of modern neural networks. In <em>International conference on machine learning</em> (pp. 1321–1330). PMLR.</a></p><p>[4]<a href="https://citeseerx.ist.psu.edu/document?repid=rep1&amp;type=pdf&amp;doi=04e10f745a7267453788a22f5150b5a32b2b3951"> Zadrozny, B. and Elkan, C., 2002, July. Transforming classifier scores into accurate multiclass probability estimates. In <em>Proceedings of the eighth ACM SIGKDD international conference on Knowledge discovery and data mining</em> (pp. 694–699).</a></p><p>[5] <a href="https://proceedings.neurips.cc/paper/2019/file/1c336b8080f82bcc2cd2499b4c57261d-Paper.pdf">Widmann, D., Lindsten, F. and Zachariah, D., 2019. Calibration tests in multi-class classification: A unifying framework. <em>Advances in neural information processing systems</em>, <em>32</em>.</a></p><p>[6] <a href="https://github.com/conorwalsh99/calibra">Walsh, C. (n.d.) <em>calibra</em>. GitHub. Available at: https://github.com/conorwalsh99/calibra (Accessed: 24 October 2024).</a></p><p>[7] <a href="https://link.springer.com/content/pdf/10.1007/s10994-023-06336-7.pdf">Silva Filho, T., Song, H., Perello-Nieto, M., Santos-Rodriguez, R., Kull, M. and Flach, P., 2023. Classifier calibration: a survey on how to assess and improve predicted class probabilities. <em>Machine Learning</em>, <em>112</em>(9), pp.3211–3260.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5a9f56173af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>