
<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.2">Jekyll</generator><link href="https://cgarbin.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://cgarbin.github.io/" rel="alternate" type="text/html" /><updated>2024-07-21T21:33:59-04:00</updated><id>https://cgarbin.github.io/feed.xml</id><title type="html">Christian Garbin’s personal blog</title><subtitle>Articles collected during my machine learning master's and Ph.D. work at Florida Atlantic University.
</subtitle><author><name>Christian Garbin</name></author><entry><title type="html">Improve writing by learning how to read</title><link href="https://cgarbin.github.io/how-to-read-and-write-a-paper/" rel="alternate" type="text/html" title="Improve writing by learning how to read" /><published>2024-05-05T00:00:00-04:00</published><updated>2024-05-05T00:00:00-04:00</updated><id>https://cgarbin.github.io/how-to-read-and-write-a-paper</id><content type="html" xml:base="https://cgarbin.github.io/how-to-read-and-write-a-paper/">&lt;p&gt;The advice in &lt;em&gt;&lt;a href=&quot;http://ccr.sigcomm.org/online/files/p83-keshavA.pdf&quot;&gt;How to Read a Paper&lt;/a&gt;&lt;/em&gt; changed how I read scientific papers. I used to read them linearly, struggling through each section in order. The three-pass approach was liberating. It freed my mind from having to understand everything the first time.&lt;/p&gt;

&lt;p&gt;Eventually, I realized I could turn the advice around to write a good paper.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;Most of what follows applies to scientific papers. However, we can use the same principles for other types of writing.&lt;/p&gt;

&lt;h2 id=&quot;what-makes-a-good-paper&quot;&gt;What makes a good paper?&lt;/h2&gt;

&lt;p&gt;Good papers have, at a minimum, these qualities:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;They are correct. Their claims are supported by evidence and are internally consistent.&lt;/li&gt;
  &lt;li&gt;They are easy to read. They are well-structured, with clear language, good grammar and attention to detail.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The first quality is exclusionary. An incorrect paper does not benefit from any other quality. We will spend the rest of this post discussing the second quality.&lt;/p&gt;

&lt;h2 id=&quot;how-to-write-a-good-paper&quot;&gt;How to write a good paper&lt;/h2&gt;

&lt;p&gt;Here, we will apply the advice from &lt;em&gt;How to Read a Paper&lt;/em&gt; to writing a good paper. We will use the three-pass approach and see how it applies to writing.&lt;/p&gt;

&lt;h3 id=&quot;the-first-pass&quot;&gt;The first pass&lt;/h3&gt;

&lt;p&gt;The main point of the first pass is to convince the user that the paper’s topic is worth reading and that it is well structured.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;ol&gt;
    &lt;li&gt;Carefully read the title, abstract, and introduction&lt;/li&gt;
    &lt;li&gt;Read the section and sub-section headings, but ignore everything else&lt;/li&gt;
    &lt;li&gt;Read the conclusions&lt;/li&gt;
  &lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;S. Keshav&lt;/cite&gt; — &lt;a href=&quot;http://ccr.sigcomm.org/online/files/p83-keshavA.pdf&quot;&gt;How to Read a Paper&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How to turn that “read” advice into “write” advice:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Choose a title that communicates the paper’s main point&lt;/strong&gt;. Don’t try to be clever. The title should be clear and concise. It should tell the reader what the paper is about.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Write a short, to the point abstract&lt;/strong&gt;. This is the first opportunity to motivate the reader. A good abstract explains the research problem, why it is important to work on it, the challenges, and the main results in a few sentences. Note that these are fundamental questions. You may not be ready to write the paper if you can’t answer them.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Write a clear introduction that sets the stage for the rest of the paper&lt;/strong&gt;. Use it to entice the reader to keep reading. The introduction should cover the same items as the abstract but in more detail.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Choose section and subsection titles that tell a story&lt;/strong&gt;. The section titles for scientific papers often follow a rigid structure (introduction, related work, methodology, results, discussion, conclusion). However, we have more freedom for the subsections. Use precise and concise titles that tell the reader what to expect. For example, “Approach 1” and “Approach 2” are not good subsection titles. Better titles to help pique the reader’s interest are “Approach 1: Using a neural network” and “Approach 2: Using a decision tree”.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here are a few lessons that took me a while to learn:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;If I don’t have good answers for the fundamental items in the abstract, my research is not yet ready. I may even have a problem with the research topic and scope, a fundamental issue that needs to be addressed before spending more time on the research.&lt;/li&gt;
  &lt;li&gt;I do not need to write the abstract and introduction first. Writing them last may be easier (as long as the abstract items have been answered – this is about writing the abstract, not the research itself).&lt;/li&gt;
  &lt;li&gt;In fact, writing a paper is not a linear process. I may write the results first, then go back to methods, then write the introduction, the abstract, the discussion, and finally, the conclusion. As long as the research is solid, choose the order that makes it easier to write.&lt;/li&gt;
  &lt;li&gt;But having a roadmap helps. I write a table of contents before starting to write. It helps me see the big picture and how to break down the sections into logical and engaging subsections.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;the-second-pass&quot;&gt;The second pass&lt;/h3&gt;

&lt;p&gt;The main point of the second pass is to help the reader understand the paper’s content.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;ol&gt;
    &lt;li&gt;Look carefully at the figures, diagrams and other illustrations in the paper. Pay special attention to graphs.
Are the axes properly labeled? Are results shown with
error bars, so that conclusions are statistically significant? Common mistakes like these will separate
rushed, shoddy work from the truly excellent.
…&lt;/li&gt;
  &lt;/ol&gt;

  &lt;p&gt;After this pass, you should be able to grasp the content of the paper. You should be able to summarize the main thrust of the paper, with supporting evidence, to someone else.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;S. Keshav&lt;/cite&gt; — &lt;a href=&quot;http://ccr.sigcomm.org/online/files/p83-keshavA.pdf&quot;&gt;How to Read a Paper&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How to turn that “read” advice into “write” advice:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Don’t rely on text alone to convey your ideas&lt;/strong&gt;. Support the text with figures, tables, and diagrams.
    &lt;ol&gt;
      &lt;li&gt;Chris Olah’s blog has superb examples of figures and diagrams supporting the text explanations, such as &lt;a href=&quot;https://colah.github.io/posts/2015-08-Understanding-LSTMs/&quot;&gt;the one on how LSTM works&lt;/a&gt;.&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use detailed captions for figures, tables, and diagrams&lt;/strong&gt;. Assume the reader will read only the captions and none of the paper’s text. The captions should be self-contained and explain the main points. “Results for approach 1” is a bad caption. A better caption to keep the reader engaged is “Result from experiments for approach 1, using neural networks to solve the problem. The graph shows it performs well in the first ten epochs, then overfits. This problem sparked the idea for approach 2 (figure 2).”&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Avoid trivial mistakes that undermine the paper’s credibility&lt;/strong&gt;. Trivial mistakes indicate sloppiness and make the reader doubt the paper’s results.
    &lt;ol&gt;
      &lt;li&gt;Make sure that the axes are properly labeled, that the figures have legends, and that the color schemes are clear and accessible (a &lt;a href=&quot;https://nickch-k.github.io/DataCommSlides/Easy_Mistakes_to_Avoid.html&quot;&gt;list of common errors and how to fix them&lt;/a&gt;).&lt;/li&gt;
      &lt;li&gt;Carefully review table columns and row labels.&lt;/li&gt;
      &lt;li&gt;Run the entire paper through a spell and grammar checker. In this day and age, there is no excuse for typos and grammar mistakes.&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here are a few lessons that that took me a while to learn:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Have a “hero picture” (or diagram). This picture summarizes or explains the most important concepts in the paper and is placed in visible places, such as the bottom of the first page or the top of the second page (and remember to write a self-contained caption). Readers are drawn to pictures. A good picture can make the reader want to read the paper. For example, the figure at the top of the second page &lt;a href=&quot;https://arxiv.org/pdf/2105.03020&quot;&gt;on this paper&lt;/a&gt; explains at a glance the main contributions of the paper: a large dataset curated by experts (self-promotion warning: I’m one of the authors, but the idea to put this picture strategically came from another coauthor – I first thought it was a gimmick, but I now appreciate the value). As a bonus, this picture can be used as a &lt;a href=&quot;https://en.wikipedia.org/wiki/Graphical_abstract&quot;&gt;graphical abstract&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Read the paper aloud, including captions (to another coauthor, if you have one). Seriously. This is the most effective of all the “how to make it easier to read” tips I know. If you can’t read it aloud without stumbling, the reader will have a hard time reading it silently.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;the-third-pass&quot;&gt;The third pass&lt;/h3&gt;

&lt;p&gt;The main point of the third pass is to convince the user that the paper’s results are significant and well-supported.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The key to the third pass is to attempt to virtually re-implement the paper: that is, making the same assumptions as the authors, re-create the work. By comparing this re-creation with the actual paper, you can easily identify not only a paper’s innovations, but also its hidden failings and assumptions.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;S. Keshav&lt;/cite&gt; — &lt;a href=&quot;http://ccr.sigcomm.org/online/files/p83-keshavA.pdf&quot;&gt;How to Read a Paper&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;How to turn that “read” advice into “write” advice:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ensure that the results are statistically significant&lt;/strong&gt;. Use error bars, p-values, or other statistical measures to show that the results are not due to chance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Perform &lt;a href=&quot;https://en.wikipedia.org/wiki/Ablation_(artificial_intelligence)&quot;&gt;ablation studies&lt;/a&gt;&lt;/strong&gt; to show the impact of different components of your approach and to prove that the results come from your approach, not other factors.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Here are a few lessons that that took me a while to learn:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Anticipate questions. If you were a reviewer, what would you ask? Answer those questions in the paper. Ask a trusted colleague to read the paper and ask them what questions they have. Don’t disregard their questions as “obvious” or “unimportant.” If they have those questions, so will the reviewers.&lt;/li&gt;
  &lt;li&gt;At the same time, keep the main body brief and use appendices for additional information. Keep the main body focused on the main points, then use the appendices to provide additional information for the curious reader.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;above-all-dont-lose-the-reader-in-the-first-pass&quot;&gt;Above all, don’t lose the reader in the first pass&lt;/h2&gt;

&lt;p&gt;If you remember only one thing from this post: &lt;strong&gt;the first pass is so important that it may be the last&lt;/strong&gt;. Don’t lose the reader in the first pass.&lt;/p&gt;

&lt;p&gt;Or, as Keshav puts it:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“[W]hen you write a paper, you can expect most reviewers (and readers) to make only one pass over it. Take care to choose coherent section and sub-section titles and to write concise and comprehensive abstracts. If a reviewer cannot understand the gist after one pass, the paper will likely be rejected; if a reader cannot understand the highlights of the paper after five minutes, the paper will likely never be read.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;S. Keshav&lt;/cite&gt; — &lt;a href=&quot;http://ccr.sigcomm.org/online/files/p83-keshavA.pdf&quot;&gt;How to Read a Paper&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;more-reading-on-writing&quot;&gt;More reading on writing&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.americanscientist.org/blog/the-long-view/the-science-of-scientific-writing&quot;&gt;The Science of Scientific Writing&lt;/a&gt; argues that &lt;em&gt;“complexity of thought need not lead to impenetrability of expression; we demonstrate a number of rhetorical principles that can produce clarity in communication without oversimplifying scientific issues.”&lt;/em&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1807.03341&quot;&gt;Troubling Trends in Machine Learning Scholarship&lt;/a&gt; says that &lt;em&gt;“papers are most valuable to the community when they act in service of the reader, creating foundational knowledge and communicating as clearly as possible.”&lt;/em&gt; – then proceeds to explain what prevents that and how to fix it.&lt;/li&gt;
  &lt;li&gt;The “Writing papers” section in &lt;a href=&quot;https://karpathy.github.io/2016/09/07/phd/&quot;&gt;Andrej Karpathy’s &lt;em&gt;A Survival Guide to a PhD&lt;/em&gt;&lt;/a&gt;. Advice from someone who has written and read many papers.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.nngroup.com/articles/how-users-read-on-the-web/&quot;&gt;How to Read on the Web&lt;/a&gt; – &lt;em&gt;“They don’t. People rarely read Web pages word by word; instead, they scan the page, picking out individual words and sentences.”&lt;/em&gt; – shows how to help guide the reader’s eyes to the most important parts of the page.&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Christian Garbin</name></author><category term="writing" /><category term="reading" /><category term="papers" /><summary type="html">Turn the advice in &quot;How to Read a Paper&quot; around to write a good paper.</summary></entry><entry><title type="html">Using LLMs to summarize GitHub issues</title><link href="https://cgarbin.github.io/using-llms-for-summarization/" rel="alternate" type="text/html" title="Using LLMs to summarize GitHub issues" /><published>2023-11-05T00:00:00-04:00</published><updated>2024-07-21T00:00:00-04:00</updated><id>https://cgarbin.github.io/using-llms-for-summarization</id><content type="html" xml:base="https://cgarbin.github.io/using-llms-for-summarization/">&lt;p&gt;This project is a learning exercise on using large language models (LLMs) for summarization. It uses GitHub issues as a practical use case that we can relate to.&lt;/p&gt;

&lt;p&gt;The goal is to allow developers to understand what is being reported and discussed in the issues without having to read each message in the thread. We will take the &lt;a href=&quot;/images/2023-11-05/github-issue-original.jpg&quot;&gt;original GitHub issue with its comments&lt;/a&gt; and generate a summary like &lt;a href=&quot;/images/2023-11-05/github-issue-summarized.jpg&quot;&gt;this one&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;UPDATE 2024-07-21&lt;/strong&gt;: With the &lt;a href=&quot;https://openai.com/index/gpt-4o-mini-advancing-cost-efficient-intelligence/&quot;&gt;announcement of GPT-4o mini&lt;/a&gt;, there are fewer and fewer reasons to use GPT-3.5 models. I updated the code to use the GPT-4o and GPT-4o mini models and to remove the GPT-4 Turbo models (they are listed under &lt;a href=&quot;https://openai.com/api/pricing/&quot;&gt;“older models we support”&lt;/a&gt;, hinting that they will eventually be removed).&lt;/p&gt;

&lt;p&gt;We will review the following topics:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;How to prepare data to use with an LLM.&lt;/li&gt;
  &lt;li&gt;How to build a prompt to summarize data.&lt;/li&gt;
  &lt;li&gt;How good are LLMs at summarizing text and GitHub issues in particular.&lt;/li&gt;
  &lt;li&gt;Developing applications with LLMs: some of their limitations, such as the context window size.&lt;/li&gt;
  &lt;li&gt;The role of prompts in LLMs and how to create good prompts.&lt;/li&gt;
  &lt;li&gt;When not to use LLMs.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The code for these experiments is available on &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/llm-github-issues&quot;&gt;this GitHub repository&lt;/a&gt;. This &lt;a href=&quot;https://youtu.be/5sDD0WNDZkc&quot;&gt;YouTube video&lt;/a&gt; walks through the sections below, but note that it uses the first version of the code. The code has been updated since then.&lt;/p&gt;

&lt;!--more--&gt;

&lt;h2 id=&quot;overview-of-the-steps&quot;&gt;Overview of the steps&lt;/h2&gt;

&lt;p&gt;Before we start, let’s review what happens behind the scenes when we use LLMs to summarize GitHub issues.&lt;/p&gt;

&lt;p&gt;The following diagram shows the main steps:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Get the issue and its comments from GitHub&lt;/em&gt;: The application converts the issue URL the user entered in (1) to a GitHub API URL and requests the issue, then the comments (2). The GitHub API returns the issue and comments in JSON format (3).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Preprocess the data&lt;/em&gt;: The application converts the JSON data into a compact text format (4) that the LLM can process. This is important to reduce token usage and costs.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Build the prompt&lt;/em&gt;: The application builds a prompt (5) for the LLM. The prompt is a text that tells the LLM what to do.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Send the request to the LLM&lt;/em&gt;: The application sends the prompt to the LLM (6) and waits for the response.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Process the LLM response&lt;/em&gt;: The application receives the response from the LLM (7) and shows it to the user (8).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/overview-steps.png&quot; alt=&quot;Overview of the steps&quot; class=&quot;align-center&quot; style=&quot;width:75%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;We will now review each step in more detail.&lt;/p&gt;

&lt;h2 id=&quot;quick-get-started-guide&quot;&gt;Quick get-started guide&lt;/h2&gt;

&lt;p&gt;This section describes the steps to go from a GitHub issue like &lt;a href=&quot;https://github.com/microsoft/semantic-kernel/issues/2039&quot;&gt;this one&lt;/a&gt; (&lt;a href=&quot;/images/2023-11-05/github-issue-original.jpg&quot;&gt;click to enlarge&lt;/a&gt;)…&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/github-issue-original.jpg&quot; alt=&quot;Original GitHub issue&quot; class=&quot;align-center&quot; style=&quot;width:10%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;…to LLM-generated summary (&lt;a href=&quot;/images/2023-11-05/github-issue-summarized.jpg&quot;&gt;click to enlarge&lt;/a&gt;):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/github-issue-summarized.jpg&quot; alt=&quot;Summarized GitHub issue&quot; class=&quot;align-center&quot; style=&quot;width:25%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Follow the “quick get-started guide” on the &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/llm-github-issues#quick-get-started-guide&quot;&gt;GitHub repository&lt;/a&gt; to start the application if you want to follow along.&lt;/p&gt;

&lt;p&gt;Once the application is running, enter the URL for the issue above, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;https://github.com/microsoft/semantic-kernel/issues/2039&lt;/code&gt;, and click the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Generate summary with &amp;lt;model&amp;gt;&lt;/code&gt; button to generate the summary. It will take a few seconds to complete.&lt;/p&gt;

&lt;div class=&quot;notice&quot;&gt;
&lt;!-- markdownlint-disable-next-line MD033 --&gt;
&lt;ul&gt;
  &lt;li&gt;Large language models are not deterministic and may be updated anytime. The results you get may be different from the ones shown here.&lt;/li&gt;
  &lt;li&gt;The GitHub issue may have been updated since the screenshots were taken.
&lt;!-- markdownlint-disable-next-line MD033 --&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;In the following sections, we will go behind the scenes to see how the application works.&lt;/p&gt;

&lt;h2 id=&quot;what-happens-behind-the-scenes&quot;&gt;What happens behind the scenes&lt;/h2&gt;

&lt;p&gt;This section describes the steps to summarize a GitHub issue using LLMs. We will start by fetching the issue data, preprocessing it, building an appropriate prompt, sending it to the LLM, and finally, processing the response.&lt;/p&gt;

&lt;h3 id=&quot;step-1---get-the-github-issue-and-its-comments&quot;&gt;Step 1 - Get the GitHub issue and its comments&lt;/h3&gt;

&lt;p&gt;The first step is to get the raw data using the GitHub API. In this step we translate the URL the user entered into a GitHub API URL and request the issue and its comments. For example, the URL &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;https://github.com/microsoft/semantic-kernel/issues/2039&lt;/code&gt; is translated into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039&lt;/code&gt;. The GitHub API returns a JSON object with the issue. &lt;a href=&quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039&quot;&gt;Click here&lt;/a&gt; to see the JSON object for the issue.&lt;/p&gt;

&lt;p&gt;The issue has a link to its comments:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&quot;comments_url&quot;: &quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039/comments&quot;,
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;We use that URL to request the comments and get another JSON object. &lt;a href=&quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039/comments&quot;&gt;Click here&lt;/a&gt; to see the JSON object for the comments.&lt;/p&gt;

&lt;h3 id=&quot;step-2---translate-the-json-data-into-a-compact-text-format&quot;&gt;Step 2 - Translate the JSON data into a compact text format&lt;/h3&gt;

&lt;p&gt;The JSON objects have more information than we need. Before sending the request to the LLM, we need to extract the pieces we need for the following reasons:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Large objects cost more because &lt;a href=&quot;https://openai.com/pricing&quot;&gt;most LLMs charge per token&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;It takes longer to process large objects.&lt;/li&gt;
  &lt;li&gt;Large objects may not fit in the LLM’s context window (the context window is the number of tokens the LLM can process at a time).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this step, we take the JSON objects and convert them into a compact text format. The text format is easier to process and takes less space than the JSON objects.&lt;/p&gt;

&lt;p&gt;This is the start of the JSON object returned by the GitHub API for the issue.&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;{
  &quot;url&quot;: &quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039&quot;,
  &quot;repository_url&quot;: &quot;https://api.github.com/repos/microsoft/semantic-kernel&quot;,
  &quot;labels_url&quot;: &quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039/labels{/name}&quot;,
  &quot;comments_url&quot;: &quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039/comments&quot;,
  &quot;events_url&quot;: &quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039/events&quot;,
  &quot;html_url&quot;: &quot;https://github.com/microsoft/semantic-kernel/issues/2039&quot;,
  &quot;id&quot;: 1808939848,
  &quot;node_id&quot;: &quot;I_kwDOJDJ_Yc5r0jtI&quot;,
  &quot;number&quot;: 2039,
  &quot;title&quot;: &quot;Copilot Chat: [Copilot Chat App] Azure Cognitive Search: kernel.Memory.SearchAsync producing no   ...

  &quot;body&quot;: &quot;**Describe the bug**\r\nI'm trying to build out the Copilot Chat App as a RAG chat (without
           skills for now). Not sure if its an issue with Semantic Kernel or my cognitive search...
           ...many lines removed for brevity...
           package version 0.1.0, pip package version 0.1.0, main branch of repository]\r\n\r\n**Additional
           context**\r\n&quot;,
   ...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;And this is the compact text format we create out of it.&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Title: Copilot Chat: [Copilot Chat App] Azure Cognitive Search: kernel.Memory.SearchAsync producing no
results for queries
Body (between '''):
'''
**Describe the bug**
I'm trying to build out the Copilot Chat App as a RAG chat (without skills for now). Not sure if its an
issue with Semantic Kernel or my cognitive search setup. Looking for some guidance.
...many lines removed for brevity...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To get from the JSON object to the compact text format we do the following:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Remove all fields we don’t need for the summary. For example, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;repository_url&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;node_id&lt;/code&gt;, and many others.&lt;/li&gt;
  &lt;li&gt;Change from JSON to plain text format. For example, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{&quot;title&quot;: &quot;Copilot Chat: [Copilot Chat App] Azure ...&lt;/code&gt; becomes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Title: Copilot Chat: [Copilot Chat App] Azure ...&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Remove spaces and quotes. They count as tokens, which increase costs and processing time.&lt;/li&gt;
  &lt;li&gt;Add a few hints to guide the LLM. For example, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Body (between ''')&lt;/code&gt; tells the LLM that the body of the issue is between the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;'''&lt;/code&gt; characters.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/llm-github-issues/blob/main/docs/post-processed-issue-comments.txt&quot;&gt;Click here&lt;/a&gt; to see the result of this step. Compare with the JSON object for the &lt;a href=&quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039&quot;&gt;issue&lt;/a&gt; and &lt;a href=&quot;https://api.github.com/repos/microsoft/semantic-kernel/issues/2039/comments&quot;&gt;comments&lt;/a&gt; to see how much smaller the text format is.&lt;/p&gt;

&lt;h3 id=&quot;step-3---build-the-prompt&quot;&gt;Step 3 - Build the prompt&lt;/h3&gt;

&lt;p&gt;A &lt;a href=&quot;https://developers.google.com/machine-learning/resources/prompt-eng&quot;&gt;prompt&lt;/a&gt; tells the LLM what to do, along with the data it needs.&lt;/p&gt;

&lt;p&gt;Our prompt is stored in &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/llm-github-issues/blob/main/llm.ini&quot;&gt;this file&lt;/a&gt;. The prompt instructs the LLM to summarize the issue and the comments in the format we want (the &lt;em&gt;“Don’t waste…“&lt;/em&gt; part comes from &lt;a href=&quot;https://learn.microsoft.com/en-us/semantic-kernel/ai-orchestration/plugins/&quot;&gt;this example&lt;/a&gt;).&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;You are an experienced developer familiar with GitHub issues.
The following text was parsed from a GitHub issue and its comments.
Extract the following information from the issue and comments:
- Issue: A list with the following items: title, the submitter name, the submission date and
  time, labels, and status (whether the issue is still open or closed).
- Summary: A summary of the issue in precisely one short sentence of no more than 50 words.
- Details: A longer summary of the issue. If code has been provided, list the pieces of code
  that cause the issue in the summary.
- Comments: A table with a summary of each comment in chronological order with the columns:
  date/time, time since the issue was submitted, author, and a summary of the comment.
Don't waste words. Use short, clear, complete sentences. Use active voice. Maximize detail, meaning focus on the content. Quote code snippets if they are relevant.
Answer in markdown with section headers separating each of the parts above.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;step-4---send-the-request-to-the-llm&quot;&gt;Step 4 - Send the request to the LLM&lt;/h3&gt;

&lt;p&gt;We now have all the pieces we need to send the request to the LLM. Different LLMs have different APIs, but most of them have a variation of the following parameters:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The model: The LLM to use. As a general rule, larger models are better but are also more expensive and take more time to build the response.&lt;/li&gt;
  &lt;li&gt;System prompt: The instructions we send to the LLM to tell it what to do, what format to use, and so on. This is usually not visible to the user.&lt;/li&gt;
  &lt;li&gt;The user input: The data the user enters in the application. In our case, the user enters the URL for the GitHub issue and we use it to create the actual user input (the parsed issue and comments).&lt;/li&gt;
  &lt;li&gt;The temperature: The higher the temperature, the more creative the LLM is. The lower the temperature, the more predictable it is. We use a temperature of 0.0 to get more precise and consistent results.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are the main ones we use in this project. There are &lt;a href=&quot;https://txt.cohere.com/llm-parameters-best-outputs-language-ai/&quot;&gt;other parameters&lt;/a&gt; we can adjust for other use cases.&lt;/p&gt;

&lt;p&gt;This is the relevant code in &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/llm-github-issues/blob/main/llm.py&quot;&gt;llm.py&lt;/a&gt;:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;n&quot;&gt;completion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;client&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;completions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;create&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;messages&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;role&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;system&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;content&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prompt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;role&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;user&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;content&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;user_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# We want precise and repeatable results
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;step-5---show-the-response&quot;&gt;Step 5 - Show the response&lt;/h3&gt;

&lt;p&gt;The LLM returns a JSON object with the response and usage data. We show the response to the user and use the usage data to calculate the cost of the request.&lt;/p&gt;

&lt;p&gt;This is a sample response from the LLM (using the &lt;a href=&quot;https://platform.openai.com/docs/guides/gpt/chat-completions-api&quot;&gt;OpenAI API&lt;/a&gt;):&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;ChatCompletion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;choices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;finish_reason&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'stop'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;index&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;message&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ChatCompletionMessage&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;content&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;
&lt;span class=&quot;s&quot;&gt;'&amp;lt;response removed to save space&amp;gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;role&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'assistant'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;function_call&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;created&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1698528558&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'gpt-3.5-turbo-0613'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;object&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;'chat.completion'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;usage&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;CompletionUsage&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;completion_tokens&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;304&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;prompt_tokens&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1301&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_tokens&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1605&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Besides the response, we get the token usage. The cost is not part of the response. We must calculate that ourselves following the &lt;a href=&quot;https://openai.com/pricing&quot;&gt;published pricing rules&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;At this point, we have everything we need to show the response to the user.&lt;/p&gt;

&lt;h2 id=&quot;developing-applications-with-llms&quot;&gt;Developing applications with LLMs&lt;/h2&gt;

&lt;p&gt;In this section we will go through a few examples to see how to use LLMs in applications. We will start with simple cases that work well, then move on to cases where things don’t behave as expected and how to work around them.&lt;/p&gt;

&lt;p&gt;This is a summary of what is covered in the following sections.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;#a-simple-github-issue-to-get-started&quot;&gt;A simple GitHub issue first to see how LLMs can summarize&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#a-large-github-issue&quot;&gt;A large GitHub issue that doesn’t fit in the context window of a basic LLM&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#better-summaries-with-a-more-powerful-model&quot;&gt;A more powerful model for a better summary&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#the-introduction-of-gpt-4o-mini&quot;&gt;The introduction of GPT-4o mini&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#the-importance-of-using-a-good-prompt&quot;&gt;The importance of using a good prompt&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#if-all-we-have-is-a-hammer&quot;&gt;Sometimes we should not use an LLM&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;a-simple-github-issue-to-get-started&quot;&gt;A simple GitHub issue to get started&lt;/h3&gt;

&lt;p&gt;We will start with a simple case to see how well LLMs can summarize.&lt;/p&gt;

&lt;p&gt;Start the application as described in the “quick get-started guide” on the &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/llm-github-issues#quick-get-started-guide&quot;&gt;GitHub repository&lt;/a&gt; to follow along. Then choose the first issue in the list of samples, &lt;em&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;https://github.com/openai/openai-python/issues/488&amp;gt; (simple example)&lt;/code&gt;&lt;/em&gt; and click the &lt;em&gt;“Generate summary with…“&lt;/em&gt; button (&lt;a href=&quot;/images/2023-11-05/example1-choose-issue.jpg&quot;&gt;click to enlarge&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/example1-choose-issue.jpg&quot; alt=&quot;Choose example GitHub issue for first example&quot; class=&quot;align-center&quot; style=&quot;width:50%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;After a few seconds we should get a summary like the picture below. At the top we can see the token count, the cost (derived from the token count), and how long it took for the LLM to generate the summary. After that we see the LLM’s response. Compared with the &lt;a href=&quot;https://github.com/openai/openai-python/issues/488&quot;&gt;original GitHub issue&lt;/a&gt;, the LLM does a good job of summarizing the main points of the issue and the comments. We can see at a glance the main points of the issue and its comments (&lt;a href=&quot;/images/2023-11-05/example1-summary.png&quot;&gt;click to enlarge&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/example1-summary.png&quot; alt=&quot;Summarized first example&quot; class=&quot;align-center&quot; style=&quot;width:50%;&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;a-large-github-issue&quot;&gt;A large GitHub issue&lt;/h3&gt;

&lt;p&gt;Now choose the issue &lt;em&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;https://github.com/scikit-learn/scikit-learn/issues/26817 (large, requires GPT-3.5 16k or GPT-4)&lt;/code&gt;&lt;/em&gt; and click the &lt;em&gt;“Generate summary with…“&lt;/em&gt; button. Do not change the LLM model yet.&lt;/p&gt;

&lt;p&gt;It will fail with this error:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Error code: 400 - {'error': {'message': &quot;This model's maximum context length is 4097 tokens. However, your messages resulted in 4154 tokens. Please reduce the length of the messages.&quot;, 'type': 'invalid_request_error', 'param': 'messages', 'code': 'context_length_exceeded'}}&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Each LLM has a limit on the number of tokens it can process at a time. This limit is the &lt;em&gt;context window&lt;/em&gt; size. The context window must fit the information we want to summarize and the summary itself. If the information we want to summarize is larger than the context window, as we saw in this case, the LLM will reject the request.&lt;/p&gt;

&lt;p&gt;There are a few ways to work around this problem:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Break up the information into smaller pieces that fit in the context window. For example, we could &lt;a href=&quot;https://github.com/microsoft/azure-openai-design-patterns/blob/main/patterns/01-large-document-summarization/README.md&quot;&gt;ask for a summary of each comment separately&lt;/a&gt;, then combine them into a single summary to show to the user. This may not work well in all cases, for example, if one comment refers to another.&lt;/li&gt;
  &lt;li&gt;Use a model with a larger context window.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We will use the second option. Click on &lt;em&gt;“Click to configure the prompt and the model”&lt;/em&gt; at the top of the screen, select the GPT-4o model and click the &lt;em&gt;“Generate summary with gpt-4o”&lt;/em&gt; button (&lt;a href=&quot;/images/2023-11-05/example2-choose-16k-model.jpg&quot;&gt;click to enlarge&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/example2-choose-larger-context-model.png&quot; alt=&quot;Switch to model with larger context window&quot; class=&quot;align-center&quot; style=&quot;width:50%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Now we get a summary from the LLM.&lt;/p&gt;

&lt;p&gt;Why don’t we start with GPT-4o to avoid such problems? Money. As a general rule, LLMs with larger context windows cost more. If we use an AI provider such as OpenAI, we must &lt;a href=&quot;https://openai.com/pricing&quot;&gt;pay more per token&lt;/a&gt;. If we run the model ourselves, we need to buy more powerful hardware. Either way, using a larger context window costs more.&lt;/p&gt;

&lt;h3 id=&quot;better-summaries-with-a-more-powerful-model&quot;&gt;Better summaries with a more powerful model&lt;/h3&gt;

&lt;p&gt;As a result of using GPT-4o, we also get better summaries.&lt;/p&gt;

&lt;p&gt;Why don’t we use GPT-4o from the start? In addition to the above reason (money), there is also higher latency. As a general rule, better models are also larger. They need more hardware to run, translating into &lt;a href=&quot;https://openai.com/pricing&quot;&gt;higher costs per token&lt;/a&gt; and a longer time to generate a response.&lt;/p&gt;

&lt;p&gt;We can see the difference comparing the token count, cost, and time to generate the summary between the gpt-3.5-turbo and the gpt-4o models.&lt;/p&gt;

&lt;p&gt;How do we pick a model? It depends on the use case. Start with the smallest (and thus cheaper and faster) model that produces good results. Create some heuristics to decide when to use a more powerful model. For example, switch to a larger model if the comments are larger than a certain size and if the users are willing to wait longer for better results (sometimes an average result faster is better than the perfect result later).&lt;/p&gt;

&lt;h3 id=&quot;the-introduction-of-gpt-4o-mini&quot;&gt;The introduction of GPT-4o mini&lt;/h3&gt;

&lt;p&gt;The previous sections compared GPT-3.5 Turbo against GPT-4o to emphasize the differences between a smaller and a much larger model. However, in July 2024, OpenAI introduced the &lt;a href=&quot;https://openai.com/index/gpt-4o-mini-advancing-cost-efficient-intelligence/&quot;&gt;GPT-4o mini model&lt;/a&gt;. It comes with the same 128k tokens context window as the GPT-4o model but with a much lower cost. It’s even cheaper than the GPT-3.5 models. See the &lt;a href=&quot;https://openai.com/api/pricing/&quot;&gt;OpenAI API pricing&lt;/a&gt; for details.&lt;/p&gt;

&lt;p&gt;GPT-4o (not mini) is still a better model, but its price and latency may not justify the better results. For example, the following table shows the summary for a large issue (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;https://github.com/qjebbs/vscode-plantuml/issues/255&lt;/code&gt;). GPT-4o is on the left, and GPT-4o mini is on the mini. The difference in costs is staggering, but the results are not that much different.&lt;/p&gt;

&lt;p&gt;The message is that unless you have a specific reason for using GPT-3.5 Turbo, you should start a new project with the GPT-4o mini model. It will produce results comparable to GPT-4o for less than the GPT-3.5 Turbo cost.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;GPT-4o summary&lt;/th&gt;
      &lt;th&gt;GPT-4o mini summary&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;3,859 tokens, US $0.0303&lt;/td&gt;
      &lt;td&gt;4,060, tokens, US $0.0012&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2023-11-05/gpt-4o-summary.png&quot; alt=&quot;GPT-4o summary&quot; /&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2023-11-05/gpt-4o-mini-summary.png&quot; alt=&quot;GPT-4o mini summary&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;the-importance-of-using-a-good-prompt&quot;&gt;The importance of using a good prompt&lt;/h3&gt;

&lt;p&gt;Precise instructions in the prompt are important to get good results. To illustrate what a difference a good prompt makes:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Select the &lt;em&gt;“gpt-3.5”&lt;/em&gt; model.&lt;/li&gt;
  &lt;li&gt;Select the GitHub issue &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;https://github.com/openai/openai-python/issues/488&lt;/code&gt; from the sample list.&lt;/li&gt;
  &lt;li&gt;Click the &lt;em&gt;“Generate summary with…“&lt;/em&gt; button.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We get a summary of the comments like this one (&lt;a href=&quot;/images/2023-11-05/prompt-original.jpg&quot;&gt;click to enlarge&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/prompt-original.jpg&quot; alt=&quot;Summarization with a good prompt&quot; class=&quot;align-center&quot; style=&quot;width:50%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;If we remove from the prompt the line &lt;em&gt;“Don’t waste words. Use short, clear, complete sentences. Use active voice. Maximize detail, meaning focus on the content. Quote code snippets if they are relevant.”&lt;/em&gt;, we get this summary. Note how the text is more verbose and is indeed “wasting words” (&lt;a href=&quot;/images/2023-11-05/prompt-after-removal-of-instructions.jpg&quot;&gt;click to enlarge&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2023-11-05/prompt-after-removal-of-instructions.jpg&quot; alt=&quot;Comment summary after removing instructions from the prompt&quot; class=&quot;align-center&quot; style=&quot;width:50%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;To remove the line, click on &lt;em&gt;“Click to configure the prompt and the model”&lt;/em&gt; at the top of the screen and remove the line from the prompt, then click on the &lt;em&gt;“Generate summary with…“&lt;/em&gt; button again. Reload the page to restore the line.&lt;/p&gt;

&lt;p&gt;Getting the prompt right is still an experimental process. It goes under the name of &lt;em&gt;prompt engineering&lt;/em&gt;. These are some references to learn more about prompt engineering.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/advanced-prompt-engineering&quot;&gt;Prompt engineering techniques (Azure)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://platform.openai.com/docs/guides/gpt-best-practices&quot;&gt;GPT best practices (OpenAI)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.promptingguide.ai/&quot;&gt;Prompt engineering guide&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;!-- markdownlint-disable-next-line MD026 --&gt;
&lt;h3 id=&quot;if-all-we-have-is-a-hammer&quot;&gt;If all we have is a hammer…&lt;/h3&gt;

&lt;p&gt;Once we learn we can summarize texts with an LLM, we are tempted to use it for everything. Let’s say we also want to know the number of comments on the issue. We could ask the LLM by adding it to the prompt.&lt;/p&gt;

&lt;p&gt;Click on &lt;em&gt;“Click to configure the prompt and the model”&lt;/em&gt; at the top of the screen and add the line &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;- Number of comments in the issue&lt;/code&gt; to the prompt as shown below. Leave all other lines unchanged.&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;You are an experienced developer familiar with GitHub issues.
The following text was parsed from a GitHub issue and its comments.
Extract the following information from the issue and comments:
- Issue: A list with the following items: title, the submitter name, the submission date and
time, labels, and status (whether the issue is still open or closed).
- Number of comments in the issue  &amp;lt;-- ** ADD THIS LINE **
...remainder of the lines...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The LLM will return &lt;em&gt;a&lt;/em&gt; number of comments, but it will usually be wrong. Select, for example, the issue &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;https://github.com/qjebbs/vscode-plantuml/issues/255&lt;/code&gt; from the sample list. None of the models get the number of comments correctly.&lt;/p&gt;

&lt;p&gt;Why? Because &lt;strong&gt;LLMs are not “executing” instructions&lt;/strong&gt;, they are simply &lt;a href=&quot;https://writings.stephenwolfram.com/2023/02/what-is-chatgpt-doing-and-why-does-it-work/&quot;&gt;generating one token at a time&lt;/a&gt;.&lt;/p&gt;

&lt;p class=&quot;notice--warning&quot;&gt;This is an important concept to keep in mind. &lt;strong&gt;LLMs do not understand what the text means&lt;/strong&gt;. They just pick the next token based on the previous ones. They are not a replacement for code.&lt;/p&gt;

&lt;p&gt;What to do instead? If we have easy access to the information we want, we should just use it. In this case, we can get the number of comments from the GitHub API response.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;    &lt;span class=&quot;n&quot;&gt;issue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;comments&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;get_github_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;st&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;session_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;issue_url&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;num_comments&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;comments&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &amp;lt;--- This is all we need
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;what-we-learned-in-these-experiments&quot;&gt;What we learned in these experiments&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;LLMs are good at summarizing text if we use the right prompt.&lt;/li&gt;
  &lt;li&gt;Summarizing larger documents requires larger context windows or more sophisticated techniques.&lt;/li&gt;
  &lt;li&gt;Getting good results requires good prompts. Good prompts are still an experimental process.&lt;/li&gt;
  &lt;li&gt;Sometimes we should not use an LLM. If we can easily get the information we need from the data, we should do that instead of using an LLM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;related-projects&quot;&gt;Related projects&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/gpt-all-local&quot;&gt;This project&lt;/a&gt; lets you ask questions on a document and get answers from an LLM. It uses techniques similar to this project but with a significant difference: the LLM runs locally on your computer.&lt;/p&gt;</content><author><name>Christian Garbin</name></author><category term="generative-ai" /><category term="llm" /><category term="summarization" /><category term="prompt-engineering" /><summary type="html">A learning exercise on using large language models (LLMs) for summarization. It uses GitHub issues as a practical use case that we can relate to.</summary></entry><entry><title type="html">Writing good Jupyter notebooks</title><link href="https://cgarbin.github.io/writing-good-jupyter-notebooks/" rel="alternate" type="text/html" title="Writing good Jupyter notebooks" /><published>2022-09-19T00:00:00-04:00</published><updated>2023-02-01T00:00:00-05:00</updated><id>https://cgarbin.github.io/writing-good-jupyter-notebooks</id><content type="html" xml:base="https://cgarbin.github.io/writing-good-jupyter-notebooks/">&lt;p&gt;&lt;a href=&quot;https://jupyter.org/&quot;&gt;Jupyter notebooks&lt;/a&gt; are an excellent tool for data scientists and machine learning practitioners. However, if not approached with a few techniques, they can turn into a pile of unintelligible, unmaintainable code.&lt;/p&gt;

&lt;p&gt;This post will discuss some techniques I use to write good Jupyter notebooks. We will start with a notebook that is not wrong but is not well written. We will progressively change it until we arrive at a good notebook.&lt;/p&gt;

&lt;p&gt;But first, what is a good Jupyter notebook? Good notebooks have the following properties:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;They are organized logically, with sections clearly delineated and named.&lt;/li&gt;
  &lt;li&gt;They have important assumptions and decisions spelled out.&lt;/li&gt;
  &lt;li&gt;Their code is easy to understand.&lt;/li&gt;
  &lt;li&gt;Their code is flexible (easy to modify).&lt;/li&gt;
  &lt;li&gt;Their code is resilient (hard to break).&lt;/li&gt;
&lt;/ul&gt;

&lt;!--more--&gt;

&lt;p class=&quot;notice--info&quot;&gt;This post is adapted from a guest lecture I gave to &lt;a href=&quot;https://www.ogemarques.com/&quot;&gt;Dr. Marques’&lt;/a&gt; data science class. If you are pressed for time, check out the &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks&quot;&gt;GitHub repository&lt;/a&gt;, starting with the &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/presentation.pdf&quot;&gt;presentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We will use as an example a notebook that attempts to answer the question &lt;em&gt;“is there gender discrimination in the salaries of an organization?”&lt;/em&gt; Our dataset is a list of salaries and other attributes from that organization. We will start from the first step in any data project, exploratory data analysis (EDA), clean up the dataset, and finally, attempt to answer the question.&lt;/p&gt;

&lt;p&gt;To illustrate how to go from a notebook that is not wrong but is also not good, we will go through the following steps:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;#step-1---the-original-notebook&quot;&gt;Step 1&lt;/a&gt;: the original notebook, the one that lacks structure and proper coding practices.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#step-2---add-a-description-organize-it-into-sections-and-add-exploratory-data-analysis&quot;&gt;Step 2&lt;/a&gt;: add a description, organize into sections, add exploratory data analysis.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#step-3---make-data-cleanup-more-explicit-and-explain-why-specific-numbers-were-chosen&quot;&gt;Step 3&lt;/a&gt;: make data cleanup more explicit and explain why specific numbers were chosen (the assumptions behind them).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#step-4---make-the-code-more-flexible-and-more-difficult-to-break&quot;&gt;Step 4&lt;/a&gt;: make the code more flexible with constants and make the code more difficult to break.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#step-5---make-the-graphs-easier-to-read&quot;&gt;Step 5&lt;/a&gt;: make the graphs easier to read.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#step-6---describe-the-limitations-of-the-conclusion&quot;&gt;Step 6&lt;/a&gt;: describe the limitations of the conclusion.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;step-1---the-original-notebook&quot;&gt;Step 1 - The original notebook&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/salary-discrimination-by-gender-step-1.ipynb&quot;&gt;This is the original notebook&lt;/a&gt;. It is technically correct, but far from what is acceptable for a project of this importance.&lt;/p&gt;

&lt;p&gt;The first hint of a problem is the structure of the notebook: it doesn’t have any. It’s a collection of cells, one after the other.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-1.drawio.png&quot; alt=&quot;Step 1 - This notebook has no structure and other problems&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Other problems with this notebook:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;There is no description of what the notebook is about.&lt;/li&gt;
  &lt;li&gt;There is no exploratory data analysis (EDA) to explain why we can (or cannot) trust our data.&lt;/li&gt;
  &lt;li&gt;The data cleanup (the magic numbers) is not explained, e.g. why were those numbers used?&lt;/li&gt;
  &lt;li&gt;Because of the magic numbers, the code is not flexible. We don’t know where they are used and the effect of changing one of them.&lt;/li&gt;
  &lt;li&gt;There is no explanation for the code blocks.&lt;/li&gt;
  &lt;li&gt;There is no explanation for the conclusion.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will fix some of the issues in the next step.&lt;/p&gt;

&lt;h2 id=&quot;step-2---add-a-description-organize-it-into-sections-and-add-exploratory-data-analysis&quot;&gt;Step 2 - Add a description, organize it into sections, and add exploratory data analysis&lt;/h2&gt;

&lt;p&gt;Starting in this step, we will make incremental changes to the notebook. Each change will bring us closer to a good notebook. Changes from the previous step are highlighted with a “REWORK NOTE” comment and an explanation of what has changed. Here is an example:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/rework-note.drawio.png&quot; alt=&quot;Rework note&quot; class=&quot;align-center&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In this step, we make the following improvements:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Add a clear “what is this notebook about?” description.&lt;/li&gt;
  &lt;li&gt;Add an exploratory data analysis (EDA) section.&lt;/li&gt;
  &lt;li&gt;Split the notebook into sections.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-2.drawio.png&quot; alt=&quot;Step 2 - Add sections headers and EDA&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/salary-discrimination-by-gender-step-2.ipynb&quot;&gt;This is the reworked notebook&lt;/a&gt;. It is better, but we can still improve it:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Make the data cleanup more explicit.&lt;/li&gt;
  &lt;li&gt;Explain what the code blocks are doing.&lt;/li&gt;
  &lt;li&gt;Explain why specific numbers were chosen (the assumptions behind them).&lt;/li&gt;
  &lt;li&gt;Make the graphs easier to read.&lt;/li&gt;
  &lt;li&gt;Make the code more flexible with constants.&lt;/li&gt;
  &lt;li&gt;Make the code more resilient (harder to break).&lt;/li&gt;
  &lt;li&gt;Describe the limitations of the conclusion.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will fix some of the issues in the next step.&lt;/p&gt;

&lt;h2 id=&quot;step-3---make-data-cleanup-more-explicit-and-explain-why-specific-numbers-were-chosen&quot;&gt;Step 3 - Make data cleanup more explicit and explain why specific numbers were chosen&lt;/h2&gt;

&lt;p&gt;In this step, we make the following improvements:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Make the data cleanup more explicit.&lt;/li&gt;
  &lt;li&gt;Explain why specific numbers were chosen (the assumptions behind them).&lt;/li&gt;
  &lt;li&gt;Explain what the code blocks are doing.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The following figure shows how we explain why we are removing all employees that are 66 or older and add a reference to back up our decision (the hyperlink in the text). We also explain why we think this is a good decision.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-3.drawio.png&quot; alt=&quot;Step 3 - Making data cleanup more explicit&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p class=&quot;notice&quot;&gt;Why should we document decisions to this level of detail? One reason is to remember why we made them. But, more importantly, &lt;strong&gt;we, the data scientists, may not be the domain experts&lt;/strong&gt;. In this example, the domain experts are the HR and legal departments. We need to engage them to validate our decisions. Documenting to this level of detail &lt;strong&gt;invites a dicussion with the domain experts to validate the decisions&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/salary-discrimination-by-gender-step-3.ipynb&quot;&gt;This is the reworked notebook&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;step-4---make-the-code-more-flexible-and-more-difficult-to-break&quot;&gt;Step 4 - Make the code more flexible and more difficult to break&lt;/h2&gt;

&lt;p&gt;In this step, we make the following improvements:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Make the code more flexible with constants. If we need to change decisions, for example, the age cutoff, we have only one place to change.&lt;/li&gt;
  &lt;li&gt;Make the code more difficult to break. By following patterns, we reduce the chances of introducing bugs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this piece of code, we remove everyone who made less than the minimum age working full time (see the &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/salary-discrimination-by-gender-step-4.ipynb&quot;&gt;notebook&lt;/a&gt; for details).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-4.1.drawio.png&quot; alt=&quot;Step 4 - Salary cutoff&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;There are a few notable items in this code:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;We use a constant if we need to make changes later (more flexible code).&lt;/li&gt;
  &lt;li&gt;We use a generic name for the constant (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SALARY_CUTOFF&lt;/code&gt;), so we don’t need to change it later if we change the cutoff value. If we had named it something more specific, like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MINIMUM_WAGE&lt;/code&gt;, we would need to change the constant name if we changed the value. This makes the code less flexible and less resilient.&lt;/li&gt;
  &lt;li&gt;We don’t modify the original data. We create a filter instead, so we can see the effect of each filter separately and backtrack one change at a time if we need to.&lt;/li&gt;
  &lt;li&gt;The filter variable also has a generic name (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;low_salaries&lt;/code&gt;), for the same reasons we used a generic name for the constant.&lt;/li&gt;
  &lt;li&gt;We print the results of the operation (the cutoff value and how many items it removed from the dataset), so we can discuss with the domain experts if our decision makes sense. For example, we could ask an HR representative if they expected to see this many employers removed when we set this salary cutoff. It may catch errors in the dataset or in the code.&lt;/li&gt;
&lt;/ol&gt;

&lt;p class=&quot;notice&quot;&gt;Regarding the last item, printing the operation results: showing the effect of filtering data (how many employees were removed) helps &lt;strong&gt;validate the decisions with the domain experts&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;When we clean up the age column, we keep using the same patterns:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;We create a filter for the data we want to exclude, as we did for the salary filter.&lt;/li&gt;
  &lt;li&gt;We follow a pattern for the variable name. The salary one was named &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SALARY_CUTOFF&lt;/code&gt;, so this one is also suffixed with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;..._CUTOFF&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;We choose a generic variable name. If we name it something more specific, e.g. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RETIRED_AGE&lt;/code&gt; and decide to change the age cutoff later, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RETIRED_&lt;/code&gt; part may no longer make sense. A generic name (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AGE_CUTOFF&lt;/code&gt;) requires only a change to the value, making the code more resilient.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-4.2.drawio.png&quot; alt=&quot;Step 4 - Age cutoff, following the same patterns as the salary cutoff&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;With all the filters in place, we can clean up the data in one step. Because all the filters we created are to exclude data, we can confidently negate all of them to get the data we want to keep. If we use different types of filters (exclude and include), we have to carefully think about how to apply each of them, opening the door for bugs.&lt;/p&gt;

&lt;p class=&quot;notice&quot;&gt;This is an important concept: don’t make your brain hold more information than it absolutely has to (don’t create &lt;a href=&quot;https://en.wikipedia.org/wiki/Cognitive_load#Extraneous&quot;&gt;extraneous cognitive load&lt;/a&gt;). If we follow a pattern, we have only one thing to remember, the pattern itself.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-4.3.drawio.png&quot; alt=&quot;Step 4 - Applying the filters to clean up the data&quot; class=&quot;align-center&quot; style=&quot;width:80%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/salary-discrimination-by-gender-step-4.ipynb&quot;&gt;This is the reworked notebook&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;step-5---make-the-graphs-easier-to-read&quot;&gt;Step 5 - Make the graphs easier to read&lt;/h2&gt;

&lt;p&gt;In this step, we make the graphs easier to read.&lt;/p&gt;

&lt;p&gt;First, we add transparency when plotting multiple variables on the same graph.&lt;/p&gt;

&lt;p&gt;This is the &lt;a href=&quot;https://seaborn.pydata.org/generated/seaborn.pairplot.html&quot;&gt;pairplot&lt;/a&gt; from the previous step, without transparency:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-5.1.drawio.png&quot; alt=&quot;Step 5 - Pairplot without transparency&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;And this is the pairplot with transparency:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-5.2.drawio.png&quot; alt=&quot;Step 5 - Pairplot with transparency&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Adding transparency lets us see the clusters of data, the areas where we have many data points, as opposed to the places where we have few data points. It helps identifies patterns in the data.&lt;/p&gt;

&lt;p&gt;Another technique to make graphs readable is to &lt;a href=&quot;https://en.wikipedia.org/wiki/Data_binning&quot;&gt;bin the data&lt;/a&gt;. This is the graph from the previous step that plots age vs. salary:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-5.3.drawio.png&quot; alt=&quot;Step 5 - Salary by age before binning&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;It is impossible to see any pattern in such a graph. To make it more legible, we will &lt;a href=&quot;https://en.wikipedia.org/wiki/Data_binning&quot;&gt;bin the data&lt;/a&gt;. But the question is, “what bins make sense for this case?” Since we are analyzing salaries, we chose 22 as our first bin because this is usually the &lt;a href=&quot;https://nonpartisaneducation.org/Review/Resources/Int__lHigherEd_AppendixA.pdf&quot;&gt;age of graduation&lt;/a&gt;. After that, we will bin every five years for the first years to account for rapid promotions and rises that happen at the start of a career, then bin every ten years for later stages in the career, where promotions are rarer. We also document those assumptions clearly to discuss them with the domain experts.&lt;/p&gt;

&lt;p&gt;This is the new graph:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-5.4.drawio.png&quot; alt=&quot;Step 5 - Salary by age after binning&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/salary-discrimination-by-gender-step-5.ipynb&quot;&gt;This is the reworked notebook&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;step-6---describe-the-limitations-of-the-conclusion&quot;&gt;Step 6 - Describe the limitations of the conclusion&lt;/h2&gt;

&lt;p&gt;We now have a good notebook. It is organized in sections, uses constants to make the code more understandable and resilient, the graphs are well formatted, and we added explanations for all assumptions and decisions.&lt;/p&gt;

&lt;p&gt;We are now at the last step, where we present the conclusion to the original question, &lt;em&gt;“is there gender discrimination in the salaries of an organization?”&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;In real life, the data we have is not perfect and complex questions don’t always have simple answers. And that’s the case here. We have a few limitations that prevent us from giving a definitive answer to the question. But we have enough to spur some action. Our job at this point is to document what we found and the limitations of our analysis.&lt;/p&gt;

&lt;p&gt;In the conclusion section, we clearly document:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;That we used proxy variables.&lt;/li&gt;
  &lt;li&gt;Despite the dataset’s limitations, we have tentative conclusions.&lt;/li&gt;
  &lt;li&gt;That we need more precise data, but at the same time, we have enough to take action (and avoid &lt;a href=&quot;https://en.wikipedia.org/wiki/Analysis_paralysis]&quot;&gt;analysis paralysis&lt;/a&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/images/2022-09-19/step-6.drawio.png&quot; alt=&quot;Step 6 - Conclusions and limitations&quot; class=&quot;align-center&quot; style=&quot;width:66%;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks/blob/master/salary-discrimination-by-gender-step-6.ipynb&quot;&gt;This is the final notebook&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;We write notebooks for our stakeholders, not for ourselves.&lt;/p&gt;

&lt;p&gt;To write good notebooks, we need to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Organize them logically so that the stakeholders can follow the analysis.&lt;/li&gt;
  &lt;li&gt;Make the code easy to understand, easy to change (flexible), and hard to break (resilient), so we can modify it confidently as we review the results with the stakeholders.&lt;/li&gt;
  &lt;li&gt;Spell out critical assumptions and decisions so stakeholders can validate them (or challenge them).&lt;/li&gt;
  &lt;li&gt;Clearly document the limitations of the analysis so stakeholders can decide if they are acceptable or not.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;running-the-examples&quot;&gt;Running the examples&lt;/h2&gt;

&lt;p&gt;The notebooks are available on &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/writing-good-jupyter-notebooks&quot;&gt;this GitHub repository&lt;/a&gt;.&lt;/p&gt;</content><author><name>Christian Garbin</name></author><category term="jupyter-notebooks" /><category term="python" /><category term="data-science" /><summary type="html">How to write well-structured, understandable, flexible, and resilient Jupyter notebooks.</summary></entry><entry><title type="html">Vision transformer properties</title><link href="https://cgarbin.github.io/vision-transformers-properties/" rel="alternate" type="text/html" title="Vision transformer properties" /><published>2022-07-23T00:00:00-04:00</published><updated>2022-07-23T00:00:00-04:00</updated><id>https://cgarbin.github.io/vision-transformers-properties</id><content type="html" xml:base="https://cgarbin.github.io/vision-transformers-properties/">&lt;p&gt;Transformers crossed over from natural language into computer vision in a few low-key steps until the &lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;An Image is Worth 16x16 Words&lt;/a&gt; paper exploded into the machine learning scene late in 2020.&lt;/p&gt;

&lt;p&gt;Convolutional neural networks (CNNs) and recurrent neural networks (RNNs) were the dominant architectures in computer vision tasks until transformers arrived on the scene. When I started studying vision transformers, I assumed they were a replacement for CNNs and RNNs. I learned that they are more than that. They are a fundamentally different approach to the problem, resulting in some interesting properties.&lt;/p&gt;

&lt;p&gt;In this article we will review transformers’ properties in computer vision tasks that set them apart from CNNs and RNNs.&lt;/p&gt;

&lt;p&gt;If you haven’t read the &lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;paper&lt;/a&gt; yet, start with the accompanying blog post &lt;a href=&quot;https://ai.googleblog.com/2020/12/transformers-for-image-recognition-at.html&quot;&gt;Google AI Blog: Transformers for Image Recognition at Scale&lt;/a&gt;. It has a nice animation and covers the topics in the paper at a higher level. This &lt;a href=&quot;https://www.youtube.com/watch?v=DVoHvmww2lQ&quot;&gt;six-minute video from AI Coffee Break with Letitia  &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt; is an excellent introduction to the paper or a refresher if it has been a while since you read it.&lt;/p&gt;

&lt;p&gt;If this is your first encounter with transformers, start with transformers in natural language processing to learn the fundamental concepts, then come back to vision transformers. Check out &lt;a href=&quot;/understanding-transformers-in-one-morning/&quot;&gt;Understanding transformers in one morning&lt;/a&gt; if you are not yet familiar with the topic.&lt;/p&gt;

&lt;h2 id=&quot;how-transformers-process-images&quot;&gt;How transformers process images&lt;/h2&gt;

&lt;p&gt;First, a brief review of how transformers were adapted from natural language processing (NLP) to computer vision.&lt;/p&gt;

&lt;p&gt;Transformers operate on sequences. In NLP the sequence is a piece of text. For example, in the sentence “the cat refused to eat the food because it was cold” we can correlate the word “it” to “food” (not “cat”) and use that to illustrate the concept of “attention.” It is easy to conceive text as a sequence of words and imagine transformer concepts that way.&lt;/p&gt;

&lt;p&gt;But what is a “sequence” in computer vision? That is the first significant difference between transformers in computer vision and transformers in NLP.&lt;/p&gt;

&lt;p&gt;A naive solution would be to treat an image as a sequence of pixels. The problem with this approach is that it generates humongous sequences. A 256 x 256 RGB image, commonly used to train models, results in a sequence of 196,608 pixels (256 x 256 x 3 RGB channels). This large sequence would require too many computing resources for training and inference. To help visualize: a 400-page book has about 200,000 words. In this one-to-one mapping of pixels to words, it would be the equivalent of feeding that book to a transformer network at once.&lt;/p&gt;

&lt;p&gt;To make the problem tractable, &lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;An Image is Worth 16x16 Words&lt;/a&gt; partitions images into squares called &lt;em&gt;patches&lt;/em&gt;. Each patch is the equivalent of a token in an NLP transformer. Back to the 256 x 256 image, partitioning it into 16 x 16 squares results in 256 patches (tokens). Each patch is still a large number of pixels, but the problem is more tractable now because the number of tokens is much smaller.&lt;/p&gt;

&lt;p&gt;In addition to the patches, the network has one more token, the class token. This token is the image classification (“cat”, “dog”, …). Beyond that, the transformer network in &lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;An Image is Worth 16x16 Words&lt;/a&gt; is the same as the transformers used in natural language processing. In the words of the paper, “&lt;em&gt;The “Base” and “Large” models are directly adopted from &lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT&lt;/a&gt;&lt;/em&gt;”.&lt;/p&gt;

&lt;p&gt;The picture below, from &lt;a href=&quot;https://ai.googleblog.com/2020/12/transformers-for-image-recognition-at.html&quot;&gt;Google’s blog post&lt;/a&gt;, shows the network architecture. Token zero is the class token. The patches are extracted from the image and used as tokens. This transformer is known as &lt;strong&gt;&lt;em&gt;ViT&lt;/em&gt;&lt;/strong&gt;, the vision transformer. The term &lt;em&gt;ViT&lt;/em&gt; is commonly used in the literature to refer to this architecture.&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/vit-architecture.gif&quot; alt=&quot;ViT architecture&quot; /&gt;&lt;figcaption&gt;
      The vision transformer (ViT) architecture from &lt;a href=&quot;https://ai.googleblog.com/2020/12/transformers-for-image-recognition-at.html&quot;&gt;Google’s blog post&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;h2 id=&quot;how-are-transformers-different-from-cnns-in-computer-vision&quot;&gt;How are transformers different from CNNs in computer vision?&lt;/h2&gt;

&lt;p&gt;Convolutional neural networks (CNN) work in small image areas. The learned weights are related to that small area, as shown in this picture from &lt;a href=&quot;https://arxiv.org/abs/1906.05909&quot;&gt;Stand-Alone Self-Attention in Vision Models&lt;/a&gt;.&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/cnn-locality.png&quot; alt=&quot;CNN locality inductive bias&quot; /&gt;&lt;figcaption&gt;
      CNN locality inductive bias &lt;a href=&quot;https://arxiv.org/abs/1906.05909&quot;&gt;Stand-Alone Self-Attention in Vision Models&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;p&gt;In other words, the concept of “locality” (pixels closer to each other are related) is part of the CNN architecture as a &lt;em&gt;prior&lt;/em&gt;, or &lt;em&gt;&lt;a href=&quot;https://towardsdatascience.com/the-inductive-bias-of-ml-models-and-why-you-should-care-about-it-979fe02a1a56&quot;&gt;inductive bias&lt;/a&gt;&lt;/em&gt;, a piece of knowledge that the network creators embedded into the network’s architecture. This piece of knowledge makes assumptions about what the best solution is for a specific problem. Perhaps there are better ways to solve the problem, but we are constraining the solution space to the inductive biases that are part of the network architecture.&lt;/p&gt;

&lt;p&gt;On the other hand, a transformer network doesn’t have such inductive biases embedded into its architecture. For example, It has to learn that “locality” is a good thing in computer vision problems on its own.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;This lack of inductive bias in the network architecture is a fundamental difference between transformers and CNNs&lt;/strong&gt;. In more practical terms, a transformer network does not make assumptions about the structure of the problem. As a result of that, the network has to learn the concepts.&lt;/p&gt;

&lt;p&gt;Eventually, the transformer network does &lt;a href=&quot;http://jbcordonnier.com/posts/attention-cnn/&quot;&gt;learn convolutions&lt;/a&gt; and locality. The picture below (from &lt;a href=&quot;https://arxiv.org/pdf/2010.11929.pdf&quot;&gt;An Image is Worth 16x16 Words&lt;/a&gt;) shows the size of the image area attended by each head in each layer. In the lower layers (left), some heads attend to pixels close to each other (bottom of the graph), and other heads attend to pixels further away (top of the graph). As we move up in the layers (right of the graph), heads attend to pixels farther out in the image area (top of the graph). In other words, lower layers have both local and global attention, while higher layers have global attention. The network was not told to behave this way. It learned this attention pattern on its own.&lt;/p&gt;

&lt;p&gt;In the words of the authors:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;This “attention distance” is analogous to receptive field size in CNNs. We find that some heads attend to most of the image already in the lowest layers, showing that the ability to integrate information globally is indeed used by the model. Other attention heads have consistently small attention distances in the low layers. This highly localized attention is less pronounced in hybrid models that apply a ResNet before the Transformer (Figure 7, right), suggesting that it may serve a similar function as early convolutional layers in CNNs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://arxiv.org/pdf/2010.11929.pdf&quot;&gt;An Image is Worth 16x16 Words&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/vit-head-attention.png&quot; alt=&quot;ViT head attention by layer&quot; /&gt;&lt;figcaption&gt;
      ViT head attention by layer – &lt;a href=&quot;https://arxiv.org/pdf/2010.11929.pdf&quot;&gt;An Image is Worth 16x16 Words&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;h2 id=&quot;fewer-assumptions--more-interesting-solutions&quot;&gt;Fewer assumptions → more interesting solutions&lt;/h2&gt;

&lt;p&gt;If, in the end, transformers learn convolutions and locality anyway, what have we gained by using transformers for computer vision? Why go through all the trouble of training transformers to do what CNNs do from the start?&lt;/p&gt;

&lt;p&gt;In the words of Lucas Beyer (&lt;a href=&quot;https://youtu.be/BP5CM0YxbP8?t=3295&quot;&gt;Standford CS 25 lecture&lt;/a&gt;), one of the technical contributors to &lt;a href=&quot;https://arxiv.org/pdf/2010.11929.pdf&quot;&gt;ViT&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[W]e want the model to have as little of our thinking built-in, because what we may think that is good to solve the task may actually not be the best to solve the task. … [W]e want to encode as little as possible into the model, such that if we just throw massive amounts of data in a difficult task at it, it might think things that are even better than [what we would have assumed]… Ideally, we want [a] model that is powerful enough to learn about this concept [locality] itself, if it’s useful to solve the task. If it’s not useful to solve the task, then if we had put it in, there is no way for the model not to do this.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;Lucas Beyer&lt;/cite&gt; – &lt;a href=&quot;https://youtu.be/BP5CM0YxbP8?t=3295&quot;&gt;Standford CS 25 lecture&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;what-else-do-transformers-learn-on-their-own&quot;&gt;What else do transformers learn on their own?&lt;/h2&gt;

&lt;p&gt;So, transformers learned to behave like CNNs. What else could they be learning on their own? By changing how a transformer model is trained, &lt;a href=&quot;https://arxiv.org/pdf/2104.14294.pdf&quot;&gt;Emerging Properties in Self-Supervised Vision Transformers&lt;/a&gt; found out that:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[W]e make the following observations: first, self-supervised ViT features contain explicit information about the semantic segmentation of an image, which does not emerge as clearly with supervised ViTs, nor with convnets. Second, these features are also excellent k-NN classifiers.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://arxiv.org/pdf/2104.14294.pdf&quot;&gt;Emerging Properties in Self-Supervised Vision Transformers&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;p&gt;More concretely, when trained to perform object classification, transformers also learn object segmentation on their own, as shown in the following picture from the paper (for a more lively demonstration, see their &lt;a href=&quot;https://ai.facebook.com/blog/dino-paws-computer-vision-with-self-supervised-transformers-and-10x-more-efficient-training/&quot;&gt;blog post&lt;/a&gt;).&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/transformer-segmentation.png&quot; alt=&quot;Transformer segmentation&quot; /&gt;&lt;figcaption&gt;
      Transformer segmentation – &lt;a href=&quot;https://arxiv.org/pdf/2104.14294.pdf&quot;&gt;Emerging Properties in Self-Supervised Vision Transformers&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;p&gt;Segmenting an image requires some understanding of what the objects are, i.e., understanding the semantics of an image and not just treating it as a collection of pixels. The fact that the transformer model is segmenting the image indicates that it is also extracting semantic meanings. From their &lt;a href=&quot;https://ai.facebook.com/blog/dino-paws-computer-vision-with-self-supervised-transformers-and-10x-more-efficient-training/&quot;&gt;blog post&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;DINO learns a great deal about the visual world. By discovering object parts and shared characteristics across images, the model learns a feature space that exhibits a very interesting structure. If we embed ImageNet classes using the features computed using DINO, we see that they organize in an interpretable way, with similar categories landing near one another. This suggests that the model managed to connect categories based on visual properties, a bit like humans do.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://ai.facebook.com/blog/dino-paws-computer-vision-with-self-supervised-transformers-and-10x-more-efficient-training/&quot;&gt;Advancing the state of the art in computer vision with self-supervised Transformers and 10x more efficient training&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/transformer-class-separation.gif&quot; alt=&quot;Transformer class separation&quot; /&gt;&lt;figcaption&gt;
      Transformer class separation – &lt;a href=&quot;https://ai.facebook.com/blog/dino-paws-computer-vision-with-self-supervised-transformers-and-10x-more-efficient-training/&quot;&gt;Advancing the state of the art in computer vision with self-supervised Transformers and 10x more efficient training&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.10497&quot;&gt;Intriguing Properties of Vision Transformers&lt;/a&gt; explores more properties of vision transformers, such as dealing with occlusion better than CNNs.&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/intriguing-properties-occlusion.png&quot; alt=&quot;Transformer deal with occlusion better than CNNs&quot; /&gt;&lt;figcaption&gt;
      Transformer deal with occlusion better than CNNs – &lt;a href=&quot;https://arxiv.org/abs/2105.10497&quot;&gt;Intriguing Properties of Vision Transformers&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;p&gt;They introduce a “shape token” to train transformers to be more shape-biased than they naturally are to get automated object segmentation (rightmost column in the picture below).&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The [results] show that properly trained ViT models offer shape-bias nearly as high as the human’s ability to recognize shapes. This leads us to question if positional encoding is the key that helps ViTs achieve high performance under severe occlusions (as it can potentially allow later layers to recover the missing information with just a few image patches given their spatial ordering).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.10497&quot;&gt;Intriguing Properties of Vision Transformers&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/intriguing-properties-segmentation.png&quot; alt=&quot;Transformer segmentation with shape token&quot; /&gt;&lt;figcaption&gt;
      Transformer segmentation with shape token better than CNNs – &lt;a href=&quot;https://arxiv.org/abs/2105.10497&quot;&gt;Intriguing Properties of Vision Transformers&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.07581&quot;&gt;Vision Transformers are Robust Learners&lt;/a&gt; doesn’t have fancy pictures to illustrate what they found, but the results are no less interesting. They found out that without any specific training, vision transformers can cope with image perturbations better than CNNs.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[W]e study the robustness of the Vision Transformer … against common corruptions and perturbations, distribution shifts, and natural adversarial examples. … [W]ith fewer parameters and similar dataset and pre-training combinations, ViT gives a top-1 accuracy of 28.10% on &lt;a href=&quot;https://arxiv.org/pdf/1907.07174.pdf&quot;&gt;ImageNet-A&lt;/a&gt; which is 4.3x higher than a comparable variant of &lt;a href=&quot;https://arxiv.org/abs/1912.11370&quot;&gt;BiT&lt;/a&gt;. Our analyses on image masking, Fourier spectrum sensitivity, and spread on discrete cosine energy spectrum reveal intriguing properties of ViT attributing to improved robustness.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.07581&quot;&gt;Vision Transformers are Robust Learners&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;h2 id=&quot;why-do-vision-transformers-perform-better-than-cnns&quot;&gt;Why do vision transformers perform better than CNNs?&lt;/h2&gt;

&lt;p&gt;We are still in the early stages of understanding the differences between CNNs and vision transformers.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2108.08810&quot;&gt;Do Vision Transformers See Like Convolutional Neural Networks?&lt;/a&gt; found significant differences in the structure of vision transformers and CNNs.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[We use] &lt;a href=&quot;https://arxiv.org/abs/1905.00414&quot;&gt;CKA&lt;/a&gt; to study the internal representation structure of each model. … Figure 1 [below] shows the results as a heatmap, for multiple ViTs and ResNets. We observe clear differences between the internal representation structure between the two model architectures: (1) ViTs show a much more uniform similarity structure, with a clear grid like structure (2) lower and higher layers in ViT show much greater similarity than in the ResNet, where similarity is divided into different (lower/higher) stages.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://arxiv.org/abs/2108.08810&quot;&gt;Do Vision Transformers See Like Convolutional Neural Networks?&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/do-transformers-see-like-cnns-figure-1.png&quot; alt=&quot;Transformer vs. ResNet internal representation&quot; /&gt;&lt;figcaption&gt;
      Transformer vs. ResNet internal representation – &lt;a href=&quot;https://arxiv.org/abs/2108.08810&quot;&gt;Do Vision Transformers See Like Convolutional Neural Networks?&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;p&gt;This is the first significant difference between vision transformers and CNNs.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[T]hese results suggest that (i) ViT lower layers compute representations in a different
way to lower layers in the ResNet, (ii) ViT also more strongly propagates representations between lower and higher layers (iii) the highest layers of ViT have quite different representations to ResNet.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://arxiv.org/abs/2108.08810&quot;&gt;Do Vision Transformers See Like Convolutional Neural Networks?&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;p&gt;A possible explanation for this structural difference is how the transformer layers learn to aggregate spatial information. CNNs have fixed receptive fields (encoded in the kernel sizes and sequences of layers). Transformers do not have this prior knowledge of “receptive fields” for an image. They have to learn that spatial relations are important in image processing.&lt;/p&gt;

&lt;p&gt;The experiments in the paper confirmed the observation in &lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;the original ViT paper&lt;/a&gt; that transformers eventually settle in a structure where lower layers learn to pay attention locally and globally, while higher layers learn to pay attention globally.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[E]ven in the lowest layers of ViT, self-attention layers have a mix of local heads (small distances) and global heads (large distances). This is in contrast to CNNs, which are hardcoded to attend only locally in the lower layers.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;&lt;a href=&quot;https://arxiv.org/abs/2108.08810&quot;&gt;Do Vision Transformers See Like Convolutional Neural Networks?&lt;/a&gt;&lt;/cite&gt;&lt;/p&gt;

&lt;figure class=&quot;&quot;&gt;
  &lt;img src=&quot;/images/2022-07-23/do-transformers-see-like-cnns-figure-3.png&quot; alt=&quot;ViT attention span in lower vs., higher layers&quot; /&gt;&lt;figcaption&gt;
      Lower layers in vision transformers pay attention locally and globally – &lt;a href=&quot;https://arxiv.org/abs/2108.08810&quot;&gt;Do Vision Transformers See Like Convolutional Neural Networks?&lt;/a&gt;

    &lt;/figcaption&gt;&lt;/figure&gt;

&lt;h2 id=&quot;what-was-not-covered-here&quot;&gt;What was not covered here&lt;/h2&gt;

&lt;p&gt;Vision transformers are barely a few years old. We are still learning more about how to train them and how they behave. This is a short list of active research areas.&lt;/p&gt;

&lt;h3 id=&quot;more-efficient-training-and-inference&quot;&gt;More efficient training and inference&lt;/h3&gt;

&lt;p&gt;Networks with fewer priors embedded in their design need more data to eventually learn these priors that they don’t have. ViT was trained in a dataset of 300 million images. Large datasets are still private (for the most part) and require a huge amount of computer power to train the model.&lt;/p&gt;

&lt;p&gt;New training methods, such as &lt;a href=&quot;https://arxiv.org/abs/2012.12877&quot;&gt;data-efficient image transformers (DeiT)&lt;/a&gt; manage to train vision transformers using only ImageNet (while still large, it’s within reach of more research teams and organizations). See &lt;a href=&quot;https://arxiv.org/abs/2009.06732&quot;&gt;Efficient Transformers: a Survey&lt;/a&gt; for more work in this area.&lt;/p&gt;

&lt;h3 id=&quot;is-attention-needed&quot;&gt;Is “attention” needed?&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;“Attention” is a central concept in transformer networks&lt;/a&gt;. But is it really necessary to achieve the same results? Some intriguing research questions if we need attention at all.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.03824&quot;&gt;FNet: Mixing Tokens with Fourier Transforms&lt;/a&gt;: “We show that Transformer encoder architectures can be sped up, with limited accuracy costs, by replacing the self-attention sublayers with simple linear transformations that “mix” input tokens. … [W]e find that replacing the self-attention sublayer in a Transformer encoder with a standard, unparameterized Fourier Transform achieves 92-97% of the accuracy of BERT counterparts on the GLUE benchmark, but trains 80% faster on GPUs and 70% faster on TPUs at standard 512 input lengths.”&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.01601&quot;&gt;MLP-Mixer: An all-MLP Architecture for Vision&lt;/a&gt;  “[W]e show that while convolutions and attention are both sufficient for good performance, neither of them are necessary. We present MLP-Mixer, an architecture based exclusively on multi-layer perceptrons (MLPs) … When trained on large datasets, or with modern regularization schemes, MLP-Mixer attains competitive scores on image classification benchmarks, with pre-training and inference cost comparable to state-of-the-art models.”&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;catching-up-with-recent-developments&quot;&gt;Catching up with recent developments&lt;/h2&gt;

&lt;p&gt;Transformers are moving fast. These are some places I use to keep up with recent developments.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Yanni Kilchner reviews recent papers on his &lt;a href=&quot;https://www.youtube.com/channel/UCZHmQk67mSJgfCCTn7xBfew&quot;&gt;YouTube channel&lt;/a&gt;. It is a great place to go after reading a paper to check your understanding and insights you may have missed on a first pass.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/c/AICoffeeBreak&quot;&gt;AI Coffe Break with Letitia&lt;/a&gt; distills papers into short videos (about ten minutes or so). It’s the ideal format to review the essence of papers.&lt;/li&gt;
  &lt;li&gt;For a slower pace but a broader view, the authors of &lt;a href=&quot;https://arxiv.org/abs/2012.12556&quot;&gt;A Survey on Vision Transformer&lt;/a&gt; and &lt;a href=&quot;https://arxiv.org/abs/2101.01169&quot;&gt;Transformers in Vision: A Survey&lt;/a&gt; publish new versions of their papers every few months.&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Christian Garbin</name></author><category term="machine-learning" /><category term="computer-vision" /><category term="transformers" /><summary type="html">Vision transformers are not just a replacement for CNNs and RNNs. They have some interesting properties.</summary></entry><entry><title type="html">Understanding transformers in one morning</title><link href="https://cgarbin.github.io/understanding-transformers-in-one-morning/" rel="alternate" type="text/html" title="Understanding transformers in one morning" /><published>2022-07-22T00:00:00-04:00</published><updated>2024-05-06T00:00:00-04:00</updated><id>https://cgarbin.github.io/understanding-transformers-in-one-morning</id><content type="html" xml:base="https://cgarbin.github.io/understanding-transformers-in-one-morning/">&lt;p&gt;Transformers are (deservedly so) a hot topic in machine learning.&lt;/p&gt;

&lt;p&gt;If you are new to transformers, the resources in this article will help you understand their fundamentals and applications. It will take about one morning (four hours, give or take) to go through all items.&lt;/p&gt;

&lt;p&gt;I created the list after spending much longer than one morning wading through many articles and videos. I lost time going around in circles, wasting time with superficial sources, or stumbling on articles that were too deep for my level when I first encountered them but were great once I was more prepared.&lt;/p&gt;

&lt;p&gt;This list is organized in a logical sequence, building up the knowledge from the first principles, then going deeper into the details. They are the videos and articles that helped me the most. I hope they help you as well.&lt;/p&gt;

&lt;!--more--&gt;

&lt;h2 id=&quot;hour-1---the-paper&quot;&gt;Hour 1 - The paper&lt;/h2&gt;

&lt;p&gt;First, read Google AI Research’s blog post &lt;a href=&quot;https://ai.googleblog.com/2017/08/transformer-novel-neural-network.html&quot;&gt;Google AI Blog: Transformer: A Novel Neural Network Architecture for Language Understanding&lt;/a&gt;. Don’t follow the links; just read the post. Then read the paper &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt;. Don’t worry about understanding the details at this point. Get familiar with terminology and pictures.&lt;/p&gt;

&lt;p&gt;The paper has about 6,000 words. It would take twenty minutes to read at the average reading pace of 300 words per minute. But it’s a scientific paper, so it will take longer. Using the &lt;a href=&quot;https://web.stanford.edu/class/ee384m/Handouts/HowtoReadPaper.pdf&quot;&gt;three-pass approach&lt;/a&gt;, let’s reserve an hour to read it.&lt;/p&gt;

&lt;h2 id=&quot;hour-2---key-concepts&quot;&gt;Hour 2 - Key concepts&lt;/h2&gt;

&lt;p&gt;The second hour is about understanding the key concepts in the paper with Rasa’s Algorithm Whiteboard video series.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yGTUuEx3GkA&amp;amp;t=4s&quot;&gt;Rasa Algorithm Whiteboard - Transformers &amp;amp; Attention 1: Self Attention &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt;(14 minutes): Explains &lt;strong&gt;attention&lt;/strong&gt; first with a simple example using a time series, then with a text example. The video introduces &lt;strong&gt;word embedding&lt;/strong&gt;, a key concept for NLP (natural language processing) models, including transformers. With these concepts explained, it defines &lt;strong&gt;self-attention&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tIvKXrEDMhk&quot;&gt;Rasa Algorithm Whiteboard - Transformers &amp;amp; Attention 2: Keys, Values, Queries  &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt;(13 minutes): Building on the previous video, it explains &lt;strong&gt;keys, queries, and values&lt;/strong&gt;.  First, it explains the operations that make up the &lt;strong&gt;attention layer&lt;/strong&gt; conceptually, as a process to add context to a value (you can think of a “value” as a “word” in this context). Since we are trying to create a model, it describes where we need to add trainable parameters (weights). With the concepts and weights in place, it reintroduces the operations as matrix operations that create the stackable &lt;strong&gt;self-attention block&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=23XUv0T9L5c&quot;&gt;Rasa Algorithm Whiteboard - Transformers &amp;amp; Attention 3: Multi Head Attention &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt; (11 minutes): Using a phrase as an example, it explains why we need more than one attention head to understand the context where words are used (&lt;strong&gt;multi-head attention&lt;/strong&gt;). The fact that the attention heads are independent is a crucial concept in transformers. It allows matrix operations for each head to run in parallel, significantly speeding up the training process.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EXNBy8G43MM&quot;&gt;Rasa Algorithm Whiteboard: Transformers &amp;amp; Attention 4 - Transformers &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt;(15 minutes):  With the foundational concepts explained, this video covers the pictures in the “Attention is All You Need” paper that make up the &lt;strong&gt;transformer architecture&lt;/strong&gt;. The new concept introduced here is &lt;strong&gt;positional encoding&lt;/strong&gt;. It ends by highlighting how the transformer architecture lends itself to &lt;strong&gt;parallelization&lt;/strong&gt; in ways other attention architectures cannot.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We just finished the second hour of the morning’s understanding transformers. Rasa’s videos are a great introduction but are still informal. That’s not a bug – it’s a feature. They introduce the key concepts in simple terms, making them easy to follow.&lt;/p&gt;

&lt;h2 id=&quot;hour-3---digging-into-details&quot;&gt;Hour 3 - Digging into details&lt;/h2&gt;

&lt;p&gt;Now we will switch to a more formal introduction with these two lectures from professor &lt;a href=&quot;https://peterbloem.nl/&quot;&gt;Peter Bloem&lt;/a&gt;, VU University in Amsterdam.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KmAISyVvE1Y&amp;amp;list=PLIXJ-Sacf8u60G1TwcznBmK6rEL3gmZmV&amp;amp;index=2&quot;&gt;Lecture 12.1 Self-attention &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt;(23 minutes): Explains, with the help of illustrations, the matrix operations to calculate self-attention, then moves on to keys, queries, and values. With the basic concepts in place, it explains why we need multi-head attention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oUhGZMCTHtI&amp;amp;list=PLIXJ-Sacf8u60G1TwcznBmK6rEL3gmZmV&amp;amp;index=3&quot;&gt;Lecture 12.2 Transformers &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt;(18 minutes): Examines the pieces that make up the transformer model in the paper. The pictures from the paper are dissected with some math and code.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;hour-4---pick-your-adventure&quot;&gt;Hour 4 - Pick your adventure&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Go wide with &lt;a href=&quot;https://sea-adl.org/2019/12/03/lstm-is-dead-long-live-transformers/&quot;&gt;LSTM is dead, long live Transformers  &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt; (30 minutes): This talk gives a sense of history, explaining how we approached natural language problems in the past, their limitations, and how transformers overcame those limitations. It shows how to implement the transformer calculations with Python code. If you are better at visualizing code than math (like me), this can help you understand the operations.&lt;/li&gt;
  &lt;li&gt;Go deep with &lt;a href=&quot;http://nlp.seas.harvard.edu/annotated-transformer/&quot;&gt;The Annotated Transformer&lt;/a&gt; (30 to 60 minutes to read, hours and hours to experiment):  This article by the Harvard NLP team annotates the transformer paper with modern (as of 2022) PyTorch code. Each section of the paper is supplemented by the code that implements it. Part 3, “A Real World Example”, implements a fully functional German-English translation example using a &lt;a href=&quot;https://torchtext.readthedocs.io/en/latest/datasets.html#multi30k&quot;&gt;smaller dataset&lt;/a&gt; that makes it workable on smaller machines.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;where-to-go-from-here&quot;&gt;Where to go from here&lt;/h2&gt;

&lt;p&gt;It is a good time to reread the paper. It will make more sense now.&lt;/p&gt;

&lt;p&gt;These are other articles and videos that helped me understand transformers. Some of them overlap with the ones above, and some are complementary.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Positional embedding (encoding) is a key concept in understanding transformers. The transformer paper assumes that the reader knows that concept and briefly explains the reasons to use sine and cosine. &lt;a href=&quot;https://www.youtube.com/watch?v=1biZfFLPRSY&quot;&gt;This video  &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt; from &lt;em&gt;AI Coffee Break with Letitia&lt;/em&gt; explains in under ten minutes the concepts and the reasons to use sine and cosine.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;http://peterbloem.nl/blog/transformers&quot;&gt;Transformers from scratch&lt;/a&gt; is the accompanying blog post to hour 3, “Digging into details.” Professor Bloem describes some concepts explored in the video and adds code to show they are implemented.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://e2eml.school/transformers.html&quot;&gt;Transformers from Scratch&lt;/a&gt; (same title, different article) takes more time than other articles to explain one-hot encoding, dot product, and matrix multiplication, among others, with illustrations. By the time it gets to “attention as matrix multiplication”, it’s easier to understand the math. This post can be a good refresher if you are rusty on the math side of machine learning.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.tensorflow.org/text/tutorials/transformer&quot;&gt;Transformer model for language understanding&lt;/a&gt; is TensorFlow’s official implementation of the paper. It is not as annotated as the PyTorch code in &lt;a href=&quot;http://nlp.seas.harvard.edu/annotated-transformer/&quot;&gt;The Annotated Transformer&lt;/a&gt;, but still helpful if you are in a TensorFlow shop.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://johnthickstun.com/docs/transformers.pdf&quot;&gt;The Transformer Model in Equations&lt;/a&gt; is exactly what the name says, transformers as mathematical operations. The “Discussion” section is an insightful explanation of the equations, valuable even if you don’t have a strong math background (like me).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://jalammar.github.io/illustrated-transformer/&quot;&gt;The Illustrated Transformer&lt;/a&gt; is an often-cited source for understanding transformers. It is a good source if someone can read only one article beyond the paper.&lt;/li&gt;
  &lt;li&gt;Andrej Karpathy’s &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out  &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt; walks through the code to build a transformer model from scratch. At just under two hours, it’s the best investment of time at the code level I have found. Andrej is a great teacher and knows what he is talking about.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a sense of history, these two papers are highly cited as works that led to the transformer architecture.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Neural Machine Translation by Jointly Learning to Align and Translate&lt;/a&gt; is the paper credited with introducing the “attention” mechanism.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Effective Approaches to Attention-based Neural Machine Translation&lt;/a&gt; builds on the previous paper, introducing other important concepts, including dot-product attention. This &lt;a href=&quot;https://www.tensorflow.org/text/tutorials/nmt_with_attention&quot;&gt;official Tensorflow notebook&lt;/a&gt; implements a Spanish-to-English translation based on the paper.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally, &lt;a href=&quot;https://www.youtube.com/watch?v=rBCqOTEfxvg&quot;&gt;Attention is all you need; Attentional Neural Network Models &lt;i class=&quot;fab fa-youtube&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt;&lt;/a&gt; is a talk by Łukasz Kaiser, one of the &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;paper’s&lt;/a&gt; authors. He builds up the solution, starting with how natural language translation used to be solved in the past, the limitations, and how transformers solve them. So far, it’s what I would expect from one of the authors. What makes this video interesting to me is how humble Łukasz is. He explains the trials and errors and, at one point, how they had to ask for help to train the model they created.&lt;/p&gt;

&lt;p&gt;Reading a scientific paper makes it look like a linear story from problem to solution (“we had an idea and implemented it”). Watching Łukasz talk helps us understand how these great solutions don’t arrive out of thin air. Researchers build on top of previous work, try many variations, make mistakes, and ask for help to complete their work. Then they write the paper…&lt;/p&gt;

&lt;hr /&gt;

&lt;p class=&quot;small&quot;&gt;If your interests are in computer vision, &lt;a href=&quot;/vision-transformers-properties/&quot;&gt;it turns out transformers work quite well for that too&lt;/a&gt;.&lt;/p&gt;</content><author><name>Christian Garbin</name></author><category term="machine-learning" /><category term="natural-language-processing" /><category term="nlp" /><category term="transformers" /><summary type="html">Transformers: from zero to hero in one morning (or at least know enough to discuss transformers intelligently and apply them to your projects).</summary></entry><entry><title type="html">Applications of transformers in computer vision</title><link href="https://cgarbin.github.io/transformers-in-computer-vision/" rel="alternate" type="text/html" title="Applications of transformers in computer vision" /><published>2021-12-01T00:00:00-05:00</published><updated>2021-12-01T00:00:00-05:00</updated><id>https://cgarbin.github.io/transformers-in-computer-vision</id><content type="html" xml:base="https://cgarbin.github.io/transformers-in-computer-vision/">&lt;p&gt;This article describes the evolution of transformers, their application in natural language processing (NLP), their surprising effectiveness in computer vision, ending with applications in healthcare.&lt;/p&gt;

&lt;p&gt;It starts with the motivation and origins of transformers, from the initial attempts to apply a specialized neural network architecture (recurrent neural network – RNN) to natural language processing (NLP), the evolution of such architectures (long short-term memory and the concept of attention), to the creation of transformers and what makes them perform well in NLP. Then it describes how transformers are applied to computer vision. The last section describes some of the applications of transformers in healthcare (an area of interest for my research).&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;Side note: It was originally written as a survey paper for a class I took. Hence the references are in bibliography format instead of embedded links.&lt;/p&gt;

&lt;p class=&quot;notice--info&quot;&gt;if you are new to transformers, see &lt;a href=&quot;/understanding-transformers-in-one-morning/&quot;&gt;Understanding transformers in one morning&lt;/a&gt; and &lt;a href=&quot;/vision-transformers-properties/&quot;&gt;Vision transformer properties&lt;/a&gt;.&lt;/p&gt;

&lt;h1 id=&quot;the-origins-of-transformers--natural-language-processing&quot;&gt;The origins of transformers – natural language processing&lt;/h1&gt;

&lt;h2 id=&quot;when-context-matters&quot;&gt;When context matters&lt;/h2&gt;

&lt;p&gt;In some machine learning applications, we train models by feeding one input at a time. The trained model is then used in the same way: given one input, make a prediction. The typical example is image recognition and classification. We train the model by feeding one image at a time. Once trained, we feed one image and the model returns a prediction.&lt;/p&gt;

&lt;p&gt;However, there are other classes of problems where a single input is not enough to make a prediction. Natural language processing is a prominent example. When translating a sentence, it is not enough to look at one word at a time. The context in which a word is used matters. For example, the Portuguese word legal is translated in different ways to English.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Isso é um argumento &lt;strong&gt;legal&lt;/strong&gt; → This is a &lt;strong&gt;legal&lt;/strong&gt; argument&lt;/p&gt;

  &lt;p&gt;Isso é um seriado &lt;strong&gt;legal&lt;/strong&gt; → This is a &lt;strong&gt;nice&lt;/strong&gt; TV series&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In these applications of machine learning, context matters. The translation of “legal” depends on the word that came before it. If we represent the phrases as vectors (so a model can process them), we could, for example, represent the first phrase as the vector &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p1=[87,12,43,215,102]&lt;/code&gt; and the second sentence as the vector &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;p2=[87,12,43,175,102]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;A model attempting to translate the word “legal”, encoded as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;102&lt;/code&gt;, must remember what came before it. The model must translate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;102&lt;/code&gt; one way if it was preceded by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;215&lt;/code&gt; (p1) and another way if it was preceded by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;175&lt;/code&gt; (p2).&lt;/p&gt;

&lt;p&gt;The model must have a “memory” of what it has seen so far. Or, in other words, the model’s output is contextual: it is based not only on its current state (the current input – the current word) but also on previous states (what came before the current input – the words that came before). To understand the context, the model must “remember” what it has seen so far, instead of taking only one input at a time, i.e. the model must work with a sequence of input values.&lt;/p&gt;

&lt;h2 id=&quot;remembering-the-past--recurrent-neural-networks&quot;&gt;Remembering the past – recurrent neural networks&lt;/h2&gt;

&lt;p&gt;Recurrent neural networks (RNNs) are a class of networks that can model such problems. The figure below shows the standard representation of an RNN cell. The blue arrow indicates the “temporal loop” in the network: the result from a previous input, known as the state, is fed into the network when processing a new input. Using the state from a previous input when processing new input allows the network to “remember” what it has seen so far.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/rnn-one-cell.png&quot; alt=&quot;One cell of an RNN&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The temporal loop can be conceptually represented as passing the state from the past steps into the future steps. In the figure below, the RNN cell is unrolled (repeated) to represent the state from previous steps passed into the subsequent ones (this process is also called “unfolding” the network).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/rnn-unrolled.png&quot; alt=&quot;Unrolled RNN&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;forgetting-the-past--vanishing-and-exploding-gradients&quot;&gt;Forgetting the past – vanishing and exploding gradients&lt;/h2&gt;

&lt;p&gt;RNNs are trained with a variation of back-propagation, similar to how we train other types of neural networks. First, we choose how many steps we will unroll the network, and then we apply a specialized version of back-propagation (Ian et al., 2016).&lt;/p&gt;

&lt;p&gt;Ideally, we would like to create an RNN with as many unrolled steps as possible, to have as much context as possible (i.e. remember very large sentences or even entire pieces of text). However, a large number of unrolled steps has an unfortunate effect: vanishing and exploding gradients, which limits the size of the network we can build (Bengio et al., 1994) (Pascanu et al., 2013).&lt;/p&gt;

&lt;p&gt;In practice, the result is that we have to limit the number of unrolled steps of an RNN, thus limiting how far back the network can “remember” information.&lt;/p&gt;

&lt;h2 id=&quot;going-further-into-the-past--long-short-term-memory&quot;&gt;Going further into the past – long short-term memory&lt;/h2&gt;

&lt;p&gt;Long short-term memory (LSTM) is a recurrent network architecture created to deal with the vanishing and exploding gradient problem of the classical RNN architecture (Hochreiter &amp;amp; Schmidhuber, 1997). They do so by having a more complex cell design. In this design, the gradients are all contained within the LSTM cell, making them more stable because they no longer have to traverse the entire network.&lt;/p&gt;

&lt;p&gt;The figure below, from (Greff et al., 2017), compares an RNN cell (left) with a typical LSTM cell (right), including the “forget gate” that enables it to learn long sequences that are not partitioned into subsequences (Gers et al., 1999).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/rnn-lstm-compared.png&quot; alt=&quot;RNN and LSTM compared&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;deciding-where-to-look--attention&quot;&gt;Deciding where to look – attention&lt;/h2&gt;

&lt;p&gt;With LSTM we have a solution to look further into the past and process larger sentences. Now we need to decide where to look when processing a sentence because the order of the words is important for language processing. A model cannot mindlessly translate one word at a time.&lt;/p&gt;

&lt;p&gt;A typical example where the order of words matters is the placement of adjectives. Back to the first example, we can see that the placement of “legal” varies in each language.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Isso é um argumento &lt;strong&gt;legal&lt;/strong&gt; → This is a &lt;strong&gt;legal&lt;/strong&gt; argument&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;How does a model know that “legal” goes to a different position in the translated phrase? The solution has two parts. First, the model needs to process the entire sentence, not each word separately. Then, the model needs to learn that it has to pay more attention to some parts of the phrases than others, at different times (in the example above, although “legal” comes last in the input, the model has to learn that in the output it must come first).&lt;/p&gt;

&lt;p&gt;RNN encoder/decoder networks (Cho et al., 2014) are used for the first part, processing the entire sentence. An encoder/decoder has two neural networks: one that converts (encodes) a sequence of words into a representation suitable to train a network, and another network that takes the encoded representation and translates (decodes) it. The decoder, armed with a full sequence of words and not just one word, implements the second part of the solution: decide in which sequence it must process the words (which may not be in the same order they were received, as in this case).&lt;/p&gt;

&lt;p&gt;This process is known as &lt;em&gt;attention&lt;/em&gt; (Bahdanau et al., 2014) (Luong et al., 2015), as in “where should the decoder look to produce the next output”.&lt;/p&gt;

&lt;h2 id=&quot;attention-is-all-we-need--transformers&quot;&gt;“Attention is all we need” – transformers&lt;/h2&gt;

&lt;p&gt;Adding the concept of attention significantly improved the accuracy of the networks, but it is still part of a time-consuming process, the training of the encoder and decoder RNNs.&lt;/p&gt;

&lt;p&gt;If what we want is the information to calculate attention, can we do that in a faster way? It turns out we can. Transformer networks dispense with RNNs and directly compute the important piece of information we want, attention. They achieve better accuracy for a fraction of the training time (Jakob, 2017) (Vaswani et al., 2017).&lt;/p&gt;

&lt;p&gt;Instead of using RNNs, transformers use stacks of feed-forward layers (a simple layer of neurons, without cycles, unlike RNNs). The figure below, from the original paper (Vaswani et al., 2017), shows the network architecture.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/transformer-model-architecture.png&quot; alt=&quot;Transformer model architecture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Dispensing with RNNs has two effects: the training process can be parallelized (RNNs are sequential by definition: the state of a previous step is fed into the next step) and computations are much faster. The following table, from (Vaswani et al., 2017), shows the smaller computational complexity of the transformer model compared to RNNs and convolutional neural networks (CNNs).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/transformer-computational-complexity.png&quot; alt=&quot;Transformer computational complexity&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The rightmost columns of the following table, also from (Vaswani et al., 2017), compares the training cost (in FLOPs). The transformer models are two to three orders the magnitude less expensive to train.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/transformer-training-cost.png&quot; alt=&quot;Transformer training cost&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The best performing language models today, BERT (Devlin et al., 2019), GPT-2 (Radford et al., 2019), and GPT-3 (Brown et al., 2020), are based on the transformer architecture. The combination of a simpler network and parallelization allowed the creation of these large, sophisticated models.&lt;/p&gt;

&lt;p&gt;A key concept of the transformer architecture is the “multi-head self-attention” layer. “Multi”  refers to the fact that instead of having one attention layer, transformers have multiple attention layers running in parallel. In addition, the layers employ self-attention (Cheng et al., 2016) (Lin et al., 2017). With such a construct, transformers can efficiently weigh in the contribution of multiple parts of a sentence simultaneously. Each self-attention layer can encode longer range dependencies, capturing the relationship between words that are further apart (compared to RNNs and CNNs).&lt;/p&gt;

&lt;p&gt;The ability to pay attention to multiple parts of the input and the encoding of longer-range dependencies results in better accuracy. The figure below (Alammar, 2018b) shows how self-attention allows a model to learn that “it” refers more strongly to “The animal” in the sentence.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/transformer-attention-example.png&quot; alt=&quot;Transformer attention example&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Research continues to create larger transformer models. A recent advancement in the architecture of transformers is Big Bird (Zaheer et al., 2021). It removes the original model’s quadratic computational and memory dependency on the sequence length by introducing sparse attention. By removing the quadratic dependency, larger models can be built, capable of processing larger sequences.&lt;/p&gt;

&lt;h1 id=&quot;transformers-in-computer-vision&quot;&gt;Transformers in computer vision&lt;/h1&gt;

&lt;p&gt;The concepts of “sequence” and “attention” can also be applied to computer vision. The original applications of attention in image processing used RNNs, like the NLP counterparts. Neural networks with attention were used for image classification (Mnih et al., 2014), multiple object recognition (Ba et al., 2015), and image caption generation (Xu et al., 2016). These applications of attention to computer vision experienced the same issues that afflicted NLP architectures based on RNN: vanishing or exploding gradients and long times to train the model.&lt;/p&gt;

&lt;p&gt;And, just like in NLP, the solution was to apply self-attention, using the transformer architecture. One of the first applications of transformers in computer vision was in image generation (Parmar et al., 2018). (Carion et al., 2020) applied transformers to object detection and segmentation using a hybrid architecture, with a CNN used to extract image features.&lt;/p&gt;

&lt;p&gt;Then (Dosovitskiy et al., 2020, which includes references to earlier works they built upon), dropped all other types of networks, creating a “pure” transformer architecture for image recognition. In the figure below, from that paper, we can see the same elements of the NLP transformer architecture, now applied to computer vision: the lack of more complex networks (like RNN or CNN) that results in fast training time, the concept of sequences (created by splitting the image into patches), and the multi-headed attention. This architecture is known as ViT (Vision Transformer).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/vision-transformer-architecture.png&quot; alt=&quot;Vision Transformer architecture&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The resulting transformer models are more accurate than the convolutional neural network (CNN) models typically used in computer vision and, more importantly, significantly faster to train. In the table below, from (Dosovitskiy et al., 2020), the first three columns are three versions of the transformer model. The last row shows how the transformer-based networks (first three columns) use substantially less computational resources for training than CNN-based networks (last two columns).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/vision-transformer-performance.png&quot; alt=&quot;Vision Transformer performance&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Transformers in computer vision is still an active area of research. At the time of this writing (November of 2021), the recently-published Swin Transformer architecture (Liu et al., 2021) used a shifted windows approach (figure below, from the paper) to achieve state-of-the-art results in image classification, object detection, and image segmentation. The shifted window architecture allows a transformer network to cope with the “…large variations in the scale of visual entities and the high resolution of pixels in images compared to words in text.”&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/swin-transformer.png&quot; alt=&quot;Swin Transformer&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;transformers-in-healthcare&quot;&gt;Transformers in healthcare&lt;/h1&gt;

&lt;p&gt;Applications of Transformers in healthcare fall, in general terms, into the following categories:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Natural language process (NLP)&lt;/em&gt;: extract information from medical records to make predictions.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Genomics and proteomics&lt;/em&gt;:  processing the large sequences from genetic and proteomic.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Computer vision&lt;/em&gt;: image classification, segmentation, augmentation, and generation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following sections describe some of these applications. Note from the dates of the references that this is a recent and active area of research. Many of the current applications of CNNs and RNNs in the same areas have evolved over the years until they reached their current performance. It is expected that these early (and promising) applications of transformers will improve over time as research continues.&lt;/p&gt;

&lt;h2 id=&quot;nlp-applications&quot;&gt;NLP applications&lt;/h2&gt;

&lt;p&gt;The healthcare industry has been accumulating written records for many years. There is a wealth of information stored in these records from consultation notes, lab exam summaries, and radiologists’ reports. Most of them are already stored in electronic health records (EHR), ready to be consumed by computers. Transformers’ success with NLP makes them a good fit to process EHR. Some of the applications include:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;BEHRT (Li et al., 2020), as the name indicates, was inspired by BERT (Devlin et al., 2019). Trained on medical records, BEHRT can predict 301 diseases in a future visit of a patient. It improved the state-of-the-art in this task by “8.0–13.2% (in terms of average precision scores for different tasks)”. In addition to the improvements in prediction, the attention mechanism has the potential to make the model more interpretable, an important feature for healthcare applications.&lt;/li&gt;
  &lt;li&gt;(Kodialam et al., 2020) introduces SARD (self-attention with reverse distillation), where the input to the model is not the raw text from medical records but a summary of a medical visit. While BEHRT can handle 301 conditions, SARD can handle “…a much larger set of 37,004 codes, spanning conditions, medications, procedures, and physician specialty.”&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;genomics-and-proteomics-applications&quot;&gt;Genomics and proteomics applications&lt;/h2&gt;

&lt;p&gt;Transformers’ ability to process sequences makes them natural candidates for genomics and proteomics applications, where large, complex sequences abound.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;AlphaFold2 (Jumper et al., 2021) is an evolution of the first AlphaFold. It decisively won the 14th Critical Assessment of Structural Prediction (CASP), a competition to predict the structure (“folds”) of proteins. Understanding the structure of proteins is important because the function of a protein is directly related to its structure. Given that the structure of a protein is determined by its amino acid sequence, it is not surprising to learn that one of the most important changes in AlphaFold2 was the addition of attention via transformers (Rubiera, 2021). AlphaFold2’s transformer architecture has been named EvoFormer.&lt;/li&gt;
  &lt;li&gt;(Avsec et al., 2021) applied transformers to gene expression. They named the architecture Enformer (“a portmanteau of enhancer and transformer”). Gene expression is a fundamental building block in biology. It is “the process by which information from a gene is used in the synthesis of a functional gene product that enables it to produce end products, protein or non-coding RNA, and ultimately affect a phenotype, as the final effect.” (Wikipedia, 2021).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With these applications in mind, the figure below (Avsec, 2021) illustrates why the ability to process larger sequences makes transformers an effective architecture for genomics and proteomics applications. The dark blue area shows how far the Enformer architecture can look for interactions between DNA base pairs (200,000), compared with the previous state-of-the-art Basenji2 architecture (40,000 base pairs).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/enformer.png&quot; alt=&quot;Enformer&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;computer-vision-applications&quot;&gt;Computer vision applications&lt;/h2&gt;

&lt;p&gt;Transformers are improving the following areas of healthcare computer vision:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Label generation&lt;/em&gt;: extract accurate labels from medical records to train image classification networks.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Large image analysis&lt;/em&gt;: process the large images generated in some medical areas.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Improvements to explainability&lt;/em&gt;: produce explanations that are easier to interpret for medical professionals.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following sections expand on those areas.&lt;/p&gt;

&lt;h3 id=&quot;label-generation&quot;&gt;Label generation&lt;/h3&gt;

&lt;p&gt;Medical image applications that identify diseases and other features in images are trained with supervised or semi-supervised learning, which means they need many images with accurate labels. Labeling medical images requires experts that are few, expensive, or both.&lt;/p&gt;

&lt;p&gt;On the other hand, there are many images with accompanying medical reports, for example, the radiological reports from x-rays. An application capable of reliably extracting labels from the reports can boost the number of images in medical image datasets. However, medical reports are created by human experts for other human experts. The reports contain complex sentences that record not only the expert’s certainty about findings but also other potential findings and exclusions. Telling apart positive, potential, and negated (excluded) findings is a complex task.&lt;/p&gt;

&lt;p&gt;CheXpert (Irvin et al., 2019) made available over 100,000 chest x-ray images with labels extracted from the medical reports using a rule-based NLP parser. The same team later developed ChexBert (Smit et al., 2020) based on (as the name implies) BERT (Devlin et al., 2019). CheXBert performed better than CheXPert and, crucially, it performs better in uncertainty (“potential”, “unremarkable”, and similar words) and negation cases, which are notoriously difficult to analyze.&lt;/p&gt;

&lt;p&gt;These results indicate that transformer-based labeling extraction can improve the labels of existing datasets and help create more trustworthy labeled medical images, which are necessary to advance research in healthcare computer vision.&lt;/p&gt;

&lt;h3 id=&quot;large-image-analysis&quot;&gt;Large image analysis&lt;/h3&gt;

&lt;p&gt;Some medical diagnosis images, such as those used in histopathology, are large, in the hundreds of megabytes to the gigapixel range. Traditional neural networks cannot handle such images in one piece. Before transformers, a common solution was to split the image into multiple patches and process them separately with a CNN-based network  (Komura &amp;amp; Ishikawa, 2018). Dividing an image into arbitrary patches may lose context information about the overall image structure and features.&lt;/p&gt;

&lt;p&gt;Holistic Attention Network – HATNet (Mehta et al., 2020) is a transformer-based architecture that takes a different approach, borrowing concepts from NLP. Instead of analyzing each patch separately, it considers each patch a “word” and combines them into bags of words. The bags of words are then processed by a transformer network that aggregates information from the different patches into a global image representation. HATNet is “8% more accurate and about 2× faster than the previous best network”.&lt;/p&gt;

&lt;p&gt;More important than the immediate results of HATNet is the innovative approach that opens up the door to more research into processing large medical images. For example, TransUNet (Chen et al., 2021) takes a similar approach for medical image segmentation. As in image classification, CNNs have been traditionally applied to medical image segmentation. Using CNNs for segmentation has a related problem as for classification: the CNNs lose global context. TransUNet resolves that problem with a hybrid architecture: a CNN is used to extract features from the large-dimensional images, which are then passed to a  transformer network. It improved the state-of-the-art Synapse multi-organ CT segmentation by several percentage points.&lt;/p&gt;

&lt;h3 id=&quot;improvements-in-interpretability&quot;&gt;Improvements in interpretability&lt;/h3&gt;

&lt;p&gt;In high-stakes applications, such as healthcare, interpretable results help improve “auditability, system verification, enhance trust, and user adoption” (Reyes et al., 2020). Specifically for medical images, interpretability is related to explaining what pieces of an image the model considered for inference.&lt;/p&gt;

&lt;p&gt;Although still a new field, the interpretability of image classification with transformers shows early signs that it can result in more precise, and thus more helpful, interpretations of what a model is “looking” at. In the figure below, from (Chefer et al., 2021), the rightmost column shows their new method to extract interpretability from a transformer multi-class image classification task. It generates class-specific visualizations with better-defined activations. The closest alternative method is Grad-CAM (Selvaraju et al., 2020) (other methods cannot even generate class-specific visualizations), but it has significantly more extraneous artifacts in the visualization.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/interpretability.png&quot; alt=&quot;Interpretability&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The transformer’s attention map also shows promising results for interpretability. In the figure below, from (Matsoukas et al., 2021), the top row shows the original image of a dermoscopic image (left), an eye fundus (center), and a mammography (right). The middle row is a Grad-CAM saliency map, traditionally used to interpret the classification from CNNs. The bottom row is a saliency map from a transformer attention layer. The attention layer saliency shows a more well-defined saliency area, making the results easier to interpret (although the paper notes that this assumption has to be tested with medical professionals).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/saliency-maps.png&quot; alt=&quot;Interpretability&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;conclusions&quot;&gt;Conclusions&lt;/h1&gt;

&lt;p&gt;Transformers were first used in NLP applications, resulting in impressive language models like BERT, GPT-2, and GTP-3. Their ability to learn the association between pieces of a large sequence of data (attention) is now being used in computer vision. The resulting models are faster to train and more accurate than CNNs for image classification.&lt;/p&gt;

&lt;p&gt;From the literature references, we notice that applying transformers to computer vision is still a new area. CNN- and RNN-based solutions evolved over many years of research. We should expect transformers also to evolve. In fact,  several approaches are already being tried to create more efficient transformer architectures by, for example, reducing the quadratic complexity of the attention mechanism (May, 2020), (Tay et al., 2020), (Choromanski &amp;amp; Colwell, 2020).&lt;/p&gt;

&lt;p&gt;Efficient transformer architectures will have two effects. From one side, larger and larger sequences will be handled, improving the results in applications where the size of the sequence is critical for the results (for example, large resolution images used in healthcare). On the other hand, for the same sequence length, it will become faster, and thus cheaper, to train transformers, democratizing their use.&lt;/p&gt;

&lt;p&gt;And, as a final benefit, we may end up with one unified network architecture that can be applied to two important fields, natural language processing, and computer vision.&lt;/p&gt;

&lt;h1 id=&quot;appendix-a---a-reading-list-for-rnn-lstm-attention-and-transformers-in-nlp&quot;&gt;Appendix A - A reading list for RNN, LSTM, attention, and transformers in NLP&lt;/h1&gt;

&lt;p&gt;While researching this paper, I started with the original application of the networks, natural language processing (NLP). After researching the applications for image processing, it became clear that starting with NLP was indeed a good choice. The concepts of sequence and attention are easier to illustrate and follow in that area. Once learned in that context, they can be transferred to computer vision.&lt;/p&gt;

&lt;p&gt;This appending is a reading list in the context of NLP to help other readers, and the future self of the author when he will (inevitably) have forgotten some of the concepts.&lt;/p&gt;

&lt;p&gt;The seminal paper on encoder/decoder combined with RNN for natural language processing is (Cho et al., 2014).  (Sutskever et al., 2014) introduced sequence-to-sequence using long short-term memory (LSTM) networks. (Bahdanau et al., 2014) and (Luong et al., 2015) are credited with developing the attention mechanism.  (Vaswani et al., 2017) is the original paper on transformers (reading the accompanying Google’s blog post (Jakob, 2017) makes it easier to follow the paper).&lt;/p&gt;

&lt;p&gt;The explanations of RNN and LSTM in this paper are simplified because I wanted to focus on transformers. I did not discuss the different types of RNNs and the inner working of the LSTM cell. For a step-by-step, illustrated explanation of how LSTMs work and why it is an effective RNN architecture, see (Olah, 2015). For other RNN architectures, see (Olah &amp;amp; Carter, 2016).&lt;/p&gt;

&lt;p&gt;(Alammar, 2018a) describes step-by-step, with the help of animated visualizations the sequence-to-sequence, encoder/decoder, RNN, and attention concepts, including details of how they work. (Alammar, 2018b) builds on that to explain how transformers use the important concept of self-attention, with detailed illustrations.&lt;/p&gt;

&lt;p&gt;Finally, as a historical note: finding the original paper on recurrent networks (RNNs) turned out to be elusive. Like many ideas, it evolved over time. (Rumelhart et al., 1987) is credited in several places as the first mention and description of a “recurrent network”, although it did not describe the back-propagation through time (BPTT) method used to train RNNs nowadays.&lt;/p&gt;

&lt;h1 id=&quot;appendix-b---the-quadratic-bottleneck&quot;&gt;Appendix B - The quadratic bottleneck&lt;/h1&gt;

&lt;p&gt;As a general rule, the longer the sequence a transformer can process, the better results it will have. However, it comes at the cost of large amounts of memory and processing power required for training and inference. The self-attention mechanism of the standard transformer architecture is a quadratic function (figure below, from (Tay et al., 2020)).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-12-01/quadratic-problem.png&quot; alt=&quot;The quadratic problem&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Several approaches are being tried to reduce the quadratic complexity, creating more efficient transformer architectures (May, 2020), (Tay et al., 2020), (Choromanski &amp;amp; Colwell, 2020).&lt;/p&gt;

&lt;p&gt;Efficient transformer architectures will have two effects. From one side, larger and larger sequences will be handled, improving the results in applications where the size of the sequence is critical for the results (for example, large resolution images used in healthcare). On the other hand, for the same sequence length, it will become faster, and thus cheaper, to train transformers, democratizing their use.&lt;/p&gt;

&lt;h1 id=&quot;references&quot;&gt;References&lt;/h1&gt;

&lt;ol&gt;
  &lt;li&gt;Alammar, J. (2018a, May 9) &lt;a href=&quot;https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/&quot;&gt;Visualizing A Neural Machine Translation Model (Mechanics of Seq2seq Models With Attention)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Alammar, J. (2018b, June 27) &lt;a href=&quot;http://jalammar.github.io/illustrated-transformer/&quot;&gt;The Illustrated Transformer&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Avsec, Ž. (2021, October 4) &lt;a href=&quot;https://deepmind.com/blog/article/enformer&quot;&gt;Predicting gene expression with AI. Deepmind&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Avsec, Ž., Agarwal, V., Visentin, D., Ledsam, J. R., Grabska-Barwinska, A., Taylor, K. R., Assael, Y., Jumper, J., Kohli, P., &amp;amp; Kelley, D. R. (2021) &lt;a href=&quot;https://doi.org/10.1038/s41592-021-01252-x&quot;&gt;Effective gene expression prediction from sequence by integrating long-range interactions. Nature Methods, 18(10), 1196–1203&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Ba, J., Mnih, V., &amp;amp; Kavukcuoglu, K. (2015) &lt;a href=&quot;http://arxiv.org/abs/1412.7755&quot;&gt;Multiple Object Recognition with Visual Attention&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Bahdanau, D., Cho, K., &amp;amp; Bengio, Y. (2014) &lt;a href=&quot;https://arxiv.org/abs/1409.0473v7&quot;&gt;Neural Machine Translation by Jointly Learning to Align and Translate&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Bengio, Y., Simard, P., &amp;amp; Frasconi, P. (1994) &lt;a href=&quot;https://doi.org/10.1109/72.279181&quot;&gt;Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks, 5(2), 157–166.&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G., Henighan, T., Child, R., Ramesh, A., Ziegler, D. M., Wu, J., Winter, C., … Amodei, D. (2020) &lt;a href=&quot;http://arxiv.org/abs/2005.14165&quot;&gt;Language Models are Few-Shot Learners&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Carion, N., Massa, F., Synnaeve, G., Usunier, N., Kirillov, A., &amp;amp; Zagoruyko, S. (2020) &lt;a href=&quot;http://arxiv.org/abs/2005.12872&quot;&gt;End-to-End Object Detection with Transformers&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Chefer, H., Gur, S., &amp;amp; Wolf, L. (2021) &lt;a href=&quot;http://arxiv.org/abs/2012.09838&quot;&gt;Transformer Interpretability Beyond Attention Visualization&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Chen, J., Lu, Y., Yu, Q., Luo, X., Adeli, E., Wang, Y., Lu, L., Yuille, A. L., &amp;amp; Zhou, Y. (2021) &lt;a href=&quot;http://arxiv.org/abs/2102.04306&quot;&gt;TransUNet: Transformers Make Strong Encoders for Medical Image Segmentation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Cheng, J., Dong, L., &amp;amp; Lapata, M. (2016) &lt;a href=&quot;http://arxiv.org/abs/1601.06733&quot;&gt;Long Short-Term Memory-Networks for Machine Reading&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Cho, K., van Merrienboer, B., Gulcehre, C., Bahdanau, D., Bougares, F., Schwenk, H., &amp;amp; Bengio, Y. (2014) &lt;a href=&quot;http://arxiv.org/abs/1406.1078&quot;&gt;Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Choromanski, K., &amp;amp; Colwell, L. (2020, October 23) &lt;a href=&quot;http://ai.googleblog.com/2020/10/rethinking-attention-with-performers.html&quot;&gt;Rethinking Attention with Performers&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Devlin, J., Chang, M.-W., Lee, K., &amp;amp; Toutanova, K. (2019) &lt;a href=&quot;http://arxiv.org/abs/1810.04805&quot;&gt;BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., &amp;amp; Houlsby, N. (2020) &lt;a href=&quot;https://arxiv.org/abs/2010.11929v2&quot;&gt;An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Gers, F. A., Schmidhuber, J., &amp;amp; Cummins, F. (1999) &lt;a href=&quot;https://doi.org/10.1049/cp:19991218&quot;&gt;Learning to forget: Continual prediction with LSTM. 1999 Ninth International Conference on Artificial Neural Networks ICANN 99. (Conf. Publ. No. 470), 2, 850–855 vol.2&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Greff, K., Srivastava, R. K., Koutník, J., Steunebrink, B. R., &amp;amp; Schmidhuber, J. (2017) &lt;a href=&quot;https://doi.org/10.1109/TNNLS.2016.2582924&quot;&gt;LSTM: A Search Space Odyssey. IEEE Transactions on Neural Networks and Learning Systems, 28(10), 2222–2232&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Hochreiter, S., &amp;amp; Schmidhuber, J. (1997) &lt;a href=&quot;https://doi.org/10.1162/neco.1997.9.8.1735&quot;&gt;Long Short-Term Memory. Neural Computation, 9(8), 1735–1780&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Ian, G., Yoshua, B., &amp;amp; Aaron, C. (2016) &lt;a href=&quot;https://www.deeplearningbook.org/&quot;&gt;Deep Learning&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Jakob, U. (2017) &lt;a href=&quot;http://ai.googleblog.com/2017/08/transformer-novel-neural-network.html&quot;&gt;Transformer: A Novel Neural Network Architecture for Language Understanding&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Jumper, J., Evans, R., Pritzel, A., Green, T., Figurnov, M., Ronneberger, O., Tunyasuvunakool, K., Bates, R., Žídek, A., Potapenko, A., Bridgland, A., Meyer, C., Kohl, S. A. A., Ballard, A. J., Cowie, A., Romera-Paredes, B., Nikolov, S., Jain, R., Adler, J., … Hassabis, D. (2021) &lt;a href=&quot;https://doi.org/10.1038/s41586-021-03819-2&quot;&gt;Highly accurate protein structure prediction with AlphaFold. Nature, 596(7873), 583–589&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Kodialam, R. S., Boiarsky, R., Lim, J., Dixit, N., Sai, A., &amp;amp; Sontag, D. (2020) &lt;a href=&quot;http://arxiv.org/abs/2007.05611&quot;&gt;Deep Contextual Clinical Prediction with Reverse Distillation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Komura, D., &amp;amp; Ishikawa, S. (2018) &lt;a href=&quot;https://doi.org/10.1016/j.csbj.2018.01.001&quot;&gt;Machine Learning Methods for Histopathological Image Analysis. Computational and Structural Biotechnology Journal, 16, 34–42&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Li, Y., Rao, S., Solares, J. R. A., Hassaine, A., Ramakrishnan, R., Canoy, D., Zhu, Y., Rahimi, K., &amp;amp; Salimi-Khorshidi, G. (2020) &lt;a href=&quot;https://doi.org/10.1038/s41598-020-62922-y&quot;&gt;BEHRT: Transformer for Electronic Health Records. Scientific Reports, 10(1), 7155&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Lin, Z., Feng, M., Santos, C. N. dos, Yu, M., Xiang, B., Zhou, B., &amp;amp; Bengio, Y. (2017) &lt;a href=&quot;http://arxiv.org/abs/1703.03130&quot;&gt;A Structured Self-attentive Sentence Embedding&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Liu, Z., Lin, Y., Cao, Y., Hu, H., Wei, Y., Zhang, Z., Lin, S., &amp;amp; Guo, B. (2021) &lt;a href=&quot;http://arxiv.org/abs/2103.14030&quot;&gt;Swin Transformer: Hierarchical Vision Transformer using Shifted Windows&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Luong, M.-T., Pham, H., &amp;amp; Manning, C. D. (2015) &lt;a href=&quot;http://arxiv.org/abs/1508.04025&quot;&gt;Effective Approaches to Attention-based Neural Machine Translation&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Matsoukas, C., Haslum, J. F., Söderberg, M., &amp;amp; Smith, K. (2021) &lt;a href=&quot;http://arxiv.org/abs/2108.09038&quot;&gt;Is it Time to Replace CNNs with Transformers for Medical Images?&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;May, M. (2020, March 14) &lt;a href=&quot;https://www.pragmatic.ml/a-survey-of-methods-for-incorporating-long-term-context/&quot;&gt;A Survey of Long-Term Context in Transformers. Machine Learning Musings&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Mehta, S., Lu, X., Weaver, D., Elmore, J. G., Hajishirzi, H., &amp;amp; Shapiro, L. (2020) &lt;a href=&quot;http://arxiv.org/abs/2007.13007&quot;&gt;HATNet: An End-to-End Holistic Attention Network for Diagnosis of Breast Biopsy Images&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Mnih, V., Heess, N., Graves, A., &amp;amp; kavukcuoglu,  koray. (2014) &lt;a href=&quot;https://proceedings.neurips.cc/paper/2014/hash/09c6c3783b4a70054da74f2538ed47c6-Abstract.html&quot;&gt;Recurrent Models of Visual Attention. Advances in Neural Information Processing Systems, 27&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Olah, C. (2015, August 27) &lt;a href=&quot;https://colah.github.io/posts/2015-08-Understanding-LSTMs/&quot;&gt;Understanding LSTM Networks. Colah’s Blog&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Olah, C., &amp;amp; Carter, S. (2016) &lt;a href=&quot;https://doi.org/10.23915/distill.00001&quot;&gt;Attention and Augmented Recurrent Neural Networks. Distill, 1(9), e1&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Parmar, N., Vaswani, A., Uszkoreit, J., Kaiser, Ł., Shazeer, N., Ku, A., &amp;amp; Tran, D. (2018) &lt;a href=&quot;https://arxiv.org/abs/1802.05751v3&quot;&gt;Image Transformer&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Pascanu, R., Mikolov, T., &amp;amp; Bengio, Y. (2013) &lt;a href=&quot;http://arxiv.org/abs/1211.5063&quot;&gt;On the difficulty of training Recurrent Neural Networks&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., &amp;amp; Sutskever, I. (2019) &lt;a href=&quot;https://www.semanticscholar.org/paper/Language-Models-are-Unsupervised-Multitask-Learners-Radford-Wu/9405cc0d6169988371b2755e573cc28650d14dfe&quot;&gt;Language Models are Unsupervised Multitask Learners&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Reyes, M., Meier, R., Pereira, S., Silva, C. A., Dahlweid, F.-M., Tengg-Kobligk, H. von, Summers, R. M., &amp;amp; Wiest, R. (2020) &lt;a href=&quot;https://doi.org/10.1148/ryai.2020190043&quot;&gt;On the Interpretability of Artificial Intelligence in Radiology: Challenges and Opportunities. Radiology: Artificial Intelligence, 2(3), e190043&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Rubiera, C. O. (2021) &lt;a href=&quot;https://www.blopig.com/blog/2021/07/alphafold-2-is-here-whats-behind-the-structure-prediction-miracle/&quot;&gt;AlphaFold 2 is here: What’s behind the structure prediction miracle - Oxford Protein Informatics Group. Oxford Protein Informatics Group&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Rumelhart, D. E., Hinton, G., &amp;amp; Williams, R. (1987) &lt;a href=&quot;https://ieeexplore.ieee.org/document/6302929&quot;&gt;Learning Internal Representations by Error Propagation. In Parallel Distributed Processing: Explorations in the Microstructure of Cognition: Foundations (pp. 318–362). MIT Press&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Selvaraju, R. R., Cogswell, M., Das, A., Vedantam, R., Parikh, D., &amp;amp; Batra, D. (2020) &lt;a href=&quot;https://doi.org/10.1007/s11263-019-01228-7&quot;&gt;Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization. International Journal of Computer Vision, 128(2), 336–359&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Sutskever, I., Vinyals, O., &amp;amp; Le, Q. V. (2014) &lt;a href=&quot;http://arxiv.org/abs/1409.3215&quot;&gt;Sequence to Sequence Learning with Neural Networks&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Tay, Y., Dehghani, M., Bahri, D., &amp;amp; Metzler, D. (2020) &lt;a href=&quot;http://arxiv.org/abs/2009.06732&quot;&gt;Efficient Transformers: A Survey&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., &amp;amp; Polosukhin, I. (2017) &lt;a href=&quot;http://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Wikipedia. (2021) &lt;a href=&quot;https://en.wikipedia.org/w/index.php?title=Gene_expression&amp;amp;oldid=1051856939&quot;&gt;Gene expression&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Xu, K., Ba, J., Kiros, R., Cho, K., Courville, A., Salakhutdinov, R., Zemel, R., &amp;amp; Bengio, Y. (2016) &lt;a href=&quot;http://arxiv.org/abs/1502.03044&quot;&gt;Show, Attend and Tell: Neural Image Caption Generation with Visual Attention&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Zaheer, M., Guruganesh, G., Dubey, A., Ainslie, J., Alberti, C., Ontanon, S., Pham, P., Ravula, A., Wang, Q., Yang, L., &amp;amp; Ahmed, A. (2021) &lt;a href=&quot;http://arxiv.org/abs/2007.14062&quot;&gt;Big Bird: Transformers for Longer Sequences&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;</content><author><name>Christian Garbin</name></author><category term="machine-learning" /><category term="computer-vision" /><category term="transformers" /><summary type="html">The evolution of transformers, their application in natural language processing (NLP), their surprising effectiveness in computer vision, ending with applications in healthcare.</summary></entry><entry><title type="html">Machine learning interpretability with feature attribution</title><link href="https://cgarbin.github.io/machine-learning-interpretability-feature-attribution/" rel="alternate" type="text/html" title="Machine learning interpretability with feature attribution" /><published>2021-04-26T00:00:00-04:00</published><updated>2022-12-20T00:00:00-05:00</updated><id>https://cgarbin.github.io/machine-learning-interpretability-feature-attribution</id><content type="html" xml:base="https://cgarbin.github.io/machine-learning-interpretability-feature-attribution/">&lt;p&gt;There are many discussions in the machine learning (ML) community about model interpretability and explainability. The discussions take place in several contexts, ranging from using interpretability and explainability techniques to increase the robustness of a model, all the way to increasing end-user trust in a model.&lt;/p&gt;

&lt;p&gt;This article reviews &lt;em&gt;feature attribution&lt;/em&gt;, a technique to interpret model predictions. First, it reviews commonly-used feature attribution methods, then demonstrates feature attribution with SHAP, one of these methods.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;Feature attribution methods “&lt;a href=&quot;https://cloud.google.com/ai-platform/prediction/docs/ai-explanations/overview&quot;&gt;indicate how much each feature in your model contributed to the predictions for each given instance.&lt;/a&gt;” They work with tabular data, text, and images. The following pictures show an example for each case.&lt;/p&gt;

&lt;p&gt;An example of feature attribution for text (from &lt;a href=&quot;https://www.mdpi.com/1099-4300/23/1/18#&quot;&gt;Explainable AI: A Review of Machine Learning Interpretability Methods&lt;/a&gt;):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/example-feature-attribution-text.png&quot; alt=&quot;Feature attribution - text&quot; /&gt;&lt;/p&gt;

&lt;p&gt;An example of feature attribution for tabular data (from &lt;a href=&quot;https://shap.readthedocs.io/en/latest/example_notebooks/tabular_examples/tree_based_models/Catboost%20tutorial.html&quot;&gt;SHAP tutorial - official documentation&lt;/a&gt;):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/example-feature-attribution-tabular.png&quot; alt=&quot;Feature attribution - tabular&quot; /&gt;&lt;/p&gt;

&lt;p&gt;An example of feature attribution for a model that identifies a cat in a picture (from &lt;a href=&quot;https://github.com/marcotcr/lime&quot;&gt;LIME’s GitHub&lt;/a&gt;):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/example-feature-attribution-image.png&quot; alt=&quot;Feature attribution for image identification&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;what-feature-attributions-are-used-for&quot;&gt;What feature attributions are used for&lt;/h2&gt;

&lt;p&gt;The prominent use cases for feature attribution are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Debug models&lt;/em&gt;: verify that models make predictions for the right reasons. For example, in the first picture below, a model predicts diseases in X-ray images based on the metal tags the X-ray technicians place on patients, not the actual disease marks (an example of &lt;a href=&quot;https://arxiv.org/abs/1907.02893&quot;&gt;spurious correlation&lt;/a&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Audit models&lt;/em&gt;: verify that models are not looking at attributes that encode bias (gender, race, among others) when making decisions. For example, in the second picture below, the middle column shows a gender-biased model that predicts professions by looking at the face in the image. The rightmost column shows where a debiased model looks to make predictions.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Optimize models&lt;/em&gt;: simplify correlated features and remove features that do not contribute to predictions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The figure below (&lt;a href=&quot;https://journals.plos.org/plosmedicine/article?id=10.1371/journal.pmed.1002683&quot;&gt;source&lt;/a&gt;) is an example of feature attribution to debug a model (verify what the model uses to predict diseases). In this case, the model is looking at the wrong place to make predictions (using the X-ray markers instead of the pathology).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/use-debug-model.png&quot; alt=&quot;Using interpretability to debug models&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The figure below (&lt;a href=&quot;https://arxiv.org/abs/1610.02391&quot;&gt;source&lt;/a&gt;) is an example of feature attribution to audit a model. The middle column shows how the model predicts all women as “nurse”, never as “doctor” – an example of gender bias. The rightmost column shows a corrected model.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/use-audit-model.png&quot; alt=&quot;Using interpretability to audit models&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;where-feature-attribution-is-in-relation-to-other-interpretability-methods&quot;&gt;Where feature attribution is in relation to other interpretability methods&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1912.05100&quot;&gt;Explainability fact sheets&lt;/a&gt; defines the following explanation families (borrowed from &lt;a href=&quot;https://dl.acm.org/doi/10.1145/169891.169951&quot;&gt;Explanation facilities and interactive systems&lt;/a&gt;):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Association between antecedent and consequent&lt;/em&gt;: “model internals such as its parameters, feature(s)-prediction relations such as explanations based on feature attribution or importance and item(s)-prediction relations, such as influential training instances”.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Contrast and differences&lt;/em&gt;: “prototypes and criticisms (similarities and dissimilarities) and class-contrastive counterfactual statements”.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Causal mechanism&lt;/em&gt;: “a full causal model”.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Feature attribution is part of the first family, the association between antecedent and consequent.&lt;/p&gt;

&lt;p&gt;Using the framework in the &lt;a href=&quot;https://christophm.github.io/interpretable-ml-book/taxonomy-of-interpretability-methods.html&quot;&gt;taxonomy of interpretable models&lt;/a&gt;, we can further narrow down feature attribution methods as:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Post-hoc&lt;/em&gt;: They are usually used after the model is trained and usually with black-box models. Therefore, we are interpreting the results of the model, not the model itself (c)reating interpretable models is yet &lt;a href=&quot;https://arxiv.org/abs/1811.10154&quot;&gt;another area of research&lt;/a&gt;). The typical application for feature attribution is to interpret the predictions of black-box models, such as deep neural networks (DNNs) and random forests. These models are too complex to be directly interpreted. Thus we are left with interpreting the model’s results, not the model itself.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Result of the interpretation method&lt;/em&gt;: They result in feature summary statistics (and visualization - most summary statistics can be visualized in one way or another).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Model-agnostic or model-specific&lt;/em&gt;: Shapley-value-based feature attribution methods can be used with different model architectures - they are model agnostic. Gradient-based feature attribution methods are based on gradients; therefore, they can be used only with models trained with gradient descent (neural networks, logistic regression, support vector machines, for example) - they are model specific.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Local&lt;/em&gt;: They explain an individual prediction of the model, not the entire model (that would be “global” interpretability).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Putting it all together, feature attribution methods are post-hoc, local interpretation methods. They can be model-agnostic (e.g., SHAP) or model-specific (e.g., Grad-CAM).&lt;/p&gt;

&lt;h2 id=&quot;limitations-and-traps-of-feature-attribution&quot;&gt;Limitations and traps of feature attribution&lt;/h2&gt;

&lt;h3 id=&quot;feature-attributions-are-approximations&quot;&gt;Feature attributions are approximations&lt;/h3&gt;

&lt;p&gt;In their typical application, explanations have a fundamental limitation when applied to black-box models: they are approximations of how the model behaves.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“[Explanations] cannot have perfect fidelity with respect to the original model. If the explanation was completely faithful to what the original model computes, the explanation would equal the original model, and one would not need the original model in the first place, only the explanation.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;Cynthia Rudin&lt;/cite&gt; — &lt;a href=&quot;https://arxiv.org/abs/1811.10154&quot;&gt;Stop Explaining Black Box Machine Learning Models for High Stakes Decisions and Use Interpretable Models Instead&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;More succinctly:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;“Explanations must be wrong.”&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;Cynthia Rudin&lt;/cite&gt; — &lt;a href=&quot;https://arxiv.org/abs/1811.10154&quot;&gt;Stop Explaining Black Box Machine Learning Models for High Stakes Decisions and Use Interpretable Models Instead&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we are going through the exploration of the feature attributions, we must keep in my mind that we are analyzing two items at the same time:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;What the model predicted.&lt;/li&gt;
  &lt;li&gt;How feature attribution &lt;em&gt;approximates&lt;/em&gt; what the model considers to make the prediction.&lt;/li&gt;
&lt;/ol&gt;

&lt;p class=&quot;notice--warning&quot;&gt;Therefore, &lt;strong&gt;never mistake the explanation for the actual behavior of the model&lt;/strong&gt;. This is a critical conceptual limitation to keep in mind.&lt;/p&gt;

&lt;p&gt;Because the explanations are approximations, they may disagree with each other. For example, in the figure below, LIME (left) and SHAP (right) disagree not only in the magnitude of features’ contributions but also in the direction (sign). This disagreement is more common than we may think. Refer to the excellent paper &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/2202.01602&quot;&gt;The Disagreement Problem in Explainable Machine Learning: A Practitioner’s Perspective&lt;/a&gt;&lt;/em&gt; for more details and how practitioners deal with this issue (the figure comes from the paper).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/disagreement.png&quot; alt=&quot;Explanation methods may disagree&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;feature-attribution-may-not-make-sense&quot;&gt;Feature attribution may not make sense&lt;/h3&gt;

&lt;p&gt;Feature attributions do not have any understanding of the model they are explaining. They simply explain what the model predicts, &lt;a href=&quot;https://arxiv.org/abs/1811.10154&quot;&gt;not caring if the prediction is right or wrong&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/explaining-wrong-prediction.png&quot; alt=&quot;Explaining wrong predictions&quot; /&gt;&lt;/p&gt;

&lt;p class=&quot;notice--warning&quot;&gt;Therefore, &lt;strong&gt;never confuse “explaining” with “understanding”&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;feature-attributions-are-sensitive-to-the-baseline&quot;&gt;Feature attributions are sensitive to the baseline&lt;/h3&gt;

&lt;p&gt;Another conceptual limitation is the choice of a baseline. The attributions are not absolute values. They are the contributions compared to a baseline. To better understand why baselines are important, see how Shapley values are calculated in the &lt;a href=&quot;#shapley-values&quot;&gt;Shapley values section&lt;/a&gt;, then the section on baselines right after it.&lt;/p&gt;

&lt;h3 id=&quot;feature-attributions-are-slow-to-calculate&quot;&gt;Feature attributions are slow to calculate&lt;/h3&gt;

&lt;p&gt;Moving on to practical limitations, an important one is performance. Calculating feature attributions for large images is time-consuming.&lt;/p&gt;

&lt;p&gt;When used to help explain the predictions of a model to end-users, consider that it may make the user interface look unresponsive. You may have to compute the attributions offline or, at a minimum, indicate to the user that there is a task in progress and how long it will take.&lt;/p&gt;

&lt;h3 id=&quot;user-interactions-are-complex&quot;&gt;User interactions are complex&lt;/h3&gt;

&lt;p&gt;The attributions we get from the feature attributions algorithms are just numbers. To make sense of them, we need to apply visualization techniques.&lt;/p&gt;

&lt;p&gt;For example, simply overlaying the raw attribution values on an image may leave out important pixels that contributed to the prediction, as illustrated in figure 2 of &lt;a href=&quot;http://ceur-ws.org/Vol-2327/IUI19WS-ExSS2019-16.pdf&quot;&gt;this paper&lt;/a&gt;. Compare the number of pixels highlighted in the top-right picture with the one below it, adjusted to show more contributing pixels.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/user-interaction-example.png&quot; alt=&quot;Example of user interaction&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Showing all information at once to the users may also induce them to make more mistakes. For example, when showing the feature attributions overlaid to a medical image, &lt;a href=&quot;https://www.aaojournal.org/article/S0161-6420(18)31575-6/fulltext&quot;&gt;this paper&lt;/a&gt; found out that it increased overdiagnosing of a medical condition. It points to the fact that just because we can explain something, we shouldn’t necessarily put that explanation in front of users without considering how it will change their behavior.&lt;/p&gt;

&lt;h2 id=&quot;well-known-feature-attribution-methods&quot;&gt;Well-known feature attribution methods&lt;/h2&gt;

&lt;p&gt;The following table was compiled with the article &lt;a href=&quot;https://thegradient.pub/a-visual-history-of-interpretation-for-image-recognition/&quot;&gt;A Visual History of Interpretation for Image Recognition&lt;/a&gt; and the paper &lt;a href=&quot;https://www.mdpi.com/1099-4300/23/1/18&quot;&gt;Explainable AI: A Review of Machine Learning Interpretability Methods&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Each row has an explanation method, when it was introduced, a link to the paper that introduced it, and an example of how the method attributes features. The entries are in chronological order.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Method and introductory paper&lt;/th&gt;
      &lt;th&gt;Feature attribution example (from the paper)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;CAM (class activation maps)&lt;br /&gt;2015-12&lt;br /&gt; &lt;a href=&quot;https://arxiv.org/abs/1512.04150&quot;&gt;Learning Deep Features for Discriminative Localization&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-cam.png&quot; alt=&quot;CAM example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;LIME (local interpretable model-agnostic explanations)&lt;br /&gt;2016-08&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1602.04938&quot;&gt;“Why Should I Trust You?”: Explaining the Predictions of Any Classifier&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-lime.png&quot; alt=&quot;LIME example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Grad-CAM&lt;br /&gt;2016-10&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1610.02391&quot;&gt;Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-grad-cam.png&quot; alt=&quot;Grad-CAM example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Integrated gradients&lt;br /&gt;2017-03&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1703.01365&quot;&gt;Axiomatic Attribution for Deep Networks&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-integrated-gradients.png&quot; alt=&quot;integrated gradients example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;DeepLIFT (Deep Learning Important FeaTures)&lt;br /&gt;2017-04&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1704.02685&quot;&gt;Learning Important Features Through Propagating Activation Differences&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-deeplift.png&quot; alt=&quot;DeepLIFT example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;SHAP (SHapley Additive exPlanations)&lt;br /&gt;2017-05&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1705.07874&quot;&gt;A Unified Approach to Interpreting Model Predictions&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-shap.png&quot; alt=&quot;SHAP example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;SmoothGrad&lt;br /&gt;2017-06&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03825&quot;&gt;SmoothGrad: removing noise by adding noise&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-smoothgrad.png&quot; alt=&quot;SHAP example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Anchors&lt;br /&gt;2018&lt;br /&gt;&lt;a href=&quot;https://homes.cs.washington.edu/~marcotcr/aaai18.pdf&quot;&gt;Anchors: High Precision Model-Agnostic Explanations&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-anchors.png&quot; alt=&quot;Anchors example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;CEM (contrastive explanations method)&lt;br /&gt;2018-02&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1802.07623&quot;&gt;Explanations based on the Missing: Towards Contrastive Explanations with Pertinent Negatives&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-cem.png&quot; alt=&quot;CEM example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;This looks like that&lt;br /&gt;2018-06&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1806.10574&quot;&gt;This Looks Like That: Deep Learning for Interpretable Image Recognition&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-this-looks-like-that.png&quot; alt=&quot;This looks like that example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;XRAI&lt;br /&gt;2019-06&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/1906.02825&quot;&gt;XRAI: Better Attributions Through Regions&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-xrai.png&quot; alt=&quot;XRAI example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Contrastive Explanations&lt;br /&gt;2021-09&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/abs/2103.01378&quot;&gt;Contrastive Explanations for Model Interpretability&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-26/method-example-contrastive-explanations.png&quot; alt=&quot;Contrastive explanations example&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;a-feature-attribution-example-with-shap&quot;&gt;A feature attribution example with SHAP&lt;/h2&gt;

&lt;p&gt;SHAP (SHapley Additive exPlanations) was introduced in the paper &lt;a href=&quot;https://arxiv.org/abs/1705.07874&quot;&gt;A Unified Approach to Interpreting Model Predictions&lt;/a&gt;. As the title indicates, SHAP &lt;a href=&quot;https://github.com/slundberg/shap#methods-unified-by-shap&quot;&gt;unifies&lt;/a&gt; LIME, Shapley sampling values, DeepLIFT, QII, layer-wise relevance propagation, Shapley regression values, and tree interpreter.&lt;/p&gt;

&lt;p&gt;Because of SHAP’s claim to unify several methods, in this section we review how it works. It starts with an example of SHAP for image classification, then explains the theory behind it. For a more detailed review of SHAP, including code, please see &lt;a href=&quot;/shap-experiments-image-classification/&quot;&gt;this article&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;example-with-mnist&quot;&gt;Example with MNIST&lt;/h3&gt;

&lt;p&gt;The code for the examples described in this section is available on &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/shap-experiments-image-classification&quot;&gt;this GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The following figure shows the SHAP feature attributions for a convolutional neural network that classifies digits from the MNIST dataset.&lt;/p&gt;

&lt;p&gt;The leftmost digit is the sample from the MNIST dataset. The text at the top shows the actual label from the dataset (8) and the label the network predicted (also 8, thus a correct prediction). The next ten digits are the SHAP feature attributions for each class (the digits zero to nine, from left to right). At the top of each class we see the probability assigned by the network. In this case, the network gave the probability 99.54% to the digit 8, so it’s correct and very confident about the prediction.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/shap-example-mnist.png&quot; alt=&quot;SHAP example with MNIST&quot; /&gt;&lt;/p&gt;

&lt;p&gt;SHAP uses colors to explain attributions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Red pixels&lt;/em&gt; increases the probability of a class being predicted&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Blue pixels&lt;/em&gt; decrease the probability of a class being predicted&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We can see that the contours of the digit 8 are assigned high probability. We can also see that the empty space inside the top loop is relevant to detecting a digit 8. The empty spaces to the left and right of the middle, where the bottom and top half of the digit meet are also important. In other words, it’s not only what is present that is important to decide what digit an image is, but also what is absent.&lt;/p&gt;

&lt;p&gt;Looking at digits 2 and 3, we can see in blue the reasons why the network assigned lower probabilities to them.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-26/shap-colors.png&quot; alt=&quot;SHAP color coding example&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;shapley-values&quot;&gt;Shapley values&lt;/h3&gt;

&lt;p&gt;SHAP uses an approximation of Shapley value for feature attribution. The Shapley value determines the contribution of individuals in interactions that involve multiple participants.&lt;/p&gt;

&lt;p&gt;For example (based on &lt;a href=&quot;https://storage.googleapis.com/cloud-ai-whitepapers/AI%20Explainability%20Whitepaper.pdf&quot;&gt;this article&lt;/a&gt;), a company has three employees, Anne, Bob, and Charlie. The company has ended a month with a profit of 100 (the monetary unit is not essential). The company wants to distribute the profit to the employees according to their contribution.&lt;/p&gt;

&lt;p&gt;We have so far two pieces of information, the profit when the company had no employee (zero) and the profit with all three employees on board.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Employees&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Profit&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;em&gt;None&lt;/em&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;100&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Going through historical records, the company determined the profit when different combinations of employees were working in the past months. They are added to the table below, between the two lines of the previous table.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt; &lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Employees&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Profit&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;em&gt;None&lt;/em&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;10&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bob&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;20&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;30&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;5&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne, Bob&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;60&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;70&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;7&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;90&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;8&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;100&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;At first glance, it looks like Bob contributes 50 to the profit: in line 2 we see that Anne contributes 10 to the profit and in line 5 the profit of Anne and Bob together is 60. The conclusion would be that Bob contributed 50. However, when we look at line 4 (only Charlie) and line 6 (Bob and Charlie), we now conclude that Bob contributes 40 to the profit, contradicting the first conclusion.&lt;/p&gt;

&lt;p&gt;Which one is correct? Both. We are interested in each employee’s contribution when they are working together. &lt;em&gt;This is a collaborative game&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;To understand the individual contributions, we start by analyzing all possible paths from “no employee” to “all three employees”.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Path&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Combination to get to all employees&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne → Anne, Bob → Anne, Bob, Charlie&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne → Anne, Charlie → Anne, Bob, Charlie&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bob → Anne, Bob → Anne, Bob, Charlie&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bob → Bob, Charlie → Anne, Bob, Charlie&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;5&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Charlie → Anne, Charlie → Anne, Bob, Charlie&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Charlie → Bob, Charlie → Anne, Bob, Charlie&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;We then calculate each employee’s contribution in that path (this part is important). For example, in the first path, Anne contributes 10 (line 1 in the previous table), Bob contributes 50 (line 5, minus Anne’s contribution of 10), and Charlie contributes 40 (line 8 in the previous table, minus line 5). The total contribution must add to the total profit (this part is also important): Anne = 10 + Bob = 50 + Charlie = 40 → 100.&lt;/p&gt;

&lt;p&gt;Repeating the process above, we calculate each employee’s contribution for each path. Finally, we average the contributions — &lt;strong&gt;this is the Shapley value for each employee&lt;/strong&gt; (last line in the table).&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Path&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Combination to get to all employees&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Anne&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Bob&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Charlie&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne → Anne, Bob → Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;10&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;50&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;40&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Anne → Anne, Charlie → Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;10&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;10&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;80&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bob → Anne, Bob → Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;40&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;20&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;40&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bob → Bob, Charlie → Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;30&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;20&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;50&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;5&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Charlie → Anne, Charlie → Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;30&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;40&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;30&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;6&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Charlie → Bob, Charlie → Anne, Bob, Charlie&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;60&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;10&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;30&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: right&quot;&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Average (Shapley value)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;30&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;25&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;45&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;In this example we managed to calculate each individual’s contribution for all possible paths in a reasonable time. In machine learning, the “individuals” are the features in the dataset. There may be thousands or even millions of features in a dataset. For example, in image classification, each pixel in the image is a feature.&lt;/p&gt;

&lt;p&gt;SHAP uses a similar method to explain the contribution of features to a model’s prediction. However, calculating the contribution of each feature is not feasible in some cases (e.g. images and their millions of pixels). The combination of paths to try is exponential (factorial, to be precise). SHAP makes simplifications to calculate the features’ contributions. It is crucial to remember that &lt;strong&gt;SHAP is an approximation, not the actual contribution value&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;the-importance-of-the-baseline&quot;&gt;The importance of the baseline&lt;/h3&gt;

&lt;p&gt;In the example above, we asked “what is each employee’s contribution to the profit?”. Our baseline was the company with zero employees and no profit.&lt;/p&gt;

&lt;p&gt;We could have asked a different question: “what is the contribution of Bob and Charlie, given that Anne is already an employee?”. In this case, our baseline is 10, the profit that Anne adds to the company by herself. Only paths 1 and 2 would apply, with the corresponding changes to the average contribution.&lt;/p&gt;

&lt;p&gt;SHAP (and other feature attribution methods) calculate the feature contribution compared to a baseline. For example, in feature attribution for image classification, the baseline is an image or a set of images.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The choice of the baseline affects the calculations&lt;/em&gt;. &lt;a href=&quot;https://distill.pub/2020/attribution-baselines/&quot;&gt;Visualizing the Impact of Feature Attribution Baselines&lt;/a&gt; discussed the problem and its effect on feature attribution.&lt;/p&gt;

&lt;h2 id=&quot;appendix---interpretability-vs-explainability&quot;&gt;Appendix - interpretability vs. explainability&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://www.manning.com/books/interpretable-ai&quot;&gt;Ajay Thampi’s Interpretable AI&lt;/a&gt; book distinguishes between interpretability and explainability this way:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Interpretability&lt;/em&gt;: “It is the degree to which we can consistently estimate what a model will predict given an input, understand how the model came up with the prediction, understand how the prediction changes with changes in the input or algorithmic parameters and finally understand when the model has made a mistake. Interpretability is mostly discernible by experts who are either building, deploying or using the AI system and these techniques are building blocks that will help you get to explainability.”&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Explainability&lt;/em&gt;: “[G]oes beyond interpretability in that it helps us understand in a human-readable form how and why a model came up with a prediction. It explains the internal mechanics of the system in human terms with the intent to reach a much wider audience. Explainability requires interpretability as building blocks and also looks to other fields and areas such as Human-Computer Interaction (HCI), law and ethics.”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Other sources treat interpretability and explainability as equivalent terms (for example, &lt;a href=&quot;https://arxiv.org/abs/1706.07269&quot;&gt;Miller’s work&lt;/a&gt; and &lt;a href=&quot;https://christophm.github.io/interpretable-ml-book/interpretability.html&quot;&gt;Molan’s online book on the topic&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;This article uses “interpretability” as defined in Ajay Thampi’s book. We distinguish between interpretability and explainability to not involve aspects of displaying the interpretation of a model’s prediction to end-users. This would add to the discussion other topics such as user interface and user interaction. While important for the overall discussion of ML interpretability and explainability, these topics are not relevant to the scope of this work. However, we preserve the original term when quoting a source. If the source chose “explainability”, we quote it so.&lt;/p&gt;

&lt;p&gt;Therefore, when we discuss “interpretability” here, we mean the interpretation that is shown to a machine learning practitioner, someone familiar with model training and evaluation. We discuss interpretability in a more technical format with this definition in place, assuming that the consumer of the interpretability results has enough technical background to understand it.&lt;/p&gt;</content><author><name>Christian Garbin</name></author><category term="machine-learning" /><category term="explainability" /><category term="interpretability" /><category term="shap" /><summary type="html">A review of _feature attribution_, a technique to interpret model predictions. First, it reviews commonly-used feature attribution methods, then demonstrates feature attribution with SHAP, one of these methods.</summary></entry><entry><title type="html">An overview of deep learning for image processing</title><link href="https://cgarbin.github.io/deep-learning-for-image-processing-overview/" rel="alternate" type="text/html" title="An overview of deep learning for image processing" /><published>2021-04-26T00:00:00-04:00</published><updated>2022-02-04T00:00:00-05:00</updated><id>https://cgarbin.github.io/deep-learning-for-image-processing-overview</id><content type="html" xml:base="https://cgarbin.github.io/deep-learning-for-image-processing-overview/">&lt;p&gt;Deep learning revolutionized image processing. It made previous techniques, based on manual feature extraction, obsolete. This article reviews the progress of deep learning, with ever-growing networks and the new developments in the field.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;Deep learning is a sub-area of machine learning, which in turn is a sub-area of artificial intelligence (&lt;a href=&quot;https://commons.wikimedia.org/wiki/File:AI-ML-DL.svg&quot;&gt;picture source&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-02-28/AI-ML-DL.png&quot; alt=&quot;Deep learning&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The best way I found to explain deep learning is in contrast to traditional methods. Yann LeCun, one of the founders of deep learning, gave an &lt;a href=&quot;https://www.youtube.com/watch?v=Qk4SqF9FT-M&quot;&gt;informative talk&lt;/a&gt; on the evolution of learning techniques, starting with the traditional ones and ending with deep learning. He focuses on image recognition in that talk.&lt;/p&gt;

&lt;p&gt;It is a worthwhile investment of one hour of our time to listen to someone who was not only present but actively driving the evolution of deep learning. The two pictures immediately below are from his speech.&lt;/p&gt;

&lt;h2 id=&quot;traditional-image-recognition-vs-deep-learning&quot;&gt;Traditional image recognition vs. deep learning&lt;/h2&gt;

&lt;p&gt;In traditional image recognition, we use hand-crafted rules to extract features from an image (&lt;a href=&quot;https://youtu.be/Qk4SqF9FT-M?t=305&quot;&gt;source&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-02-28/image-processing-traditional.png&quot; alt=&quot;Traditional image processing&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In contrast, deep learning image recognition is done with trainable, multi-layer neural networks. Instead of hand-crafting the rules, we feed labeled images to the network. The neural network, through the training process, extracts the features needed to identify the images (&lt;a href=&quot;https://youtu.be/Qk4SqF9FT-M?t=435&quot;&gt;source&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-02-28/image-processing-deep-learning.png&quot; alt=&quot;Deep learning image processing&quot; /&gt;&lt;/p&gt;

&lt;p&gt;“Deep” comes from the fact that neural networks (in this application) use several layers. For example, LeNet-5, named after Yann LeCunn (of the presentation above) and shown in the (historic) picture below (&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf&quot;&gt;source&lt;/a&gt;), has seven layers.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-02-28/lenet-5.png&quot; alt=&quot;Deep learning network example&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;what-deep-learning-networks-learn&quot;&gt;What deep learning networks “learn”&lt;/h2&gt;

&lt;p&gt;Each layer “learns” (“extracts” is a better technical term) different aspects (“features” in the pictures above) of the images. Lower layers extract basic features (such as edges), and higher layers extract more complex concepts (that frankly, &lt;a href=&quot;https://distill.pub/2017/feature-visualization/&quot;&gt;we don’t quite know how to explain yet&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;The picture below (&lt;a href=&quot;https://distill.pub/2017/feature-visualization/&quot;&gt;source&lt;/a&gt;) shows the features that each layer of a deep learning network extracts. On the left, we have the first layers of the network. They extract basic features, such as edges. As we move to the right, we see the upper layers of the network and the features they extract.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-02-28/layer-visualization.png&quot; alt=&quot;Visualization of features in layers of a network&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Unlike traditional image processing, a deep learning network is not manually configured to extract these features. They learn it through the &lt;a href=&quot;https://developers.google.com/machine-learning/crash-course/training-neural-networks/video-lecture&quot;&gt;training process&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;the-evolution-of-deep-learning&quot;&gt;The evolution of deep learning&lt;/h2&gt;

&lt;p&gt;Deep learning for image processing entered the mainstream in the late 1990s when &lt;a href=&quot;https://cs231n.github.io/convolutional-networks/&quot;&gt;convolutional neural networks&lt;/a&gt; were applied to image processing. After stalling a bit in the early 2000s, deep learning took off in the early 2010s. In a short span of a few years, bigger and bigger network architectures were developed. Over time, what “deep” meant was stretched even further.&lt;/p&gt;

&lt;p&gt;The table below shows the evolution of deep learning network architectures.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;When/What&lt;/th&gt;
      &lt;th&gt;Notable features&lt;/th&gt;
      &lt;th&gt;Canonical depiction&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1990s&lt;br /&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-98.pdf&quot;&gt;LeNet&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;Trainable network for image recognition.&lt;br /&gt;- Gradient-based learning&lt;br /&gt;- Convolutional neural network&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-02-28/lenet-5.png&quot; alt=&quot;LeNet&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2012&lt;br /&gt;&lt;a href=&quot;https://proceedings.neurips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdf&quot;&gt;AlexNet&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;One network outperformed, by a large margin, model ensembling (best in class at the time) in &lt;a href=&quot;https://www.image-net.org/&quot;&gt;ImageNet&lt;/a&gt;.&lt;br /&gt;- Deep convolutional neural network&lt;br /&gt;- Overcame overfitting with data augmentation and dropout&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-02-28/alexnet.png&quot; alt=&quot;AlexNet&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2014&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/pdf/1409.4842.pdf&quot;&gt;Inception&lt;/a&gt;&lt;br /&gt;(GoogLeNet)&lt;/td&gt;
      &lt;td&gt;Very deep network (over 20 layers), composed of building blocks, resulting in a “network in a network” (inception).&lt;/td&gt;
      &lt;td&gt;Partial depiction&lt;br /&gt;&lt;img src=&quot;/images/2021-02-28/inception.png&quot; alt=&quot;Inception&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2014&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/pdf/1409.1556.pdf&quot;&gt;VGGNet&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;Stacks of small convolution filters (as opposed to one large filter) to reduce the number of parameters in the network.&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-02-28/vggnet.png&quot; alt=&quot;AlexNet&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2015&lt;br /&gt;&lt;a href=&quot;https://arxiv.org/pdf/1512.03385.pdf&quot;&gt;ResNet&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;Introduced skip connections (residual learning) to train very deep networks (152 layers). At the same time, the network is compact (few parameters for its size).&lt;/td&gt;
      &lt;td&gt;Partial depiction&lt;br /&gt;&lt;img src=&quot;/images/2021-02-28/resnet.png&quot; alt=&quot;Inception&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Network architectures continue to evolve today. So many architectures have been put into practice that we now need a &lt;a href=&quot;https://arxiv.org/abs/1901.06032&quot;&gt;taxonomy to categorize them&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-02-28/taxonomy.png&quot; alt=&quot;CNN taxonomy&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;recent-trends&quot;&gt;Recent trends&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Efficiently scaling CNNs&lt;/em&gt;: There are different ways to scale CNN-based networks. The &lt;a href=&quot;https://arxiv.org/abs/1905.11946&quot;&gt;EfficientNet&lt;/a&gt; family of networks shows that we don’t always need large CNN networks to get good results.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Back to basics&lt;/em&gt;: The &lt;a href=&quot;https://arxiv.org/abs/2105.01601&quot;&gt;MLP-Mixer&lt;/a&gt; network does away with CNN layers altogether. It uses only simpler multi-layer perceptron (MLP) layers, resulting in networks with faster throughput, predicting more images per second than other network architectures.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Transformers&lt;/em&gt;: Transformer-based networks, after their success with natural language processing (NLP), &lt;a href=&quot;/transformers-in-computer-vision/&quot;&gt;are being applied to image processing&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Learning concepts&lt;/em&gt;: by training with images and their textual descriptions (multimodal learning), OpenAI created &lt;a href=&quot;https://openai.com/blog/clip/&quot;&gt;CLIP&lt;/a&gt;, a network that seems to have learned the concepts of images. Traditional image classification relied on extracting features from the images. They work well on images with the same characteristics but fail when they are different. For example, they identify the picture of a banana but not the sketch of a banana. On the other hand, CLIP seems to have learned the concept of the images. It identifies pictures and sketches of bananas (see the illustration in the &lt;a href=&quot;https://openai.com/blog/clip/&quot;&gt;article&lt;/a&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;keeping-up-with-new-developments&quot;&gt;Keeping up with new developments&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://paperswithcode.com/&quot;&gt;Papers with Code&lt;/a&gt; maintains a &lt;a href=&quot;https://paperswithcode.com/sota/image-classification-on-imagenet&quot;&gt;leaderboard of the state of the art&lt;/a&gt;, including links to the papers that describe the network used to achieve each result.&lt;/p&gt;</content><author><name>Christian Garbin</name></author><category term="machine-learning" /><category term="deep-learning" /><category term="computer-vision" /><summary type="html">Deep learning (large, multi-layered neural networks) have been successfully applied to computer vision tasks. This article reviews its origins, the evolution of network architectures, and recent developments.</summary></entry><entry><title type="html">Exploring SHAP explanations for image classification</title><link href="https://cgarbin.github.io/shap-experiments-image-classification/" rel="alternate" type="text/html" title="Exploring SHAP explanations for image classification" /><published>2021-04-25T00:00:00-04:00</published><updated>2021-04-25T00:00:00-04:00</updated><id>https://cgarbin.github.io/shap-experiments-image-classification</id><content type="html" xml:base="https://cgarbin.github.io/shap-experiments-image-classification/">&lt;p&gt;This article explores how to interpret predictions of an image classification neural network using &lt;a href=&quot;https://arxiv.org/abs/1705.07874&quot;&gt;SHAP (SHapley Additive exPlanations)&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The goals of the experiments are to:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Explore how SHAP explains the predictions. This experiment uses a (fairly) accurate network to understand how SHAP attributes the predictions.&lt;/li&gt;
  &lt;li&gt;Explore how SHAP behaves with inaccurate predictions. This experiment uses a network with lower accuracy and prediction probabilities that are less robust (more spread among the classes) to understand how SHAP behaves when the predictions are not reliable (a hat tip to &lt;a href=&quot;https://arxiv.org/abs/1811.10154&quot;&gt;Dr. Rudin’s work&lt;/a&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;!--more--&gt;

&lt;h2 id=&quot;why-use-shap-instead-of-another-method&quot;&gt;Why use SHAP instead of another method?&lt;/h2&gt;

&lt;p&gt;This project is my first opportunity to delve into model interpretability at the code level. I picked &lt;a href=&quot;https://arxiv.org/abs/1705.07874&quot;&gt;SHAP (SHapley Additive exPlanations)&lt;/a&gt; to get started because of &lt;a href=&quot;https://github.com/slundberg/shap#methods-unified-by-shap&quot;&gt;its promise to unify various methods&lt;/a&gt; (emphasis ours):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“…various methods have recently been proposed to help users interpret the predictions of complex models, but it is often unclear how these methods are related and when one method is preferable over another. To address this problem, &lt;b&gt;we present a unified framework for interpreting predictions&lt;/b&gt;, SHAP (SHapley Additive exPlanations). SHAP assigns each feature an importance value for a particular prediction. Its novel components include: (1) the identification of a new class of additive feature importance measures. … The new class unifies six existing methods, …”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;overview-of-shap-feature-attribution-for-image-classification&quot;&gt;Overview of SHAP feature attribution for image classification&lt;/h2&gt;

&lt;h3 id=&quot;how-shap-works&quot;&gt;How SHAP works&lt;/h3&gt;

&lt;p&gt;SHAP is based on &lt;a href=&quot;https://en.wikipedia.org/wiki/Shapley_value&quot;&gt;Shapley value&lt;/a&gt;, a method to calculate the contributions of each player to the outcome of a game. See &lt;a href=&quot;https://cgarbin.github.io/machine-learning-interpretability-feature-attribution/#shapley-values&quot;&gt;this article&lt;/a&gt; for a simple, illustrated example of how to calculate the Shapley value and &lt;a href=&quot;https://towardsdatascience.com/shap-explained-the-way-i-wish-someone-explained-it-to-me-ab81cc69ef30&quot;&gt;this article by Samuelle Mazzanti&lt;/a&gt; for a more detailed explanation.&lt;/p&gt;

&lt;p&gt;The Shapley value is calculated with all possible combinations of players. Given N players, it has to calculate outcomes for 2^N combinations of players. In the case of machine learning, the “players” are the features (e.g. pixels in an image) and the “outcome of a game” is the model’s prediction. Calculating the contribution of each feature is not feasible for large numbers of N. For example, for images, N is the number of pixels.&lt;/p&gt;

&lt;p&gt;Therefore, SHAP does not attempt to calculate the actual Shapley value. Instead, it uses sampling and approximations to calculate the SHAP value. See &lt;a href=&quot;https://arxiv.org/abs/1705.07874&quot;&gt;chapter 4 of the SHAP paper for details&lt;/a&gt;.&lt;/p&gt;

&lt;h3 id=&quot;visualizing-shap-attributions&quot;&gt;Visualizing SHAP attributions&lt;/h3&gt;

&lt;p&gt;SHAP uses colors to explain attributions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Red pixels increase the probability of a class being predicted&lt;/li&gt;
  &lt;li&gt;Blue pixels decrease the probability of a class being predicted&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following picture and text come from the &lt;a href=&quot;https://github.com/slundberg/shap#deep-learning-example-with-deepexplainer-tensorflowkeras-models&quot;&gt;SHAP README&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-25/example-from-shap-readme.png&quot; alt=&quot;SHAP example&quot; /&gt;&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“The plot above explains ten outputs (digits 0-9) for four different images. Red pixels increase the model’s output while blue pixels decrease the output. The input images are shown on the left, and as nearly transparent grayscale backings behind each explanation. The sum of the SHAP values equals the difference between the expected model output (averaged over the background dataset) and the current model output. Note that for the ‘zero’ image the blank middle is important, while for the ‘four’ image the lack of a connection on top makes it a four instead of a nine.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is an essential part of the explanation: &lt;em&gt;“Note that for the ‘zero’ image the blank middle is important, while for the ‘four’ image the lack of a connection on top makes it a four instead of a nine.”&lt;/em&gt; In other words, it’s not only what is present that is important to decide what digit an image is, but also &lt;strong&gt;&lt;em&gt;what is absent&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;experiments&quot;&gt;Experiments&lt;/h2&gt;

&lt;p&gt;This &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/shap-experiments-image-classification/blob/master/shap-experiments-image-classification.ipynb&quot;&gt;Jupyter notebook&lt;/a&gt; shows how to use SHAP’s DeepExplainer to visualize feature attribution in image classification with neural networks. See the &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/shap-experiments-image-classification/blob/master/running-the-code.md&quot;&gt;instructions to run the code&lt;/a&gt; for more details.&lt;/p&gt;

&lt;p&gt;SHAP has multiple explainers. The notebook uses the DeepExplainer explainer because it is the one used in &lt;a href=&quot;https://shap.readthedocs.io/en/latest/image_examples.html&quot;&gt;the image classification SHAP sample code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The code is based on the &lt;a href=&quot;https://shap.readthedocs.io/en/stable/example_notebooks/image_examples/image_classification/PyTorch%20Deep%20Explainer%20MNIST%20example.html&quot;&gt;SHAP MNIST example&lt;/a&gt;, available as a Jupyter notebook &lt;a href=&quot;https://github.com/slundberg/shap/blob/master/notebooks/image_examples/image_classification/PyTorch%20Deep%20Explainer%20MNIST%20example.ipynb&quot;&gt;on GitHub&lt;/a&gt;. This notebook uses the PyTorch sample code because at this time (April 2021), SHAP does not support TensorFlow 2.0. &lt;a href=&quot;https://github.com/slundberg/shap/issues/850&quot;&gt;This GitHub issue&lt;/a&gt; tracks the work to support TensorFlow 2.0 in SHAP.&lt;/p&gt;

&lt;p&gt;The experiments are as follows:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Train a CNN to classify the MNIST dataset.&lt;/li&gt;
  &lt;li&gt;Show the feature attributions for a subset of the training set using SHAP DeepExplainer.&lt;/li&gt;
  &lt;li&gt;Review and annotate some of the attributions to better understand what they reveal about the model and the explanation itself.&lt;/li&gt;
  &lt;li&gt;Repeat the steps above with the CNN that is significantly less accurate.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;an-important-caveat&quot;&gt;An important caveat&lt;/h3&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;strong&gt;“Explanations must be wrong.”&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;Cynthia Rudin&lt;/cite&gt; — &lt;a href=&quot;https://arxiv.org/abs/1811.10154&quot;&gt;Stop Explaining Black Box Machine Learning Models for High Stakes Decisions and Use Interpretable Models Instead&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we are going through the exploration of the feature attributions, we must keep in my mind that we are analyzing two items at the same time:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;What the model predicted.&lt;/li&gt;
  &lt;li&gt;How the feature attribution explainer &lt;em&gt;approximates&lt;/em&gt; what the model considers to make the prediction.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The explainer &lt;em&gt;approximates&lt;/em&gt; the model and sometimes (as in this case) also uses an approximation of the input. Therefore, some of the attributions that may not make much sense may result from these approximations, not necessarily the model’s behavior.&lt;/p&gt;

&lt;p class=&quot;notice--warning&quot;&gt;Therefore, &lt;strong&gt;never mistake the explanation for the actual behavior of the model&lt;/strong&gt;. This is a critical conceptual limitation to keep in mind.&lt;/p&gt;

&lt;p&gt;See more on &lt;a href=&quot;/machine-learning-interpretability-feature-attribution/&quot;&gt;this post about feature attribution&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;some-results-from-the-experiments&quot;&gt;Some results from the experiments&lt;/h2&gt;

&lt;p&gt;This section explores some of the feature attributions resulting from the experiments (see the &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/shap-experiments-image-classification/blob/master/shap-experiments-image-classification.ipynb&quot;&gt;notebook&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Before reading further: this is my first foray into the details of feature attribution with SHAP (or any other method). Some of the items reported below are questions I need to investigate further to understand better how feature attribution in general, and SHAP in particular, work.&lt;/p&gt;

&lt;p&gt;Some candidates for research questions are noted in the explanations.&lt;/p&gt;

&lt;h3 id=&quot;accurate-network&quot;&gt;Accurate network&lt;/h3&gt;

&lt;p&gt;This section explores feature attribution using the (fairly) accurate network. This network achieves 97% overall accuracy.&lt;/p&gt;

&lt;p&gt;Each picture below shows these pieces of information:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The leftmost digit is the example from the MNIST dataset that the network predicted. The text at the top of the picture shows the actual and predicted values. The predicted value is the largest of all probabilities (without applying a threshold).&lt;/li&gt;
  &lt;li&gt;Following that digit, there are ten digits, one for each class (from left to right: zero to nine), with the feature attributions overlaid on each digit. The text at the top shows the probability that the network assigned for that class.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some of the feature attributions are easy to interpret. For example, this is the attribution for a digit “1”.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-25/accurate-digit-1.png&quot; alt=&quot;SHAP attributions for digit 1&quot; /&gt;&lt;/p&gt;

&lt;p&gt;We can see that the presence of the vertical pixels at the center of the image increases the probability of predicting a digit “1”, as we would expect. The absence of pixels around that vertical line also increases the probability.&lt;/p&gt;

&lt;p&gt;The two examples for the digit “8” below are also easy to interpret. We can see that the blank space in the top loop and the blank spaces on both sides of the middle part of the image are important to define an “8”.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-25/accurate-digit-8-1.png&quot; alt=&quot;SHAP attributions for digit 8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-25/accurate-digit-8-2.png&quot; alt=&quot;SHAP attributions for digit 8&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In the two examples for the digit “2” below, on the other hand, the first one is easy to interpret, but the attributions for the second make less sense. While reviewing them, note that the scale for the SHAP values is different for each example. The range of values in the second example is an order of magnitude larger. It does not affect a comparative analysis but it may be important in other cases to note the scale before judging the attributions.&lt;/p&gt;

&lt;p&gt;In the first example we can see which pixels are more relevant (red) to predict the digit “2”. We can also see what pixels were used to reduce the probability of predicting the digit “7” (blue), the second-highest predicted probability.&lt;/p&gt;

&lt;p&gt;In the second picture, the more salient attributions are on the second-highest probability, the digit “7”. It’s almost as if the network “worked harder” to reject that digit than to predict the digit “2”. Although the probability of the digit “7” is higher in this second example (compared to the digit “7” in the first example), it’s still far away from the probability assigned to the digit “2”.&lt;/p&gt;

&lt;p class=&quot;notice--info&quot;&gt;&lt;strong&gt;RESEARCH QUESTION 1&lt;/strong&gt;: What causes SHAP sometimes to highlight the attributions of a class that was not assigned the highest probability?&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-25/accurate-digit-2-1.png&quot; alt=&quot;SHAP attributions for digit 2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-25/accurate-digit-2-2.png&quot; alt=&quot;SHAP attributions for digit 2&quot; /&gt;&lt;/p&gt;

&lt;h3 id=&quot;inaccurate-network&quot;&gt;Inaccurate network&lt;/h3&gt;

&lt;p&gt;This section explores feature attribution using the inaccurate network. This network achieves 87% overall accuracy. Besides the low overall accuracy, each prediction has a larger probability spread. In some cases, the difference between the largest and the second-largest probability is very small, as we will soon see.&lt;/p&gt;

&lt;p&gt;In the example for the digit “0” below, the network incorrectly predicted it as “5”. But it didn’t miss by much. The difference in probability between “5” (incorrect) and “0” (correct) is barely 1%. Also, the two probabilities add up to 54%. In other words, the two top probabilities add up to about half of the total probability. The prediction for this example is not only wrong but uncertain across several classes (labels).&lt;/p&gt;

&lt;p&gt;SHAP still does what we ask: shows the feature attributions for each class. For the three classes with the highest probability, we can see that:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Digit “0”: The empty middle is the important part, as we have seen in other cases for this digit.&lt;/li&gt;
  &lt;li&gt;Digit “8”: The top and bottom parts look like the top and bottom loops of the digit “8”, resulting in the red areas we see in the attribution. The empty middle is now a detractor for this class (blue). An actual digit “8” would have something here, where the bottom and top loops meet.&lt;/li&gt;
  &lt;li&gt;Digit “5”: Left this one for last because it is the one with the highest probability (but not by much) and also the one hardest to explain. It is almost as if just a few pixels (in red) were enough to assign a probability higher than the correct digit “0”.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-25/inaccurate-digit-0.png&quot; alt=&quot;SHAP attributions for digit 0&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This example shows an important concept about explanations for black-box models: they explain what the model is predicting, but they do not attempt to explain if the predictions are correct.&lt;/p&gt;

&lt;p&gt;Hence the call to &lt;a href=&quot;https://arxiv.org/abs/1811.10154&quot;&gt;stop explaining black-box models&lt;/a&gt; (at least for some applications). But this is a story for another day…&lt;/p&gt;

&lt;h3 id=&quot;aggregate-attributions-for-accurate-vs-inaccurate-networks&quot;&gt;Aggregate attributions for accurate vs. inaccurate networks&lt;/h3&gt;

&lt;p&gt;Instead of plotting attributions one by one, as we saw in the previous examples, SHAP can also plot multiple images in the same plot. One advantage of this plot is that all images share the same SHAP scale.&lt;/p&gt;

&lt;p&gt;The plots below show all the attributions for all test digits. The accurate network is on the left and the inaccurate network is on the right.&lt;/p&gt;

&lt;p&gt;In the plot for the accurate network we can see that all samples have at least one class (digit) with favorable attributions (red). The plot is dotted with red areas. In the inaccurate network we don’t see the same pattern. The plot is mainly gray.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Accurate&lt;/th&gt;
      &lt;th&gt;Inaccurate&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-25/accurate-all.png&quot; alt=&quot;Accurate&quot; /&gt;&lt;/td&gt;
      &lt;td&gt;&lt;img src=&quot;/images/2021-04-25/inaccurate-all.png&quot; alt=&quot;Inaccurate&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p class=&quot;notice--info&quot;&gt;&lt;strong&gt;RESEARCH QUESTION 2&lt;/strong&gt;: Given this pattern, is it possible to use the distribution of attributions across samples to determine if a network is accurate (or not)? In other words, if all we have is the feature attributions for a reasonable number of cases but don’t have the actual vs. predicted labels, could we use that to determine whether a network is accurate (or not)?&lt;/p&gt;

&lt;h2 id=&quot;limitations-of-these-experiments&quot;&gt;Limitations of these experiments&lt;/h2&gt;

&lt;p&gt;SHAP attributes features based on a baseline input. This is this line of code in the Jupyter notebook:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;expl&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DeepExplainer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;background_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The baseline images are extracted from the test set here:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;...&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;BACKGROUND_SIZE&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;background_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BACKGROUND_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The choice of baseline images can significantly affect the SHAP results (the results of any method that relies on baseline images, to be precise), as demonstrated in &lt;a href=&quot;https://distill.pub/2020/attribution-baselines/&quot;&gt;Visualizing the Impact of Feature Attribution Baseline&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In the experiments we conducted here we used a relatively small set of images for the baseline and we didn’t attempt to get an equal distribution of the digits in that baseline (other than a simple manual check of distributions - see the notebook).&lt;/p&gt;

&lt;p class=&quot;notice--info&quot;&gt;&lt;strong&gt;RESEARCH QUESTION 3&lt;/strong&gt;: Would a larger number of baseline images, with equal distribution of digits, significantly affect the results? More generically, what is a reasonable number of baseline images to start trusting the results?&lt;/p&gt;

&lt;h2 id=&quot;code&quot;&gt;Code&lt;/h2&gt;

&lt;p&gt;See instructions &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/shap-experiments-image-classification/blob/master/running-the-code.md&quot;&gt;here&lt;/a&gt; to prepare the environment and run the code.&lt;/p&gt;

&lt;h2 id=&quot;more-on-explainability-and-interpretability&quot;&gt;More on explainability and interpretability&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;There are other methods to explain and interpret models with feature attribution. See &lt;a href=&quot;/machine-learning-interpretability-feature-attribution/&quot;&gt;this post&lt;/a&gt; for a brief overview.&lt;/li&gt;
  &lt;li&gt;See &lt;a href=&quot;https://cgarbin.github.io/machine-learning-interpretability-feature-attribution/#shapley-values&quot;&gt;this section&lt;/a&gt; for a detailed explanation of Shapley values.&lt;/li&gt;
&lt;/ul&gt;</content><author><name>Christian Garbin</name></author><category term="machine-learning" /><category term="computer-vision" /><category term="image-classification" /><category term="explainability" /><category term="interpretability" /><category term="shap" /><summary type="html">How to interpret predictions of an image classification neural network using SHAP.</summary></entry><entry><title type="html">Machine learning, but not understanding</title><link href="https://cgarbin.github.io/machine-learning-but-not-understanding/" rel="alternate" type="text/html" title="Machine learning, but not understanding" /><published>2021-04-10T00:00:00-04:00</published><updated>2021-04-10T00:00:00-04:00</updated><id>https://cgarbin.github.io/machine-learning-but-not-understanding</id><content type="html" xml:base="https://cgarbin.github.io/machine-learning-but-not-understanding/">&lt;p&gt;In the expression &lt;em&gt;machine learning&lt;/em&gt;, are the machines actually learning anything?&lt;/p&gt;

&lt;p&gt;In the book “Artificial Intelligence, a guide for thinking humans” Melanie Mitchell explains that&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Learning in neural networks simply consists in gradually modifying the weights on connections so that each output’s error gets as close to 0 as possible on all training examples.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;Melanie Mitchell&lt;/cite&gt; — Artificial Intelligence, a guide for thinking humans&lt;/p&gt;

&lt;p&gt;Let’s explore what “learning” means for machine learning, guided by Mitchell’s book. More specifically, we will concentrate on “deep learning”, a branch of machine learning that has powered most of the recent advances in artificial intelligence.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;All quoted text in this article is from Dr. Mitchell’s book “Artificial Intelligence, a guide for thinking humans”.&lt;/p&gt;

&lt;h1 id=&quot;an-extremely-short-explanation-of-deep-learning&quot;&gt;An extremely short explanation of deep learning&lt;/h1&gt;

&lt;p&gt;Deep learning uses layers of “units”’ (also called &lt;em&gt;neurons&lt;/em&gt;, but some people, including Mitchell and I, prefer the more generic &lt;em&gt;units&lt;/em&gt; term, to not confuse with biological neurons) to extract patterns from labeled data. The internal layers are called “hidden layers”. The last layer is called the “output layer”, or the classification layer.&lt;/p&gt;

&lt;p&gt;In the following figure (from Mitchell’s book), a neural network comprised of several hidden layers (only one shown) was trained to classify handwritten digits. The output layer has ten units, one for each possible digit.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/neural-network.png&quot; alt=&quot;From Mitchell, Artificial Intelligence, chapter 2&quot; /&gt;&lt;/p&gt;

&lt;p&gt;How does a neural network learn? Back to Mitchell’s quote:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Learning in neural networks simply consists in gradually modifying the weights on connections so that each output’s error gets as close to 0 as possible on all training examples.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Going through the sentence pieces:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;training examples&lt;/em&gt;: The labeled examples we present to the network to train it. For example, we present a picture of a square or a triangle and its corresponding label, “square” or “triangle”.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;output’s error&lt;/em&gt;: How far the network’s prediction is from the correct label of the example picture.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;weights on connections&lt;/em&gt;: A large-precision decimal number that adjusts the output of a unit in one layer to the input of a unit in the next layer. The weights are where the “knowledge” of the neural network is encoded.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;gradually modifying&lt;/em&gt;: This is the neural network learning process. An algorithm carefully modifies the weights on the connections to get closer to the expected output. Repeating the adjustment step over time (many, many times) allows the network to learn from the training examples.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;an-important-consequence-of-this-process&quot;&gt;An important consequence of this process&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;“The machine learns what it observes in the data rather than what you (the human) might observe. If there are statistical associations in the training data, even if irrelevant to the task at hand, the machine will happily learn those instead of what you wanted it to learn.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Thus, neural networks are not “learning” in the sense that we would understand the term. They are not learning higher-level concepts from the samples used to train them. They are extracting patterns from the data presented to them during training (and they assume that the labels are correct). That’s all.&lt;/p&gt;

&lt;p&gt;Or, as Mitchell puts more eloquently:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“The phrase “barrier of meaning” perfectly captures an idea that has permeated this book: humans, in some deep and essential way, understand the situations they encounter, whereas no AI system yet possesses such understanding. While state-of-the-art AI systems have nearly equaled (and in some cases surpassed) humans on certain narrowly defined tasks, these systems all lack a grasp of the rich meanings humans bring to bear in perception, language, and reasoning. This lack of understanding is clearly revealed by the un-humanlike errors these systems can make; by their difficulties with abstracting and transferring what they have learned; by their lack of commonsense knowledge; … The barrier of meaning between AI and human-level intelligence still stands today.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Should we be concerned that deep learning is not “learning”? We should, if we don’t understand what it implies for real-life applications.&lt;/p&gt;

&lt;p&gt;In the next sections we will explore how neural networks lack the grasp of “rich meanings we humans bring to bear in perception”, illustrating it with some “un-humanlike errors these systems can make; by their difficulties with abstracting and transferring what they have learned; by their lack of commonsense knowledge”.&lt;/p&gt;

&lt;p&gt;You can run the examples used in the text with the Jupyter notebook on &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/machine-learning-but-not-understanding&quot;&gt;this GitHub repository&lt;/a&gt;. The examples use small pictures to run quickly on any computer.&lt;/p&gt;

&lt;h1 id=&quot;telling-squares-and-triangles-apart&quot;&gt;Telling squares and triangles apart&lt;/h1&gt;

&lt;p&gt;We will see how a neural network trained to tell squares and triangles apart behaves.&lt;/p&gt;

&lt;p&gt;For human beings, the pictures below show squares and triangles. Some are small, some are large, some are in a light background, some are in a darker background. But they are all clearly either a square or a triangle in a frame.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/squares-triangles.png&quot; alt=&quot;Swuares and triangles&quot; /&gt;&lt;/p&gt;

&lt;p&gt;In this section we will go through the typical process of training a neural network to classify squares and triangles:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Get a dataset with labeled pictures of squares and triangles&lt;/li&gt;
  &lt;li&gt;Split the dataset into a training set and a test set&lt;/li&gt;
  &lt;li&gt;Train the network with the training set&lt;/li&gt;
  &lt;li&gt;Validate the neural network accuracy with the test set&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;After we are done with that, we will predict similar images to see how the network handles them.&lt;/p&gt;

&lt;h2 id=&quot;the-squares-vs-triangles-training-examples&quot;&gt;The “squares vs. triangles” training examples&lt;/h2&gt;

&lt;p&gt;This is how some of the training images look like. Each picture is a square or a triangle in different positions. The dataset has hundreds of these pictures.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/output_12_0.png&quot; alt=&quot;Samples squares and triangles&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;the-squares-vs-triangles-neural-network&quot;&gt;The “squares vs. triangles” neural network&lt;/h2&gt;

&lt;p&gt;We train a &lt;a href=&quot;https://cs231n.github.io/convolutional-networks/&quot;&gt;convolutional neural network&lt;/a&gt; (CNN) to classify a picture as a “square” or as a “triangle”, using the training examples. We chose a CNN architecture because it is well suited to image classification.&lt;/p&gt;

&lt;p&gt;If you would like to see the details of the training process, see the Jupyter notebook on &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/machine-learning-but-not-understanding&quot;&gt;this GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;how-does-the-neural-network-perform&quot;&gt;How does the neural network perform?&lt;/h2&gt;

&lt;p&gt;Before we started the training process, we set aside 10% of the pictures to use later (67 pictures). They are pictures that the neural network was not trained on. This is the &lt;em&gt;test set&lt;/em&gt;. We use the test set to measure the performance of the neural network.&lt;/p&gt;

&lt;p&gt;A traditional measure of performance is “accuracy”. It measures the percentage of pictures in the test set that were correctly classified.&lt;/p&gt;

&lt;p&gt;First, we ask the neural network to predict what the pictures are (more details on how that happens &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/decision-threshold-effect-on-accuracy&quot;&gt;here&lt;/a&gt;), then we compare with the actual labels and calculate the accuracy.&lt;/p&gt;

&lt;p&gt;Our neural network classified 65 out 67 pictures correctly, for an accuracy of 97%. This is a pretty good accuracy for a relatively small neural network that can be trained quickly.&lt;/p&gt;

&lt;p&gt;Let’s visualize where the neural network made the mistakes. The picture below shows the mistakes with a red border. All other pictures were classified correctly. Below each picture is the neural network’s classification.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/output_25_0.png&quot; alt=&quot;Mistakes&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Despite the good accuracy, does the neural network understand the concept of what it is learning?&lt;/p&gt;

&lt;h2 id=&quot;when-are-squares-not-squares&quot;&gt;When are squares not squares?&lt;/h2&gt;

&lt;p&gt;When they are larger. At least for this neural network.&lt;/p&gt;

&lt;p&gt;In this section we will use the neural network we just trained to classify a set of squares. But there is a twist to these squares: they are larger than the ones we used in the training set.&lt;/p&gt;

&lt;p&gt;This is how they look like.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/output_28_0.png&quot; alt=&quot;Larger squares&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Using the neural network, we classify the large squares and calculate the accuracy, just like we did with the test set.&lt;/p&gt;

&lt;p&gt;But this time, out of 77 large squares, only 43 are classified as squares. The other 34 are classified as triangles. With an accuracy of 55.8%, the neural network is barely better than flipping a coin.&lt;/p&gt;

&lt;p&gt;Below are all the squares in this set and how the neural network classified them. The ones with the red border were incorrectly classified as triangles (there are many of them).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/output_34_0.png&quot; alt=&quot;Large squares wrongly classified as triangles&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;why-does-this-experiment-matter&quot;&gt;Why does this experiment matter?&lt;/h2&gt;

&lt;p&gt;The simplest and fastest way to improve this neural network is to increase the size of the training and test sets. In this case, we should add larger squares to the training set and retrain the neural network. It will very likely perform better.&lt;/p&gt;

&lt;p&gt;But this does not address the fundamental problem: &lt;strong&gt;&lt;em&gt;the neural network does not understand the concept of “square”.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Quoting Mitchell again (emphasis added):&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“The phrase “barrier of meaning” perfectly captures an idea that has permeated this book: humans, in some deep and essential way, understand the situations they encounter, whereas no AI system yet possesses such understanding. While state-of-the-art AI systems have nearly equaled (and in some cases surpassed) humans on certain narrowly defined tasks, &lt;b&gt;these systems all lack a grasp of the rich meanings humans bring to bear in perception, language, and reasoning. This lack of understanding is clearly revealed by the un-humanlike errors these systems can make; by their difficulties with abstracting and transferring what they have learned; by their lack of commonsense knowledge;&lt;/b&gt; … The barrier of meaning between AI and human-level intelligence still stands today.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Even if we collect lots and lots and lots of examples, we are confronted with &lt;strong&gt;&lt;em&gt;the long-tail problem&lt;/em&gt;&lt;/strong&gt;:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“[T]he vast range of possible unexpected situations an AI system could be faced with.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example, let’s say we trained our autonomous driving system to recognize a school zone by the warning sign painted on the road (&lt;a href=&quot;https://virtualdriveoftexas.com/texas-school-zones/&quot;&gt;source&lt;/a&gt;):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/school-spelled-right.png&quot; alt=&quot;School warning&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Then, one day our autonomous driving system comes across these real-life examples (&lt;a href=&quot;https://www.anyvan.com/blog/whats-going-on/back-to-shcool-for-some/&quot;&gt;source 1&lt;/a&gt;, &lt;a href=&quot;https://www.wibw.com/content/news/School-misspelled-at-Florida-crosswalk-508798331.html?ref=331&quot;&gt;source 2&lt;/a&gt;):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/school-spelled-wrong-1.png&quot; alt=&quot;School warning mispelled&quot; /&gt;
&lt;img src=&quot;/images/2021-04-10/school-spelled-wrong-2.png&quot; alt=&quot;School warning mispelled&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Any (well, most) human beings would still identify them as warning signs for school zones (presumably, the human would chuckle, then - hopefully - slow down).&lt;/p&gt;

&lt;p&gt;Would the autonomous driving system identify them correctly? The honest answer is “we don’t know”. It depends on how it was trained. Was it given these examples in the training set? In enough quantities to identify the pattern? Did the test set have examples? Were they classified correctly?&lt;/p&gt;

&lt;p&gt;But no matter how comprehensive we make the training and test sets and how methodically we inspect the classification results, we are faced with the fundamental problem: &lt;strong&gt;&lt;em&gt;the neural network does not understand the concept of “school zone warning”&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The autonomous driving system lacks common sense.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“…humans also have a fundamental competence lacking in all current AI systems: common sense. We have vast background knowledge of the world, both its physical and its social aspects.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The neural network may be &lt;em&gt;learning&lt;/em&gt;, but it is definitely not &lt;em&gt;understanding&lt;/em&gt;.&lt;/p&gt;

&lt;h1 id=&quot;not-understanding-squares---part-2&quot;&gt;Not understanding “squares” - part 2&lt;/h1&gt;

&lt;p&gt;In the first section we changed the shape of an object. In this section we will not change the object. We will change the environment instead.&lt;/p&gt;

&lt;p&gt;We will train a neural network to classify squares and triangles again. This time they are in different environments, represented by different background colors. The squares are in a lighter background and the triangles are on a dark(er) background (we can think of the backgrounds as “twilight” and “night”).&lt;/p&gt;

&lt;p&gt;The picture below shows how they look like.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/output_38_0.png&quot; alt=&quot;Darker background&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Following the same steps we used in the first section, we train a neural network to classify the squares and triangles.&lt;/p&gt;

&lt;p&gt;Once the network is trained, we use the test set to calculate the neural network accuracy and find out that it is a perfect 100% accuracy score. All squares and triangles in the test set were classified correctly.&lt;/p&gt;

&lt;p&gt;If you would like to see the details of the training process, see the Jupyter notebook on &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/machine-learning-but-not-understanding&quot;&gt;this GitHub repository&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;So far, so good, but…&lt;/p&gt;

&lt;h2 id=&quot;in-the-dark-all-squares-are-triangles&quot;&gt;In the dark, all squares are triangles&lt;/h2&gt;

&lt;p&gt;What happens if the squares are now in the same environment as the triangles (all squares are in the “night” environment)?&lt;/p&gt;

&lt;p&gt;This is how the squares look like in the darker environment.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/output_47_0.png&quot; alt=&quot;Squares in darker background&quot; /&gt;&lt;/p&gt;

&lt;p&gt;When we ask the neural network to classify these squares, we find out that the performance is now abysmal. The accuracy is 0%. All squares are misclassified as triangles.&lt;/p&gt;

&lt;p&gt;To confirm, we can visualize the predictions. The wrong predictions have a red frame around them (all of them are wrong in this case).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/output_52_0.png&quot; alt=&quot;Squares in darker background wrongly predicted as triangles&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;why-does-this-experiment-matter-1&quot;&gt;Why does this experiment matter?&lt;/h2&gt;

&lt;p&gt;The neural network we just trained fails in the same way the first neural network failed: it doesn’t understand the concepts of “square” and “triangle”. It is just looking for any sort of pattern in the training data. It doesn’t know if a pattern makes sense or not, it just knows there is a pattern there.&lt;/p&gt;

&lt;p&gt;In this case, the neural network is very likely learning not from the shape, but from the background (a case of &lt;a href=&quot;https://arxiv.org/abs/1907.02893&quot;&gt;spurious correlation&lt;/a&gt;). It is assuming that a darker background means “triangle” because it doesn’t really understand the concept of what makes a triangle a triangle.&lt;/p&gt;

&lt;p&gt;Sometimes this leads to some funny examples, like the neural network that “learned” to classify land vs. water birds based on the background. The duck on the right was misclassified as a land bird, simply because it was not in its usual water environment (&lt;a href=&quot;https://arxiv.org/abs/2005.04345&quot;&gt;source&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/land-and-waterbirds.png&quot; alt=&quot;Water birds vs. land birds&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Other times the mistakes are more consequential, for example, when neural networks misclassify X-rays based on markings left by radiologists in the images. Instead of learning actual attributes of a disease, the neural network “learned” from the marks left behind in the images. Images without such marks may be classified as “healthy”. The consequences can be catastrophic (&lt;a href=&quot;https://storage.googleapis.com/cloud-ai-whitepapers/AI%20Explainability%20Whitepaper.pdf&quot;&gt;source&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/images/2021-04-10/x-ray-pen-marks.png&quot; alt=&quot;X-ray with pen marks&quot; /&gt;&lt;/p&gt;

&lt;h1 id=&quot;should-we-be-concerned-that-deep-learning-is-not-understanding&quot;&gt;Should we be concerned that deep “learning” is not “understanding”?&lt;/h1&gt;

&lt;p&gt;Mitchell asks the following question in her book:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“but the question remains: Will the fact that these systems lack humanlike understanding inevitably render them fragile, unreliable, and vulnerable to attacks? And how should this factor into our decisions about applying AI systems in the real world?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Until we achieve humanlike understanding, we should be concerned that neural networks do not generalize well.&lt;/p&gt;

&lt;p&gt;Does it mean we need to stop using neural networks until then? No.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“I think the most worrisome aspect of AI systems in the short term is that we will give them too much autonomy without being fully aware of their limitations and vulnerabilities.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Deep learning has successfully improved our lives. It’s “just” a matter of understanding its limitations, applying it judiciously, for the tasks that it’s well suited.&lt;/p&gt;

&lt;p&gt;To do that we need to educate the general public and, more importantly, the technical community. Too often we hype the next “AI has achieved humanlike performance in [&lt;em&gt;some task here&lt;/em&gt;]”, when in fact we should say “under these specific circumstances, for this specific application, AI has performed well”.&lt;/p&gt;

&lt;h1 id=&quot;source-code-for-the-experiments&quot;&gt;Source code for the experiments&lt;/h1&gt;

&lt;p&gt;The source code for the experiments described here is on &lt;a href=&quot;https://github.com/fau-masters-collected-works-cgarbin/machine-learning-but-not-understanding&quot;&gt;this GitHub repository&lt;/a&gt;. It uses small pictures to run quickly on a regular computer.&lt;/p&gt;

&lt;p&gt;Feel free to modify the pictures, the neural network model, and other parameters that affect the results.&lt;/p&gt;

&lt;p&gt;But remember that when the results improve, it’s not the neural network that is learning more all of a sudden. &lt;em&gt;You&lt;/em&gt; are improving it.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;“Because of the open-ended nature of designing these networks, in general it is not possible to automatically set all the parameters and designs, even with automated search. Often it takes a kind of cabalistic knowledge that students of machine learning gain both from their apprenticeships with experts and from hard-won experience.”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p class=&quot;small&quot;&gt;&lt;cite&gt;Melanie Mitchell&lt;/cite&gt; — Artificial Intelligence, a guide for thinking humans&lt;/p&gt;</content><author><name>Christian Garbin</name></author><category term="machine-learning" /><category term="failure" /><summary type="html">In the expression 'machine learning', are the machines actually learning anything? Let's explore what 'learning' means for machine learning, guided by Melanie Mitchell's book 'Artificial Intelligence, a guide for thinking humans. We will see that machines don't learn in the same way we understand 'learn'.</summary></entry></feed>