<?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 Matt Parvaneh on Medium]]></title>
        <description><![CDATA[Stories by Matt Parvaneh on Medium]]></description>
        <link>https://medium.com/@mattparvaneh?source=rss-5175c1788c24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PMppbPZM8CHpdhD1</url>
            <title>Stories by Matt Parvaneh on Medium</title>
            <link>https://medium.com/@mattparvaneh?source=rss-5175c1788c24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:26:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattparvaneh/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[A Gentle Introduction to Explainability for LLMs]]></title>
            <link>https://medium.com/demistify/a-gentle-introduction-to-explainability-for-llms-5176f1c0c8ea?source=rss-5175c1788c24------2</link>
            <guid isPermaLink="false">https://medium.com/p/5176f1c0c8ea</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[explainable-ai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Matt Parvaneh]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 20:22:14 GMT</pubDate>
            <atom:updated>2025-01-29T20:22:14.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-Vqltf3bn9XgBHTh" /><figcaption>Image source: <a href="https://theblue.ai/blog/llm-observability-en/">https://theblue.ai/blog/llm-observability-en/</a></figcaption></figure><p>If you have spent any time on the internet recently, you’ve almost certainly heard of Large Language Models. Powering our favorite tools such as ChatGPT and Claude, these models are making our lives significantly easier due to their ever-impressive language generation skills. They have taken on the role of being our own personal AI assistants, helping us with tasks as simple as writing emails all the way to navigating critical decisions in life (I totally haven’t used ChatGPT for this…)</p><p>However, they aren’t only capable of providing us with answers for generic daily tasks or writing-specific activities. They are trained on such a vast, diverse trove of data, allowing them to do more than just calm my neurosis about whether an important email sounds polite enough. Even if they are not yet <em>perfectly </em>ready for it, they have the potential to serve as an assistive tool to professionals that work in high-stakes environments, such as doctors or lawyers. The critical problem that hinders widespread use of LLMs in environments like these is that these users need to be certain of the veracity of the claims being made by the tools. Otherwise, there could be dire consequences.</p><p>Consider the following example:</p><blockquote>Somewhere in a futuristic hospital, a young doctor is operating a very busy ER late at night, and a new patient comes in. The doctor makes some initial observations about the patient’s symptoms and orders some blood work to be collected immediately. Given the pressure that they feel to juggle all the other patients in the room, the doctor decides to rely on a chatbot for a quick diagnosis. In the prompt, they pass in information such as the list of symptoms (e.g., chronic fatigue, joint pain, and a persistent mild rash), along with the results of the blood work and ask it to make a diagnosis and suggest a treatment plan. The chatbot comes back with its answer, believing that the most likely ailment the patient has is an autoimmune disorder (e.g., Lupus), so it prescribes a steroidal anti-inflammatory drug as an immediate treatment. The doctor, short on time, follows this plan to help the patient and sends them on their way. In actuality, the patient had a viral infection which manifested the same physical symptoms. Steroidal anti-inflammatory drugs have an immunosuppressant effect, and in this case, make it harder for the patient’s body to fight off the infection. As a result, the patient comes back to the ER just a few days later, still alive thankfully, but in much worse condition than before.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*39BUi1RzwtDAxuEK" /><figcaption>Image Source: <a href="https://www.vecteezy.com/vector-art/8573227-illustration-with-a-doctor-and-a-patient-consultation-with-the-doctor-at-the-hospital-making-a-diagnosis-prescribing-treatment-vector-illustration">https://www.vecteezy.com/vector-art/8573227-illustration-with-a-doctor-and-a-patient-consultation-with-the-doctor-at-the-hospital-making-a-diagnosis-prescribing-treatment-vector-illustration</a></figcaption></figure><p>Errors of this nature often happen because the data used to train a model shapes the types of responses that it will give. A pre-trained LLM that hasn’t been fine-tuned specifically for medical diagnostics probably hasn’t seen the most representative dataset of cases similar to the one provided by the fictitious doctor above. Thus, it might be doomed to constantly get the answer wrong for this type of question, as it can only answer it based on what it knows. To make matters worse, we as users cannot see what data was most relevant toward generating a particular answer that the LLM came up with. All of this is to say that while LLMs are incredibly useful and probably should become a commonplace tool for use in these types of situations in the future, there are many important situations where they must be used with <em>extreme</em> care right now. In order for these tools to be ready for safe use in these environments, an important prerequisite is that their results should be <em>explainable</em>.</p><h3>What is Explainability?</h3><p>In the realm of AI, <em>explainability</em> refers to the ability to <em>break down </em>the way that a model or system was able to come to an output. As both creators and users of these tools, we want to develop an understanding of how a model works as a whole, as well as how it generates specific predictions. Consider the example of an overly simple decision tree that predicts whether an individual owns a house, split on the features of a age and income as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*dIrsUjVeuXyA-EbW" /></figure><p>For example, if we consider a 32 year old that has an annual income of $450,000, our tree would predict that they do own a house, and we can clearly see why when we trace through the tree.</p><p>However, with models as complex as LLMs, it is not so simple. Modern models have immense numbers of parameters and are trained on unfathomably vast amounts of data, making it hard to see how each of these components shapes the way the model works.</p><p>LLMs undergo a process of <strong>next-token prediction</strong>, whereby they generate a probability distribution over their vocabulary and pick one of the most statistically likely tokens that would come next. The likelihood of a token coming next is based on the relationships the LLM has learned about language, syntax, and semantics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pg42QogWmbXylB3U" /></figure><p>That’s another part of the problem. It’s simply <em>learning the way we generate language</em>. When it comes to answering questions, it’s putting together strings of words that would be statistically most likely to come together in response to a prompt, and most of the time, it ends up being right. But when it comes down to it, an LLM does not go through the same steps of logical reasoning that we as humans would to reach an answer. Despite all these challenges, there have been massive undertakings in recent research to try and elucidate what goes on underneath-the-hood in LLMs.</p><h3>Explainability for LLMs</h3><h4>How do LLMs Make Specific Predictions</h4><p>One of the first ways we look into explaining how LLMs work is by focusing on how they generate <em>specific</em> <em>outputs</em> or <em>local explanations</em>. These are particularly useful because they can help us see what goes on inside the LLM to generate output from a specific prompt. If you’re thinking that we will get simple explanations that mimic a human thought process, then you’re out of luck. What we do see instead, is a very useful overview of how an LLM picks the most likely tokens to string together to generate a response to our prompt.</p><p>Most research on local explanations focus on two types of methods: <em>feature-attribution methods</em> and <em>attention-based methods </em>[1]. Feature attribution methods are those that focus on how the features of the input — tokens, in LLMs — affect the output generated by the model. The reason that these methods are called attribution methods is because we know that every single word in our input prompt exerts some role on the final output generated by the LLM, no matter how small. So, we <em>attribute</em> a particular weight to each token that describes its contribution to the final output. Attention-based methods are those that look at the way the attention mechanism in the transformer architecture that underlies LLMs captures relationships amongst tokens, giving us an idea again of how influential certain relationships between tokens are to the generation of output.</p><h4>Shapley Values</h4><p>A good example representing how we can provide local explanations through feature-attribution is known as the Shapley value method. Calculating these Shapley values requires extensive mathematics which we won’t go into here, but <a href="https://arxiv.org/abs/2404.01332">this paper</a> provides a great example of it. The Shapley value method is based on ideas from game theory, so we decide to treat each word in the prompt as a member of a game. The game here is one of prediction influence. <em>How much</em> can each player influence the LLM’s next token prediction? The higher the player contributes toward the overall prediction made by the LLM, the higher its payout (or attribution) [2]. Let’s go through a small example that illustrates how this works at a high level.</p><p>We begin with a simple prompt for a sentence completion task. We provide the entirety of a sentence except for the last word, and ask the LLM to predict <em>one</em> token that represents the word that most likely finishes off a sentence, like so:</p><blockquote>“I want to drive a ____”</blockquote><p>Let’s say that the LLM predicts the token <strong>“car”</strong> to complete the sentence. Then, we proceed to see how each word in the input prompt contributes to the prediction of “car” as the next token, as opposed to something else, like “truck”. We can figure out how each word contributes to the token prediction by <em>generating every possible ordered subset of words</em> in the prompt that excludes one of the words, and seeing what the likelihood of the token “car” being predicted is (e.g., excluding “drive”, we get “I”, “I want”, “I want to”, “I want to a”). And we have to do this for every word in the prompt. Using a lot of complex mathematical formulas, we can aggregate the results in such a way that we get final “attributions” or numerical scores that represent the influence that a specific token had on the prediction of the token “car”. In this case, maybe it looked something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F556XrSkO0Sb3VJw" /></figure><p>A method like this gives us a clear idea of what words are very influential toward the output that our LLM came up with. While it might not be easy to extract re-usable, broad insights about how the LLM captures relationships in language, it can give us an idea of why the prompt that we wrote directly caused the output that we saw.</p><h4>Attention-based Methods</h4><p>Another common class of local explanation methods for LLM results are those that focus on the attention mechanism of the model’s transformer architecture. For anyone who is not familiar, attention refers to the way that transformer models capture relationships between all the different tokens in a sequence, learning which ones are most important to correlate together. This helps it understand how the words in the sentence relate to each other, allowing it to digest the semantics of the sequence so that it can generate the right output [1]. To see how we can look at these underlying attention “scores” between elements of a sequence for explainability, let’s consider the example of sentiment analysis for movie review as the task of choice for our LLM.</p><p>Given some movie reviews, we want our model to predict whether they are <em>positive</em>, <em>neutral</em>, or <em>negative</em> reviews. Here, we are going to use a version of BERT that is fine-tuned for this type of task to make our prediction. Let’s say we give it the following review:</p><blockquote><em>“The movie was so bad, I would have rather stared at a blank screen for 2 hours!”</em></blockquote><p>Ouch. What does Bert think?</p><blockquote><strong>Sentiment Prediction:</strong> <em>Negative</em></blockquote><p>Yikes.</p><p>Well, we got our prediction, but in the theme of this article, we want to know <em>why</em> we got this prediction. Recall that we said that the attention mechanism allows us to focus on the relationships between every pair of words in our sequence. The relationship for each pair is given an attention score, a numerical value where <em>higher</em> means that the relationship between these two words is very important to the overall meaning of the sentence. The best way to visualize these scores is through a heat map, like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/0*baRinVqjHKl1H_Fk" /></figure><p>Here, we can see the scores for every pair of words in the sequence. Take special note of pairs with the [CLS] token — in the BERT model, this is a token that encodes and aggregates important information about the sequence in order to make a classification. If we take a look along the top row, we can see that some words are given more attention toward the overall classification (i.e., <em>negative</em>) which can be seen as lighter shades of purple. Here, some key words that meet this description are “bad” and “blank”. Even amongst pairs of words in the sentence itself, you can see that the model tends to associate important relationships between certain words by attending to them together, for example “so” and “bad”.</p><p>It’s clear to see that this can help us in seeing how the model captures relationships between words in the process of figuring out how to make a specific prediction. However, it is not always easy to interpret something like this. All of this is to say that while useful, it can be important to use a method like this in conjunction with others to get a clearer picture of why the model does what it does.</p><h3>What do LLMs know in general?</h3><p>Like I mentioned above, sometimes a local explanation might leave a bit more to be desired when it comes to understanding our models. When we want to see broader patterns regarding how our LLM works, we can lean on <em>global explanations</em>, which focus on the semantic knowledge and relationships that LLMs inherently possess. This is more intrinsically tied to the overall architecture and learned parameters of the LLM, gained through the training process.</p><h4>Probing methods</h4><p>Probing is a method that can be employed to ask the LLM questions directly when we have expected answers in mind. This helps us see what kind of information the LLM has been able to learn and verify that it is consistent with our own knowledge in the real-world. A common example of probing that is typically seen in modern research is known as <em>knowledge probing</em>. All this method entails is simply asking an LLM questions about simple facts that we know to be true, and seeing if it knows them too [1]. For example, if we want to test an LLM’s knowledge on stable facts such as historical events, we could just ask it questions and verify the answers that it happens to give us, like so:</p><p><strong>When was the Declaration of Independence of the United States signed?</strong> Answer: August 2, 1776 (<em>Correct</em>)</p><p><strong>Who was the leader of Great Britain during World War II?</strong> Answer: Winston Churchill (<em>Correct</em>)</p><p><strong>Who was the first emperor to rule entirely within the Edo period in Japan? </strong>Answer: Emperor Komei (<em>incorrect</em>, it should be Emperor Go-Mizunoo)</p><p>In this case, we can tell that this LLM may not be completely reliable as a source of historical facts, since it cannot consistently output the correct answer every single time. However, what makes a probing method like this so useful is that we can ask questions like this to identify gaps in the knowledge possessed by an LLM. In so doing, we can infer what types of information it may not have seen in its training data, leading to hallucinations like these. For creators of LLMs, this could tell them what data needs to be added into subsequent training processes to improve the quality of the output of these models.</p><h3>What is Missing?</h3><h4>Are these methods enough?</h4><p>While I only explained a tiny fraction of the existing explainability methods out there, in my opinion, it feels like there is something missing. It is clear from the methods we have discussed in this article that almost all of them require at least some level of technical knowledge of LLM internals. This does not take away from how useful any of these methods are. For example, these techniques can be leveraged by researchers and developers to figure out what can be done to improve the quality of responses generated by the LLM. In the same vein, many of these methods provide a way of debugging issues with response generation, such as hallucinations or bizarre token prediction behaviour.</p><p>However, there does not yet seem to be any mechanism of explainability geared toward the end-user, particularly the non-technical one. If we recall the motivating example for this article — safe use of LLMs in high-stakes applications — we would want professionals with no understanding of LLM internals to be able to gain insights into how the tools generate their answers. This would help them have more confidence in whether they can trust the answer given by a model, or whether they should treat it with a bit more skepticism and rely more on their own knowledge.</p><h4>Future direction of explainability research</h4><p>Addressing the missing factors listed above is certainly not easy. It may even be enough to let the experts use these current methods to improve models to the point where problems like hallucination are less likely to occur. However, there is current research trending in the direction of allowing real-time end-user explainability to become more of a possibility.</p><p>One such effort involves the inclusion of explicit confidence indicators for every LLM response. These indicators would be created by taking the probabilities generated for specific token predictions by the LLM (i.e., logits) or through methods that can estimate uncertainty in predictions using Bayesian methods [3]. With this, you could allow the LLM to provide its own confidence score along with its response, denoting how strongly it believes the response to be correct.</p><p>There are also approaches taken from the Human-Computer Interaction (HCI) side of computing that investigate what kinds of explanations would be most digestible to users, so that they trust the LLM’s responses more and use them responsibly. All of these directions would help usher in the development of real-time end-user explanations into commercial chatbot tools, making it easier for the average user to incorporate LLM-generated responses into their decision making processes.</p><h3>What can you do right now?</h3><p>All this aside, what can <em>you</em> <em>do</em> <em>right now</em> to gain more confidence in the responses that are generated by the LLMs you use? While I am not an expert on building with LLMs yet myself, here are some suggestions that I think could be really useful:</p><p><strong>1. Incorporate Retrieval-Augmented Generation (RAG) into your systems.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/0*9BIj6vFUJ6oc_hbL" /></figure><p>RAG is a very popular augmentation to LLM-based systems where you store supplementary information that is external to the LLM’s own knowledge, but is available for access by the LLM. By storing relevant documents in a vector database (e.g., specific case law excerpts for a legal chatbot), the system in question can query this database for documents that are semantically related to the prompt in question, and then provide the LLM with this additional information. Given that this information should be factually correct, it makes the LLM <em>a lot</em> <em>less likely</em> to hallucinate. Beyond this, you can even get the system to reference the documents that it used to generate its answers, so you can basically check its sources for yourself. This is effectively an example of real-time explainability!</p><p><strong>2. Engineer your prompts to evoke a reasoning trace in natural language.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*3oHSHxERNsYyjJBo" /><figcaption>Image source: <em>Chain-of-Thought Prompting Elicits Reasoning in Large Language Models (Wei et al.) — </em><a href="https://arxiv.org/abs/2201.11903">https://arxiv.org/abs/2201.11903</a></figcaption></figure><p>For any prompts that require simple reasoning from an LLM, you can make sure to ask it to explain itself explicitly as part of its response. These types of instructions will get the LLM to output a reasoning trace, logically explaining each step it took to arrive at its answer. We know that the underlying mechanism of answer generation is the next token prediction mechanism, which uses tokens that are statistically likely to come after one another. LLMs do not directly undergo the same reasoning process that we as humans would, which would be something like what we are getting it to do here.</p><p>However, we cannot be so sure that this type of reasoning is not valid either. There is an argument to be made about emergent properties of LLMs, which mean features of the system that exist due to the complex interactions between all of its individual components. It is a very interesting idea which you can read more about <a href="https://duncsand.medium.com/explainable-ai-140912d31b3b">here</a> in an article by Duncan Anderson, and it could be a reason to actually treat these types of explanations of the LLMs’ reasoning as useful. Regardless, it can give you an idea of what steps the LLM would take to reach the specific answer, and you can individually fact-check each step in its answer generation process.</p><p><strong>3. Fine-tune the model to your specific downstream task (if applicable)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*KroTcC_q6WW04Z4R" /><figcaption>Image source: <a href="https://www.labellerr.com/blog/reinforcement-learning-from-human-feedback/">https://www.labellerr.com/blog/reinforcement-learning-from-human-feedback/</a></figcaption></figure><p>Finally, if you are using your model for a very specific task, for example, text classification or medical diagnosis, you can fine-tune it to achieve better prediction accuracy or output quality for these tasks. By including more comprehensive labeled training data related to the task at hand, we can make sure that the LLM improves its own internal knowledge of how to complete the task effectively. While this may not directly provide any kind of explainability benefit to our model, it can allow us to have more peace of mind in that we know the model has likely improved its learning and internal representations of knowledge for our domain of interest.</p><h3>References</h3><p>[1] H. Luo and L. Specia, “From understanding to utilization: A survey on explainability for large language models,” arXiv.org, <a href="https://arxiv.org/abs/2401.12874">https://arxiv.org/abs/2401.12874</a> (accessed Jan. 26, 2025).</p><p>[2] B. Mohammadi, “Explaining large language models decisions using Shapley Values,” arXiv.org, <a href="https://arxiv.org/abs/2404.01332">https://arxiv.org/abs/2404.01332</a> (accessed Jan. 26, 2025).</p><p>[3] F. Tonolini, N. Aletras, J. Massiah, and G. Kazai, “Bayesian prompt ensembles: Model uncertainty estimation for black-box large language models,” ACL Anthology, <a href="https://aclanthology.org/2024.findings-acl.728/">https://aclanthology.org/2024.findings-acl.728/</a> (accessed Jan. 26, 2025).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5176f1c0c8ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/demistify/a-gentle-introduction-to-explainability-for-llms-5176f1c0c8ea">A Gentle Introduction to Explainability for LLMs</a> was originally published in <a href="https://medium.com/demistify">deMISTify</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vision Transformers (ViT): a Promising Approach for Action Recognition]]></title>
            <link>https://medium.com/demistify/vision-transformers-vit-a-promising-approach-for-action-recognition-b0005c5063ae?source=rss-5175c1788c24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0005c5063ae</guid>
            <category><![CDATA[vision-transformer]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[action-recognition]]></category>
            <dc:creator><![CDATA[Matt Parvaneh]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 05:57:49 GMT</pubDate>
            <atom:updated>2024-11-01T05:57:49.815Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*PcSbdCS4doYmpIjS" /><figcaption>Labeled examples of actions performed in videos. (Source: <a href="https://link.springer.com/article/10.1007/s10489-021-03068-w">https://link.springer.com/article/10.1007/s10489-021-03068-w</a>)</figcaption></figure><p>Within the field of computer vision, there has always been a multitude of interesting problems to be solved. As of late, however, it feels like many of the core tasks, such as object detection and image segmentation, have already been solved. These tasks have massive bodies of literature surrounding them and models that are extremely accurate at completing them. Despite this, there is one field that still looks to be in its early days of solutioning, being video processing.</p><p>Video processing, while harbouring some history over the past two decades, is a field that has only recently seen major strides, particularly due to many advancements in deep learning. A likely reason for this is that video processing as a whole has more complexity than regular image processing alone, because the visuals are not static! With videos, we have to consider time (also known as the “temporal dimension”), on top of the existing spatial dimensions of images. It is a relatively similar problem to image processing, but we now have to shift to a paradigm of thinking about processing a sequence of images through time. This brings with it plenty of new challenges, like making sure we don’t lose context or semantics over time steps, so that the output of our models remains accurate! Evidently, there is a lot more to think about when considering how we should build models to operate on video inputs than for images alone.</p><p>Video processing as a general field entails using specialized computer vision models to extract insights from videos, which can be anything from object detection to the classification of activities in them. One of the most interesting and important applications of video processing, that we are going to talk about here, is <strong>action recognition</strong>. Action recognition is the process of getting models to be able to correctly classify and further analyze human actions in video. This kind of task is invaluable, as it would allow for the automation of what would typically be very time-consuming and manual tasks in a variety of different contexts. For example, with highly accurate action recognition, security and surveillance systems would automatically be able to detect any unlawful actions on the premises being monitored, or any kind of autonomous vehicle would be able to classify actions of pedestrians or other cars on the road and respond accordingly.</p><p>In recent years, one of the most dominant models to handle this type of task was the <strong>3-Dimensional Convolutional Neural Network</strong>, or <strong>3DCNN</strong>. This took the ideas of a CNN and applied them in conjunction with a new temporal dimension, treating video as a sequence of static image frames over time. Assuming no familiarity with CNNs, here is a brief explanation: CNNs are a type of neural network specialized for computer vision. These networks consist of multiple layers, each of which learns a set of features about images by applying “filters” that extract a specific feature (e.g., vertical edges) across the entire image. Each layer learns a unique set of features, which start off looking at lower-level, localized elements of images (e.g., edges, texture) whereas the deeper layers close to the output will learn very high-level patterns or elements (e.g., shapes, faces). Overall, when an input image is put into a model like this, the idea is that it will be transformed into a new representation which make it easier to extract specific insights. These insights are often tied to classification tasks, where we might do something like recognize what type of object is seen in the image. A 3DCNN, as mentioned above, takes this idea and extends it to video input, by treating videos as a sequence of images or “frames” over time. The idea is that we can make our filters 3D to apply them over a chunk of several frames of the video at once, to try and capture our features over small regions of the video input field, and for a few sequential frames at a time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*nkHQnuSXfWSGW6HH" /><figcaption>A 3 x 3 x 3 filter (width x height x depth) operating over an input image (in blue, on the left), which results in a single output (green square, on the right). (Source:<a href="https://www.tensorflow.org/tutorials/video/video_classification">https://www.tensorflow.org/tutorials/video/video_classification</a>)</figcaption></figure><p>While these models were quite effective at correctly recognizing actions in videos, they still seemed to have some limitations. The biggest problem with the 3DCNN architecture, especially for the task of action recognition, was that it lacked the ability to truly learn long-range dependencies well. To make the idea of a long-range dependency clearer, think of long-running actions in a video, like a person walking or holding on to something. 3DCNNs were not good at capturing patterns like these over long time-ranges, because the depth of their filters (which determines how many frames or “time-steps” they look at at once) had to be kept small for them to work properly. In addition to this, the increase in their receptive fields (what the current layer can “see” in the video frames) in deeper layers of the network may cause lots of important patterns in the frames to get glossed over. Overall, this left something more to be desired in terms of models in the field of action recognition. It was believed that something that could classify and recognize actions in videos more accurately could be created…</p><h3>Enter Vision Transformers</h3><p>This is where Vision Transformers (ViTs) come in! At this point, everyone with even a hobbyist’s interest in Machine Learning has heard of the transformer model, and ViTs are simply an application of this architecture to CV tasks.</p><h3>What Are They?</h3><p>Transformers, in general, have become one of the most popular neural network architectures in recent years. If you are not familiar with them, <a href="https://blogs.nvidia.com/blog/what-is-a-transformer-model/">NVIDIA’s blog</a> provides an amazing explanation of how they work at a high-level. As a quick overview, transformers are models that are exceptional at breaking down sequences of inputs (like a sentence) into smaller parts, and understanding how those parts all relate to one another. By doing this, it learns important relationships within the sequences it receives as input, that helps it generate correct outputs tailored to the task at hand. Examples of outputs for a transformer are new sequences of data (e.g., the same input sentence translated into a different language) or classifications related to the input sequence (e.g., analyzing the sentiment of a sentence).</p><p>In this section, we will go through a more detailed overview of the inner workings of a Vision Transformer, specifically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/0*4yAgp0bjyWYXLaqu" /><figcaption>Original design of a ViT for Static Image Processing. Source: <a href="https://arxiv.org/abs/2010.11929">https://arxiv.org/abs/2010.11929</a></figcaption></figure><p>A pure vision transformer takes in patches of a single image as input. This is a way of <em>tokenizing </em>our input image, exactly like we would have with a transformer that operates on natural language! We want to turn our inputs into smaller parts called tokens, so that we can determine how each of these tokens relates to all the other ones in the sequence. Whether the input sequence is as simple as a sentence, or as complex as a high-resolution video, this idea is the same in all transformer models. In the case of a ViT, we want to successfully determine what other image patches are important to pay <em>attention</em> to for any given image patch.</p><p>Regular transformer models tend to have an encoder-decoder architecture, which can also be seen in ViTs. However, it is more common for ViTs to have an encoder component on its own. As such, this type of encoder-only architecture will be explained here.</p><p>An encoder is a neural network with the purpose of encoding our input image in a new representation that captures the relationships between all the different smaller patches of it. As input, the encoder takes in a vector of all the patches in a single image concatenated together. Each vector contains not only an image, but positional encodings as well. These help the encoder retain the spatial information about how all the patches are put together in the overall image. This vectorized input will go through a number of layers stacked on top of each other, most notably including some layers that have the <strong>Self-Attention</strong> mechanism. These special layers calculate <em>attention values</em> for the input, which is a mathematical representation of how important each patch of the image is to every other patch. These layers will often be referred to as <em>Multi-Head Attention layers</em>, because we perform this process of calculating attention a number of times for the same input, so we can learn multiple new representations of the input. Each head will likely generate slightly different attention values, representing learned relationships between the different patches that are all unique. The concept of attention can definitely be confusing at first, but the most important takeaway here is that the <strong>encoder is learning broad contextual relationships between all the parts of the image</strong>. This attention mechanism is intended to help the ViT understand both the granular features within the image, as well as how they fit into the context of the picture as a whole. The idea is that this will allow us to generate final outputs that may be more accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*tYWQJeQ-wIMzqUWB.png" /><figcaption>Example of a ViT architecture for classifying plants. Source: <a href="https://www.researchgate.net/figure/Structure-and-Processing-Method-of-Visual-Transformer_fig4_371428193">https://www.researchgate.net/figure/Structure-and-Processing-Method-of-Visual-Transformer_fig4_371428193</a></figcaption></figure><p>The output of the encoder will typically feed into a Multi-layer Perceptron (MLP) head, which will often be a block of fully-connected layers with activation functions, including a Softmax activation at the end. This MLP head is responsible for taking the encoded input, and generating an output from it. The Softmax activation in the MLP head is crucial here, because it creates a probability distribution over our possible outputs. In the case of using a ViT for image classification, the output of this MLP head would be a set of probability scores for all the classes of animals that our model knows, allowing us to select the most likely one each time (e.g., for classification of images of animals, outputs would be “cat”, “dog”, etc.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*HZBIkRVAOGIKGbo5" /><figcaption>Source: <a href="https://openaccess.thecvf.com/content/ICCV2021/papers/Arnab_ViViT_A_Video_Vision_Transformer_ICCV_2021_paper.pdf">https://openaccess.thecvf.com/content/ICCV2021/papers/Arnab_ViViT_A_Video_Vision_Transformer_ICCV_2021_paper.pdf</a></figcaption></figure><p>Now, we started off this article talking about videos, so I’m sure you’ve been wondering how this all applies to that. Right now, all that has been explained is the application of ViTs to static images. Well, if we think of videos as a collection of frames over time, then this makes it really easy to apply ViTs to video. If we turn a single image into a set of patches with dimensions <em>W x H</em>, as shown in the figure above, we can repeat this process T times for every frame in the video, and pass that into the encoder as a data matrix of dimensions <em>W x H x T </em>[1]. While there are other architectures for a ViT, this is a very popular one, and it is quite simple to understand as well.</p><h3>Why Are They So Good?</h3><p>You might be wondering about the benefits that the task of video processing has seen from the introduction of ViTs. As mentioned earlier, a key problem with the 3DCNN architecture that created a need for a better solution was its inability to learn long-range dependencies on input data very well. Of course, when considering videos, this is important. Especially for action recognition, you want a model to be able to notice actions that are sustained across time in the video, and how they might evolve. With the attention mechanism that the underlying transformer architecture of ViTs provides, this is much easier. It provides a built-in method of “focusing” on other parts of the input, which can be frames in previous or subsequent time steps of a video. This attention mechanism allows for the model to focus on as much of the adjacent frames or patches within an image as it needs to, determining relationships through sequences of time in a video that are <em>much longer</em> than what 3DCNNs are capable of.</p><p>In addition to this, ViTs have empirically shown themselves to be a lot <em>more accurate</em> at action recognition and image classification under <strong>different kinds of alterations</strong> to images [2]. For example, if frames in a video were to suddenly have occlusions, thanks to the context we have kept through attention, ViTs tend to show an ability to still make the right predictions. On the other hand, 3DCNNs tend to struggle with this. These are merely two examples of how ViTs address some of the shortcomings of 3DCNNs, which allows them to perform better in comparison!</p><p>Of course, no solution is completely flawless, and some of the issues that can be seen with ViTs include that they are computationally expensive (the calculation of attention requires plenty of floating-point operations, a.k.a FLOPs) and they often need to be trained on very large datasets to start seeing improved accuracy over traditional models like CNNs. However, bear in mind that ViTs are relatively new, and there are already significant advancements working on addressing these limitations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/0*RY5WskjLolhneG9l" /><figcaption>Architecture Diagram of the SAIS model, explained below. Source: <a href="https://www.nature.com/articles/s41551-023-01010-8">https://www.nature.com/articles/s41551-023-01010-8</a></figcaption></figure><h3>ViTs: They’re Surgically Precise!</h3><p>An interesting application of ViTs to action recognition was performed in 2023 by Kiyasseh et al., who set out to <strong>decode surgeon activity from surgical videos</strong>. As a brief explanation to why this is necessary, being able to classify the activity of surgeons during operation can help automate the process of labeling and analyzing the surgical phases and gestures within an operation. These labeled videos can be used to teach students how to perform procedures and show surgeons themselves what could have been done better, all of which will contribute to surgeons doing better by their patients in the future.</p><p>The researchers built a model they referred to as SAIS (Surgical Activity Intelligence System) and fed it intraoperative videos of tissue dissection and suturing from the Keck Hospital of USC as input [3]. Specifically, they had the model take a sequence of video frames and a sequence of optical flow maps of the video in parallel, to two separate sets of pre-trained ViTs. Optical flow maps refer to the patterns of how objects and other visual elements move through a video over time, allowing the ViT to get a better understanding of the temporal dynamics of the video. The network begins by extracting the spatial features of both the surgical video frames and the optical flow maps, capturing relationships between frames of each type of data through the attention mechanism. For this particular study, it was important for the model to be able to pick up on more granular, individual surgical gestures (e.g., a <em>hook</em>, <em>clip</em>, or <em>cut</em> during dissection) as well as broader phases of actions within surgery (e.g., <em>needle driving</em> during suturing), both of which are possible with ViTs thanks to the attention mechanism!</p><p>Once the spatial and temporal dynamics have been learned and extracted individually within each modality of input (image and optical flow), these new, learned representations of each type of input are combined. This creates a final new representation of the content in the surgical videos, with an understanding of the progression of actions in the video over time. This aggregated output then goes through a number of other sets of layers in the SAIS model (which you can read about in more detail <a href="https://www.nature.com/articles/s41551-023-01010-8">here</a>), ultimately resulting in one of three types of classification outputs, listed below:</p><ul><li>Recognition of <strong>subphases</strong> during surgery (e.g., <em>needle driving</em> during suturing)</li><li>Classification of surgical <strong>gestures </strong>(granular actions, e.g., <em>cut</em> during the dissection subphase)</li><li>Assessment of <strong>skill levels </strong>(classify level of skill for a given surgical action as <em>low</em> or <em>high)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*inXBCwq8fNKoj9tT" /><figcaption>Three types of classifications in the study. Image Source: <a href="https://www.nature.com/articles/s41551-023-01010-8">https://www.nature.com/articles/s41551-023-01010-8</a></figcaption></figure><p>What is remarkable about this study is that the same architecture could be used across all the various classification tasks, albeit with fine-tuning to make sure the SAIS model would be successful across all of them. For each type of classification, it was shown that the SAIS model reliably decoded all of the types of outputs above, generalizing not only across a variety of different videos in the dataset, but also across different hospitals (e.g., testing on surgical video data from hospitals outside of USC). This was a major advancement, not only because it performed so well, but also since it performed significantly better than historical models that were adapted for this kind of task, such as I3D (Inflated 3D ConvNet, a type of 3DCNN as mentioned earlier) [3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*7Fj42sfUoEdnwRlX" /><figcaption>AUC graphs for surgical subphase prediction, including generalization to videos from different hospitals.<em> </em>Source: <a href="https://www.nature.com/articles/s41551-023-01010-8">https://www.nature.com/articles/s41551-023-01010-8</a></figcaption></figure><p>What is so important about this result is that it can be applied broadly to so many other industries. An architecture like this, while adapted to the task of surgical action recognition, could likely be used as inspiration for action recognition in other fields. Whether we use this type of architecture in fields like security to detect criminal activity automatically, or in novel contexts like sports, to help athletes understand videos of their opponents’ tactics better, there will be a lot of amazing applications to come out of this!</p><h3>References</h3><p>[1] A. Arnab <em>et al.</em>, “Vivit: A video vision transformer,” <em>2021 IEEE/CVF International Conference on Computer Vision (ICCV)</em>, pp. 6816–6826, Oct. 2021. doi:10.1109/iccv48922.2021.00676</p><p>[2] Tobias van der Werff, “CNN vs. Vision Transformer: A practitioner’s guide to selecting the right model,” Tobias van der Werff, <a href="https://tobiasvanderwerff.github.io/2024/05/15/cnn-vs-vit.html">https://tobiasvanderwerff.github.io/2024/05/15/cnn-vs-vit.html</a> (accessed Oct. 31, 2024).</p><p>[3] D. Kiyasseh <em>et al.</em>, “A Vision Transformer for decoding surgeon activity from surgical videos,” <em>Nature Biomedical Engineering</em>, vol. 7, no. 6, pp. 780–796, Mar. 2023. doi:10.1038/s41551–023–01010–8</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0005c5063ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/demistify/vision-transformers-vit-a-promising-approach-for-action-recognition-b0005c5063ae">Vision Transformers (ViT): a Promising Approach for Action Recognition</a> was originally published in <a href="https://medium.com/demistify">deMISTify</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>