<?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 Rodrigo Morales on Medium]]></title>
        <description><![CDATA[Stories by Rodrigo Morales on Medium]]></description>
        <link>https://medium.com/@romoflow?source=rss-d58d1cf73159------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y3N1_7FMfmoilgMUNfxBoQ.png</url>
            <title>Stories by Rodrigo Morales on Medium</title>
            <link>https://medium.com/@romoflow?source=rss-d58d1cf73159------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:28:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romoflow/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[Bridging minds and machines]]></title>
            <link>https://medium.com/@romoflow/bridging-minds-and-machines-8087c8203d33?source=rss-d58d1cf73159------2</link>
            <guid isPermaLink="false">https://medium.com/p/8087c8203d33</guid>
            <category><![CDATA[brain-computer-interface]]></category>
            <category><![CDATA[neural-decoding]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neuro-ai]]></category>
            <dc:creator><![CDATA[Rodrigo Morales]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 22:46:09 GMT</pubDate>
            <atom:updated>2025-11-12T22:46:09.238Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep learning for neural decoding in brain-computer interfaces</h4><p>Look for a nearby object and pick it up. Notice that once you decide to do this, your body seamlessly executes your intention and, almost magically, an instant later you are already holding the object. This can give the illusion that performing such an act is a simple matter, but if we dive deeper into how your nervous system orchestrates this, it is far from simple.</p><p>This remarkable process involves countless neurons in your motor cortex encoding your intended action as specific patterns of activity that are successively propagated and transformed into new ones by populations of neurons in different parts of your brain. These patterns then reach your spinal cord where they are decoded into the precise signals to produce the muscles contractions that result in you reaching and grasping the object. Apparently ordinary actions like moving around and speaking your mind are in fact quite extraordinary.</p><p>Sadly, for millions this mirage of simplicity has been shattered by conditions like amyotrophic lateral sclerosis (ALS), stroke, or spinal cord injury. For them, movement and speech, among many other cognitive capabilities, are no longer a reality, since damaged tissue in their nervous system impedes the full realization of their intentions. For instance, in cases with spinal cord damage, the motor cortex and the rest of the brain areas might perform their regular activity patterns to initiate the desired movement, but the injured spinal cord can no longer interpret these signals from the brain and command the necessary muscle contractions.</p><p>Brain-computer interfaces (BCIs) are a technology that can transform the life of people suffering from these conditions by helping to restore some of the lost functions. A BCI is a system that enables a person to operate a device, like a prosthetic limb or a speech synthesiser, by using only their <a href="https://www.youtube.com/watch?v=QRt8QCx3BCo">thoughts</a>.</p><p>When the user thinks of performing an action with the device, the system should record and interpret the associated neural activity to then execute the intended action. So, a crucial step in this process is to accurately infer the intention from the neural activity, a process known as neural decoding. For example, in a task called motor imagery, the user imagines performing a specific movement like grasping with the right hand while the system records the concurrent neural activity. Then, the imagined movement needs to be decoded from this recording.</p><p>Neural decoding is a difficult problem that requires finding complex patterns hidden in the high-dimensional, noisy neural recordings. Fortunately, over the last years, we have seen astonishing technological developments in systems adept at complex pattern recognition: the deep neural networks behind state-of-the-art AI systems. It is, then, no surprise that deep learning is increasingly being adopted for neural decoding and is starting to revolutionize the field, enabling more powerful BCIs. However, we are still in the early days of this paradigm shift and there are many lessons from the development of AI that could be borrowed for neural decoding.</p><p>So, in this article we will discuss in more detail the role that deep learning is playing in neural decoding and the main advantages it provides. Borrowing from lessons in other AI applications, we will also explore some areas of opportunity that remain open for this paradigm to fulfill its great promise in neural decoding. Finally, we point out some challenges unique to real-world BCI applications that should be considered when applying deep learning in this domain.</p><h4>The role of deep learning in neural decoding</h4><p>To better understand how deep learning enhances neural decoding, it is useful to break down the full process. As mentioned above, the end goal is to infer some target variable, like a movement intention or a phoneme to be spoken, from the neural activity recorded from the brain. So, the first step is to record such activity from brain areas that are likely to be relevant for the specific decoding task, such as the primary motor cortex (M1) that plays a central role in the initiation of voluntary movement or the ventral motor cortex (vMC) involved in the control of the muscles responsible for speech articulation.</p><p>There are various methods for recording brain activity with different trade-offs in terms of practicality, resolution, and cost. A common non-invasive choice is electroencephalography (EEG) which involves placing electrodes on the scalp to detect voltage fluctuations resulting from the underlying neural activity. It has high temporal resolution, which means it is good at detecting when the measured activity occurred, but low spatial resolution, which means it is not great at pinpointing exactly where in the brain it occurred. It is a portable, low cost option with a relatively simple setup that makes it attractive for BCI applications.</p><p>On the other hand, a common invasive approach is electrocorticography (ECoG) which involves placing electrodes on the surface of the brain beneath the skull. This allows to measure the neural electrical signals more directly, leading to higher temporal and spatial resolution. However, the setup is costlier and riskier as it requires a surgical procedure to implant the electrodes.</p><p>Some techniques do not directly record the brain’s voltage variations, but rather a proxy, like changes in blood oxygenation correlated with neural activity. Functional near-infrared spectroscopy (fNIRS) is a non-invasive approach that measures this signal by sending light in the near-infrared spectrum through the scalp and skull to quantify changes of blood oxygenation in the underlying brain tissue. It is a low cost, portable option with a simple set up, low temporal resolution, and medium spatial resolution.</p><p>Other methods often used in research studies are functional magnetic resonance imaging (fMRI) and magnetoencephalography (MEG), but these have limited viability for practical BCI applications as they require the use of bulky equipment in special rooms, which makes them costly and non-portable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNiDX5KCn0YEe6YqW0jZTQ.png" /><figcaption><strong>Summary of common recording methods.</strong> Images sources: <a href="https://commons.wikimedia.org/wiki/File:EEG_Neurotech.jpg">EEG</a>, <a href="https://commons.wikimedia.org/wiki/File:Intracranial_electrode_grid_for_electrocorticography.png">ECoG</a>, <a href="https://commons.wikimedia.org/wiki/File:Blonde_fNIRS_lady.jpg">fNIRS</a>, <a href="https://commons.wikimedia.org/wiki/File:190603_Functional_magnetic_resonance_imaging_at_the_Imperial_Centre_for_Psychedelic_Research.jpg">fMRI</a>, <a href="https://commons.wikimedia.org/wiki/File:NIMH_MEG.jpg">MEG</a>.</figcaption></figure><p>Once the neural activity is recorded, the challenge is then to train a model to use that data as input and output the decoding target variable. It is here where deep learning plays a pivotal role, since this essentially requires associating complex patterns in the data with the decoding variable, a task at which deep neural networks excel. In this regard, deep learning brings two major advantages: increasing the predictive accuracy with which the target variable can be decoded and reducing the amount of manual data preprocessing required by previous approaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EAQZXnTUpoiUOf0U-QG2g.png" /><figcaption><strong>Deep learning for neural decoding. </strong>Using neural recordings as input data, a neural network can be trained to output the decoding target. Images sources: <a href="https://commons.wikimedia.org/wiki/File:EEG_Cap_-_The_Noun_Project.svg">EEG Cap</a>, <a href="https://commons.wikimedia.org/wiki/File:ElectroEncephalogram.png">Electroencephalogram</a>, <a href="https://commons.wikimedia.org/wiki/File:Neural_network.svg">Neural Network</a>.</figcaption></figure><p>Traditional decoding approaches require intensive preprocessing to extract relevant features from the raw data in a process called feature engineering. In this paradigm, the effectiveness of the approach relies heavily on the pre-defined set of features, also called a representation, computed to solve the decoding task. In contrast, deep neural networks can automatically learn hierarchical representations from the raw data, where each layer of the network learns to compute a set of features, which are then the input for the next layer to compose them into more complex ones.</p><p>The initial layers might learn basic features, such as simple frequency components in the data. Subsequent layers then combine these basic features to form more complex representations, like patterns of brain activity related to specific movements. Crucially, this mapping is adjusted based on the feedback received from the errors in decoding the target variable, which encourages the model to learn features that are useful to solve the decoding task.</p><p>This learning approach allows the network to automatically discover a highly flexible mapping from the raw inputs to the decoding output. This makes it a more scalable approach by reducing the burden on the engineers of the system to design and test a potentially large set of different features. Moreover, the mappings learnt can contain more complex and subtler patterns that would have been difficult to explicitly specify in advance, but are highly relevant to the task. Ultimately, this results in improved performance when decoding the target variable.</p><p>There is already abundant research showcasing the added flexibility and better performance achieved by deep learning approaches compared to previous ones. For instance, deep learning approaches outperform traditional feature engineering in a common benchmark of <a href="https://doi.org/10.3389/fnins.2022.1003984">motor imagery using EEG data</a> from the BCI Competition IV, as well as in a <a href="https://doi.org/10.1007/978-3-030-46931-3_18">mental arithmetic task with fNIRS data</a>. There are numerous other examples of deep learning outperforming traditional approaches <a href="https://doi.org/10.1093/bib/bbaa355">across tasks and modalities</a>.</p><p>So, as the potential for better performance and greater scalability of deep learning in neural decoding becomes increasingly clear, its adoption in the BCI community is growing as well. However, its full potential remains largely untapped. Recent advancements in AI applications suggest areas of opportunity for deep learning to further enhance neural decoding. Yet, as these advancements are pursued, care must be taken to address particular challenges faced by BCI applications beyond predictive performance, so that they can truly materialize in real-world usage.</p><h4>Opportunities for deep learning in neural decoding</h4><p>Large-scale datasets enable the training of larger, deeper networks that are capable of learning more complex representations and achieving enhanced performance. However, adequately recording and, especially, labelling data for a neural decoding task is costly, time-consuming, and full of practical challenges, which often limit the scale of the endeavour. Instead, research studies usually rely on relatively small-scale datasets with a few subjects and samples, limiting the performance enhancements from deep learning.</p><p>Self-supervised learning is a flexible framework for training neural networks that helps to address this issue by leveraging large amounts of unlabelled data, which are easier to gather. With this approach, a deep neural network is first trained to solve a pretext task that does not require manual labelling. After this pre-training stage, the network is then fine-tuned to solve the actual objective task. This fine-tuning does require labelled data, but substantially less than if the model were being trained from scratch.</p><p>As an illustrative example, this framework is how large language models (LLMs) are trained on vast amounts of label-free text data. In this case, the pretext task is predicting the next word in a sentence. This allows the model to learn the general patterns and structure of the data, like the correct grammar of a language and what words tend to co-occur. Then, this forms the basis for fine-tuning the network in an actual objective task, such as building an assisting chatbot on top of the base LLM.</p><p>This approach has seen tremendous success in AI, and there is ongoing research to apply it in neural decoding. For instance, in motor imagery with EEG data, networks are pre-trained using pretext tasks like <a href="https://doi.org/10.1109/TNSRE.2022.3199363">predicting the next slice of data</a> or applying different transformations to it (e.g., rearranging or flipping it) for the network to <a href="https://doi.org/10.1088/1741-2552/ad48bc">identify the type of transformation applied</a>. After fine-tuning in the actual motor imagery task, the network achieves enhanced performance by leveraging the representations learnt during pre-training. <a href="https://doi.org/10.48550/arXiv.2406.04328">Similar work in speech decoding with MEG</a> data also combines different datasets, showcasing the capacity of the self-supervised framework to find general structure in diverse neural data.</p><p>Another way to enhance the effectiveness of neural networks is to enrich the information contained in the data used to train them. Data fusion is a powerful approach to achieve this by combining data obtained from recording with multiple methods simultaneously.</p><p>As we mentioned earlier, different recording modalities have different strengths in terms of spatial and temporal resolution; however, a combination of them can leverage their complementary advantages to provide a more complete view of the neural activity. For instance, combining the strong temporal resolution of EEG with the spatial resolution of fNIRS is proving particularly effective. Moreover, both are non-invasive, low-cost, and portable approaches which makes them suitable for BCI applications.</p><p><a href="https://hal.science/hal-04636122v1">Fusion can be performed at three stages of processing</a>: the entry level, where the raw data is combined; the feature level, where features are extracted independently from each modality and then combined; and the decision level, where separate models are trained for each modality and then their predictions are combined. In decision-level and feature-level fusion, each modality can be processed somewhat independently, and the integration occurs at later stages of processing. In contrast, entry-level fusion requires early integration of the heterogeneous data to process it together.</p><p>Deep neural networks are highly suitable for fusion, since their flexibility allows them to process heterogeneous data from multiple sources and integrate them at different stages of processing. For example, <a href="https://doi.org/10.1109/TBME.2021.3132861">some work</a> has effectively applied feature-level fusion of EEG and fNIRS data to decode spoken and imagined speech outperforming approaches using each modality in isolation.</p><p>However, deep learning’s greatest potential can be harnessed with early fusion because this allows leveraging the correlations, interactions, and synergies between the modalities to learn richer features from the multimodal raw data. This has already been <a href="https://doi.org/10.1109/TNSRE.2022.3149899">shown in motor imagery</a> where an early fusion of EEG and fNIRS data outperformed not only approaches using each modality in isolation but also state-of-the-art late fusion approaches.</p><p>Extensive datasets are not only required for training neural networks but are also crucial for evaluating and benchmarking their performance. Large-scale, standardized benchmarks enable a proper comparison between different algorithms and highlight challenging aspects of a problem to help focus efforts in addressing them. They are crucial to track and catalyze progress in a field, as has been clearly shown in AI applications where they have been a powerful driver of the amazing progress that the field has experienced over more than a decade.</p><p>In neural decoding, there are open datasets from past <a href="https://www.bbci.de/competition/iv/">BCI competitions</a> and other benchmarks for various tasks, but they are not as universally adopted nor do they have the scale to serve as a unifying standard to track and catalyze the progress of deep learning approaches. This prevents a thorough comparison of different algorithms, making it difficult to assess which methods are state-of-the-art in various decoding problems and to use them as a base for further improvement.</p><p>The challenges for building large-scale benchmarks are not only those associated with the costs of recording and labeling neural data, which we already mentioned, but also the difficulties with standardising heterogeneous neural datasets. Even within a single domain and modality, such as motor imagery with EEG, there are numerous datasets, but they are scattered and use different recording configurations and task specifications which makes integrating them into a single suite for training and evaluation far from trivial.</p><p>There are, however, ongoing efforts to achieve this. For instance, the <a href="https://neurotechx.github.io/moabb/">Mother of all BCI Benchmarks (MOABB)</a> collects <a href="https://hal.science/hal-04537061">36 distinct EEG datasets across three task categories</a> (e.g., motor imagery). It is a significant step towards standardized, open benchmarks, and one of its key contributions is showing that an algorithm’s performance can vary substantially across different datasets, stressing the need for comprehensive benchmarks. However, as the collection consists of relatively small datasets independently used for training and evaluation, it limits the realization of deep learning’s major benefit: learning representations from large-scale data.</p><p>Another promising effort in this direction is <a href="https://doi.org/10.48550/arXiv.2406.07151">EEG-IMAGENET</a>, a unified dataset of recordings from 16 participants exposed to 4000 images containing objects from 80 distinct categories for visual decoding. Its scale, being 5 times larger than similar benchmarks, is better suited for evaluating deep learning algorithms, and it has helped in establishing the state-of-the-art performance in two decoding tasks: reconstruction of the image viewed and classification of the object’s category in it. Overall, more contributions of this kind are needed across tasks and modalities.</p><p>There are many other promising and active research directions to enhance the predictive performance of deep learning in neural decoding, but the ones we have discussed have been crucial for the successful development of other AI applications. This brings hope that their success will transfer to neural decoding, enabling more powerful BCIs. However, this domain poses some unique challenges, both technical and ethical, that will need to be addressed in the process.</p><h4>Neural decoding is not just another AI application</h4><p>From a technical standpoint, computational efficiency is a critical constraint in BCIs. Maintaining system latency at a minimum is paramount, as even a few seconds’ delay between thought and action can render a BCI impractical. Offloading the processing to powerful cloud servers, as is common in other AI applications, can introduce unacceptable levels of latency. So, on-device computation should be maximized, but, also, BCI devices need to remain lightweight for portability.</p><p>High throughput is also crucial, as this can make an enormous difference for a BCI user. For instance, achieving a decoding rate nearing 150 words per minute would close the gap with the average talking speed, enabling fully practical communication. Altogether, the requirements of high throughput and low latency combined with the hardware limitations stress the necessity for decoding algorithms to be not only accurate, but also efficient.</p><p>This is particularly relevant for deep learning, considering that the advancements we have discussed imply scaling up deep neural networks, and this naturally translates into higher computational requirements. So, an additional effort will need to be made to achieve this in an efficient way for them to remain a viable option for real-world BCIs.</p><p>Encouragingly, a great amount of effort and capital is being invested in both software (e.g., model distillation) and hardware (e.g., more advanced chips) improvements to make neural networks run more efficiently with continual breakthroughs pushing the frontier of possibilities. So, a combination of these advances with ingenuity in the development of the decoding networks can enable them as practical options for BCIs.</p><p>Another particular aspect of decoding is that it is a highly dynamic problem, where sustained strong performance is difficult to achieve. To begin with, there is cross-subject variability that can cause a model trained to decode one person’s intentions to not transfer directly to a different person without some prior calibration.</p><p>Moreover, there is also within-subject variability that can come from physiological sources, as the brain is constantly changing, or technical sources, like an electrode position moving after being implanted. In either case, a decoding algorithm that works at a particular point in time for a given person is not guaranteed to work for a prolonged period even for that same person.</p><p>To increase their practicality, decoding algorithms need to be able to adapt to these changing environments, which is something that deep learning approaches tend to struggle with. So, effort will need to be spent in developing not only accurate and efficient deep neural networks, but also adaptive ones.</p><p>Finally, neural data is not simply another kind of data. From a privacy perspective, it is on a tier of its own. This becomes more relevant as recording techniques and decoding algorithms improve and more granular information about a person’s thoughts, intentions, and cognitive state can be inferred from recordings.</p><p>Widely-accepted guidelines to properly deal with this data in order to preserve the privacy of the users and ensure that it is used for their benefit and not to their detriment are yet to be defined. As deep learning approaches enhance predictive accuracy, addressing the societal questions about the proper use of neural data will become more pressing. Ethical and regulatory frameworks will need to be established to safeguard the applications built on top of this data and help in building users’ trust.</p><p>Deep learning is an exciting prospect for the advancement of neural decoding to enable more powerful BCIs. While its potential to enhance accuracy is becoming increasingly clear and its adoption is growing, there are still many untapped opportunities to fully leverage the capabilities of this powerful paradigm. Yet, as this progress occurs, some challenges, ranging from technical to societal, will need to be addressed for this approach to fully deliver on its promise of positively transforming the lives of millions.</p><p><em>Originally published on </em><a href="https://ofcarbonandsilicon.substack.com/p/bridging-minds-and-machines?r=29bckd"><em>Of Carbon &amp; Silicon</em></a>, <em>my publication exploring AI, neuroscience, and their intersection. </em><a href="https://ofcarbonandsilicon.substack.com/subscribe"><em>Subscribe</em></a><em> to receive future articles directly.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8087c8203d33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Of Carbon & Silicon]]></title>
            <link>https://medium.com/@romoflow/of-carbon-silicon-a03d26705a5f?source=rss-d58d1cf73159------2</link>
            <guid isPermaLink="false">https://medium.com/p/a03d26705a5f</guid>
            <category><![CDATA[neuro-ai]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rodrigo Morales]]></dc:creator>
            <pubDate>Thu, 23 Oct 2025 20:55:32 GMT</pubDate>
            <atom:updated>2025-10-23T20:55:32.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding AI, Neuroscience, and NeuroAI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*7NGfvNiWQEIblL2ijAI0RA.png" /></figure><p>Creating artificial systems that match and surpass human intelligence is one of humanity’s most ambitious pursuits. Understanding how the brain gives rise to the faculties of an intelligent mind is one of life’s most profound questions. What is even more fascinating is that these two endeavours are deeply intertwined. Insights from neuroscience have been a source of inspiration in the design of AI systems that, in turn, are revolutionizing the study of the brain. Can AI hold the key to unlock the mysteries of the brain’s inner workings? Can this deeper understanding inspire further advancements in AI?</p><p>To delve into these fascinating questions, I’m launching a new publication: <a href="https://ofcarbonandsilicon.substack.com/"><em>Of Carbon &amp; Silicon</em></a>. Here, we disentangle the fundamental concepts behind AI breakthroughs from the noise surrounding them. We examine the role AI is playing in shaping discoveries in neuroscience. We reflect on novel insights into the principles of brain function and hypothesise how they could influence future AI systems. We approach this rigorously while prioritising clarity: technical details are included only when they serve to illuminate core ideas.</p><p>Whether you’re an AI scientist or engineer, a neuroscientist or neural engineer, or simply someone curious about natural and artificial intelligence, here you’ll find insights to expand your understanding of both brains and machines. If, like me, you are fascinated by these questions, I invite you to <a href="https://ofcarbonandsilicon.substack.com/embed">subscribe</a> to this publication and don’t miss out on this journey to explore the frontier of AI, neuroscience, and their intersection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a03d26705a5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you see what I see?]]></title>
            <link>https://medium.com/@romoflow/do-you-see-what-i-see-f7fdf281f2c0?source=rss-d58d1cf73159------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7fdf281f2c0</guid>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[representation-learning]]></category>
            <category><![CDATA[neuro-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[computationalneuroscience]]></category>
            <dc:creator><![CDATA[Rodrigo Morales]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 21:48:02 GMT</pubDate>
            <atom:updated>2024-12-18T21:48:02.460Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparing brain and AI representations with Representational Similarity Analysis</h4><p>Going for a walk might appear like an effortless activity, but inside your brain billions of neurons are firing activity patterns that allow you to make sense of the outside world. For instance, your brain needs to make sense of the visual scene by detecting the edges of the sidewalk, the shapes of objects, and potential obstacles like moving cars in your path. It needs to understand the sounds surrounding you by parsing the pitch, rhythm, and, ultimately, the meaning of words spoken nearby. It needs to identify landmarks, checkpoints, and their relative positions to build a mental map of your route. The patterns of neuronal activity encoding these and many other aspects of the outside world are called internal representations and are the means by which your brain internalises the information you are perceiving to effectively process it and direct follow-up behaviour.</p><p>Representations also play a crucial role in the effectiveness of deep artificial neural networks (ANNs) powering cutting-edge AI systems. Perhaps the most distinguishable feature of this revolutionary paradigm is its ability to learn useful representations from data to solve the task at hand. For example, a network can learn to encode features like edges, shapes, and textures from images. It can then learn to compose these simple features into more complex ones like faces or vehicle parts in order to recognize the objects in the images. Analogous to how it is done by neuronal activity in the brain, these features are encoded in the patterns of activations of the network’s computational units along the sequential layers of processing by which its input is transformed into new representations that allow the network to accomplish its goal.</p><p>Given the conceptual resemblance with which ANNs and the brain encode internal representations and the growing ability of AI systems to replicate (and surpass) human-like performance across tasks in various domains, it is natural to wonder if the representations learned by the layers of computational units in ANNs are similar to those encoded by neuron populations in the brain. Representational Similarity Analysis (RSA) is a computational neuroscience approach to quantitatively answer this question.</p><p>RSA was introduced by Nikolaus Kriegeskorte, Marieke Mur, and Peter Bandettini in <a href="https://www.frontiersin.org/journals/systems-neuroscience/articles/10.3389/neuro.06.004.2008/full"><em>Representational similarity analysis — connecting the branches of systems neuroscience</em></a>. While it is not the only approach to compare representations in the brain and in computational systems, it is one of the most widely used in the academic literature because of its simplicity and flexibility. RSA has other applications, mentioned in the paper, like comparing representations across species and relating neural recordings to behaviour, but these will not be our focus. Specifically, in this article, we will delve into how RSA works, explore its role in comparing representations between neuron populations and ANNs, and discuss key factors to consider when using this method.</p><h3>The RSA approach</h3><p>The core idea behind RSA is that two representations are similar if the patterns of differences in how they encode distinct stimuli are alike. Given a set of stimuli, the method summarizes a representation as a matrix that measures how dissimilarly it encodes all the different pairs of stimuli. Then, to compare different representations we can simply compare their signature dissimilarity matrices. In the rest of this section, we unpack this procedure.</p><p>To illustrate each step of RSA, we construct a very simple example. Suppose we have four stimuli consisting of images displaying a blue bar. The bar on each image has a different orientation and color intensity as shown in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*c8kkZA6Ga5UMLY7j0BNGww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mWRl-Zv9RLyJStO16a7FoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mnFcWQqBpcHevy42Qyf6mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*jk35eEftzUkNNWWYMNie8Q.png" /><figcaption><strong>Figure 1. Stimuli set. </strong>To illustrate RSA, we consider a set of four images of blue bars with different degrees of orientation and color intensity. Image by author.</figcaption></figure><p>Then, let’s consider three distinct stylized populations of neurons:</p><ol><li>The “Preferred Orientation” population consists of 10 neurons. Each has a distinct preferred orientation to which it maximally responds. The response decays exponentially as the stimulus orientation drifts from the neuron’s preferred one.</li><li>The “Threshold orientation” population consists of 5 neurons. Each responds only to stimuli with an orientation above its threshold. Once the orientation exceeds the neuron’s threshold, its activity starts to increase following an “S-shaped” logistic curve.</li><li>The “Preferred intensity” population. Analogous to the preferred orientation population, each of the 10 neurons in this population has a preferred color intensity. Each neuron’s response also decays exponentially as the stimulus color intensity drifts from its preferred one, independently of the orientation.</li></ol><p>The tuning curves showing the response of each neuron in the populations to the stimulus property to which they are selective are shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*n5diQ6HVGMifapL5WO3Osw.png" /><figcaption><strong>Figure 2. Tuning curves of neurons population. </strong>Each curve represents the response of a neuron in the respective population depending on the parameter (orientation or color intensity) value of the stimulus. Image by author.</figcaption></figure><p>Now, to perform RSA, we first need to obtain the internal representation of the populations of interest. In the case of the brain, this is obtained by recording the activity of the populations that we suspect would encode some properties of the stimuli when exposed to them. Crucially, RSA is agnostic to the recording modality. For instance, it can compare direct measurements of neuronal electrical activity obtained via electrophysiology to correlated signals, such as the hemodynamic response measured with fMRI. In our example, since we are simulating the neurons’ responses, we can simply evaluate their tuning curves on the respective parameter value (orientation or intensity) of each of the four stimuli. These are shown in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_EvpGa0QCJqpR7pu8CgF6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t4rimbkxd3XekicCbgRnAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wuga_WGoeFI4HZWMywaKDg.png" /><figcaption><strong>Figure 3. Populations responses to stimuli. </strong>Each row corresponds to the population’s responses to the stimulus displayed on the left. Each column corresponds to the activity of a neuron responding to the different stimuli. Note that only neurons for which the stimuli parameter fits within their range of selective values show positive activity. Image by author.</figcaption></figure><p>Then, given each population’s responses, the next step is to summarize the representation into a dissimilarity matrix, adequately called Representational Dissimilarity Matrix (RDM). An RDM is a square matrix of size <em>S×S,</em> where <em>S</em> is the number of stimuli. Each entry in the matrix quantifies the dissimilarity between the representations of a pair of stimuli. For instance, the entry in the first row and second column measures the dissimilarity between the population response to the first and second stimuli. The ordering of the stimuli can be arbitrary, but an ordering based on some property, like color or orientation, can make a visual analysis of the RDM easier, especially when the set of stimuli is large.</p><p>To compute the dissimilarity values between the pairs of stimulus-evoked responses that fill the RDM, we need to choose a dissimilarity or distance metric. This is an important design choice as it can have a meaningful impact on the conclusions of the analysis. In many cases, the correlation distance is a good choice, because, as mentioned in the paper introducing RSA, “it is invariant to differences in the mean and variability of the dissimilarities.” This distance metric is computed as:<em> 1-r, </em>where <em>r </em>is the Pearson correlation coefficient between the two sets of responses corresponding to the pair of stimuli being compared. It can range between 0, indicating the lowest dissimilarity, and 2, indicating the highest dissimilarity. Note that, by construction, the RDM will be symmetric, as long as an appropriately symmetric distance metric is used.</p><p>Following along with our example, we compute the RDM for each of the three populations described above using the correlation distance suggested in the paper. These are shown in Figure 4. Note that for the orientation-selective populations, the representations between stimuli with similar orientation are less dissimilar, whereas for the other population, stimuli with the same color intensity have a dissimilarity of 0. In this simple example, a visual inspection of the RDMs immediately shows that the two orientation-selective representations have closer dissimilarity patterns between themselves than to the population selective to color intensity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2P4EMwaaam8k3XZFJcwRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-zvlvy0pIQQbn1C1mxVJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcFY6LUQ_ITFAmkLPqWfKw.png" /><figcaption><strong>Figure 4. RDMs of the three populations. </strong>Each entry in the matrix represents the dissimilarity between the representations of the respective pair of stimuli. By construction, the matrices are symmetric and have zero dissimilarity along the diagonal (since each stimulus representation is identical to itself). Image by author.</figcaption></figure><p>By summarizing the representations into an RDM, we abstract away details like the size of the populations, the modality used to record from them, or even if we are dealing with biological or artificial populations. In every case, we end up with an RDM representing the differences in how each population encodes the different stimuli and serving as the signature of its representations. This enables us to directly compare two sets of representations by simply comparing their RDMs, and if the RDMs are similar we consider the respective representations to be similar. In other words, we consider the representations to be similar if the differences in how they encode different stimuli are similar, or, as the RSA paper puts it, we “assess second-order dissimilarity: the dissimilarity of dissimilarity matrices”.</p><p>So, to conclude with the RSA, we perform the comparison of RDMs using a similarity metric. This metric does not need to be the same as the one used to construct the RDMs. In fact, the the RSA paper suggests using the Spearman’s rank correlation coefficient for this purpose, since, besides being robust to differences in the mean and variance of the variables compared, like the Pearson correlation coefficient used for the RDMs, it can also capture monotonic non-linear associations between them. Since the RDMs are symmetric, we just need to compute the similarity between the values of their upper (or lower) triangular. This will result in a single number ranging from -1 to 1 which we interpret as a score of how similarly the two populations encode the different stimuli presented to them.</p><p>In our example, we proceed in this way to obtain a similarity of 0.88 between the preferred orientation and threshold orientation populations, of -0.36 between the preferred orientation and preferred intensity populations, and of -0.43 between the threshold orientation and preferred intensity populations. These results are unsurprising, since the two populations which, by design, are responsive to the orientation of the bar encode similar representations and have a high representational similarity. Moreover, both of them have a low representational similarity with the population that responds to color intensity instead of orientation.</p><p>In a simple example like this, the conclusion was straightforward to see without going through the trouble of performing RSA, but it served to illustrate the rationale behind RSA and how to perform it. In practice, RSA is a powerful approach that can deal with more complex populations encoding more complex features from more complex stimuli.</p><h3>RSA with artificial neural networks</h3><p>Now, we’ll see how RSA allows to compare representations encoded by neurons to representations encoded by computational units in ANNs. Deep ANNs are composed of multiple layers of processing. The initial layer receives the raw stimulus and maps it to a new representation, which is then passed on to the next layer. In this way, each subsequent layer transforms the representation it receives into a new one, which is forwarded to the following layer. So, each layer encodes a representation which can be examined by analyzing the activation values of its units which collectively produce the output representation.</p><p>The purpose of the transformations done across the layers of the network is to progressively build a representation that enables the network to accomplish its objective task. So, the network must be trained on a task where the stimulus properties we want to analyze are relevant. For instance, if we are interested in visual features, we should train the network on a visual task for which these features are useful and, therefore, are likely to be encoded in the network’s representations. Moreover, the representations built by deep networks are hierarchical: earlier layers tend to encode simple features which are then composed into more complex ones in later layers. For example, the encoding of simple features like edges is more likely to occur in the earlier layers of a convolutional network, whereas more complex features like faces are more likely to be encoded in the final layers.</p><p>We continue with the oriented blue bars example to showcase how we can use RSA with an ANN. For this purpose, we train a simple convolutional neural network (CNN) consisting of a convolutional layer with max pooling followed by a fully connected layer to identify the orientation of the bar in the stimuli images. However, four examples won’t suffice to properly train the network, so we generate more images of this kind, but with different orientation and color intensity values. Then, after training the network, we can inspect its representations of the four stimuli we used for the RSA example as shown in Figure 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SY-_xDJcmcNv7tMeW0zndw.png" /><figcaption><strong>Figure 5. Activation values of the units in the final hidden layer of the CNN for the different input stimuli. </strong>Image by author</figcaption></figure><p>Here, we consider only the activations of the 160 units preceding the final fully connected layer as these should contain the encoded orientation of the bar in the image required to make the final prediction, but in practice, for more complex cases, it is better to consider the activations from various different layers as it is difficult to anticipate exactly what kinds of features each layer will encode.</p><p>Now, we can proceed to construct the RDM for these representations. As described in the previous section, we compute the correlation dissimilarity across the four sets of activations corresponding to each stimulus. The resulting RDM is shown in the left panel of Figure 6. Finally, we compare this with each of the RDMs of the three neuron populations from the previous section by computing the Spearman rank correlation between the values in their respective upper (or lower) triangular. The resulting similarity scores are shown in the right panel of Figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9SHoOEmFdijUOTHHg-e5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*mN99xc379OAK_xTFSCjfLA.png" /><figcaption><strong>Figure 6. Left: RDM of the final hidden layer of the CNN. Right: Representational similarity between the CNN’s final hidden layer and the neurons populations. </strong>The hidden layer’s representations of bars with similar orientations are less dissimilar which translates in a higher representational similarity with the orientation-selective populations. Image by author.</figcaption></figure><p>The CNN has a high representational similarity with the orientation-selective populations, which indicates that they all encode similar features of the stimuli. In this case, we know that the shared feature is precisely the orientation of the bar. Notably, the population with the highest representational similarity to the CNN is the threshold orientation population. This is, most likely, because each computational unit in the CNN performs a threshold-based, non-linear computation to generate its output. However, in more complex cases one must be cautious when interpreting common computational mechanisms in RSA, since these cannot be inferred from representational similarity alone. On the other hand, the CNN has the lowest similarity with the population selective to color intensity, which indicates that the network is not encoding the color intensity as it is not required to solve its orientation prediction task.</p><p>Beyond our didactical example, there are studies using RSA in the academic literature to explore interesting similarities between biological and artificial representations. A notable example is the work by Seyed-Mahdi Khaligh-Razavi and Nikolaus Kriegeskorte in <a href="https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003915"><em>Deep Supervised, but Not Unsupervised, Models May Explain IT Cortical Representation</em></a>, where they compare the representations from CNNs and other computational models of the visual system with those recorded from the <a href="http://www.scholarpedia.org/article/Inferior_temporal_cortex">inferior temporal (IT) cortex</a> of humans and monkeys, which is an area that serves a primary role in visual recognition. Their main conclusion is that the final layer of a deep CNN pre-trained to perform object recognition has the highest representational similarity with both the human’s and monkey’s IT representation of the same set of images.</p><h3>Limitations of RSA and conclusion</h3><p>RSA is not without its limitations. As the RSA paper warns, the method might produce unreliable results when the stimuli set is small. We can see this in the oriented blue bars example. Note (in Figure 1) that as the bar rotates around its fixed lower-left corner, its upper edge position changes accordingly (as if it were the end of a clock hand). So, a representation encoding the orientation angle would be highly correlated with a representation encoding the coordinates of the edge position, making them indistinguishable through the lens of RSA. Given their high representational similarity, we could interpret that both encode the same feature of the stimuli while in fact they do not.</p><p>We can mitigate this issue by expanding the stimuli set, for instance, by varying the position of the bar’s centre of rotation, so that we include images with equally-oriented bars on different positions of the image. RSA with this enriched stimuli set could disentangle a representation that encodes orientation from one that encodes position. In general, the more varied the stimuli set, the more effective RSA will be.</p><p>Finally, we should be careful to not overinterpret the results of RSA. As we mentioned before, a high representational similarity does not imply that the two systems being compared reached their representations by a common mechanism. In general, RSA alone cannot even determine exactly what features of the stimuli the representations share. Two representations can be correlated and yet encode different aspects of the stimuli as we explained above with the orientation and position of the bars in the example. This is a particularly insidious risk with more complex stimuli. For instance, if two representations discern equally well human faces from animal faces there are multiple features that can be used for this purpose and RSA, even with a very rich stimuli set, probably will not be able to completely distinguish the ones that the representations are considering.</p><p>Despite these caveats, RSA remains an effective, simple, and highly flexible method to compare representations from different populations of neurons, both biological and artificial. The approach relies on measuring the representational similarity of stimuli dissimilarities. It can compare representations across brain areas, recording modalities, species, and between biological and artificial networks of neurons. It enables a wide range of use cases based on understanding how different neural representations relate to each other.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7fdf281f2c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An applied introduction to hierarchical clustering]]></title>
            <link>https://medium.com/@romoflow/an-applied-introduction-to-hierarchical-clustering-7453f1519544?source=rss-d58d1cf73159------2</link>
            <guid isPermaLink="false">https://medium.com/p/7453f1519544</guid>
            <category><![CDATA[hierarchical-clustering]]></category>
            <category><![CDATA[data-mining]]></category>
            <category><![CDATA[text-embedding]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rodrigo Morales]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 22:33:57 GMT</pubDate>
            <atom:updated>2024-06-09T22:33:57.199Z</atom:updated>
            <content:encoded><![CDATA[<h4>Organizing news into categories and subcategories</h4><p>In certain applications, we want to segment a dataset into groups of similar data points, but we do not have a predefined set of categories for doing so. In these cases, we can use clustering algorithms to automatically find such groups or clusters in the data. In particular, some methods can achieve this in a hierarchical fashion, meaning that broad clusters at a higher levels of the hierarchy can be decomposed into more granular subclusters at lower levels. This is particularly beneficial for applications where we expect to find a nested structure of this kind, but we cannot fully describe it in advance.</p><p>News categorization is an example of an application well suited for hierarchical clustering. News can be categorized with varying levels of specificity. We might be interested in broad topics like politics, science, or business, but also in more granular subtopics like domestic or international politics. Moreover, we might not know all the categories and subcategories that we expect to find beforehand, and these can vary as certain categories that are present in the news from one day may not be present in the news of another.</p><p>There are numerous approaches to perform hierarchical clustering, but in this introductory article we focus on a simple and effective algorithm called agglomerative clustering. As shown in Figure 1, the elementary step of this algorithm consists in merging two similar clusters into a supercluster composed of all the data points contained in the pair being combined. Starting with each data point as its own separate cluster, called a singleton, this process goes on until eventually all clusters have been merged into a single, grand cluster containing the whole dataset. As a result of this process, the algorithm builds a hierarchy of clusters where each step of the algorithm corresponds to a new level in the hierarchy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*moYLRegytfyKWNsO60LDug.png" /><figcaption><strong>Figure 1. Merging of clusters. </strong>The basic step of the agglomerative clustering algorithm is to combine two similar clusters into one containing all the data points from the pair being merged. Image by author.</figcaption></figure><p>The rest of the article expands on the agglomerative algorithm and the hierarchical clustering it builds. The news categorization example serves as a concrete illustration for the main ideas. For this purpose, we use a <a href="https://www.kaggle.com/datasets/khoshbayani/news-texts">dataset</a> containing brief summaries of daily world news. This dataset was kindly gathered and published in Kaggle by Mohammad Khoshbayani (@khoshbayani). To keep the example simple and didactical, we will focus only on the news from March 25, 2024 (a date somewhat arbitrarily chosen because it is recent and with a large enough number of news).</p><p>The algorithm requires a numerical representation of data points, while the dataset we are using consists of textual summaries. To address this, we use text embeddings. Text embeddings are a fascinating topic in itself and a comprehensive coverage of them is well beyond the scope of this article, but for our purposes it suffices to know that they are numerical representations of pieces of text (news summaries in this case) that encode their semantic content. Crucially for our purpose, texts that are semantically similar to each other have similar embeddings. Then, we can feed these embeddings into the agglomerative algorithm with the hope that it will find the desired categorization. The specific embeddings model we use is from the the <a href="https://deepmind.google/research/publications/85521/">Gecko</a> family.</p><h3>How are clusters combined?</h3><p>As mentioned in the introduction, the fundamental idea behind agglomerative clustering is to sequentially merge together the two clusters that are most similar to each other. For this purpose, we need to define a way to measure similarity between any given pair of clusters, but first, we need to measure similarity between pairs of data points as this will form the basis for computing similarity between clusters.</p><p>There are various metrics for measuring similarity (or dissimilarity) between pairs of data points. A canonical example is the euclidean distance between the two points which, geometrically, can be seen as the length of the straight line joining the two points (See Figure 2). The larger this distance is, the less similar (or more dissimilar) the two points are.</p><p>Another similarity metric is the cosine similarity which, geometrically, is the cosine of the angle between the two points represented as normalized vectors (see Figure 2). The smaller the angle between the two vectors, the larger the cosine similarity will be. In the extreme case where the two vectors are pointing in the exact same direction, the cosine similarity is 1. In the other extreme where the vectors are pointing in opposite directions, the similarity value is -1. In this way, the cosine similarity is bounded to be between -1 and 1 where -1 indicates that the vectors are “as dissimilar as they can be” whereas a value of 1 means that they are “as similar as they can be”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*c89PRi-0G6L9dwGYXtaqNA.png" /><figcaption><strong>Figure 2. Euclidean distance and cosine similarity between two data points p and q. </strong>The euclidean distance is the length of the straight line joining the two points and it is a measure of how dissimilar the two points are. The cosine similarity is the cosine of the angle between the two points represented as normalized vectors and it measures how similar the two data points are. Image by author.</figcaption></figure><p>There are numerous other similarity metrics (like the <a href="https://en.wikipedia.org/wiki/Taxicab_geometry">Manhattan</a> or <a href="https://en.wikipedia.org/wiki/Mahalanobis_distance">Mahalanobis</a> distances) and the best choice among them depends largely on the application at hand. For our example application of news categorization, the cosine similarity is particularly relevant, since it is precisely the metric used by the language <a href="https://deepmind.google/research/publications/85521/">model</a> to define how similar the embeddings of a pair of texts are. Then, embeddings from semantically similar texts should have a high cosine similarity as shown in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*5iWdNtyqcbWGyT1zFvJD7w.png" /><figcaption><strong>Figure 3. Cosine similarity between pairs of news embeddings. </strong>Keywords were extracted from the news summaries to label the data points in the visualization, but the embeddings are computed on the full summaries. Note that embeddings from news covering the same or similar topics have a higher cosine similarity as expected. The values in the diagonal are equal to 1 as they correspond to the similarity between an embedding and itself, but are omitted from the color scale to highlight the non-diagonal values in the visualization. Image by author.</figcaption></figure><p>Now, from a similarity metric <em>between data points</em> we build up a similarity metric <em>between clusters</em>. The three most common approaches for doing this consist in computing the pairwise similarities between the data points of the two clusters being considered, and then aggregating this into a single similarity value. Each approach is characterized by the aggregation function used:</p><ol><li><strong>Single linkage</strong> takes the maximum among the pairwise similarities as the similarity between the two clusters: the similarity between clusters <em>A</em> and <em>B</em> corresponds to the maximum similarity between a data point in <em>A</em> and a data point in <em>B</em>.</li><li><strong>Complete linkage</strong> takes the minimum among the pairwise similarities as the similarity between the two clusters: the similarity between clusters <em>A</em> and<em> B</em> corresponds to the minimum similarity between a data point in <em>A</em> and a data point in <em>B</em>.</li><li><strong>Average linkage</strong> takes the average of the pairwise similarities as the similarity between the two clusters: the similarity between clusters <em>A</em> and <em>B</em> corresponds to the average similarity between the data points in <em>A</em> and the data points in <em>B</em>.</li></ol><p>In the special case where the two clusters being considered are singletons, the three criteria are equivalent, but this is not necessarily the case for larger clusters as shown in the example from Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iM-9ncR7mEIo8omC77Qjw.png" /><figcaption><strong>Figure 4. Comparison of different linkage criteria for computing similarity across clusters. </strong>This example shows the pairwise similarities between two clusters consisting of 3 news each. Single linkage takes their maximum similarity (0.43). Complete linkage takes their minimum similarity (0.14). Average linkage takes their average similarity (0.30). Image by author.</figcaption></figure><p>These approaches are called linkages because, in the context of agglomerative clustering, they define the criteria used to link or combine the two most similar clusters by defining how such similarity is measured. Single linkage can frequently lead to the merging of relatively heterogeneous clusters, because for two clusters to be deemed highly similar and merged, it suffices that they have a single pair of highly similar data points. On the other side, complete linkage will usually lead to more homogeneous clusters, since it requires that the two clusters have high similarity between all their pairs of data points for them to have high similarity. Average linkage usually sits in between the two extremes as two clusters are deemed to be highly similar if their data points are on average highly similar.</p><p>Now, we have all the necessary elements to fully describe the agglomerative clustering algorithm. Given a similarity metric and linkage criterion, the algorithm:</p><ol><li>Begins with each data point conforming its own singleton cluster.</li><li>At each step, joins the two most similar clusters according to the linkage criterion.</li><li>Ends when the last two remaining clusters have been merged into a single cluster containing all the data points.</li></ol><h3>Exploring the hierarchy of clusters</h3><p>We can see the hierarchical clustering built by the agglomerative algorithm as a binary tree. At each step, the algorithm builds up a new level of the tree by joining two nodes into one. Then, each node of the tree represents a merged cluster and its two child nodes are precisely the subclusters that were combined to form it. At the bottom of the tree lie the leave nodes corresponding to the initial singleton clusters and at the top is the root node representing the final cluster consisting of the full data set. The visualization of this tree is called a dendrogram which is shown in Figure 5 for the news categorization example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhQvvO7_ugMx3J9RxBWoTA.png" /><figcaption><strong>Figure 5. Dendrogram of the news categorization. </strong>The dendrogram illustrates the hierarchical clustering built with the agglomerative algorithm. It shows how pairs of clusters are sequentially merged to build a binary tree starting with the singleton clusters at the bottom and ending with the cluster containing the full dataset at the top. Keywords were extracted from the news summaries to label the data points in the visualization, but the embeddings of the full summaries were used for the clustering. A complete linkage was used for this clustering. Image by author.</figcaption></figure><p>The dendrogram is a visual description of the process of agglomeration. As we move from bottom to top, we can see how pairs of clusters are merged, starting with the individual data points as singletons and finishing with the remaining two clusters branches combining into the root cluster containing the full dataset. Note that the position of a merger along the y-axis indicates the similarity between the two clusters being combined which decreases as we move to the top. This is intuitive as we would expect that clusters at lower levels of the hierarchy are more similar to each other than clusters at higher levels.</p><p>In the dendrogram from the news example showed in Figure 5, we can see that the first merger combines two news covering Al Jazeera retracting a fabricated story about the IDF. The second step combines another pair of singletons from news covering leadership changes in Boeing. This process continues, and in the sixth step the first agglomeration involving a non-singleton occurs when the cluster containing the two Boeing leadership news, formed at the second step, is merged with a profile story of the new Boeing CEO. From here, we can follow the different paths to see how each of the different clusters continues combining with others.</p><p>The dendrogram also serves as a visual tool to explore clusters and subclusters at different levels of the hierarchical tree. For instance, inspecting the two last clusters before the final merger at the top, we can see that the one on the left branch consists of geopolitical news while the one on the right, of business, technology, and science news. From here, we can explore each branch towards lower levels in the hierarchy. The geopolitical news cluster divides into two subclusters, one dealing mainly with news related to Russia and the other, with news related to Israel and the war in Gaza. On the right branch, the other second-level cluster splits into one containing business and economics news and another dealing with science and technology news. Furthermore, the latter then branches into a cluster with news about research studies and another dealing with tech and social media news.</p><h3>Final considerations</h3><p>We have seen how the agglomerative algorithm builds a hierarchical structure that allows to explore clusters of data points with different levels of granularity. To conclude, we discuss some potential limitations of this approach that are worth considering.</p><p>The algorithm results can depend heavily on the linkage criterion used. This is particularly evident when contrasting complete and single linkage. As explained before, single linkage will frequently result in a few large and broad clusters absorbing the singletons throughout the process of agglomeration leading to unevenly-sized clusters while complete linkage will produce more compact, evenly-sized clusters.</p><p>For the news application we used complete linkage because it is desirable to have compact subcategories containing their own coherent set of news instead of a large loose topic absorbing most of the news. However, there might be applications better suited for single linkage or a different linkage criterion. Which linkage is the most appropriate ultimately depends on the application at hand. It is a good idea, if possible, to test and compare results under different linkages to help in deciding which one gives the best results for the purpose of the application.</p><p>Another shortcoming of the algorithm is that it is computationally expensive. While efficient implementations can achieve a time complexity quadratic in the size of the dataset this might still be prohibitive for very large datasets. Other approaches like <a href="https://dl.acm.org/doi/abs/10.1145/235968.233324">BIRCH</a> are better suited to handle these (see this <a href="https://www.sciencedirect.com/science/article/abs/pii/S095219762200046X">survey</a> for a detailed explanation of the computational complexities of different methods). Even when considering moderately-sized datasets the computation required to perform various tests, for instance to assess different linkage criteria, can compound the computational cost rendering the application unfeasible.</p><p>A final, more subtle consideration, is that there is not always a single correct hierarchy to cluster the data. In particular, the type of hierarchy that we have in mind might not always be the one resulting from the algorithm. For instance, in the news categorization application there are some tech regulation and social media news that were merged along the branch of the science and technology news. However, one might argue that an equally valid path for them was to be merged with more politically-themed news. Similar ambiguities in the correctness of the hierarchy might be present in other applications, and the algorithm might not resolve them as desired.</p><p>Altogether, the agglomerative algorithm is a very simple and effective tool to perform a hierarchical clustering on simple applications like the one showcased in this article. For more complex applications it can still serve as a solid starting point to iterate upon. Furthermore, it serves as a good introduction into the topic as it, intuitively, demonstrates how we can automatically find a hierarchical group structure in the data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7453f1519544" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you really that sure?]]></title>
            <link>https://medium.com/@romoflow/are-you-really-that-sure-a086b0ab9b78?source=rss-d58d1cf73159------2</link>
            <guid isPermaLink="false">https://medium.com/p/a086b0ab9b78</guid>
            <category><![CDATA[calibration]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[robustness]]></category>
            <category><![CDATA[confidence-score]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rodrigo Morales]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 20:51:54 GMT</pubDate>
            <atom:updated>2024-02-07T20:51:54.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*VBXj8uynmPStp5RCA9npEQ.png" /></figure><h4>Calibration of deep neural networks for classification</h4><p>Imagine you receive the results of a test for a disease, and it indicates that you got it with 90% probability. This prediction not only has a direct effect on your wellbeing but might determine the course of action for the treatment. If the diagnostic was inaccurate and actually you have the disease with only 50% probability, this would probably lead to different choices of treatment.</p><p>If a probabilistic prediction is not an accurate estimate of the likelihood of the event being predicted, we say that it is not well calibrated. The example above illustrates how valuable calibrated predictions can be. This is an essential requirement in safety critical applications like medicine, but even in more mundane applications, accurate probabilistic predictions can be of great importance as well.</p><p>As another example, think of a customer support chatbot that needs to detect the intent of a user question to give an adequate answer. The action taken by the chatbot might depend on the confidence of having correctly identified the purpose of the query; perhaps if there is high uncertainty in its prediction, it might refrain from giving an answer and instead ask the user to reword the question or direct her to a human agent. In scenarios like this one, an accurate assessment of the prediction’s confidence is required for the adequate functioning of the system.</p><p>Deep neural networks are the state-of-the-art approach in a growing number of classification problems across different domains ranging from image classification to text classification. They typically output a confidence score associated with their class prediction. This score is interpreted as the probability that such prediction is correct. However, recent research has shown that these probabilistic predictions tend to be poorly calibrated. This has important implications as their use continues to grow, especially in safety critical applications where calibration is essential. Fortunately, the literature has also found effective and practical frameworks to address this issue.</p><p>The rest of the article expands on the calibration of deep neural networks for classification. First, we formalize the general notion of calibration in this context to then explain how calibration can be assessed. Equipped with these concepts, we review the recent literature evaluating the calibration of deep networks. Finally, we distill a practical approach to improve calibration in cases that require so.</p><h3>What exactly is calibration?</h3><p>As described above, the core idea of a well calibrated prediction is that its confidence or uncertainty expressed via a probability value is an accurate estimate of the likelihood of the prediction being correct.</p><p>In the context of classification problems, a classifier needs to predict one out of K classes. Associated with the class being predicted, the model outputs a normalized confidence score, which can be interpreted as the probability with which the class prediction is correct. We denote the class prediction<a href="#75fc">¹</a> as <em>y´</em>, and its associated confidence score, <em>confidence(y´).</em></p><p>Additionally, we assume that there is a ground-truth distribution<a href="#5c4d">²</a> over the class labels denoted by <em>P(Y)</em>, so that <em>P(Y=y) </em>is the probability with which the ground-truth class is <em>y. </em>In particular, the probability that the true class is the predicted class is given by <em>P(Y=y’). </em>Then, if a model is perfectly calibrated this probability must be equal to the confidence of the prediction, so that: <em>P(Y=y’)=confidence(y’)</em></p><p>More plainly, if a perfectly calibrated model predicts a class with, say 80% confidence, the probability of that class being the ground-truth should be 80%. If such probability is distinct from 80%, the model is miscalibrated.</p><p>It is important to note that calibration is distinct from accuracy of the class predictions. Accuracy compares the class prediction with the observed class, whereas calibration is a comparison between the prediction’s confidence score and the probability with which such predicted class is the correct one. For this reason, it is possible to have a model with high accuracy but poor calibration. Moreover, two models that have the same accuracy, even the same class predictions, need not be equally well calibrated as shown in the rain prediction example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pk3hRwQ874sis6-qcIMBig.png" /><figcaption><strong>Table 1. Accuracy is not the same as calibration. </strong>Two models with the same class predictions can be differently calibrated depending on their confidence scores. Both models have the same class predictions and therefore the same accuracy, but Model A is worse calibrated than Model B, since its confidence scores are a worse reflection of the likelihood of the correctness of its predictions.</figcaption></figure><p>Both models have the same class predictions and, therefore, the same accuracy (4 out of 6), but model A is worse calibrated than model B. To see why this is the case, note that on 75% (3 out of 4) of the days when the models predict rain, it actually rains. Model B estimates this uncertainty accurately, since whenever it predicts rain it does so with a 75% confidence, but Model A expresses an overestimated 85% confidence when predicting rain. The analogous situation occurs when the models predict no rain: Model A confidence of 70% is a poor reflection of the actual frequency of 50%, whereas Model B confidence of 50% is an accurate estimate of it.</p><h3>How to assess calibration?</h3><p>The simple example above illustrates how we can empirically evaluate the calibration of a model by comparing the confidence of its predictions with the relative frequency with which they are correct (i.e. their accuracy). In the example, we concluded that model B is better calibrated because its confidence scores are better aligned with the frequencies with which its predictions are correct. Now we dive into specific metrics to quantify this notion.</p><p>The gold standard of a perfectly calibrated model is given by the equality: <em>P(Y=y’)=confidence(y’) </em>which states that the probability of the class prediction being correct is equal to its confidence score. Unfortunately, in practice a model will not be perfectly calibrated. Then, the key idea to measure miscalibration is to determine by how much these two quantities differ.</p><p>We can obtain the confidence score as part of a classifier’s output. If we had access to the ground-truth distribution<em> P(Y), </em>it would be trivial to measure the absolute difference between <em>P(Y=y’) </em>and <em>confidence(y’), </em>and such difference, called the calibration error, could serve as our miscalibration metric. Unfortunately, in practical applications, we do not have access to the distribution <em>P(Y), </em>and even for individual examples, the ground-truth class probability <em>P(Y=y’) </em>is not observable: we only observe class labels, not the probabilities associated with them.</p><p>This absence of individual ground-truth probability values makes evaluating calibration particularly challenging, since we cannot simply compute the calibration error, |<em>P(Y=y’)-confidence(y’)|,</em> for each example in the dataset. Some metrics address this issue by computing the calibration error for groups of examples, where <em>P(Y=y’) </em>can be approximated with the accuracy in the group.</p><p>This is the motivation behind a widely-used metric called Expected Calibration Error (ECE) proposed by <a href="https://ojs.aaai.org/index.php/AAAI/article/view/9602">Naeini et al. 2015</a>. This metric computes the calibration error across bins of examples in the following way:</p><ol><li>Partition the dataset into N bins of uniform length whose limits are the confidence levels of the predictions. For example, we could use 10 bins with limits: [0, 0.1), [0.1, 0.2),…, [0.9, 1] so that the first bin contains all the examples for which the prediction has a confidence smaller than 0.1, the second bin, all the examples with confidence scores between 0.1 and 0.2, and so on for the rest of the bins.</li><li>Within each bin we can approximate <em>P(Y=y´) </em>as the fraction of correct predictions, this is, the accuracy within the bin<a href="#f10f">³</a>. Similarly, we can interpret <em>confidence(y’) </em>as the average confidence of the predictions within the bin and, in this way, compute the calibration error for each bin.</li><li>Finally, we do a weighted average of the calibration errors across the different bins, where the weights are given by the fraction of examples belonging to each bin.</li></ol><p>An example of this computation using only 4 bins is shown in Table 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8T2RrB1LC0owSxyXsIvosA.png" /><figcaption><strong>Table 2. The Expected Calibration Error (ECE) </strong>is computed by taking a weighted average of the calibration error across the different confidence bins used to partition the dataset.</figcaption></figure><p>An important limitation of the ECE is that the decision on how to set the bins is arbitrary and can have a substantial effect on the value of the metric as noted by <a href="https://openaccess.thecvf.com/content_CVPRW_2019/html/Uncertainty_and_Robustness_in_Deep_Visual_Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.html">Nixon et al. 2019</a> and <a href="https://arxiv.org/abs/2308.11838">Tao et al. 2023</a>. Therefore, it is recommendable to evaluate the results under different bin configurations to ensure their robustness.</p><p>There are variations of the ECE that attempt to address some of its limitations. The Maximum Calibration Error (MCE) proposed by <a href="https://ojs.aaai.org/index.php/AAAI/article/view/9602">Naeini et al. 2015</a> takes the maximum across the bin-wise calibration errors instead of the weighted average. This is a worst-case-scenario metric which makes it better suited for high-risk applications. The Adaptive Calibration Error (ACE) proposed by <a href="https://openaccess.thecvf.com/content_CVPRW_2019/html/Uncertainty_and_Robustness_in_Deep_Visual_Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.html">Nixon et al. 2019</a> set the bins so that they all have the same number of examples which means that they all contribute equally to the average calibration error. A potential issue with this approach is that some bins might span a very wide range of confidence levels, since they are no longer guaranteed to have uniform width.</p><p>Other metrics avoid partitioning the dataset into bins by using the observed class of each example instead of its unobservable class probability. For instance, the Negative Log-likelihood (NLL) or cross-entropy loss is the negative logarithm of the confidence score of the correct class label, <em>y*, </em>added over all the examples<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*3I16pIEq_aQRZBRAK8xm_Q.png" /></figure><p>Note that the NLL will be lower as the confidence for the correct class is higher (or equivalently the confidence for the wrong classes is lower). In fact, the NLL is a proper scoring rule, which essentially means that it is minimized if the confidence scores of the predictions match exactly the ground-truth distribution of the classes; this is, if the predictions are perfectly calibrated. Moreover, it is a differentiable loss function with respect to the parameters of a neural network which makes it a common choice of training objective in deep learning algorithms, and, as we will see later, it can also be helpful to improve their calibration.</p><p>All the metrics overviewed provide a summary value of the calibration across the whole dataset, but they might hide calibration issues in local confidence regions. For instance, in the example of Table 2, the calibration error in the low confidence levels (between 0 and 0.50) is considerably higher than in the high confidence levels (between 0.50 and 0.1), but because the lower confidence bins contain less examples and, therefore, have a relatively low weight in the average, this issue is masked in the ECE.</p><p>Through visualization, we can get a more complete picture of the calibration error across the different confidence levels. Two standard visualizations used for this purpose are reliability diagrams and calibration curves as the ones shown in Figure 1. These can highlight miscalibration in specific confidence regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*0LctySigIvnwHf8_p7uFOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*A1yy9XsxommOe1IFd5YSXw.png" /><figcaption><strong>Figure 1. Plots for evaluating calibration. </strong>The plots use the data from the example in Table 2. The reliability diagram in the left plots the accuracy across the different confidence bins. The calibration plot in the right plots the accuracy against the average confidence of the predictions in the bins. Both of these plots show that, in this example, there is higher miscalibration in lower confidence bins.</figcaption></figure><p>In practice, it is always a good idea to use more than one metric for validation, since different metrics, or even the same metric under different bin schemes, can give meaningfully different results as noted by <a href="https://openaccess.thecvf.com/content_CVPRW_2019/html/Uncertainty_and_Robustness_in_Deep_Visual_Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.html">Nixon et al. 2019</a>. In addition, it is a good practice to complement the metrics with visualizations that can give a more complete picture of the calibration profile of a model.</p><h3>Are deep neural networks calibrated?</h3><p>Now that we have properly defined what is calibration and how to evaluate it, we can turn to the central question: are deep neural networks calibrated? Recent research exploring this question suggests that typically they are not.</p><p>An empirical study by <a href="https://proceedings.mlr.press/v70/guo17a.html">Guo et al. 2017</a> evaluates the calibration of various architectures in different classification tasks to find that deep networks tend to be miscalibrated. Moreover, their results suggest that larger convolutional networks (either deeper or wider) which tend to have higher accuracy also tend to be <em>worse </em>calibrated.</p><p>However, it is not a general rule that networks with greater accuracy are worse calibrated. The architecture type can also be an important factor as found by <a href="https://proceedings.mlr.press/v70/guo17a.html">Minderer et al. 2021</a>. In particular, their evaluations indicate that recent non-convolutional architectures like Vision Transformers tend to be better calibrated than convolutional architectures like ResNets <em>and</em> have higher accuracy while taking into account the network’s size. Moreover, this advantage is preserved even after applying a post-processing calibration improvement called temperature scaling which we will cover in the next section.</p><p>Even though some architectures appear to be better calibrated than others in specific tasks, there is not a single one that is guaranteed to be the best calibrated in every dataset. Even within a single domain (e.g. image classification) calibration of a given model is not guaranteed to generalize to different datasets as found by <a href="https://arxiv.org/abs/2308.11838">Tao et al. 2023</a>. This means that if a model achieves good calibration in a specific dataset, we shouldn’t assume that it will be equally well calibrated in a distinct dataset coming from a different distribution. This has important implications in practice, where distribution shift is common.</p><p>The conclusion from the literature is clear: we cannot simply expect that a deep network will be well calibrated “out of the box”. Then, in applications where calibration is important, this must be explicitly evaluated. Fortunately, the literature also reveals that it is possible to achieve both high accuracy and good calibration. Moreover, it has found effective methods to improve calibration of deep networks, one of which we now explain.</p><h3>How to address calibration?</h3><p>Many methods have been recently proposed to improve calibration in deep neural networks (see <a href="https://arxiv.org/abs/2308.01222">Wang 2023</a> for a thorough survey), but here we will focus on one that stands out because of its effectiveness and simplicity: temperature scaling proposed by <a href="https://proceedings.mlr.press/v70/guo17a.html">Guo et al. 2017</a>.</p><p>Typically, the outputs of the last layer of a classifier network are unnormalized scores for the class predictions, called logits. These are then normalized via a softmax function to get the confidence scores associated with the class predictions. The softmax normalization preserves the ranking of the logits, so that the class with the highest logit will also be the class with the highest confidence score, and then it will be the predicted class. Moreover, the relative difference between the logits of different classes will ultimately dictate the relative difference between their confidence scores. In particular, if the highest logit is very large relative to the others, the network will output a very high confidence in its prediction.</p><p>Given the importance of the logits in determining the confidence scores, adjusting them can alter the calibration of the network’s predictions. This is the key idea behind temperature scaling which essentially involves rescaling the logics so that the confidence scores resulting from them are better calibrated. Crucially, the logits of all the classes are rescaled by the same factor, <em>T, </em>called the temperature.</p><p>More concretely, if the original logit of a given class k is denoted by <em>logit(k)</em> , then after temperature scaling it is given by <em>logit(k) / T</em>. By rescaling the logits, the temperature parameter can either sharpen or smooth the confidence scores, as shown in Figure 2, and, in this way, have an effect on the calibration of the predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*pxJHnF3G7rqeso3InI3krA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*07h7umWWXGvmS2NrrAYYAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4dWB4vtrW0qnDKD51fT7Lg.png" /><figcaption><strong>Figure 2. Effect of temperature scaling on confidence scores.</strong> A low value of the temperature (e.g. T=0.1) will sharpen the confidence scores, whereas a large value (e.g. T=10) will smooth them. Note that T=1 is equivalent to not applying temperature scaling. Also note that although the confidence scores change, their relative order does not; thus, temperature scaling does not change the class prediction only the confidence score associated with it.</figcaption></figure><p>Since the same parameter, <em>T, </em>is used for all the classes, their confidence scores ranking will not change after the rescaling, and then the class prediction will also stay the same. This is a nice feature of this method, since it is specifically targeted at improving calibration by modifying the confidence scores while leaving the class predictions unchanged, and, therefore, their accuracy as well. These are great news if we have a model that already has high accuracy but needs to improve calibration, since the latter can be adjusted without disrupting the former.</p><p>The next question is, of course, how to set<em> T</em> in order to improve calibration? Here we can leverage the NLL reviewed above. Recall that the NLL is minimized when the confidence scores are perfectly calibrated. Moreover, as a loss function, it is differentiable with respect to the temperature parameter, <em>T. </em>Then, we can find the optimal value of <em>T</em> with respect to the NLL via a gradient-based algorithm, such as the ones used to fit all the other parameters in the network.</p><p>All this properties make temperature scaling an approach that can be embedded smoothly into a deep learning framework. The following approach can be implemented in practice to train a calibrated network:</p><ol><li>On the first stage of training, we can disregard calibration and the temperature parameter to focus exclusively on learning the rest of the network’s parameters using the training set to obtain the highest accuracy we can or whatever other target metric we desire.</li><li>After the parameters of the network have been learned and we have reached the desired level of performance for the class predictions, we can assess if the network needs to be recalibrated using a held-out validation set.</li><li>If the network needs to improve its calibration, as it will often be the case, we fix all the learned parameters of the network and fit only the temperature parameter to minimize the NLL on the validation set. It is important to do this as a separate step in a dataset held out from the first stage of training, because otherwise, if the temperature parameter is optimized jointly with the rest of the parameters, it will be overfit the training set resulting in a miscalibrated network.</li><li>Finally, we reassess the accuracy and the calibration performance in a held-out test set. Note that this test set shouldn’t have been used to neither learn the parameters of the network nor the temperature.</li></ol><p>This simple framework has consistently proved effective to improve the calibration of deep neural networks. However, it is not without its limitations. Mainly, we should remember that a model that has been calibrated using this approach in a particular dataset is not guaranteed to remain calibrated in a different dataset coming from another distribution. So, if there is distribution shift, the model can become miscalibrated again. Since distributions are rarely stable in practice, it is recommended to continuously monitor the calibration metrics of the network after deploying it in the application of interest.</p><h3>Conclusion</h3><p>In this article, we explored the notion of calibration which can be summarized as the degree to which a classifier’s confidence is an accurate estimate of its prediction being correct. We defined different metrics used to evaluate calibration to find that binned metrics can be very sensitive to the binning scheme used. The Negative Log-likelihood appeared as a good alternative to these as it does not requires binning, is minimized when the predictions are perfectly calibrated, and is a differentiable loss function. We reviewed the literature exploring the calibration of deep neural networks which suggests that they usually are miscalibrated, but their calibration can be improved while preserving their accuracy. Finally, we explored temperature scaling, a simple and effective approach to improve calibration which involves rescaling the logits to make the confidence scores better calibrated while preserving the class predictions.</p><h3>Footnotes</h3><ol><li>In the context of binary classification, we can unambiguously talk of a single class prediction. In multi-class classification we should specify to which class the prediction refers. For clarity in the discussion, throughout the article, we talk about a single class prediction which can be interpreted as the class prediction with the highest confidence score. <a href="#c22f">^</a></li><li>More precisely, here we are referring to the distribution of the class given the features, <em>P(Y|X)</em>, but since the features will not play an important role in the rest of the discussion we express it as simply <em>P(Y)</em> to avoid notation clutter. <a href="#bf20">^</a></li><li>In the case of multi-class classification, we are implicitly using only the class prediction with the highest confidence to evaluate calibration. This is a common approach when evaluating calibration, but there are metrics that allow to measure calibration across all the classes e.g. see <a href="https://openaccess.thecvf.com/content_CVPRW_2019/html/Uncertainty_and_Robustness_in_Deep_Visual_Learning/Nixon_Measuring_Calibration_in_Deep_Learning_CVPRW_2019_paper.html">Nixon et al. 2019</a>. <a href="#0130">^</a></li></ol><h3>References</h3><ol><li>Naeini, Mahdi Pakdaman, Gregory Cooper, and Milos Hauskrecht. “Obtaining well calibrated probabilities using bayesian binning.” <em>Proceedings of the AAAI conference on artificial intelligence</em>. Vol. 29. №1. 2015.</li><li>Nixon, Jeremy, et al. “Measuring Calibration in Deep Learning.” <em>CVPR workshops</em>. Vol. 2. №7. 2019.</li><li>Tao, Linwei, et al. “A benchmark study on calibration.” <em>arXiv preprint arXiv:2308.11838</em> (2023).</li><li>Guo, Chuan, et al. “On calibration of modern neural networks.” <em>International conference on machine learning</em>. PMLR, 2017.</li><li>Minderer, Matthias, et al. “Revisiting the calibration of modern neural networks.” <em>Advances in Neural Information Processing Systems</em> 34 (2021): 15682–15694.</li><li>Wang, Cheng. “Calibration in deep learning: A survey of the state-of-the-art.” <em>arXiv preprint arXiv:2308.01222</em> (2023).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a086b0ab9b78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neurons, action potentials, and synapses]]></title>
            <link>https://medium.com/@romoflow/neurons-action-potentials-and-synapses-ee9722a9a3af?source=rss-d58d1cf73159------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee9722a9a3af</guid>
            <category><![CDATA[neurons]]></category>
            <category><![CDATA[synapse]]></category>
            <category><![CDATA[neurobiology]]></category>
            <category><![CDATA[action-potential]]></category>
            <category><![CDATA[neuroscience]]></category>
            <dc:creator><![CDATA[Rodrigo Morales]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 23:04:11 GMT</pubDate>
            <atom:updated>2023-07-20T23:04:11.881Z</atom:updated>
            <content:encoded><![CDATA[<h4>A description of how signals are transmitted in the brain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*zYIaxdmK07VgYFm6y9qmTQ.jpeg" /><figcaption>Generated with Bing image creator</figcaption></figure><p>One of the most fascinating questions in science is how biophysical processes in the brain can give rise to mental capabilities. While many aspects of this question remain open, the fundamental mechanisms that enable brain capacity have been widely studied. The basis is the transmission of signals across billions of neurons. This signal processing at scale enable us to give meaning to our world and act on it; to have subjective experience; to feel; to develop abstract concepts; in short, to think.</p><p>In this article, we explore the fundamental biophysical processes that underlie signals transmission in the brain. The main goal is to provide a clear explanation that highlights the core principles. For this reason, we consider a somewhat stylized description of these processes that abstracts some details and omits some particularities which, although interesting themselves and relevant for some topics in neuroscience, are not essential for the understanding of the foundational ideas.</p><p>The intent is that any reader interested in a brief introduction to the topic can fully understand the core ideas which might serve as foundations for expanded study into particular aspects. However, the explanations are as precise and complete as possible trying to cover the essential biophysical dynamics that enable neural signals transmission.</p><p>The article is for the most part self-contained and does not require any prior knowledge beyond high-school biology. For this purpose, in the first section, we go over a brief overview of the main concepts required to follow along the rest of the article; the next two sections describe how a signal originates and propagates within a neuron; the subsequent section explain how signals can traverse from one neuron to others; the final section concludes.</p><h3>Neurons, synapses, and ions</h3><p>Before fully diving into signal processing in the brain, we briefly overview the anatomy and electrical properties of neurons. A neuron is a specialized brain cell. In many respects, it is similar to cells in other parts of the body. For example, it also consist of a nucleus and a cytoplasm enclosed by a plasma membrane. However, it has a unique structure that enables it to function as a signal transmitter.</p><p>The main components of a neuron are its soma or cell body which contains the nucleus; dendrites which are branched structures that extend from the soma and serve to receive incoming signals from other neurons; the axon which is a long thin structure that extends from the soma and branches into terminals to send signals to other neurons. In some neurons, the axon is also covered by a layer of a fatty substance called myelin. This myelin sheath does not cover the full length of the axon but has some gaps which are called nodes of Ranvier. All these components are depicted in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*bllsx7bAentDVj2wJVaUVQ.png" /><figcaption><strong>Figure 1. Basic anatomy of a neuron.</strong> Original image by Dhp1080, CC BY-SA 3.0 &lt;<a href="http://creativecommons.org/licenses/by-sa/3.0/">http://creativecommons.org/licenses/by-sa/3.0/</a>&gt;, via Wikimedia Commons</figcaption></figure><p>For two neurons to send or receive signals from each other they must be “connected”. A synapse is the site where this occurs. Typically, in a synapse an axon terminal from one neuron (called the presynaptic neuron) connects with a dendrite of a second neuron (called the postsynaptic neuron). The synaptic cleft is a small gap between the two neurons which, as we’ll see later, serves as the intermediary medium for their communication.</p><p>A signal travels within a neuron as an electric current, so understanding the electrical properties of neurons is required to grasp how this can happen. The membrane of a neuron concentrates electrically charged atoms called ions which endow it with an electrical charge. Crucially, the concentration of a particular ion is different on each side of the membrane (inside and outside the neuron). These differences of concentrations across the membrane are called concentration gradients.</p><p>Concentration gradients induce a difference in charge across the membrane called the membrane potential. For example, if the membrane potential is negative it means that the inside is more negatively (or less positively) charged than the outside. The membrane potential is not fixed, since it depends on the concentration of ions which can change over time. However, a common reference value is the resting potential (approximately -70mV) which refers to the potential when the neuron is at rest, meaning not generating and propagating electrical signals.</p><p>Three ions and their concentration gradients are of particular importance: sodium (Na+), potassium (K+), and calcium (Ca2+). When the neuron is at rest, Na+ is more concentrated on the outside relative to the inside, K+ is more concentrated on the inside, and Ca2+ is much more concentrated on the outside. These relative concentrations are maintained by specialized proteins called pumps: the sodium-potassium pump transports Na+ to the outside of the neuron and K+ to the inside and the calcium pump removes Ca2+ from the inside of the neuron.</p><p>When there is a concentration gradient, ions will tend to diffuse from the region with higher concentration towards the region with lower concentration. This will induce a change in the membrane potential that will tend to balance the diffusion until an equilibrium is reached where the current from the potential cancels out the diffusion current so that there is no net flow of ions across the membrane. For example, since there is a higher concentration of Na+ outside the neuron, they will tend to diffuse to the inside. This will increase the membrane potential, since positively charged ions are entering the membrane. But then, in turn, this increased potential will tend to repel positively charged ions, such as Na+, balancing the diffusion in this way.</p><p>However, the above example assumes that ions can freely move across the membrane, which is not always the case. In particular, the permeability of the membrane to a particular ion can change thanks to specialized proteins called gated ion channels. They are called gated because they can be open in which case they allow the passage of particular ions across them or closed in which case they block such passage as shown in Figure 2. They can have a high degree of selectivity for allowing only a specific type of ions to cross. Two important types are voltage-gated channels which open or close depending on the value of the membrane potential and transmitter-gated channels which open or close in the presence or absence of special molecules called neurotransmitters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*8D5ccKZpSPWKtvjwx7_oWw.jpeg" /><figcaption><strong>Figure 2. Sodium channels. </strong>When opened, sodium channels allow Na+ to flow across the membrane and block such passage when closed. Original image by Tom Mork, CC BY-SA 4.0 &lt;<a href="https://creativecommons.org/licenses/by-sa/4.0">https://creativecommons.org/licenses/by-sa/4.0</a>&gt;, via Wikimedia Commons</figcaption></figure><h3>The action potential</h3><p>We can now begin the story of how a neural signal is transmitted. Imagine that we use an electrode to inject cation (i.e. positively charged) current into a patch of neuron’s membrane. This depolarizes it, meaning that the membrane potential increases (becomes less negative). Crucially, if the depolarization exceeds a threshold value (typically around -55mV), it triggers a series of processes in the membrane collectively referred to as an action potential. The action potential serves as the mechanism by which neurons can encode information from incoming signals and transmit it to other neurons.</p><p>Once the depolarization crosses the threshold, the action potential begins with the opening of voltage-gated sodium channels embedded in the membrane. This enables the passage of Na+ through them, and, given their lower concentration on the inside of the membrane relative to the outside, Na+ diffuses towards the inside. This net current of Na+ into the neuron will rapidly depolarize the membrane further which is why this stage is called the rising phase of the action potential.</p><p>After some time (typically around 1–2 ms), the rising phase comes to an end by two mechanisms: First, the sodium channels will spontaneously close so that no more Na+ can pass through them. Additionally, voltage-gated potassium channels embedded in the membrane start opening due to the initial trigger that started the action potential (they open with a delay relative to the voltage-gated sodium channels). Since there is a higher concentration of K+ on the inside of the neuron relative to the outside, these ions will leave the neuron through the open channels. This combination of events will lead to a rapid decrease of the membrane potential, called hyperpolarization. For this reason, this second stage is called the falling phase of the action potential.</p><p>Finally, after some time (typically around 1–2 ms), the potassium channels close spontaneously to end the falling phase. At this point, the membrane potential has fallen more than its resting value, but once all the voltage-gated channels are closed, the sodium-potassium pumps can restore the concentration gradients, and with them the membrane potential, to their resting values. At this point, the neuron is ready to start a new action potential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*uoDANUVNtpcFgBvx5Jo_yQ.png" /><figcaption><strong>Figure 3. Phases of the action potential. </strong>During the rising phase, sodium channels open leading to an inward current of Na+ that rapidly depolarizes the membrane. During the falling phase, sodium channels close while potassium channels open allowing a K+ current to flow to the outside leading to a rapid hyperpolarization of the membrane. After potassium channels close, the membrane potential is restored to its resting value. Original image by Chris 73, updated by Diberri, converted to SVG by tiZom, and adapted with additional labels by author, CC BY-SA 3.0 &lt;<a href="https://creativecommons.org/licenses/by-sa/3.0">https://creativecommons.org/licenses/by-sa/3.0</a>&gt;, via Wikimedia Commons</figcaption></figure><p>There cannot be consecutive action potentials triggered until the full stages of the first one are completed. First, because the sodium channels remain closed for some time after their closure at the end of the rising phase, independently of the membrane potential. Therefore, the membrane is not permeable to Na+ and cannot be depolarized. During this time, the neuron is said to be in absolute refractory period because of its inability to start new action potentials. Furthermore, at the end of the falling phase the membrane is hyperpolarized below its resting value. Therefore, a stronger depolarizing current is required to exceed the threshold value of the action potential. This stage is called the relative refractory period because even though the starting of a new action potential is possible, a stronger positive current is required to do so.</p><h3>The propagation of an action potential</h3><p>The action potential serves as the mechanism by which neurons can encode information from incoming signals and transmit it to other neurons. The previous description of an action potential was limited to a single patch of membrane in the axon. Typically, action potentials start at the region where the soma joins with the axon, called the axon-hillock. However, for the signal to reach other neurons, it first needs to be propagated down the axon towards the axon terminals where the neuron forms synapses with other neurons.</p><p>Recall that once an action potential is triggered in the initial patch of the axon’s membrane, say at the axon-hillock, there is a strong inward current of Na+. Part of this current flows to the adjacent patch of membrane down the axon and depolarizes it as well. When this depolarization exceeds the threshold value, an action potential will start in the downstream patch. As a consequence, sodium channels open in the second patch allowing the influx of Na+ (rising phase), but then, in turn, this Na+ current flows to a subsequent third patch of membrane further down the axon and depolarizes it. After this depolarization surpasses the threshold value, the action potential starts in this third patch, and, in this way, the action potential continues propagating, via depolarizing current, along the subsequent patches of axon’s membrane until it reaches the axon terminals. An animation illustrating this process is shown in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*HKPn-Cw5pkYwhAbUPlFOtw.gif" /><figcaption><strong>Figure 4. Action potential propagating down the axon. </strong>The depolarizing current from the rising phase in a patch of the axon’s membrane will propagate to the adjacent patch depolarizing it and inducing the action potential in it. This process goes on until the action potential reaches the axon terminals. Image by Germis, CC BY-SA 3.0 &lt;<a href="https://creativecommons.org/licenses/by-sa/3.0">https://creativecommons.org/licenses/by-sa/3.0</a>&gt;, via Wikimedia Commons</figcaption></figure><p>Note that in the previous description, the action potential only propagates in one direction (down the axon). One could ask why the depolarization in the downstream patch of membrane does not also returns to the preceding patch to initiate an action potential and form a feedback loop? The reason is that when the downstream patch is depolarizing, the upstream patch is in refractory period where action potentials cannot be initiated.</p><p>The velocity at which action potentials can be propagated is crucial since it can limit the rate at which signals can be transmitted across neurons. There are two physical characteristics of the axon that heavily influence it:</p><ol><li><strong>Action potentials propagate faster in wider axons.</strong> If an axon is wider, there is more free space (less resistance) for the incoming Na+ to reach adjacent sections of membrane, thus a stronger current can reach them and depolarize them faster. This will occur along the full length of the axon increasing overall conduction velocity.</li><li><strong>Action potentials propagate faster in insulated axons.</strong> The membrane of the axon has pores through which ions can leak to the outside of the neuron reducing the strength of the depolarizing current flowing on the inside after an action potential is initiated. The myelin sheath that covers the axon’s membrane of some neurons serves as an an insulating layer preventing this leakage of current. Then, in these axons, a well-preserved depolarizing current from an action potential at a gap in the sheath (node of Ranvier) will reach the next one to depolarize it beyond threshold. In this way, the action potential will “jump” from one node to the next one as depicted in Figure 5.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9-tnJQpdQQrNURb5vnQGWQ.gif" /><figcaption><strong>Figure 5. Saltatory conduction. </strong>A myelin sheath increases the conduction velocity by insulating the membrane from Na+ leakage. In this way the action potential propagates rapidly from one node of Ranvier to the next one. Original video by Forsyth Tech Community College available at <a href="https://www.youtube.com/watch?v=WNRkZ3N73kk">https://www.youtube.com/watch?v=WNRkZ3N73kk</a></figcaption></figure><h3>Synaptic transmission and integration</h3><p>So far, we have been concerned on how a signal is electrically encoded and propagated within a neuron. However, adequate brain function relies on signals being transmitted across networks of neurons. Thus, it is necessary that the signal from an action potential in a neuron is able to reach other neurons. This interneuron communication happens at synapses and, therefore, the mechanism that enables it is called synaptic transmission.</p><p>The presynaptic neuron’s axon terminals form synapses with dendrites of many other postsynaptic neurons. For now, let’s focus only on one of these. When the depolarization from an action potential reaches a presynaptic axon terminal, voltage-gated calcium channels located in it will open to allow the passage of Ca2+ across the membrane. Since there is a much higher concentration of calcium outside the neuron, there will be a large influx of Ca2+ into the axon terminal. This increase of calcium concentration is the trigger that initiates the process of synaptic transmission.</p><p>The “messengers” of the synapse are special molecules called neurotransmitters. They are contained in vesicles within the axon terminal, and upon the influx of Ca2+ they are released to the outside of the membrane into the synaptic cleft. Once in the synaptic cleft, they will bind to specialized proteins called receptors which have specific binding sites for them. Receptors are embedded in the postsynaptic dendrite’s membrane (at a region called the postsynaptic density), so that they can have an effect on the postsynaptic neuron. The process of synaptic transmission is depicted in Figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LE2Doy9Gi-6GLmE_.png" /><figcaption><strong>Figure 6. Synaptic transmission. </strong>The depolarization from an action potential in the axon terminal causes the opening of voltage-gated calcium channels. This induces a large inward current of Ca2+ which serves as the signal for the release of neurotransmitter molecules into the synaptic cleft. After being released into the cleft, neurotransmitter molecules will bind to receptors in the postsynaptic density. Figure by Thomas Splettstoesser (<a href="http://www.scistyle.com/">www.scistyle.com</a>), CC BY-SA 4.0 &lt;<a href="https://creativecommons.org/licenses/by-sa/4.0">https://creativecommons.org/licenses/by-sa/4.0</a>&gt;, via Wikimedia Commons</figcaption></figure><p>Once neurotransmitter binds to a receptor, a variety of effects can follow depending on the neurotransmitter and the receptor types. An exposition of the full diversity of neurotransmitters and receptors is well beyond what we can cover here. So, we focus one neurotransmitter-receptor pair that will serve as a real example. We won’t dive into the details of their chemical properties, but only use them to illustrate the broader principles of the potential effects of synaptic transmission on the postsynaptic neuron. The neurotransmitter in question is the amino acid glutamate which is present in many synapses of the central nervous system. The AMPA family of receptors have binding sites for glutamate, and they belong to a wider category of receptors called transmitter-gated sodium channels which are sodium channels that open when their neurotransmitter is bound to them.</p><p>So, once a glutamate molecule binds to an AMPA receptor, it opens and allows an influx of Na+ into the postsynaptic neuron. This inward current of Na+ will cause a depolarization of the membrane. This depolarization is called an Excitatory Postsynaptic Potential (EPSP) and it must be noted that it is distinct from an action potential.</p><p>The depolarizing current from an EPSP typically originates at the postsynaptic density and travels down the dendrite towards the soma and the axon-hillock. However, due to leakage, part of the ionic current will escape the membrane and its strength will decay as it flows towards the axon. So, when it reaches the axon-hillock it will not be strong enough to surpass the threshold value to trigger an action potential.</p><p>However, every neuron forms synapses with thousands of others and it is the integration of these that allows the signals to keep flowing. Even though the depolarization from a single EPSP is not strong enough to trigger an action potential, the combined strength of many of them can be. In this way, a neuron can integrate the ionic current incoming from many synapses so that when this integrated depolarization reaches the axon-hillock, it is strong enough to initiate an action potential. In a sense, this action potential is the integration of the many signals being received by the postsynaptic neuron. As explained before, it will travel down the axon towards other synapses to be, in turn, transmitted to other neurons. In this way, the signals will continue to propagate throughout the neural networks of the brain.</p><h3>Final thoughts and remarks</h3><p>Signals transmission across neurons forms the cornerstone of brain function. We have explored the biophysical mechanisms that enable it. We saw how a signal starts as an electrical current of ions flowing down the axon of a neuron; how it is transmitted by chemical messengers outside the neuron into the synapses where it can induce an electrical signal in other neurons; how the integration of many signals of this kind enable their continuous propagation across neural networks.</p><p>We have scratched only the surface. There are numerous exceptions to the elemental principles we have explored. Not all synapse involve an axon and a dendrite, there are, for example, dendrite-to-dendrite synapses. Most of the synapses are chemical and operate with a neurotransmitter intermediary, but some are electrical and in them the ionic current can flow directly from one neuron into the other. We described only one type of postsynaptic response but there are a wide variety of them. Moreover, we did not cover exactly how the signal processing, enabled by the elemental biophysical mechanisms described, leads to a specific mental function.</p><p>The intention is that the words written here have provided the foundational knowledge to dive deeper into many fascinating topics in neuroscience and, especially, the motivation to do so.</p><h3>References</h3><p>The main source for this article are Chapters 2–5 from:</p><p>Bear, Mark, Barry Connors, and Michael A. Paradiso. <em>Neuroscience: exploring the brain, enhanced edition: exploring the brain</em>. Jones &amp; Bartlett Learning, 2020.</p><p>I can’t recommend this book enough for anyone interested in a clear, comprehensive, and intuitive introduction to neuroscience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee9722a9a3af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The beta-binomial model: an introduction to Bayesian statistics]]></title>
            <link>https://medium.com/@romoflow/the-beta-binomial-model-an-introduction-to-bayesian-statistics-154395875f93?source=rss-d58d1cf73159------2</link>
            <guid isPermaLink="false">https://medium.com/p/154395875f93</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[bayesian-inference]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <dc:creator><![CDATA[Rodrigo Morales]]></dc:creator>
            <pubDate>Sat, 13 Aug 2022 09:37:32 GMT</pubDate>
            <atom:updated>2022-08-13T09:37:32.159Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we introduce Bayesian inference through the beta-binomial model. This is a mathematically tractable model which allows a detailed analysis of the results and an intuitive understanding of the key elements of Bayesian inference. Even though the model itself is only suited for simple applications, the ideas it exposes remain relevant for more complex Bayesian models.</p><p>To ground the theoretical concepts, we consider an example application: analysing the home advantage in the football English Premier League (EPL) by looking into the percentage of matches won by the home team, which we call the home win rate. We deliberately focus on the 2020–2021 season to make the example more interesting. This season was particular because the matches were played without spectators or with limited attendance due to the Covid-19 pandemic.</p><p>The article does not require any prior knowledge of statistics (neither Bayesian nor frequentist), but it does assume a solid understanding of basic probability theory. In the first section, we provide a general introduction to the Bayesian inference framework. In the second section, we look into the beta-binomial model. In the third section, we use the model to infer the home win rate. In the final section, we conclude with a brief discussion on priors, which are a distinctive feature of Bayesian models.</p><h3>The Bayesian approach to statistical inference</h3><p>The Bayesian framework provides great flexibility in the quantification of uncertainty through probability theory. In this paradigm, a probability represents a measure of the degree of certainty about an event of interest. For example, during a rainy season, you might have a strong belief that it will rain on a given day. This belief can be represented with a probability value for the event of raining.</p><p>The core property of the framework is that it provides an intuitive and principled way to update probabilistic beliefs after observing data. For instance, if after waking up in this rainy season day, you look out of the window to find the sky full of clouds and people with raincoats in the street, it would be sensible to increase the probability value you had originally assigned to raining. Bayes’ theorem provides a systematic way of performing such update.</p><p>In the context of statistical inference, we are usually interested in estimating the value of a quantity of interest in the presence of uncertainty (e.g. the probability of raining or the probability that the home team wins a football match). This quantity is usually translated into a parameter of a probability distribution. We can then use the Bayesian framework to infer a probability distribution on such parameter given the observed data. For example, as we will see later, we can think of the probability of the home team winning a match as the parameter of a Bernoulli distribution, which we can infer after observing the results of some matches.</p><p>In general, we denote the parameter of interest by <em>Θ</em> and express our beliefs about its value through a probability distribution. More concretely, we can think of the probability statement <em>P(Θ=θ)</em> as the probability<a href="#4e52">¹</a> that the value of the parameter <em>Θ</em> is <em>θ</em>. Moreover, we can generalise this statement with a density function, <em>p(θ)</em>, which characterises the probability distribution on <em>Θ</em> . Such distribution allows to express our beliefs about the parameter <em>before</em> <em>observing the data; </em>thus, it is called the <strong>prior distribution</strong>. For example, if a priori we think that the local advantage is an important factor in football, then we would select a prior density that assign high probability mass to high values of the home win probability.</p><p>After we observe some data, which we denote by<em> y</em>, we need to update our beliefs accordingly. More specifically, we need to update the prior distribution, <em>p(θ),</em> to take into account the observed data. The notion of conditional probability becomes crucial for this purpose. We can express the updated distribution as<em> p(θ|y)</em> which can be understood as the distribution on <em>Θ</em> conditional on observing the data<em> y; </em>this is, <em>after observing the data</em>. Hence, it is called the <strong>posterior distribution</strong>.</p><p>The fundamental idea in Bayesian inference is to use the laws of probability to derive a rule for updating the prior, <em>p(θ)</em>, into the posterior, <em>p(θ|y)</em>. This update rule is called Bayes’ theorem. However, before looking into it, we need to think about a probability distribution on the possible values of the data<a href="#e0ab">²</a>, which we denote by <em>Y</em>. This is, we must specify a probability distribution for the data given the parameter value: <em>P(Y=y|Θ=θ)=p(y|θ)</em>. It is crucial to note that when we consider <em>p(y|θ)</em> as a function of <em>y</em>, it must be a valid probability distribution on<em> Y</em>, but when considered as a function of <em>θ</em>, it is called the <strong>likelihood function</strong> which is not necessarily a probability distribution on <em>Θ</em>.</p><p>Now, given the prior and the likelihood, we can derive the posterior with <strong>Bayes’ theorem</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*5B15wUxcwXgEXAEf_q5Gnw.png" /><figcaption><strong>Bayes’ Theorem</strong>: <em>p(θ)</em> is the prior distribution, <em>p(y|θ)</em> is the likelihood function, and p(y) is a normalizing constant, usually called the marginal likelihood.</figcaption></figure><p>Note that <em>p(y|θ)</em> in Bayes’ theorem is the likelihood function (i.e. it is viewed as a function of <em>θ</em>). <em>p(y)</em> does not depend on <em>θ </em>and it is the normalizing constant of the posterior distribution. It is called the marginal likelihood since it is obtained from marginalizing<em> Θ</em> out of the joint distribution <em>p(y,θ)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*oQw3aWaKyzGW4pGnteNr-A.png" /><figcaption>The <strong>marginal likelihood </strong>p(y) is obtained from marginalizing θ from the joint distribution p(y,θ). It can be viewed as the normalizing constant of the posterior distribution p(θ|y)</figcaption></figure><p>Once we obtain the posterior, <em>p(θ|y)</em>, we can make arbitrary probability statements about <em>Θ </em>given<em> y</em>. For example, we can consider the probability that the parameter is below a certain value: <em>P(Θ ≤ θ|y); </em>the probability that it lies within certain interval: <em>P(θ1≤Θ ≤ θ2|y);</em> or even find the values of the interval such that this probability is equal to some arbitrary value (e.g. 95%).</p><h3>The beta-binomial model</h3><p>Now we materialise the elements of Bayesian inference in the beta-binomial model. Recall that, as an illustrative example, we are interested in using the model to estimate the probability of the home team winning a match in the EPL. We call this probability the home win rate and denote it by <em>Θ</em>.</p><h4>Model specification: likelihood and prior</h4><p>The two key elements we need to specify in a Bayesian model are the prior distribution and the likelihood function. Then, we can use them in Bayes’ theorem to derive the posterior distribution.</p><p>It is usually easier to think in terms of the observable data to understand how the parameter relates to it. In light of this, we start by specifying the likelihood. In our example, we are only interested in whether the home team wins the match or not; hence, we do not need to distinguish between draws and away team wins. Then, we can think of each match in terms of a binary outcome: either the home team wins or not, and model this outcome as a Bernoulli random variable with parameter <em>Θ,</em> which represents the probability of the home team winning.</p><p>However, the data has results from more than one match (there are 380 matches in a season). Then, we need a likelihood that considers the joint outcomes of multiple Bernoulli instances. Such is the binomial distribution which models the probability of observing <em>y</em> home wins in <em>n</em> matches provided that each match has an identical home win probability given by <em>θ</em> and that the matches are independent of each other. Then, if the random variable representing the number of home wins among the <em>n</em> matches is denoted by <em>Y</em>, the binomial distribution is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*XcyiNkNJxMXAIcH8ncCacA.png" /><figcaption><strong>Binomial distribution: </strong>computes the probability of observing y home wins in n matches, when the matches are independent of each other and each match has the same home win probability, θ</figcaption></figure><p>To gain further intuition into the binomial distribution on <em>Y</em>, the figure below shows the probability mass function for some specific values of <em>Θ</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YQONwgTIDcGqba4ryLzQRQ.png" /><figcaption><strong>Binomial distribution for the home wins example under different values of Θ</strong>. The data contains results from one season which has 380 matches, then we fix n=380. Image by author.</figcaption></figure><p>To finish the model specification, we need to define a prior distribution on <em>Θ</em>. This is, arguably, a critical choice in a Bayesian model, since the results of the inference can be sensitive to it. The guiding principle for selecting a prior is that it should serve as the mechanism to endow the model with our prior knowledge about the question at hand. This knowledge might come from different sources, like expertise in the topic, previous studies, or historical data.</p><p>There might be various distribution families that are flexible enough to express our particular prior knowledge about the parameter. However, another factor to consider is mathematical convenience. In our simple example, a tractable model will provide enough flexibility to encode a wide spectrum of prior beliefs. In particular the beta distribution is a good choice, since it provides both flexibility and mathematical tractability. The beta distribution on <em>Θ</em> is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*7WH0VGdKjorFXFwP1c_YhA.png" /><figcaption><strong>Beta distribution. </strong>We use the beta distribution as the prior for Θ. It depends on two parameters (α,β) which will determine its shape and allow to encode diverse prior beliefs.</figcaption></figure><p><em>B(. , .)</em> is the <a href="https://en.wikipedia.org/wiki/Beta_function">beta function</a> which can be viewed as the normalizing constant of the distribution. α and β are parameters that define the shape of the distribution and will provide the flexibility to express a wide range of prior beliefs. The following animation shows how they achieve this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*ZAK-_QmK63vpLYiq0lWkhQ.gif" /><figcaption><strong>Beta distribution under different values of α and β</strong>. Note that the density can adopt a wide range of shapes that allow to encode diverse prior beliefs about the parameter. Image by Pabloparsil — Own work, CC BY-SA 4.0, <a href="https://commons.wikimedia.org/w/index.php?curid=89335966">https://commons.wikimedia.org/w/index.php?curid=89335966</a></figcaption></figure><p>As we will see in more depth in the next section, the summary statistics of the distribution can help to set the values of the prior parameters. The mean and variance of <em>Θ</em> under a beta distribution are given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*wPQz1ycia0l490CJfwUfWw.png" /><figcaption><strong>Mean and variance of the beta distribution.</strong> For convenience, we define k=α+β which determines the degree of concentration of the distribution.</figcaption></figure><p>For convenience, we have defined <em>k=α + β</em>. Note that the variance is decreasing in <em>k</em> which is sometimes called the concentration parameter<a href="#3aa1">³</a>.</p><h4>Derivation of the posterior</h4><p>Now we have all set to derive the posterior distribution using Bayes’ theorem. At this stage is when it becomes clear the mathematical convenience of using the beta prior. So, following Bayes’ theorem we got that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*pIkBs75hb5gbEE-jc4Rl4g.png" /><figcaption><strong>Derivation of the posterior distribution.</strong> For clarity, in the final step we have removed the constant terms that do not depend on θ. Note that the posterior is proportional to a functional form that resembles a beta distribution.</figcaption></figure><p>Note that the posterior density is proportional to the functional form of a beta distribution. A careful reader will identify that the proportionality constant must be precisely the beta normalizing constant (<em>1/B(.,.)</em>), and, therefore, the posterior is itself a beta distribution!</p><p>To see this result more clearly, let <em>α’=α+y</em> and <em>β’=n-y+β </em>and note that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*T0_SVJ40EZLNrBqpdxqQYg.png" /></figure><p>And since the posterior is a probability distribution it must be the case that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*eHvx3BC53Z2djTLqqYt3-w.png" /><figcaption><strong>The posterior is a beta distribution</strong> <strong>with parameters α’=α+y and β’=n-y+β. </strong>The normalizing constant, C, must be the beta normalizing constant, since the posterior has the functional form of a beta density.</figcaption></figure><p>Where we have deduced that the proportionality constant, <em>C</em>, must be the beta normalizing constant, since the posterior shares the functional form of a beta distribution up to a constant which must ensure that it integrates to 1 (i.e. a normalizing constant).</p><p>Now the mathematical convenience of the beta-binomial models is apparent: whenever we have a beta prior and a binomial likelihood, the posterior distribution will also be beta with parameters <em>α’=α+y</em> and <em>β’=n-y+β</em>. In cases like this one, we say that the prior distribution is conjugate with respect to the likelihood.</p><p>In the posterior distribution we can find a tradeoff between the prior knowledge and the data. To note this, we examine the posterior mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*YuUU9k2UusvxV5oibRM1PQ.png" /><figcaption><strong>The posterior mean</strong> is a weighted average between the data rate (y/n) and the prior mean (α/k). The weights are determined by n and k: if n&gt;k, the data weight is larger, and if k &gt;n, the prior weight is larger.</figcaption></figure><p>Note that the posterior mean represents a compromise between the data and the prior. In particular, the posterior mean is a weighted average of the data rate (<em>y/n</em>) and the prior mean (<em>α/k</em>), where the weights are determined by <em>n</em> and <em>k</em>. If <em>n&gt;k</em>, the data will have a larger weight than the prior, if the converse is true, the weight of the prior will be larger.</p><p>Viewing the posterior mean in this way allows an intuitive interpretation of the prior parameters: we can think of<em> k</em> as the prior sample size, this is, the number of matches that inform our prior beliefs or, equivalently, the number of matches we need to observe in the data for it for it to have a stronger weight than the prior knowledge. Similarly, we can think of <em>α</em> as the number of prior home wins. This is, out of the <em>k</em> prior matches <em>α</em> are home wins. Hence the prior mean, <em>α/k,</em> can be interpreted as the prior home win rate. Similarly, <em>β</em> can be thought of as the prior number of matches where the home team did not win.</p><h3>Inference of the home win rate</h3><p>Finally, we use the beta-binomial model to infer the home win probability in the 2020–2021 season of the EPL. For this, we use data from the results of the 380 matches in this season (data publicly available at <a href="https://www.kaggle.com/datasets/irkaal/english-premier-league-results">Kaggle</a> provided by <a href="https://www.kaggle.com/irkaal">@Alvin</a>). An important quirk of this season is that it occurred in the midst of the Covid-19 pandemic, so most of the matches were played without public or with a limited attendance, which clearly could affect the home win rate. The purpose of this example is purely didactical, since it is a real world example well suited to showcase the main ideas of the beta-binomial model and Bayesian inference.</p><p>Before deriving the posterior, we need to set the values for the prior parameters <em>α </em>and <em>β</em>. One way to do this is to use historical information. We know that in the 1900 matches of the five preceding seasons (2015–2016 to 2019–2020) the home win rate was 0.46. Then, we can think of 0.46 as the prior home win rate. Recall that we can interpret <em>k=α+β</em> as the prior sample size. In this case, it can be thought of as the number of matches that inform our prior knowledge. Thus, a sensible choice would be to set <em>k=1900</em> which is the number of historical matches that we are considering for setting the prior home win rate of <em>0.46</em>. Since <em>α </em>is the number of prior home wins, we set it to <em>α=0.46*k=874</em>. Finally, this means that<em> β=k-α=1026</em>.</p><p>Regarding the likelihood, we fix <em>n=380</em>, which is the number of matches in the observed data from the 2020–2021 season, and the observed number of home wins is <em>y=144</em>. Then, the data home win rate is <em>y/n=0.38.</em></p><p>Now, that we have our model fully specified, we can derive the posterior distribution. As explained in the previous section, the posterior is also a beta with parameters <em>α’=α+y=1018</em> and <em>β’=n-y+β=1262</em>. The figure below shows a visualisation of the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*JEo8AUGV3seydL4PiaYrKQ.png" /><figcaption><strong>Model with prior parameters α=874 and β=1026</strong>. The likelihood is scaled to make a clearer visualisation. The posterior leans towards the prior since k&gt;n. However, the data (via the likelihood) still has a noticeable effect in the posterior. Image by author.</figcaption></figure><p>Note that, as we explained in the previous section, the posterior distribution is a compromise between the prior and the likelihood. Since in this case, we set <em>k=1900&gt;380=n</em>, the prior is more concentrated than the likelihood and it has a stronger influence in the posterior. However, the likelihood still has a noticeable effect in shifting the posterior towards the data home rate win of <em>0.38</em>.</p><p>We can use the derived posterior to get the results of arbitrary probability queries. For example, we can find the central 95% probability interval (also called credible interval) for the home win rate, which is given by <em>(0.426, 0.466)</em>, as shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*1xW9_R04k9HySekrqe_tjw.png" /><figcaption><strong>The posterior 95% probability central interval of Θ is (0.426, 0.466)</strong>. It includes the prior home win rate of 0.46, but does not include the data home win rate of 0.38. Image by author.</figcaption></figure><p>We can also ask what is the probability that the home win rate is below the historical figure of 0.46, given the data. The answer is 0.90 as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*15RMNZ3B4Q2x9zviQbTfHA.png" /><figcaption><strong>The posterior probability that the home win rate is below 0.46 is 90%</strong>. Image by author.</figcaption></figure><p>Now, a reasonable argument is that our prior is overconfident because we are doing inference on a season with limited-attendance matches, whereas our prior is mostly informed by seasons before the pandemic. Then, if we are interested in assessing the home win rate during a pandemic season, it is sensible to reduce our confidence in such prior beliefs. Typically, the discussion in a Bayesian data analysis centers around the choice of prior, so it is important to properly justify this decision. Moreover, it is a good practice to assess how sensitive are the results obtained to different values of the prior parameters.</p><p>In light of the argument above, we consider an alternative model with a less-confident prior. As shown in the previous section, one way to express this is to reduce the prior sample size, <em>k</em>. For instance, let’s say that we want to reduce it to the point where we give the same weight to the prior and to the data. Then, we should set <em>k=n=380</em>. As shown in the figure below, this would induce equal weights for the data and the prior in the posterior mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*m7kOjC31xJ48bUtRBIm7LQ.png" /><figcaption><strong>Weights of the data and the prior in the posterior mean</strong> <strong>for different values of k</strong>. If we set k as the number of historical matches (1900), the prior mean will dominate the data. If we set k=n=380, the weights are equal.</figcaption></figure><p>If we proceed with this strategy and preserve the prior home win rate of <em>0.46</em>, we get the following prior parameters values: <em>α = 175 </em>and <em>β = 205. </em>Then, the resulting posterior parameters are α’=319 and β’=441 as shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*6fyFlvDGR7MYUT6E-S0Wyg.png" /><figcaption><strong>Model with prior parameters α = 175 and β=205</strong>. In this case k was selected such that the prior and the data have equal weights in the posterior mean. The posterior mean is precisely the midpoint between the maximum likelihood (y/n=0.37) and the prior mean (α/k=0.46) .</figcaption></figure><p>In this case, the posterior is centred in the midpoint between the prior mean, <em>α/k, </em>and data rate, <em>y/n, </em>which is also the maximum likelihood point. In this case, the 95% posterior credibility interval is <em>(0.385, 0.455)</em> which still does not include the observed home win rate of <em>0.38</em>, but now it also does not include the prior rate of <em>0.46</em>. Under this model specification, the probability that the home win rate is below the historical value of 0.46 is now close to 99%. So, indeed the results are sensitive to the prior parameters.</p><p>Now, a more extreme critic might argue that we should completely discard our prior knowledge, since it does not apply at all for the season we are considering<a href="#6c01">⁴</a>. This critic might ask for a more “objective” analysis in which we “let the data speak by itself”. Such setting is also possible to model with the Bayesian framework, and it might be a sensible one when we do not have any reliable prior information about the question at hand.</p><p>One way to use a prior with minimal information, also called uninformative prior or flat prior, is to choose a distribution which assigns equal density to every feasible value of <em>Θ.</em> In this case, we can use a uniform distribution on the interval [0,1]. Fortunately, the beta-binomial model is flexible enough to cover this setting, since the uniform distribution is a particular case of the beta when <em>α=β=1</em>. In this case, we get a beta posterior with <em>α’=145</em> and <em>β’=237</em>, which is shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*70hGJqMDUJXz96WeAETlWQ.png" /><figcaption><strong>Model with uninformative prior (α=β=1). </strong>In this case, the posterior is simply a scaled version of the likelihood. The data completely dominates the prior.</figcaption></figure><p>In this case the posterior is simply a scaled version of the likelihood. In particular, the posterior mode (a point estimate called maximum a posteriori) coincides with the maximum likelihood point (i.e. the data rate <em>y/n=0.38</em>). More explicitly, the value of <em>Θ</em> that maximises the likelihood also maximises the posterior density and this value is the data rate, <em>y/n,</em> which is usually called the maximum likelihood estimate<a href="#0fed">⁵</a>. Unsurprisingly, this setting provides even more distinct results: the 95% credible interval is now<em> (0.332, 0.429) </em>which does includes the observed home win rate of <em>0.38</em>, and does not include the historical figure of <em>0.46</em>. Additionally, the probability that the home win rate is below its historical value is close to 1. The table below summarises the results obtained under the three different settings of the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*QW0cSbSiKUrbn8uiYGUTAA.png" /><figcaption><strong>Results under the different model specifications</strong>. The results are clearly sensitive to the choice of prior parameters.</figcaption></figure><h3>A brief discussion on priors</h3><p>Priors are a distinctive feature of Bayesian inference. The choice of prior is inherently subjective, and, as showed in the example above, it can have a substantial effect on the results of a model. This could appear unsettling at first, and using an uninformative prior might seem as the most objective approach. However, a closer inspection reveals that such choice is not free of assumptions either. Moreover, in some cases it might even involve a very strong one! For instance, in the home advantage example, an implication of using an uninformative prior is that the information from previous seasons is deemed completely irrelevant for the estimation of the home win rate. A claim as strong as this one can only be justified under extraordinary circumstances, like a pandemic.</p><p>More generally, whenever we have reliable information about the questions at hand and it is not contain in the data, we should encode it in the prior. A prior does not necessarily introduce assumptions that were not present already, it simply makes them explicit. So, if used properly, it should be viewed as a strength of the Bayesian framework, rather than as a weakness. Altogether, it allows to have more transparency into the assumptions behind a model.</p><p>Code to reproduce example available at: <a href="https://github.com/Romoflow/beta-binomial/blob/master/model.ipynb">https://github.com/Romoflow/beta-binomial/blob/master/model.ipynb</a></p><p>Data used in the example available at: <a href="https://www.kaggle.com/datasets/irkaal/english-premier-league-results">https://www.kaggle.com/datasets/irkaal/english-premier-league-results</a></p><h4>Footnotes</h4><ol><li>This statement is not meaningful in the frequentist approach, since it consider parameters as fixed values rather than as random variables. <a href="#20fe">^</a></li><li>In this context, we use uppercase <em>Y</em> to distinguish the data as a random variable which might take on different possible values from the actual data that is observed which we denote by <em>y,</em> as it is a value of <em>Y</em>. <a href="#b2f0">^</a></li><li>For a more detailed explanation of the concentration see <em>Doing </em><a href="https://www.elsevier.com/books/doing-bayesian-data-analysis/kruschke/978-0-12-405888-0"><em>Bayesian Data Analysis</em></a> by John Kruschke. <a href="#84e4">^</a></li><li>This is perhaps too extreme, since some of the matches of the 2019–2020 season, which are part of our historical information, were already played without spectators due to the pandemic. Moreover, it is not uncommon that a few games in some seasons are played without attendance. However, for didactical purposes we entertain this argument. <a href="#02be">^</a></li><li>Finding the value that maximises the likelihood and using it as a point estimate of the parameter is a common approach in the frequentist paradigm. <a href="#9291">^</a></li></ol><h4>Further Reading</h4><p>Kruschke, J. K. (2011). <em>Doing Bayesian data analysis: A tutorial with R and BUGS.</em> Elsevier Academic Press.</p><p>Gelman, A., Carlin, J. B., Stern, H. S., &amp; Rubin, D. B. (1995). <em>Bayesian data analysis</em>. Chapman and Hall/CRC.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=154395875f93" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>