<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by FunCry on Medium]]></title>
        <description><![CDATA[Stories by FunCry on Medium]]></description>
        <link>https://medium.com/@funcry?source=rss-4a992408a97e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by FunCry on Medium</title>
            <link>https://medium.com/@funcry?source=rss-4a992408a97e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:40:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@funcry/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[In Depth Understanding of Attention Mechanism (Part II) - Scaled Dot-Product Attention and Example]]></title>
            <link>https://medium.com/@funcry/in-depth-understanding-of-attention-mechanism-part-ii-scaled-dot-product-attention-and-its-7743804e610e?source=rss-4a992408a97e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7743804e610e</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[FunCry]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 06:30:59 GMT</pubDate>
            <atom:updated>2023-09-01T07:43:52.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the <a href="https://medium.com/@funcry/understanding-attention-mechanism-in-depth-550f59ae1c19">previous article</a>, we discussed the challenges faced by machine translation and introduced the Attention mechanism proposed in <a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a>.</p><p>In this article, we will focus on introducing the Scaled Dot-Product Attention behind the Transformer and explain its computational logic and design principles in detail.</p><p>At the end of the article, we will also provide an example of using Attention, hoping to give readers a more comprehensive understanding of Attention after reading.</p><h3>Scaled Dot-Product Attention</h3><p>Now we have learned the prototype of the attention mechanism, however, it fails to address the issue of slow input processing. To enhance computation speed and harness the power of parallel computing, it is necessary to abandon the conventional one-character-at-a-time approach.</p><p>The paper <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a> introduced Scaled Dot-Product Attention to overcome this challenge. The formula is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4L90D4iDB_R1Uljs" /></figure><p>The formula may look complex, but it can be broken down into simpler steps. Let’s explore each step to understand the principle behind it.</p><h4>1. QKᵀ</h4><p>In this step, we are working with two matrices: Q (Query) and K (Key). Suppose Q has three pieces of data and K has four pieces of data. The dimensions of the two matrices are <strong>3 * dₖ</strong> and <strong>4 * dₖ</strong> , respectively.</p><p>It&#39;s important to note that the two matrices need to have the same number of columns. The interpretation is:</p><ul><li>Q has three pieces of data, and each piece of data is represented by a vector of length dₖ.</li><li>K has four pieces of data, and each piece of data is represented by a vector of length dₖ.</li></ul><p>If the dimension of the input sequences used to represent Q and K are not the same, or if you want to specify a special dₖ, you can use Linear(input_q_dim, dₖ) and Linear(input_k_dim, dₖ) to linearly transform the original Query and Key to dₖ dimensions.</p><p>The purpose of these two layers is to transform the two sequences to <strong>the same vector space</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*R_W8WqUA2mp41HQf" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*0xH6VebTvzzx6qG1" /></figure><p>Now that we have Q and K matrices (assuming dₖ = 4), let’s take a closer look at what QKᵀ is doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*wMAccADhdvhe9yf8" /></figure><p>The animation illustrates that the product of the query and key matrices, QKᵀ, yields a 3x4 matrix.</p><p>This stage corresponds to the <strong>dot-product</strong> operation, since the (i, j) entry of the resulting matrix is <strong>the dot product of row i in Q and row j in K</strong>, which also represents Kⱼ’s importance to Qᵢ.</p><p>In summary, the Scaled Dot-Product Attention mechanism performs the following steps up until now:</p><ol><li>It maps the input queries and keys to the same vector space where their inner product results in higher values for more relevant pairs (this transformation is learned by the model).</li><li>It computes the attention table A by taking the inner product of the query and key matrices.</li></ol><h4>2. softmax(A /√dₖ)</h4><p>The stage corresponds to the <strong>Scaled</strong> section in its name. To comprehend this step, it is important to first understand the softmax function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*ToO8TK7RDiuC-RUX" /></figure><p>For each row in A, the softmax function maps each element to a value between 0 and 1 such that the sum of the values in each row equals 1.</p><p>If we fix a particular coordinate zᵢ and vary only that value while holding the other elements in the vector constant, the resulting function looks similar to a sigmoid curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gwjj8Dd3fRVWA951" /></figure><p>Noticeably, the gradient of the softmax function is almost zero at extreme values, making it difficult to update the corresponding parameters during training.</p><p>If dₖ, the dimension of the key and value vectors, is set to be large, the dot product scores in the attention matrix A are more likely to fall into these regions, since there are dₖ terms to be multiplied and summed.</p><p>To mitigate this issue, the scaling factor of √dₖ is introduced to reduce the magnitude of the scores and decrease the chances of encountering vanishing gradients.</p><p>This technique helps improve the stability and convergence of the model during training.</p><p>We refer to the matrix that passes through softmax as A’.</p><p><strong>Advanced (optional):</strong></p><p>Assuming that each element in the query and key vectors is independently sampled from the standard normal distribution N(0, 1), according to the dot product formula below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*JGl54Cim0HF1iWe5" /></figure><p>the dot product of q and k follows a normal distribution with mean 0 and variance dₖ.</p><p>Dividing the dot product by √dₖ scales it to have variance 1.</p><h4>3. A’V</h4><p>Before delving into this section, let’s recall the properties of A’:</p><ol><li>A’ has the same number of rows as the number of input queries.</li><li>A’ has the same number of columns as the number of input keys.</li><li>Each element in each row of A’ lies in the range of 0 to 1, where the (i, j) entry represents the significance of the j-th key for the i-th query.</li><li>The sum of all the elements in a single row of A’ is equal to 1.</li></ol><p>Assuming A’ looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*t2OFPAg3m5-eGHAN" /></figure><p>Next, let’s discuss V, which represents the actual values behind the keys.</p><p>You can think of the keys as student IDs and the values as information such as names, classes, and grades. You use the student ID to find the person, but the relevant information is the value behind it. For the model, it is the same: the values are what it actually uses to calculate.</p><p>The dimension of V is represented by dᵥ, which can be set to any suitable value. You can also use Linear(input_k_dim, dᵥ) to convert the input vector into this dimension.</p><p>Note that I set the first parameter of the above command to input_k_dim, which is because the source of the keys and values should be the same vector, but one is converted to the space of Q for comparison, and the other is converted to actual values.</p><p>In other words, the keys and values have a one-to-one correspondence, with the first value corresponding to the first key, the second value corresponding to the second key, and so on.</p><p>The appearance of V is like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TAnWfdXSrssWyyCN" /></figure><p>Let’s take a look at what A’V does:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FA6AH2a8--8jyhm0" /></figure><p>From the above equation, we can observe that A’V will:</p><ol><li>Produce a matrix, where the number of rows is equal to the number of queries.</li><li>For each query, its final value is the weighted average of the rows in V.</li><li>The weights are based on the inner product of the query and its corresponding key.</li></ol><h4>Conclusion of Scaled Dot-Product Attention</h4><p>In fact, two things are being done:</p><ol><li>Creating a lookup table (inner product of Q and K, scaled, softmax).</li><li>Calculating the final output by taking the weighted average of the rows in V based on the attention table.</li></ol><p>You can also think of the keys and values as a kind of database, and attention is actually <strong>finding a suitable vector to represent each query based on the content in the database.</strong></p><p>In the previous explanation, Query and Key-Value are two different sequences, but in fact, <strong>their input can be the same sequence, in which case it is called Self-Attention.</strong></p><p>Self-Attention is particularly useful in natural language processing, where the output can be seen as <strong>word-embedding of each query taking the context into account</strong>.</p><h3>Example</h3><p>Finally, a practical example of using attention is provided to deepen your understanding.</p><p>Suppose we want to convert the Department of Computer Science and the Department of Philosophy (two queries) into vectors that the model can understand, and there are four subjects (four key-value pairs) in the database: English, Social Studies, Mathematics, and Physics. The attention table calculated by the model may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*80rlThpotDOWxEid" /></figure><p>The interpretation is as follows: for the Department of XX, the importance of these four subjects is …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BCoZatMErF7oR91E" /></figure><p>Next, we need the values of V. Here, I set dᵥ = 3, where the three values in V represent memory, language ability, and logical reasoning ability.</p><p>(Note: In reality, we cannot know what the columns of Value represent, and the model will find out what they should represent on its own.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*Aq3b8fJvgXM8i-f7" /></figure><p>The interpretation is as follows: for the subject of XX, the memory, language, and logical reasoning scores needed to do well are respectively …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*GkM0p0BYxBI3_f0pkcgJVw.png" /></figure><p>(The scores are purely fictional.)</p><p>Multiplying the two matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*boGrKAf0r8l4Z6zN" /></figure><p>The final result is as follows: the memory, language, and logical reasoning scores needed to do well in XX Department are respectively …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4rBxM2sFW_mezpj0" /></figure><p>The model will also use two vectors, 6.9 7.5 10.1 and 8.3 8.7 7.3, to represent the two departments, respectively.</p><p>I hope this example has provided you with a clear understanding of how attention operates and how to establish the attention dimension.</p><h3>Conclusion</h3><p>This article has provided a detailed introduction to the computation details and design logic of Scaled Dot-Product Attention, as well as an example of using Attention.</p><p>If we compare the model introduced in the previous article carefully, we will find that although the two architectures look very different, the overall logic is quite similar.</p><p>Besides attention, the Transformer architecture encompasses several other critical elements, such as the encoder and decoder structures, MultiHead, and Positional Encoding. Although this article cannot cover these aspects in depth, we hope to explore them in more detail in future write-ups.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7743804e610e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[深入理解 Attention 機制（下）- Scaled Dot-Product Attention 與其例子]]></title>
            <link>https://medium.com/@funcry/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3-attention-%E6%A9%9F%E5%88%B6-%E4%B8%8B-scaled-dot-product-attention-%E8%88%87%E5%85%B6%E4%BE%8B%E5%AD%90-bdcd0dbc4d3e?source=rss-4a992408a97e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdcd0dbc4d3e</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[FunCry]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 06:30:49 GMT</pubDate>
            <atom:updated>2023-03-01T06:33:20.998Z</atom:updated>
            <content:encoded><![CDATA[<h3>介紹</h3><p>在<a href="https://medium.com/@funcry/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3-attention-%E6%A9%9F%E5%88%B6-b40be0985e84">上一篇文章</a>中，我們介紹了機器翻譯遇到的難題，並且介紹了 <a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a> 中提出的 Attention 雛形。</p><p>這篇文章將著重介紹 Transformer 背後的 Scaled Dot-Product Attention，並詳細解釋計算邏輯還有其設計理念，文章的最後也會提供一個使用 Attention 的例子，希望能讓讀者看完後對 Attention 有更全面的理解。</p><h3>Scaled Dot-Product Attention</h3><p>之前提到的方法雖然解決了 Context Vector 不管用的問題，但如果遇到很長的句子或文章，模型還是無法快速處理輸入 。為了加快運算，運用平行計算的優勢，理想的做法應該是摒棄一個字一個字讀的方法。在 <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a> 這篇論文中，便提出了 Scaled Dot-Product Attention 來實現這樣的想法。它的計算方式如下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4L90D4iDB_R1Uljs" /></figure><p>公式看起來很複雜，為了說清楚背後的原理，我們一步一步來看究竟發生了什麼。</p><h4>1. QKᵀ</h4><p>在這一步中，Q (Query) 和 K (Key) 是兩個矩陣，我們假設 Q 裡面有三筆資料，K 裡面有四筆資料，那這兩個矩陣的維度分別是 3 * dₖ 和 4 * dₖ ，注意兩個矩陣要有一樣數量的 Column，解讀方式是：</p><ul><li>Q 矩陣裡面有三筆資料，每筆資料用一個長度為 dₖ 的向量表示</li><li>K 矩陣裡面有四筆資料，每筆資料用一個長度為 dₖ 的向量表示</li></ul><p>如果你原本用來表示 Q 和 K 的序列維度不一樣，又或者你想要制定某個特別的 dₖ，那可以分別用 Linear(input_q_dim, dₖ) 和 Linear(input_k_dim, dₖ) 來把原本的 Query 和 Key 做線性轉換成 dₖ 維。這兩個 layer 的作用是把兩個序列轉到<strong>同樣的向量空間</strong>。</p><p>現在你已經得到 Q 和 K 兩個矩陣了，他們長下面這樣（下面假設 dₖ = 4）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*R_W8WqUA2mp41HQf" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*0xH6VebTvzzx6qG1" /></figure><p>我們來看看 QKᵀ 在做的到底是什麼：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/0*wMAccADhdvhe9yf8" /></figure><p>從上面的動圖可以發現，QKᵀ 會產生一個 3 * 4 （Query 的數量 * Key 的數量）的矩陣，這個矩陣的第 i, j 個元素是由 <strong>第 i 個 q 和第 j 個 k 內積</strong> 算出來的！</p><p>這個步驟其實對應了標題 <strong>Dot-Product</strong> 的部分，計算出來的矩陣 A 像是一個查詢表，第 i, j 個元素代表的是 <strong>第 j 個 key 對第 i 個 query 的重要性</strong>。</p><p>對這一段做個結論。從輸入到做 QKᵀ 運算的這部分，模型在做的事情其實是</p><ol><li>將輸入的 Query 以及 Key 轉換到同一個向量空間，在這個向量空間裡面，越相關的 Query 和 Key 內積的值會越大（模型會自己學會要怎麼做這個轉換）</li><li>用內積算出 Attention 表，我們把這個表取名為 A。</li></ol><h4>2. softmax(A /√dₖ)</h4><p>這部分其實對應了 <strong>Scaled</strong> 的部分，要看懂的話我們必須先了解 softmax 函式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*ToO8TK7RDiuC-RUX" /></figure><p>對於 A 裡面每個 row，softmax 會把裡面每個元素轉換成 0 到 1 的之間的數值，而每個 row 的數值加起來會等於 1。我們仔細觀察 row 裡面某個元素，在其他數值不變的情況下，單一數值的座標會長下面這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gwjj8Dd3fRVWA951" /></figure><p>可以發現在特別大或特別小的地方梯度（斜率）幾乎為 0，導致參數沒辦法更新，而如果你設定的 dₖ 特別大，上面利用內積計算出來的 A 就有比較高的可能性出現落在這些地方的數值（因為總共有 dₖ 個東西要相乘後加總）</p><p>除以 <strong>√</strong>dₖ 就是為了讓數值落在這些地方的可能變小，降低訓練時受到的阻礙。</p><p>我們把通過 softmax 的矩陣稱作 A’</p><p>進階（<strong>可略過</strong>）：</p><p>假設你的 q 和 k 向量裡面每個數值都是獨立從 N(0, 1) 這個常態分布抽取出來的，根據內積的算式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/0*JGl54Cim0HF1iWe5" /></figure><p>q <strong>⋅</strong> k 的期望值會是 0，但變異數會是 dₖ，除以 <strong>√</strong>dₖ 可以把變異數拉回 1。</p><h4>3. A’V</h4><p>在開始這段之前，先複習一下 A’ 是什麼，A’</p><ol><li>有跟 Query 數量一樣多的 row</li><li>有跟 Key 數量一樣多的 column</li><li>每個 row 裡面的數值都介於 0 和 1 之間，第 j 個元素代表第 j 個 Key 對這個 Query 的重要性</li><li>單一 row 裡面所有數值加起來等於 1</li></ol><p>假設 A’ 長下面這樣</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*yixwpYGorIzhL8dt" /></figure><p>接下來要討論 V，代表的意義是 Key 背後真正的數值，可以把 Key 想像成學號，Value 想像成姓名、班級、成績等資訊，你用學號來找到這個人，但是他的相關資訊才是你真正需要的東西，對模型來說也是一樣，他真正用來計算的東西是 V 的數值。</p><p>V 的維度用 dᵥ 表示，你可以把它設成任何你認為合適的數值。一樣可以用 Linear(input_k_dim, dᵥ) 來將輸入向量轉換到這個維度。</p><p>注意上面這行指令中我把第一個參數設成 input_k_dim，這是因為 K 和 V 的源頭應該要是同一個向量，只是一個被轉去 Q 的空間和它比對，另一個被轉譯成真實的數值。換句話說，Key 和 Value 是有一對一的對應關係的，第一個 Value 對應到第一個 Key，第二個 Value 對應到第二個 Key ……</p><p>V 的樣子長下面這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TAnWfdXSrssWyyCN" /></figure><p>最後我們來看看 A’V 代表什麼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FA6AH2a8--8jyhm0" /></figure><p>從上面的算式可以發現，A’V 會：</p><ol><li>產生一個矩陣，這個矩陣 <strong>row 的數量就跟 Query 的數量一樣多</strong></li><li>對於每個 Query 來說，它的最終數值是<strong>將 V 裡面的 row 向量做加權平均</strong></li><li>加權平均的權重依據是 <strong>Query 和其對應的 Key 做內積</strong></li></ol><h4>Scale Dot-Product Attention 小結</h4><p>其實就是在做兩件事</p><ol><li>建立查詢表（Query 和 Key 內積算權重，再把權重轉換成 0 和 1 之前的數值）</li><li>根據查詢表，用 Value 矩陣的加權平均算出 Query 的最後數值</li></ol><p>你也可以把 Key-Value 想像成某種資料庫，而 Attention 在做的事情其實就是 <strong>根據資料庫裡的內容，找出一組合適的向量來代表每個 Query</strong>。</p><p>Query 和 Key-Value 在上面的介紹是兩種不同的序列，但其實<strong>兩者的輸入可以是同一個序列，在這樣的情況下就被稱為 Self-Attention</strong>。</p><p>Self-Attention 在自然語言處理特別常用到，根據上面的邏輯，可以把輸出看做<strong>考量前後文後每個字對應的 word-embedding</strong>。</p><h3>舉例</h3><p>文章的最後提供讀者一個使用 Attention 的例子，加深大家的理解。</p><p>假設今天我想要將資訊工程系和哲學系（兩個 Query）轉換成模型可以理解的向量，而資料庫裡面有英文、社會、數學、物理四個科目（四個 Key-Value pair），模型算出來的 Attention table 可能會長下面這樣：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*80rlThpotDOWxEid" /></figure><p>解讀方式如下，對於 XX 系，這四個科目的重要性分別為 ……</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4M9dzQuyzZOoSB7d" /></figure><p>接下來我們需要 Value 的數值，這裡我設定 dᵥ = 3，Value 的三個數值分別代表記憶力、語言能力、邏輯推理能力。</p><p>（注意：真實情況下我們沒辦法知道 Value 的三個 column 分別代表什麼，模型會自己找出它們該表示什麼。）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*Aq3b8fJvgXM8i-f7" /></figure><p>解讀方式如下，對於 XX 科目，記憶力、語言、邏輯推理分別需要 OO 分才能念好。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S5YwIajxnpltInOO" /></figure><p>（分數純屬虛構）</p><p>將上面的兩個矩陣相乘</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*boGrKAf0r8l4Z6zN" /></figure><p>最後算出的如下，解讀方式是 XX 系的 OO 能力分別需要達到多少分才能念好。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uM7AzIxeRUP0pkru" /></figure><p>而模型也會分別用 6.9 7.5 10.1 和 8.3 8.7 7.3 兩個向量來代表這兩個科系。</p><p>希望這個例子能讓你更了解 Attention 在做什麼，以及該如何設定 Attention 的維度。</p><h3>結論</h3><p>這篇文章詳細介紹了 Scaled Dot-Product Attention 的計算細節，設計邏輯並且提供了一個使用 Attetion 的例子，若仔細比對前一篇的模型，就會發現兩個架構雖然看起來很不一樣，大致上的邏輯卻是差不多的</p><p>實際上的 Transformer 除了 Attention 外還有許多細節，除了 Encoder 和 Decoder 的架構外，還有 MultiHead、Positional Encoding 等，日後若有機會再好好介紹這個主題。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdcd0dbc4d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In Depth Understanding of Attention Mechanism (Part I) - Origin]]></title>
            <link>https://medium.com/@funcry/understanding-attention-mechanism-in-depth-550f59ae1c19?source=rss-4a992408a97e------2</link>
            <guid isPermaLink="false">https://medium.com/p/550f59ae1c19</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[FunCry]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 07:02:55 GMT</pubDate>
            <atom:updated>2023-03-04T15:08:50.459Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In recent years, there have been significant advancements in natural language processing, from Google’s BERT in 2018 to later models like GPT and ChatGPT. The reason behind these models’ success is not only the massive amount of data and computing resources but also the transformer model behind them. This article will explore the attention mechanism that underlies the transformer, which has played a crucial role in the success of recent natural language processing models.</p><h3>Machine Translation</h3><p>Before we begin, let’s introduce a field of natural language processing: machine translation. Translation is a typical sequence-to-sequence problem, meaning:</p><ol><li>The input is a variable-length sequence (e.g., a Chinese sentence: “今天天氣很晴朗”, which literally translates to “It’s sunny today”).</li><li>The output is a variable-length sequence (e.g., an English sentence: “It’s sunny today”).</li></ol><p>If the Transformer had not yet been invented, how would a computer handle this type of problem?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*GGBKk8xE6ESaw8ih" /></figure><p>The intuitive approach would probably be like the figure above, divided into two steps:</p><ol><li><strong>Read the input sequence (Chinese sentence) one character at a time.</strong><br>In the above figure, each x corresponds to a character, and the computer would first read the first character, store it, then go on to the next character (read “今” first, then read “天”……), and then store all the information in the context vector in the middle.</li><li><strong>Calculate the output sequence (English sentence).</strong><br>When outputting, the model will output one word at a time based on the information stored in the context vector (e.g., “it”, “‘s”, “sunny”,…).</li></ol><p>While it is possible to use this type of model for machine translation, the above examples are short. If I want the machine to handle longer inputs (such as this article), the following problems arise:</p><ol><li>The context vector has low dimensionality, it might not be able to remember earlier words.</li><li>Reading input word by word is time-consuming.</li></ol><p>To address these issues, the following models are proposed.</p><h3><a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a></h3><p>(For the input sentence, I use “character” since it is talking about the Chinese language. If what you are dealing with is English, the unit is probablity “word”.)</p><p>This paper focuses on addressing the first problem mentioned above. The approach is simple: since the context vector cannot store all the information from the input sentence, <strong>we should consider</strong> <strong>the entire sentence directly when outputting</strong>. The actual process involves assigning weights to each input character during each output, and then taking the weighted average of the input characters.</p><p>In the proposed model, each input character is first converted into a hidden state (represented by ‘h’ below, which can be imagined as a word-embedding), and the model calculates the attention score based on the word being translated and the hidden state of each characters.</p><p>The function for calculating the score is learned by the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*yeaVRZ3C9Cx5gCfu" /></figure><p>Let’s take an example where the language model has already output the phrase “It’s sunny” and is now deciding on the next word to output.</p><p>To make this decision, the model needs to determine which Chinese characters are most important for the next output word. It uses a function α to calculate the importance score of each character, such as α(“sunny”, 今) = 0.8 and α(“sunny”, 天) = 0.6, among others.</p><p>Since the next word is supposed to be “today,” characters related to “今天 (today)” should have a higher score. As a result, each Chinese character may have the following scores:</p><ul><li>“今”: 0.8</li><li>“天”: 0.6</li><li>“氣”: 0.05</li><li>“很”: 0.01</li><li>……</li></ul><p>To calculate the final hidden state, the model multiplies the hidden state of each character by its corresponding importance score and then sums them up. (h(今) * 0.8 + h(天) * 0.6 + …… )</p><p>This model is essentially a prototype of the Attention mechanism, which involves two steps:</p><ol><li>Assigning a weight to each input character.</li><li>Computing a weighted sum of the input sentence.</li></ol><p>Today, when discussing the Attention mechanism, three components are often mentioned: Query, Key, and Value. Although this paper does not explicitly use these terms, we can infer from the model architecture above that:</p><ul><li>Query: the character being translated (“sunny”).</li><li>Key, Value: the hidden state of each character.</li><li>Attention score: aₜ,ᵢ which is calculated by Query and Key using the Attention function.</li></ul><p>To grasp the concept of the Attention mechanism, a possible understanding is that the model itself considers which Key (the Chinese character) holds the most significance for the current Query (the English word being translated).</p><p>In this model, Value and Key are actually the same thing.</p><h3>Conclusion</h3><p>This article provided a detailed introduction to the origin of the Attention mechanism. Although the model introduced may not be commonly used in natural language processing now, through the previous introduction, we can understand why it is necessary to develop this mechanism, and what the core concept of Attention is.</p><p><a href="https://medium.com/@funcry/in-depth-understanding-of-attention-mechanism-part-ii-scaled-dot-product-attention-and-its-7743804e610e">The next article</a> will introduce the logic and example of the Scaled Dot-Product Attention that everyone is using now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=550f59ae1c19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[深入理解 Attention 機制（上）- 起源]]></title>
            <link>https://medium.com/@funcry/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3-attention-%E6%A9%9F%E5%88%B6-b40be0985e84?source=rss-4a992408a97e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b40be0985e84</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[FunCry]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 06:59:41 GMT</pubDate>
            <atom:updated>2023-03-01T06:32:21.466Z</atom:updated>
            <content:encoded><![CDATA[<h3>介紹</h3><p>近幾年自然語言處理有很大的進展，從 2018 年 Google 推出的 BERT，到後來的 GPT、ChatGPT 等，這些模型之所以能取得這樣的成果，除了龐大的資料量及運算資源外，最重要的就是背後的 Transformer 模型，以及其使用的 Attention 機制。</p><p>今天這篇文章將分為兩個部分，上篇介紹序列到序列模型遇到的困難，以及為何要引入 Attentino 機制；下篇則著重在 Transformer 背後的 Scaled Dot-Product Attention 以及實際的使用例子。</p><h3>機器翻譯</h3><p>在開始前，我們先介紹一項自然語言處理的領域：機器翻譯。</p><p>翻譯是一種典型的序列到序列（Sequence to Sequence）問題，意思就是：</p><ol><li>輸入是一個長度可以變的序列（例如一個中文的句子。「今天天氣很晴朗」）</li><li>輸出是一個長度可以變的序列（例如一個英文的句子。”It’s sunny today”）</li></ol><p>假設今天 Transformer 還沒被發明，電腦會如何處理這類問題呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*GGBKk8xE6ESaw8ih" /></figure><p>直覺上會想到的作法大概就像上面這張圖一樣，分為兩個步驟：</p><ol><li><strong>把輸入序列（中文句子）一個字一個字讀完</strong><br>在上面這張圖中，每個 x 對應的就是一個字，而電腦會先讀第一個字，讀完後存起來，再去讀下一個字（先讀「今」，再讀「天」……），之後把所有資訊存在中間的 context vector。</li><li><strong>計算輸出序列（英文句子）</strong><br>輸出時，模型會根據 context vector 儲存的資訊，一個字一個字的輸出（”it”, “’s”, “sunny”, ……）。</li></ol><p>實作上確實可以用這樣的模型去做機器翻譯，但上面的例句都很短，如果今天我希望機器處理長一點的輸入（例如這篇文章），那就會遇到下面的問題：</p><ol><li>context vector 維度太小，把比較前面的字給忘了</li><li>讀完前面才能讀後面，速度很慢</li></ol><p>針對這兩個問題，下面的模型提出了解方</p><h3><a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a></h3><p>這篇論文主要試圖解決上面提出的第一點問題，概念其實很簡單，<strong>既然 Context Vector 沒辦法存下整個輸入句的資訊，那我就在每次輸出字時都看一遍整個句子就好了</strong>。</p><p>實際上的做法就是在輸出每個字的時候分別給輸入的每個字一個權重，再讓輸入的句子做加權平均。</p><p>在下面的模型中，輸入的每個字會被先轉成 hidden state（下面的 h，可以想像成 word-embedding），而模型根據目前翻譯到的字和每個字分別的 hiddent state 來計算 Attention 分數。</p><p>計算分數的函式會由模型自己學會。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*yeaVRZ3C9Cx5gCfu" /></figure><p>舉例：假設現在模型已經輸出 “It’s sunny”，準備要輸出下一個字</p><p>但是在輸出前，它需要先確定哪些中文字對下一個輸出來說比較重要，所以它用某個函數 α 來計算每個字該有的分數，α(&quot;sunny&quot;, 今) = 0.8, α(“sunny&quot;, 天) = 0.6 ……</p><p>照理來說，下一個字是 “today”，所以輸入中和「今天」兩個字有關的部分應該會比較高分。</p><p>因此，在輸出 “today” 前，每個中文字可能會有下面的分數。</p><ul><li>「今」：0.8</li><li>「天」：0.6</li><li>「氣」：0.05</li><li>「很」：0.01</li><li>……</li></ul><p>接下來它就把「今」的 hidden state 乘上 0.8、把「天」的 hidden state 乘上 0.6 ……，接著把所有的 hidden state 加起來，用它來計算下一個輸出的英文字應該要是什麼。</p><p>這個模型其實就是 Attention 的雛型，Attention 的概念就是：</p><ol><li>給每個輸入的字一個權重</li><li>將輸入的字做加權計算</li></ol><p>之後談到 Attention 時往往會提到三個東西，Query、Key 和 Value，雖然這篇論文沒有明確提到這三個詞，但是從上面的模型架構已經可以看出些端倪：</p><ul><li>Query: 翻譯到的前一個字（”sunny”）</li><li>Key、Value: 每個字的 hidden state</li><li>Attention 分數: α 函式算出來的分數</li></ul><p>你可以用下面的句子來理解 Attention，對於現在的 Query（正在翻譯的英文字）來說，哪個 Key（中文字）最重要。</p><p>而在這個模型中，Value 和 Key 其實是一樣的東西。</p><h3>結論</h3><p>這篇文章詳細介紹了 Attention 機制的起源，雖然現在在做自然語言處理時使用的大多不是這個模型，但透過前面的介紹可以理解為什麼需要推出這個機制，以及 Attention 的核心概念是什麼。</p><p><a href="https://medium.com/@funcry/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3-attention-%E6%A9%9F%E5%88%B6-%E4%B8%8B-scaled-dot-product-attention-%E8%88%87%E5%85%B6%E4%BE%8B%E5%AD%90-bdcd0dbc4d3e">下一篇文章</a>將介紹現在大家使用的 Scaled Dot-Product Attention 的邏輯以及使用例子。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b40be0985e84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Matrix to Represent Fully Connected Layer and Its Gradient]]></title>
            <link>https://medium.com/@funcry/using-matrix-to-represent-fully-connected-layer-and-its-gradient-35604d99d138?source=rss-4a992408a97e------2</link>
            <guid isPermaLink="false">https://medium.com/p/35604d99d138</guid>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[FunCry]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 07:45:23 GMT</pubDate>
            <atom:updated>2023-02-21T04:12:09.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Wi9LzfiHHIUEOe0SYq7IZA.png" /></figure><p>In this era of rapid machine learning development, you can easily find a instruction video on Youtube. These videos typically use diagrams similar to the one above to teach about neural networks. Although it looks simple, you can easily encounter difficulties during development if you do not have a good understanding of the math behind it. This article aims to bridge this gap by explaining how to represent fully connected layers using matrices and how to calculate its gradient.</p><p>Prerequisites:</p><ol><li>Fully Connected Layer</li><li>Gradient Descent</li><li>Chain Rule</li><li>Matrix Multiplication</li></ol><h3>Using Matrices to Represent Fully Connected Layer</h3><p>Pytorch provides the nn.Linear(input_dim, output_dim) method to initialize a fully connected layer, where Linear refers to a linear transformation.</p><p>Since any linear transformation can be represented by a matrix, it is natural to use the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*9DRJaz2JWVxP7g82.png" /></figure><p>where <strong>X</strong> is the input, represented by a row vector. <strong>W </strong>is the weight for linear transformation, with dimensions input_dim * output_dim</p><p>The reason we use <strong>XW </strong>instead of <strong>WX </strong>is because conventionally, a row is used to represent a piece of data in computer science.</p><h3>Finding Elements in W</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*a4Aj8kbl7SWNgGWWCw8ZnQ.png" /></figure><p>After drawing the above diagram, a natural question to ask is what wᵢⱼ represents. To answer this, we first need to observe the following graphs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*7zVhDlr0P0mYpYyLcygixQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*4CCWwBvVBsevYUVns66AQQ.png" /></figure><p>From these two graphs, we can see that the first column of <strong>W </strong>represents all the weights connected to z₁ and the second column represents those connected to z₂. The weight connecting xᵢ and zⱼ is represented by wᵢⱼ, and we can locate each weight in the matrix by this logic.</p><h3>Find Gradient for W</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M8ndZxNWmhLjqtL6.png" /></figure><p>During gradient descent, the ideal approach is to create another matrix, ∂L/∂<strong>W</strong>, this matrix serves as a look-up table. The (i, j) entry of this matrix represents the gradient of wᵢⱼ, which allows us to update the weights one matrix at a time using the formula mentioned above.</p><p>To create this matrix, let’s first observe the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*OlN8L5oJgbng5msJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*OjlSsHDFVUoSOIUcww92uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*HILnNPZjC_En17qhHiS5bg.png" /></figure><p>Using the chain rule formula mentioned above, we can see that for every weight w, its gradient is the product of the input x conneted to it and the gradient of its connected output z.</p><p>If we perform the calculation for each weight wᵢⱼ, we arrive at the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*5Gi_NAZpHuD7WpZYvm8V4A.png" /></figure><p>The last line gives us the formula for calculating the gradient of <strong>W</strong>.</p><h3>Batch Gradient Calculation</h3><p>When implementing machine learning, we often use batch calculation to speed up training.</p><p>To understand how the formula for calculating the gradient behaves in a batch calculation, we can examine its behavior when the batch size is equal to 1 and n.</p><blockquote>Batch Size = 1</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Ne49d_D0ijGDHdExoGz85g.png" /></figure><p>When batch size is equal to 1, the result is exactly the same as the <a href="#852d">one we derived earlier</a>.</p><blockquote>Batch Size = n</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*_Gd_-KP3bfzRdbIRKiqWQQ.png" /></figure><p>When the batch size is greater than 1, the result equals the batch gradient summed together. If you want the average gradient of the batch, don’t forget to divide the result by n.</p><h3>Find Gradient for X</h3><p>The formula for ∂L/∂<strong>W </strong>that we derived includes ∂L/∂<strong>Z</strong>. In a neural network with multiple layers, Z becomes the input vector X for the next layer after activation function. Therefore, it is necessary to calculate the gradient for X as well.</p><p>As usual, we begin by observe the following graphs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*YsrVVgYx49vtEtOJKbtMog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*bBjOCoDPtu8z9uEIKenHlg.png" /></figure><p>From the graph above, we can see that the graident for x is the product of all the w connected to it and its corresponding ∂L/∂zⱼ summed together. If we examine the weight matrix we derived earlier, we can see that the <em>i-</em>th row of <strong>W </strong>represents all the weights connected to xᵢ, which means the gradient for xᵢ is the inner product of the <em>i-</em>th row of <strong>W </strong>and ∂L/∂<strong>Z.</strong></p><p>We arrived at the following formula after some simple calculation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*BPNmV94VcDvFR0kvkH-HPg.png" /></figure><h3>The Gradient for Bias Term</h3><p>We have omitted the bias term in the previous discussion for the sake of clarity, but after some simple calculations, we can see that its gradient is the same as ∂L/∂<strong>Z.</strong></p><p>It is important to note that the gradient for the bias term should still be taken into consideration when using a batch size greater than one. Further considerations on how to adjust the bias term gradient can be left to the reader.</p><h3>Conclusion</h3><p>This article provides an explaination on how matrices can be used to represent a fully connected (Linear) layer, and how to calculate the gradient of the weights and inputs. However, when implementing backpropagation from scratch, it’s also important to consider how to connect each layer and define the derivative function of each activation function. When the layer is not linear, one should also think about the gradient, but with a solid understanding of the content discussed above, this should be a piece of cake for you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35604d99d138" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何用矩陣表示 Fully Connected Layer 及其梯度]]></title>
            <link>https://medium.com/@funcry/%E5%A6%82%E4%BD%95%E7%94%A8%E7%9F%A9%E9%99%A3%E8%A1%A8%E7%A4%BA-fully-connected-layer-%E5%8F%8A%E5%85%B6%E6%A2%AF%E5%BA%A6-15a1ca006cb?source=rss-4a992408a97e------2</link>
            <guid isPermaLink="false">https://medium.com/p/15a1ca006cb</guid>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <dc:creator><![CDATA[FunCry]]></dc:creator>
            <pubDate>Mon, 20 Feb 2023 05:57:01 GMT</pubDate>
            <atom:updated>2023-02-21T04:11:31.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>前言</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Wi9LzfiHHIUEOe0SYq7IZA.png" /></figure><p>在這個機器學習蓬勃發展的時代，隨手在 Youtube 上就能找到教學影片，這類影片大多用類似上面的圖片來描述神經網路，雖然看起來淺顯易懂，但在手刻、使用套件時很容易因為沒有想清楚背後的數學而遇到困難。這篇文章試圖彌補理論跟實作間的差距，用直觀的方式解釋要怎麼以矩陣表示 fully connected layer 以及計算梯度。</p><p>閱讀前需要先熟悉：</p><ol><li>Fully Connected Layer</li><li>梯度下降（Gradient Descent）</li><li>Chain Rule</li><li>基本的矩陣乘法</li></ol><h3>用矩陣表示 Fully Connected Layer</h3><p>在深入探討前，我們必須先了解該如何用數學表示 fully connected layer。在 pytorch 中，你可以利用 nn.Linear(input_dim, output_dim) 來初始化一個 fully connected layer，其中 Linear 代表的就是線性轉換。</p><p>我們知道所有線性轉換都可以用矩陣來表示，因此可以用下列算式來表示一個 fully connected layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*9DRJaz2JWVxP7g82.png" /></figure><p>其中 <strong>X</strong> 是線性轉換的輸入，用一個 row vector 來表示； <strong>W </strong>就是 linear layer 的權重，其維度為 input_dim * output_dim</p><p>之所以採用 <strong>XW</strong> 而不是 <strong>WX</strong> 是因為在電腦科學裡習慣以一個 row 來表示一筆資料，若用 <strong>XW</strong> 可以順應這個習慣。</p><h3>找出 W 中的元素</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*a4Aj8kbl7SWNgGWWCw8ZnQ.png" /></figure><p>在畫好上面的矩陣以及圖片後，很容易產生一個疑問：wᵢⱼ 代表的是什麼？</p><p>為了回答這個問題，我們可以先觀察下面兩張圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*7zVhDlr0P0mYpYyLcygixQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*4CCWwBvVBsevYUVns66AQQ.png" /></figure><p>從上面兩張圖可以發現 <strong>W </strong>的第一個 column 代表所有連接到 z₁ 的權重, 第二個 column 代表連接 z₂ 的權重，而由 xᵢ 連接 zⱼ 的權重就是 wᵢⱼ，透過這個方式就可以找出每個權重在矩陣裡的位置。</p><h3>計算 W 的梯度</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vGYEusxKrwsR71D6.png" /></figure><p>在計算梯度時，理想的做法應該是建立另一個矩陣 ∂L/∂<strong>W。</strong>這樣的矩陣更像是一個查詢表，其第 (i, j) 個元素代表的是 wᵢⱼ 的梯度，如此一來就能用上列公式以矩陣為單位更新權重。要計算出這個矩陣可以先做下面的觀察</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*OlN8L5oJgbng5msJ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*OjlSsHDFVUoSOIUcww92uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*HILnNPZjC_En17qhHiS5bg.png" /></figure><p>透過上面的 chain rule 算式，不難發現對於每個 w，它的梯度就是連接它的 x 去乘上另一頭 z 的梯度。</p><p>若對每個 wᵢⱼ 都做這樣的計算，我們可以得到下面的公式</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*5Gi_NAZpHuD7WpZYvm8V4A.png" /></figure><p>最下面這行就是 <strong>W </strong>的梯度公式。</p><h3>批次 (Batch) 計算梯度</h3><p>在實作機器學習時，為了加快訓練速度，往往會運用平行運算，此時便引入了 Batch 的觀念。</p><p>為了搞清楚在不同 Batch 下運用上述算式時究竟發生了什麼事情，我們可以分別觀察 Batch size 為 1 和 n 時矩陣的表現</p><blockquote>Batch Size = 1</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*Ne49d_D0ijGDHdExoGz85g.png" /></figure><p>在 batch size = 1 時，算出來的矩陣就和 <a href="#852d">前一段</a> 的預期結果一樣</p><blockquote>Batch Size = n</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*_Gd_-KP3bfzRdbIRKiqWQQ.png" /></figure><p>同樣的算式在 batch size &gt; 1 的時候，計算結果會變成個整個 batch 的梯度相加，因此在計算時如果你希望得到的是這個 batch 的平均梯度，應該要把矩陣計算結果除以 n。</p><h3>計算輸入向量的梯度</h3><p>在計算 ∂L/∂<strong>W</strong> 時，算式裡有出現 ∂L/∂<strong>Z。</strong>而 <strong>Z</strong> 在經過 activation function 後又會變成下一個層的輸入（也就是下一層的 <strong>X </strong>），因此如果你的神經網路深度多於一層，在更新權重時也需要順便計算 ∂L/∂<strong>X。</strong></p><p>我們一樣先觀察下面幾張圖：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*YsrVVgYx49vtEtOJKbtMog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*bBjOCoDPtu8z9uEIKenHlg.png" /></figure><p>可以發現每個 x 的梯度就是所有連接它的 w 各自乘上相對應的 ∂L/zⱼ 後的總和</p><p>若仔細觀察 <a href="#9b98">第一段</a> 提到的矩陣，可以發現 <strong>W</strong> 第 <em>i</em> 個 row 對應的就是所有連接 xᵢ 的權重。</p><p>所以 xᵢ 的梯度可以看做 <strong>W</strong> 的第 <em>i </em>個 row vector 和 ∂L/∂<strong>Z</strong> 做內積。</p><p>經過簡單的整理可以得到下面的公式：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*BPNmV94VcDvFR0kvkH-HPg.png" /></figure><h3>計算常數項（偏差項、Bias Term）</h3><p>上面的討論為了作圖方便刻意省略了常數項，但經過簡單的計算後不難發現 它的梯度值就和 ∂L/∂<strong>Z</strong> 一模一樣。</p><p>值得一提的是 bias term 在 batch size &gt; 1 時一樣需要經過處理，至於實際的處理方式為何就留給讀者思考。</p><h3>結論</h3><p>這篇文章解釋了如何用矩陣表示 fully connected (Linear) layer，在實作上如果想要手刻 backpropagation，還需要考慮如何連接每一層以及定義各種 activation function 的微分，在遇到不是 FC 的 layer 時也需要思考對應的微分應該長什麼樣子。</p><p>不過若能看懂這篇文章提到的算法，在處理這些問題時也能快速算出答案。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15a1ca006cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>