<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>sujinyun999.log</title>
        <link>https://velog.io/</link>
        <description>Null</description>
        <lastBuildDate>Fri, 21 Apr 2023 13:23:45 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <image>
            <title>sujinyun999.log</title>
            <url>https://velog.velcdn.com/images/sujin_yun_/profile/d557dc8a-308b-4a0d-86d0-b4aaca20f558/image.gif</url>
            <link>https://velog.io/</link>
        </image>
        <copyright>Copyright (C) 2019. sujinyun999.log. All rights reserved.</copyright>
        <atom:link href="https://v2.velog.io/rss/sujin_yun_" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[[#LoG_Reading] Structure-Aware Transformer for Graph Representation Learning]]></title>
            <link>https://velog.io/@sujin_yun_/LoGReading-Structure-Aware-Transformer-for-Graph-Representation-Learning</link>
            <guid>https://velog.io/@sujin_yun_/LoGReading-Structure-Aware-Transformer-for-Graph-Representation-Learning</guid>
            <pubDate>Fri, 21 Apr 2023 13:23:45 GMT</pubDate>
            <description><![CDATA[<h1 id="structure-aware-transformer-for-graph-representation-learning"><strong><em>Structure-Aware Transformer for Graph Representation Learning</em></strong></h1>
<p><em><strong>Background before reading this review.</strong></em></p>
<p>*Notation</p>
<p>$G = (V, E, \mathbf X)$</p>
<ul>
<li>node $u \in V$</li>
<li>node attribute $x_u \in \mathcal X \subset \mathbb R^d$</li>
<li>$\mathbf X \in \mathbb R^{n \times d}$</li>
</ul>
<ol>
<li><p>Transformers on Graph</p>
<p>GNN에서는 그래프 구조를 explicit하게 활용하는 반면, transformer는 노드의 attribute를 활용하여 노드들 사이 relation을 나타내는데 활용</p>
<p>Transformer 구성 요소</p>
<ol>
<li>Self-attention module<ul>
<li>input node feature $\mathbf X$가 linear projection을 통해 Query($\mathbf Q$), Key($\mathbf K$), Value($\mathbf V$)로 투영되고, 이를 활용하여 self-attention을 계산할 수 있음</li>
<li>multi-head attention</li>
</ul>
</li>
<li>feed-forward NN<ul>
<li>self-attention의 output이 skipconnection이나 FFN등을 거치면 하나의 transforemer layer를 통과하게됨</li>
</ul>
</li>
</ol>
</li>
<li><p>Absolute encoding</p>
<p>그래프의 위치적/구조적인 representation을 input node feature에 더하거나 concatenate하여 Transformer의 input으로 사용 : Vanilla transformer의 PE</p>
<p>Graph Transformer에서 자주 사용되는 Positional encoding method들</p>
<ul>
<li>Laplacian PE</li>
<li>Random Walk PE</li>
</ul>
<p>(-) 노드와 그 이웃들 사이의 structural similarity를 반영하지는 않음</p>
</li>
<li><p>Self-attention and kernel smoothing</p>
<p>$\operatorname{Attn}\left(x_v\right)=\sum_ {u \in V} \frac{\kappa_ {\exp }\left(x_v, x_u\right)}{\sum_ {w \in V} \kappa_ {\exp }\left(x_v, x_w\right)} f\left(x_u\right), \forall v \in V$</p>
<ul>
<li>linear value function $f(x) = \mathbf W_ {\mathbf V}x$</li>
<li>$\kappa_ {\exp }$ (non-symmetric) exponential kernel parameterized by $\mathbf W_ {\mathbf Q}, \mathbf W_ {\mathbf K}$</li>
</ul>
</li>
</ol>
<pre><code>$\kappa_ {\exp }\left(x, x^{\prime}\right):=\exp \left(\left\langle\mathbf{W}_ {\mathbf{Q}} x, \mathbf{W}_ {\mathbf{K}} x^{\prime}\right\rangle / \sqrt{d_ {\text {out }}}\right)$

-   $\langle \cdot, \cdot\rangle$ : dotproduct
-   학습가능한 exponential kernel
-   (-) only position-aware, not structure-aware encoding</code></pre><h1 id="1-problem-definition"><strong>1. Problem Definition</strong></h1>
<h2 id="limitations-of-gnn"><em><strong>Limitations of GNN</strong></em></h2>
<ol>
<li>limited expressiveness : 최대 1-WL test의 표현력을 가짐</li>
<li>Over-smoothing problem : GNN layer의 수가 충분히 커지면 모든 node representation이 상수로 수렴하게됨</li>
<li>Over-squashing problem : 그래프의 수많은 메세지들이 고정된 길이의 벡터 하나로 압축되어 발생하는 그래프 “bottleneck”으로 인해 멀리 위치한 노드의 메세지가 효율적으로 전파되지 않는 문제</li>
</ol>
<p>⇒ Beyond neighborhood aggregation!</p>
<h2 id="transformer"><em><strong>Transformer</strong></em></h2>
<ul>
<li>하나의 self-attention layer를 통해 그래프내의 어떤 노드쌍이든지 그 사이의 상호작용을 확인할 수 있음</li>
<li>GNN과 달리 중간 계층에서 structural inductive bias가 발생하지 않아 GNN의 표현력 한계를 해결</li>
<li>graph structure info를 얼마나 학습하는지 input node feature에만 structural, positional info를 encoding해 넣음</li>
<li>노드에 대한 structural, positional info만 input node feature로 encoding하지만, 그래프 구조 자체에서 학습할 수 있는 정보의 양이 제한됨</li>
</ul>
<blockquote>
<p>💡 Goal : 그래프 데이터에 Transformer를 적절히 변형해 적용하여 그래프 구조를 잘 반영하고 높은 표현력을 가지는 Achitecture를 디자인하는 것</p>
</blockquote>
<h1 id="2-motivation"><strong>2. Motivation</strong></h1>
<h2 id="message-passing-graph-neural-networks"><em><strong>Message passing graph neural networks.</strong></em></h2>
<p>최대 1-WL test로 제한된 표현력, over-smoothing, over-quashing</p>
<h2 id="limitations-of-existing-approaches"><em><strong>Limitations of existing approaches</strong></em></h2>
<ul>
<li>노드들 사이 positional relationship만 encoding하고, strucutral relationship을 직접 encoding하지않음<ul>
<li>노드들 사이 structural similarity를 확인하기가 어렵고, 노드들 사이의 structural interaction을 모델링하는데 실패하게됨</li>
</ul>
</li>
</ul>
<p>ex.</p>
<p><img src="https://user-images.githubusercontent.com/69068083/231114064-4063d3f0-f895-4d7c-a932-eddbeb77de34.png" alt="Untitled"></p>
<p>G1과 G2에서 최단거리를 활용한 positional encoding을 할경우 node u와 v가 다른 노드들에 대해 모두 같은 representation을 가지게되지만, 그래프의 실제 구조는 다름 → strucure aware에 실패</p>
<blockquote>
<p>💡 Message-passing GNN과 Transformer architecture 각각의 장점을 살려 local, global info를 모두 고려하는 transformer architecture를 제안</p>
</blockquote>
<h2 id="contribution-of-this-paper"><em><strong>Contribution of this paper</strong></em></h2>
<p>Q. Transformer구조에 structural info를 어떻게 인코딩할것인가?</p>
<p>A. Structure-aware self attention를 도입한 Structre-Aware Transformer(SAT)</p>
<ol>
<li>reformulate the self-attention mechanism<ul>
<li>kernel smoother</li>
<li>원래 노드 feature에 적용하는 exponential 커널을 확장하여 각 노드가 중심인 subgraph representation을 추출하여 local structure에도 적용</li>
</ul>
</li>
<li>subgraph representation들을 자동적으로 만들어내는 방법론 제안<ul>
<li>이를 통해 kernel smoother가 구조적/특성적 유사성을 포착할 수 있게됨</li>
</ul>
</li>
<li>GNN으로 그래프의 subgraph info를 포함하는 node representation을 만들어 기존 GNN에 추가적인 구조 개선 없이도 더 높은 성능을 냄</li>
<li>Transformer의 성능향상이 structure-aware한 측면에서 일어난 것을 증명하고 absolute encoding이 추가된 transfoemr보다 SAT가 얼마나 interpretable한지를 보여줌</li>
</ol>
<h1 id="3-method"><strong>3. Method</strong></h1>
<h2 id="structure-aware-transformer"><em><strong>Structure-Aware Transformer</strong></em></h2>
<h3 id="1-structure-aware-self-attention"><em>1. <strong>Structure-Aware Self-attention</strong></em></h3>
<p>position-aware한 structural encoding에 노드들 사이 structural similarity를 포함하기 위해 각 노드의 local structure에 관한 generalized kernel을 추가</p>
<p>각 노드가 중심이되는 subgraph set을 추가함으로써 structure-aware attention은 다음과 같이 정의될 수 있음</p>
<p>$\operatorname{SA-Attn}\left(v\right):=\sum_ {u \in V} \frac{\kappa_ {\text{graph} }\left(S_G(v), S_G(u)\right)}{\sum_ {w \in V} \kappa_ {\text{graph}}\left(S_G(v), S_G(u)\right)} f\left(x_u\right)$</p>
<ul>
<li>$S_G(v)$ : node feature $\mathbf X$와 연관된 $v$를 중심으로하는 subgraph</li>
<li>$\kappa_ {\text{graph} }$ : subgraph쌍을 비교하는 kernel</li>
</ul>
<p>⇒ attribute &amp; structural similarity 모두 표현 가능한 expressive node representation 생성 → table 1</p>
<p>⇒ 동일한 subgraph 구조를 가지는 경우에만 permutation equivariant한 성질을 갖게됨</p>
<p>$\kappa_ {\text {graph }}\left(S_G(v), S_G(u)\right)=\kappa_ {\exp }(\varphi(v, G), \varphi(u, G))$</p>
<ul>
<li>$\varphi(v, G)$ : feature $\mathbf X$를 가지는 node $v$가 중심에 있는 subgraph의 vector representation을 만들어내는 structure extractor<ul>
<li>GNN이나 differentiable Graph kernel등 subgraph의 representation을 만들 수 있는 어느 모델이든 될 수 있음</li>
<li>Task/data 특성에 따라 Edge attribute을 활용할 필요가 있는 경우 그에 맞는GNN을 선택하면 됨. 따로 edge attribute을 활용하지는 않고 subgraph extractor에서 활용</li>
</ul>
</li>
</ul>
<p><em><strong>k-subtree GNN extractor.</strong></em></p>
<p>$\varphi(u, G) = \operatorname{GNN}_G^{(k)}(u)$</p>
<ul>
<li>node u에서 시작하는 k-subtree structure의 representation생성</li>
<li>at most 1-WL test</li>
<li>작은 k 값이더라도 over-smoothing, over-squashing issue없이 좋은 성능을 내는것을 확인</li>
</ul>
<p><em><strong>k-subgraph GNN extractor.</strong></em></p>
<p>$\varphi(u, G) = \sum_ {v \in \mathcal N_k(u)} \operatorname{GNN}_G^{(k)}(v)$</p>
<ul>
<li>node u의 representation만을 사용하는데서 나아가 node u가 중심이 되는 k-hop subgraph전체의 representation을 생성하고 활용</li>
<li>node u 의 k-hop이웃 $\mathcal N_k(u)$에 대해 각 노드에 GNN을 적용한 node representation을 pooling(논문에서는 summation)</li>
<li>More powerful than 1-WL test</li>
<li>original node representation과의 concatenation을 통ㅎ structural similarity뿐만 아니라 attributed similarity도 반영</li>
</ul>
<p><em><strong>Other structure extractors.</strong></em></p>
<ul>
<li>directly learn a number of “hidden graphs” as the “anchor subgraphs” to represent subgraphs</li>
<li>domain-specific GNNs</li>
<li>non-parametric graph-kernel</li>
</ul>
<h3 id="2-structure-aware-transformer"><em>2. Structure-Aware Transformer</em></h3>
<p><img src="https://user-images.githubusercontent.com/69068083/231114106-a71006e8-a9e5-44cb-b353-578ec4e09a80.png" alt="Untitled"></p>
<p>self-attention→ skipconnection → normalization layer → FFN → normalization layer</p>
<p><em><strong>Augmentation on skip connection.</strong></em></p>
<p>$x&#39;_v = x_c +1/ \sqrt {d_v} \operatorname{SA-Attn}\left(v\right)$</p>
<ul>
<li>$d_v$ : node $v$의 degree</li>
<li>degree factor를 포함하여 연결이 많은 graph component들이 압도적인 영향을 미치지 않도록함</li>
</ul>
<p>*graph-level task를 진행해야 할 경우 input graph에 다른 노드와의 connectivity없이 virtual <code>[cls]</code>node를 추가하거나, node-level representation을 sum/average 등으로 aggregation</p>
<h3 id="3-combination-with-absolute-encoding"><em>3. Combination with Absolute Encoding</em></h3>
<p>위의 structure aware self-attention에 추가로 absolute encoding을 추가하게 되면 postion-aware한 특성이 추가되어 기존의 정보를 보완하는 역할을 하게된다. 이러한 조합을 통해 성능향상을 확인할 수 있었다.</p>
<p>RandomWalk PE</p>
<p>Absolute PE만 사용할 경우 structural bias가 과도하게 발생하지 않아서 누개의 노드가 유사한 local structure를 갖고 있더라도 비슷한 node representation이 생성되는것을 보장하기 어렵다!</p>
<p>→ Structural, positional sign으로 주로 사용되는 distance나 Laplacian-based positional representation이 노드들 사이의 structural simialrity를 포함하지 않기때문</p>
<blockquote>
<p>📌 Structural aware attenrion은 inductive bias가 더 강하더라도 노드의 strucutral similarity를 측정하는데 적합하여 유사한 subgraph구조를 가진 노드들이 비슷한 embedding을 갖게하고, expressivity가 향상되어 좋은 성능을 보임</p>
</blockquote>
<h3 id="4-expressivity-analysis"><em>4. Expressivity Analysis</em></h3>
<p>SAT에서는 각노드를 중심으로하는 k-subgraph GNN extractor가 도입되어 적어도 subgraph representation만큼은 expressive하다는 것을 보장</p>
<h1 id="4-experiment"><strong>4. Experiment</strong></h1>
<h3 id="experiment-setup"><em><strong>Experiment setup</strong></em></h3>
<p><em><strong>Dataset</strong></em></p>
<ul>
<li>ZINC</li>
<li>CLUSTER</li>
<li>PATTERN</li>
<li>OGBG-PPA</li>
<li>OGBG-CODE2</li>
</ul>
<p><em><strong>Baseline</strong></em></p>
<ul>
<li><em><strong>GNNs</strong></em><ul>
<li>GCN</li>
<li>GraphSAGE</li>
<li>GAT</li>
<li>GIN</li>
<li>PNA</li>
<li>Deeper GCN</li>
<li>ExpC</li>
</ul>
</li>
<li><em><strong>Transformers</strong></em><ul>
<li>Original Transformer with RWPE</li>
<li>Graph Transformer</li>
<li>SAN</li>
<li>Graphormer</li>
<li>GraphTrans</li>
</ul>
</li>
</ul>
<h3 id="results"><em><strong>Results</strong></em></h3>
<p><strong>Table1.</strong> SAT와 graph regression, classification task의 sota모델과 비교</p>
<ul>
<li>ZINC dataset의 경우 작을수록 더 좋은 성능을 의미하는 MAE(Mean Absolute Error), CLUSTER와 PATTERN의 경우 높을수록 더 좋은 성능을 의미하는 Acurracy가 평가지표로 사용되었음.</li>
</ul>
<p><img src="https://user-images.githubusercontent.com/69068083/231114155-056893f6-8d16-4a59-b43b-62c76fd482a3.png" alt="Untitled"></p>
<p><strong>Table2.</strong> SAT와 OGB데이터셋에서의 sota모델 비교</p>
<ul>
<li>OGB dataset의 경우 높을수록 더 좋은 성능을 의미하는 Acurracy, F1 score가 평가지표로 사용되었음.</li>
</ul>
<p><img src="https://user-images.githubusercontent.com/69068083/231114185-23daa0d6-bc32-4838-93e8-0a6d09a17f7e.png" alt="Untitled"></p>
<p><strong>Table3.</strong> structure extractor로 사용한 GNN과의 성능비교. Sparse GNN을 모든 경우에서 outperform하는 것을 확인할 수 있음</p>
<p><img src="https://user-images.githubusercontent.com/69068083/231114223-e6e32dfd-039b-4caa-b123-14e72e9fc867.png" alt="Untitled"></p>
<p><strong>Fig3.</strong> ZINC데이터셋에 SAT의 다양한 variant실험</p>
<ul>
<li>평가지표 : MAE(더 작은 지표가 좋은 성능을 의미) </li>
</ul>
<p><img src="https://user-images.githubusercontent.com/69068083/231114263-2ea26465-c8b3-4df8-b7d4-4d329d41d97b.png" alt="Untitled"></p>
<ol>
<li>structure extractor에서의 k의 영향 비교<ul>
<li>k=0일때, Absolute encoding만을 활용하는 vanilla transformer랑 같다고 볼 수 있음</li>
<li>k=3일때, optimal performance를 보임을 확인</li>
<li>k=4를 넘어서면 성능이 악화되는것을 확인할 수 있었는데, 이는 GNN에서의 알려진 사실인 더 적은 수의 layer를 가지는 network가 더 좋은 성능을 보이는 것과 마찬가지라고 할 수 있음</li>
</ul>
</li>
<li>Absolute encoding의 영향 비교<ul>
<li>RWPE vs. Laplacian PE</li>
<li>Structure-aware attention의 도입으로 인한 성능향상보다는 그 정도가 낮았지만, RWPE를 도입할 경우 성능이 더 좋은것으로 보았을 때, 두가지 encoding이 상호보완적인 역할을 한다고 해석할 수 있음</li>
</ul>
</li>
<li>Readout method의 영향 비교<ul>
<li>node-level representation을 aggregate할 때 사용하기 위한 readoutd으로 mean과 sum을 비교하였음</li>
<li>추가로 <code>[CLS]</code> 토큰을 통해 graph-level 정보를 pooling하는 방법도 같이 비교하여보았음</li>
<li>GNN에서는 readout method의 영향이 매우 컸지만 SAT에서는 매우 약한 영향만을 확인함.</li>
</ul>
</li>
</ol>
<h1 id="5-conclusion"><strong>5. Conclusion</strong></h1>
<p><em><strong>Strong Points.</strong></em></p>
<p>structural info를 graphormer에서처럼 휴리스틱하게 shortest path distance(SPD)를 활용하지 않고, 그러한 local info를 잘 배우는 GNN으로 대체한 점이 novel하다고 할 수 있음</p>
<p>Transformer의 global receptive field 특성과 GNN의 local structure특성이 상호보완적</p>
<p>encoding에 있어서도</p>
<ol>
<li>RWPE를 통한 positional encoding</li>
<li>k-subtree/subgraph GNN을 통한 structure-aware attention</li>
</ol>
<p>두가지가 상호보완적인 역할을 함</p>
<p>→ 각자가 잘 배우는 특성을 고려하여 상호보완적인 두가지 방법론을 잘 섞어서 좋은 성능을 내었고, 그 이유가 납득하기 쉬움</p>
<p><em><strong>Weak Points.</strong></em></p>
<p>그래프데이터에 Transformer를 적용한 다른 논문의 architecture인 Graphormer에서 사용한 SPD만의 장점 : 직접적으로 연결되어있지 않은, 아주 멀리에 위치한 노드쌍이더라도 shortest path상의 weighted edge aggregation을 하는 만큼 그러한 특성 반영되면 좋은 그래프 구조/ 데이터셋에서는 SAT가 capture하지 못하는 부분이 있을 것</p>
<hr>
<h1 id="author-information"><strong>Author Information</strong></h1>
<ul>
<li><p>Dexiong Chen</p>
<ul>
<li>Department of Biosystems Science and Engineering, ETH Zurich, Switzerland.</li>
<li>SIB Swiss Institute of Bioinformatics, Switzerland.</li>
</ul>
</li>
<li><p>Leslie O&#39;Bray</p>
<ul>
<li>Department of Biosystems Science and Engineering, ETH Zurich, Switzerland.</li>
<li>SIB Swiss Institute of Bioinformatics, Switzerland.</li>
</ul>
</li>
<li><p>Karsten Borgwardt</p>
<ul>
<li>Department of Biosystems Science and Engineering, ETH Zurich, Switzerland.</li>
<li>SIB Swiss Institute of Bioinformatics, Switzerland.</li>
</ul>
</li>
</ul>
<h1 id="6-reference--additional-materials"><strong>6. Reference &amp; Additional materials</strong></h1>
<ul>
<li>Github Implementation : <a href="https://github.com/BorgwardtLab/SAT"></a><a href="https://github.com/BorgwardtLab/SAT">https://github.com/BorgwardtLab/SAT</a></li>
<li>Reference : <a href="https://arxiv.org/abs/2202.03036">Structure-Aware Transformer for Graph Representation Learning</a></li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[#LoG_Reading] Graphormer : Do Transformers Really Perform Badly for Graph Representation? ]]></title>
            <link>https://velog.io/@sujin_yun_/LoGReading-Graphormer-Do-Transformers-Really-Perform-Badly-for-Graph-Representation</link>
            <guid>https://velog.io/@sujin_yun_/LoGReading-Graphormer-Do-Transformers-Really-Perform-Badly-for-Graph-Representation</guid>
            <pubDate>Fri, 21 Apr 2023 13:20:47 GMT</pubDate>
            <description><![CDATA[<blockquote>
<p>&quot;Message-passing GNNs are known to suffer from pathologies, such as oversmoothing, due to their repeated aggregation of local information [19], and over-squashing, due to the exponential blow-up in computation paths as the model depth increases [1]. As a result, there is a growing interest in deep learning techniques that encode graph structure as a soft inductive bias, rather than as a hard-coded aspect of message passing [14, 24].&quot; 
<strong>- Rethinking Graph Transformers with Spectral Attention. NeurIPS 2021 -*</strong></p>
</blockquote>
<h1 id="abstract">Abstract</h1>
<p>Graph representation learning에서 Transformer가 좋은 성능을 보이는가?</p>
<p>*<em>Graphormer
*</em></p>
<ul>
<li>standard transformer architecture</li>
<li>많은 graph representation learning task에서 좋은 성능을 보임<ul>
<li>especially on the recent OGB Large-Scale Challenge</li>
</ul>
</li>
</ul>
<p>*<em>Key Insight
*</em></p>
<ul>
<li>graph를 모델링하기위해 structural information을 효율적으로 encoding하는 방법의 필요성</li>
<li>Graphormer의 표현력을 수학적으로 characterize<ul>
<li>graph의 structural information을 encoding하는 방법을 다른 GNN variants와 비교해보았을 때, 이들을 모두 Graphormer의 특수케이스로 커버할 수 있었음</li>
</ul>
</li>
</ul>
<p>💡 <strong>Ways to encode structural information of the graph ⇒ Graphormer</strong></p>
<h1 id="1-introduction">1. Introduction</h1>
<p>Graph representation에 transformer를 적용하고자 하는 꾸준한 시도</p>
<ul>
<li><p>하지만 지금까지 가장 효과적인 방법은 feature aggregation과 같은 classic GNN variants의 몇몇 key module에만 softmax attention을 적용하는 방식 (ex. GAT)</p>
<p>  → graph representation learning에 transformer 를 적용하는것이 적절한가?</p>
</li>
</ul>
<p>Graphormer</p>
<ul>
<li>directly built upon the standard transformer architecture</li>
<li>graph-level prediction task에서의 SOTA(OGB-LSC)</li>
</ul>
<p>node $i$의 self-attention</p>
<ul>
<li>노드쌍 사이의 relation으로 확인할 수 있는 structural information을 고려하지 않음</li>
<li>node $i$와 다른 노드들 사이의 semantic similarity만 계산</li>
</ul>
<p>다음 information들을 활용해 structural encoding method 구성</p>
<ol>
<li><strong><em>Centrality Encoding</em></strong></li>
</ol>
<ul>
<li>목적 : 그래프에서의 node importance</li>
</ul>
<p>☹️ self-attention의 경우 node의 semantic feature의 유사도를 기반으로 계산되기 때문에, 다른 노드들보다 더 중요한 노드의 중요도같은 정보를 파악하기 어려움</p>
<p>💡 <strong>degree centrality</strong></p>
<ul>
<li>학습가능한 벡터가 노드의 degree에 따라 각 노드에 할당되고, 이것이 input layer의 node feature들에 더해지는 방식</li>
</ul>
<blockquote>
<p><strong>연결 중심성(Degree Centrality)
:</strong> 한 Node에 연결된 모든 Egde의 갯수(Weighted 그래프일 경우에는 모든 Weight의 합)로 중심성을 평가</p>
</blockquote>
<ol>
<li><strong><em>Spatial Encoding</em></strong></li>
</ol>
<ul>
<li>목적 : 노드들 사이 structural relation</li>
</ul>
<p>☹️ graph-structured data는 이미지나 자연어같은 structured data와는 달리 임베딩 하기위한 canonical grid(표준 격자)가 없음</p>
<ul>
<li>노드들은 non-Euclidean space에 엣지로 연결되어 존재함</li>
</ul>
<p>💡 각 노드쌍에 대해 spatial raltion을 기반으로한 학습가능한 임베딩 주기</p>
<ul>
<li>shortest path<ul>
<li>softmax attention의 bias term으로 encoded</li>
<li>additional info : edge feature(ex. 분자구조에서 두개의 원자사이 연결의 종류)를 포함하기도 함</li>
</ul>
</li>
</ul>
<p>각 노드쌍에 대해 learnable embedding(shortest path)과 edge feature의 dot product 평균을 계산해 attention module에 사용</p>
<h1 id="2-preliminary">2. Preliminary</h1>
<p><strong><em>Graph Neural Network (GNN)</em></strong></p>
<ul>
<li>AGGREGATE : 이웃노드의 정보 aggregation</li>
<li>COMBINE : 노드 representation에 이웃노드로 부터 aggregation한 정보를 융합</li>
<li>READOUT : 노드 feature를 final representation에 aggregate, by permutation invariant function</li>
</ul>
<p><strong><em>Transformer</em></strong></p>
<ul>
<li>Query</li>
<li>Key</li>
<li>Value</li>
</ul>
<p><a href="https://velog.io/@sujin_yun_/Attention-is-all-you-need#self-attention">Self-Attention</a></p>
<h1 id="3-graphormer">3. Graphormer</h1>
<h2 id="31-structural-encodings-in-graphormer">3.1 Structural Encodings in Graphormer</h2>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/bf198926-c62d-47bb-a1b4-42a67af567c2/image.png" alt=""></p>
<h3 id="311-centrality-encoding">3.1.1 Centrality Encoding</h3>
<p>Importance of node centrality</p>
<p>☹️ node embedding의 similarity를 기반으로 계산되는 기존 attention → node centrality의 특성을 반영하기 어려움</p>
<p>💡 <strong>Degree centrality</strong></p>
<ul>
<li>indegree&amp;outdegree → two real-valued embedding <strong>(learnable)</strong></li>
</ul>
<p>Apply centrality encoding to each node and <strong>simply add it to the node feature</strong></p>
<p>$h_i^{
(0)} = x_i + z^
−<em>{
deg^−(vi)} + z^
+</em>{
deg^+(vi)}$</p>
<ul>
<li>undirected : 그냥 하나로 합침</li>
</ul>
<p>💡 원래는 그냥 x(semantic embedding)로만 similarity를 구해서 attention을 구했었는데, learnable한 indegree, outdegree embedding을 더한걸 가지고 similarity를 바탕으로 attention을 계산하다 보니까 semantic correlation과 node importance모두 caputre할 수 있었다~!</p>
<h3 id="312-spatial-encoding">3.1.2 Spatial Encoding</h3>
<p>Transformer의 장점 중 <strong>global receptive field ← sequential하게가 아니라 한번에 문장내 모든 단어들에 대해 attention을 구해서 생기는 특성</strong></p>
<p>⇒ byproduct problem : sequential data에 대해 순차적 process가 들어가지 않으니까 자연어 같은 애들은 <strong>positional encoding</strong>이 들어가야됨</p>
<ul>
<li>그래프에서는 node가 sequence로 정렬되어있지 않음</li>
<li>multi-dimensional spatial space, edge로 연결</li>
</ul>
<p>💡 자연어에서는 그냥 positional encoding해주면 되는데 그래프는 sequential이 아니니까 다른 방법으로 structural information을 넣어준다 = <strong>Spatial encoding</strong></p>
<p>⇒ Spatial Encoding</p>
<ul>
<li>Graph $G$에서 $v_i, v_j$사이 spatial relation을 측정하는 function $\phi(vi_i,v_j) : V \times V \rightarrow \R$<ul>
<li>$\phi(vi_i,v_j)$는 노드들 사이 connectivity로 정의 = distance of shortest path(SPD)</li>
<li>연결안된경우 -1</li>
</ul>
</li>
<li>각 output value에 learnable scalar assign → self-attention 모듈의 bias term</li>
</ul>
<p>$$
A_{ij} = \frac{(h_iW_Q)(h_jW_k)^T}{\sqrt{d}} + b_{\phi(v_i,v_j)}
$$</p>
<ul>
<li>$A_{ij}$ : Query-Key matrix A의 $(i,j)$th element<ul>
<li>$b_{\phi(v_i,v_j)}$ : $\phi(vi_i,v_j)$에 따라 assign된 learnable scalar, shared across all layers</li>
</ul>
</li>
</ul>
<p>💡 transformer에서 query를 바탕으로 다른 모든 key value들과 연산하고 그거를 softmax먹여서 score로 사용. score랑 value들 가중합해서 attention으로 사용. 여기 나와있는 A_ij는 score느낌인듯, 근데 degree centrality가 반영된 node embedding similarity만 구한게 아니라 거기에 bias term으로 distance of shortest path도 더해준 것!</p>
<p>장점</p>
<ol>
<li>receptive field가 이웃 노드들로 제한되는 conventional GNN과 비교했을 때 <strong>transformer layer는 그래프 내의 모든 다른 노드들의 attend하며 global information을 제공</strong></li>
<li>$b_{\phi(v_i,v_j)}$을 적용함으로써, transformer layer의 각 노드는 그래프의 구조적 정보(structural information)에 따라서 adaptively attend<ul>
<li>ex. $b_{\phi(v_i,v_j)}$가 $\phi(vi_i,v_j)$에 따라 감소함수로 학습되었을 경우 → 모델은 가까운 노드를 더 attend하고, 멀리있는 노드는 상대적으로 덜 attend하게됨</li>
</ul>
</li>
</ol>
<h3 id="313-edge-encoding-in-the-attention">3.1.3 Edge Encoding in the Attention</h3>
<p>edge또한 구조적 특성을 가지는 경우</p>
<ul>
<li>ex. molecular graph, 원자쌍 사이 연결이 특정 type을 가지기도 함</li>
<li>Traditional methods for edge encoding<ol>
<li>edge features가 연관된 nodes’ features에 더해짐</li>
<li>각 노드에 대해 연관된 edges’ features는 aggregation단계에서 node features와 함께 사용됨</li>
</ol>
</li>
</ul>
<p>⇒ 연관된 노드와의 edge 정보만 propagate → whole graph representation에 edge information을 활용하기에는 효율적인 방법이 아닌듯</p>
<ul>
<li>attention mechanism은 각 node pair $(v_i, v_j)$에 대해 correlation을 추정<ul>
<li>이때 두 노드를 연결하는 edge가 고려되어야함</li>
</ul>
</li>
</ul>
<p>⇒ 노드간 shortest path를 찾고, path를 따라 edge feature와 learnable embedding(Weight embedding)을 dot product하여 평균내는 방식</p>
<ul>
<li>spatial encoding처럼 bias term을 통해 추가됨</li>
</ul>
<p>$$
A_{ij} = \frac{(h_iW_Q)(h_jW_k)^T}{\sqrt{d}} + b_{\phi(v_i,v_j)}+c_{ij}, ~~\text{where} ~c_{ij} = \frac{1}{N}\sum_{n=1}^{N}x_{e_n}(w_n^E)^T
$$</p>
<ul>
<li>$v_i$에서 $v_j$로 가는 shortest path $\text{SP}_{ij} = (e_1,e_2, ..., e_N)$</li>
<li>$x_{e_n}$ : $\text{SP}_{ij}$ 에서 $n$번째 edge $e_n$의 feature</li>
<li>$w_n^E \in \R^{d_E}$ : $n$번째 weight embedding(learnable embedding)</li>
<li>$d_E$ : edge feature의 dimensionality</li>
</ul>
<p>💡 spatial encoding할때도 shortest path를 learable scalar로 mapping해줬으니까 좀더 global한 단위의 edge feature도 마찬가의 방법으로 해준듯, 경로상 각 edge의 weight는 learnable하게 둬서 알아서 학습되도록</p>
<p>💡 노드간 거리말고 graph의 structural한 정보를 encoding한다면?
ex. 특정 구조의 subgraph -&gt; 후속 논문으로 나온 <a href="https://arxiv.org/abs/2202.03036">Structure-Aware Transformer for Graph Representation Learning</a> 의 베이스 아이디어!</p>
<h2 id="32-implementation-details-of-graphormer">3.2 Implementation Details of Graphormer</h2>
<h3 id="graphormer-layer">Graphormer Layer</h3>
<p>Built upon <a href="https://velog.io/@sujin_yun_/Attention-is-all-you-need#self-attention">classic Transformer encoder</a></p>
<ul>
<li>Multi-head self-attention(MHA)와 Feed-foward block(FFN)이전에 Layer Normalization(LN) 추가<ul>
<li><strong><a href="https://arxiv.org/abs/2002.04745">On Layer Normalization in the Transformer Architecture</a></strong></li>
</ul>
</li>
<li>FFN sub-layer에 대해서는 input, output, inner-layer를 $d$ dimension으로 통일</li>
</ul>
<p>$$
h^{
′
(l)} = MHA(LN(h^{
(l−1)})) + h^{
(l−1)}\
h^{
(l)} = FFN(LN(h^{
′
(l)}
)) + h^{
′
(l)}
$$</p>
<h3 id="special-node">Special Node</h3>
<p>Graph embedding을 만들기 위한 graph pooling function</p>
<ul>
<li>inspired by <strong><a href="https://arxiv.org/abs/1704.01212">Neural Message Passing for Quantum Chemistry</a></strong></li>
</ul>
<p><strong><em>[VNode]</em></strong></p>
<ul>
<li>그래프 내의 모든 노드와 각각 연결</li>
<li>Aggregate-Combine 단계에서 그냥 일반 노드처럼 업데이트되고. 이를 통해 그래프 전체의 representation $h_G$가 이 Vnode의 representation이됨</li>
<li>BERT에서 CLS 토큰을 sequence의 시작마다 두고 마지막에 문장 분류같은 sequence단위 downstream task에 쓰는거랑 마찬가지</li>
</ul>
<p>☹️근데 그래프 내에 모든 노드랑 연결되어있으니까 shortest path가 항상 1! 근데 얘는 virtual connection이지, 실제연결이 아님</p>
<p>💡 reset all spatial encodings for $b_{ϕ([VNode],v_j)}$ and $b_{ϕ(v_i,[VNode])}$ to a distinct learnable scalar</p>
<ul>
<li>inspired by <strong><a href="https://arxiv.org/abs/2006.15595">Rethinking Positional Encoding in Language Pre-training</a></strong></li>
</ul>
<h2 id="33-how-powerful-is-graphormer">3.3 How Powerful is Graphormer?</h2>
<p><strong><em>Fact 1. By choosing proper weights and distance function ϕ(Spatial encoding을위한 SPD를 scalar mapping해주는 function), the Graphormer layer can represent AGGREGATE and COMBINE steps of popular GNN models such as GIN, GCN, GraphSAGE.</em></strong></p>
<ol>
<li>self attention을 계산할 때 spatial encoding이 들어가서 노드의 neighbor set(SPD=1) 구분 가능 → softmax적용해서 이웃노드셋에 대한 평균 계산 가능</li>
<li>node의 degree를 위에서 구한 이웃노드셋에 대한 평균에다 곱해주면 sum으로 변환 가능</li>
<li>멀티헤드 어텐션, FFN을 통해 노드 v, 그리고 이웃 노드셋의 representation은 따로 계산된 후에 나중에 합쳐짐 ← FFN은 vanilla transformer에서도 토큰단위로 따로 들어가는 거였음</li>
</ol>
<p>😀 spatial encoding으로 WL test보다 더 expressive한 GNN(1WL test가 MPNN)</p>
<ul>
<li>appendixA에서 WL test로 구분하지 못하는 그래프를 grpahormer로 구분하는거랑 다른 GNN의 special case인거 증명</li>
</ul>
<p><strong>Connection between Self-attention and Virtual Node.</strong></p>
<p><strong>[VNode]</strong> Readout function처럼 전체그래프의 information을 aggregate하는 역할</p>
<p>☹️ can potentially lead to inadvertent over-smoothing of information propagation</p>
<p><strong><a href="https://arxiv.org/abs/1902.01020">Graph Warp Module: an Auxiliary Module for Boosting the Power of Graph Neural Networks in Molecular Graph Analysis</a></strong></p>
<p><strong><em>Fact 2. By choosing proper weights, every node representation of the output of a Graphormer layer without additional encodings can represent MEAN READOUT functions.</em></strong></p>
<ul>
<li>self attention은 전체 노드를 attend ⇒ simulate graph-level READOUT operation to aggregate information from the whole graph</li>
<li>Theoretically 뿐만아니라 empirically No over-smoothing problem ⇒ vnode추가로 graph readout 구현</li>
</ul>
<h1 id="4-experiments">4. Experiments</h1>
<h2 id="41-ogb-large-scale-challenge">4.1 OGB Large-Scale Challenge</h2>
<ul>
<li>graph-level prediction dataset</li>
</ul>
<h2 id="42-graph-representation">4.2 Graph Representation.</h2>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/1ec0007b-1f9f-49df-8518-bce4d02e97df/image.png" alt=""></p>
<h2 id="43-ablation-studies">4.3 Ablation Studies</h2>
<p><strong><em>Node Relation Encoding</em></strong></p>
<p>Positional encoding employed by previous Transfomer based-GNN</p>
<ul>
<li>Weisfeiler-LehmanPE (WL-PE) : <strong><em><a href="https://arxiv.org/abs/2001.05140">Graph-Bert: Only Attention is Needed for Learning Graph Representations</a></em></strong></li>
<li>Laplacian PE : <strong><em><a href="https://dl.acm.org/doi/10.1162/089976603321780317">Laplacian Eigenmaps for dimensionality reduction and data representation</a></em></strong></li>
</ul>
<p>💡위의 Positional encoding방법론들을 적용한 것 보다 spatial encoding을 적용한게 더 잘됨</p>
<p><strong><em>Centrality Encoding</em></strong></p>
<p>💡없는거보다 있는게 더 잘됨 → transformer architecture로 그래프 데이터를 모델링하는데 centrality encoding을 적용하는게 필수!</p>
<p><strong><em>Edge Encoding</em></strong></p>
<p><a href="https://www.notion.so/Do-Transformers-Really-Perform-Badly-for-Graph-Representation-Graphormer-67c83066a35945c39a2c2370a1ebca2d">traditional ways to encode edge</a></p>
<p>💡proposed edge encoding performs better</p>
<h1 id="5-related-work">5. Related Work</h1>
<h2 id="51-graph-transformer">5.1 Graph Transformer</h2>
<h2 id="52-structural-encodings-in-gnns">5.2 Structural Encodings in GNNs</h2>
<p><strong><em>Path and Distance in GNNs</em></strong></p>
<ul>
<li><strong><em><a href="https://arxiv.org/abs/1905.12712">Path-Augmented Graph Transformer Network</a> :</em></strong> node features, edge features, one-hot feature of the distance and ring flag feature 들을 attention 계산 시 활용</li>
</ul>
<p><strong><em>Positional Encoding in Transformer on Graph</em></strong></p>
<ul>
<li><strong><em><a href="https://arxiv.org/abs/2001.05140">Graph-Bert: Only Attention is Needed for Learning Graph Representations</a></em></strong> :<ul>
<li>absolute WL-PE, intimacy based PE, hop based PE</li>
</ul>
</li>
<li><strong><em><a href="https://arxiv.org/abs/2012.09699">A Generalization of Transformer Networks to Graphs</a></em></strong> : Absolute Laplacian PE</li>
</ul>
<p><strong><em>Edge Feature</em></strong></p>
<ul>
<li><strong><em><a href="https://arxiv.org/abs/1809.02709">Exploiting Edge Features in Graph Neural Networks</a></em></strong> : node similarity를 활용해 edge feature weight</li>
<li><strong><em><a href="https://arxiv.org/abs/1810.00826">How powerful are graph neural networks?</a></em></strong> : project edge features to an embedding vector and multiply it by attention coef, and send the result to an additional FFN sub-layer to produce edge representations</li>
</ul>
<h1 id="6-conclusion">6. Conclusion</h1>
<ul>
<li>graph structural encodings<ul>
<li>Centrality Encoding</li>
<li>Centrality Encoding</li>
<li>Edge Encoding</li>
</ul>
</li>
<li>works well on wide range of popular benchmark datasets</li>
<li>challange<ul>
<li>quadratic complexity of the self-attention module restricts Graphormer’s application on large graphs</li>
</ul>
</li>
</ul>
<blockquote>
<p>💡 GAT와 Transformer : GAT에서는 node embedding의 semantic한 similarity를 기반으로 attention을 구했다면, Transfomer는 여기에 degree centrality, spatial encoding, edge feature를 추가한 attention을 계산. 이 세가지를 attention을 구하는데 집어넣는 과정에서 각각의 representation에 대해 learnable한 function들을 도입하여 학습 과정에서 그 weight를 학습하게되는 방식.
Attention을 사용했을 때 장점은 노드의 이웃여부와 관계없이 모든 노드를 attend할 수 있다는 것 ⇒ global receptive field
🤷 그럼 기존 MPNN 레이어를 쌓아서 hop을 늘리면 되는거 아니냐 라고하면? 
⇒ 그랬을때는 oversmoothing problem(increasing the number of GNN layers, the features tend to converge to the same value)이 있음
💡 Transfomer가 CNN, LSTM, GNN, GCN 같은 애들보다 잘하는건 적은 inductive bias때문이라고 할 수 있을거 같다. 기존 모델들은 들어가는 데이터의 특성(이미지의 경우 locality, 시계열의 경우 sequential)을 살린 모델 구조라서 inductive bias가 세게 걸려있다고 할 수 있다.
반면 Transformer는 그런거 없이 개별토큰이 모든 intput에 대해 attend하기도 하고, locality나 sequentiality같은 것들은 positional encoding으로 상대적으로 약하게 걸려있다고 할 수 있다. ⇒ inductive bias가 적게 걸려있어서 NN이 학습할 수 있는게 더 많았다! ⇒ 데이터가 많을때 더 잘 작동한다!
🤷 근데 그럼 데이터가 적은데 transformer를 사용하려면? 
⇒ 추가적인 inductive bias를 줄 수 있는 방법에 대해 고민해봐야할 듯</p>
</blockquote>
]]></description>
        </item>
        <item>
            <title><![CDATA[Autoencoder의 모든 것 - 1/2 (Deep learning basic revisit,  Manifold learning)]]></title>
            <link>https://velog.io/@sujin_yun_/Autoencoder%EC%9D%98-%EB%AA%A8%EB%93%A0-%EA%B2%83</link>
            <guid>https://velog.io/@sujin_yun_/Autoencoder%EC%9D%98-%EB%AA%A8%EB%93%A0-%EA%B2%83</guid>
            <pubDate>Thu, 19 Jan 2023 13:02:01 GMT</pubDate>
            <description><![CDATA[<p>&lt;Reference&gt;
<a href="https://www.youtube.com/watch?v=o_peo6U7IRM&amp;list=PLsFtzQAC8dDetav3jSCKB_MXwvUn7yfJS&amp;t=1s">오토인코더의 모든 것 - 1/3</a></p>
<p>GAN리뷰를 마치고 같은 플레이 리스트의 오토인코더의 모든 것 강의를 듣기 시작했다! 여행 가기전에 다 듣고 가고싶었지만 맘이 붕뜨는 바람에 다 못들었었는데, 일단 Autoencoder의 introduction을 위한 Deep learning basic revisit과 Manifold learning 파트까지는 들었기 때문에 유럽행 경유지인 홍콩 공항에서 지금까지 들은 부분 먼저 올려보자,, 해서 올리는 글! 다음 비행기까지 2시간이나 남았는데 유튜브나 넷플릭스는 더이상 보기 싫어서 뒷부분 강의도 들어보려구 한다,,, 팟팅,,,</p>
<p>Autoencoder → purpose of nonlinear dimensionality reduction</p>
<p>🤷‍♂️ <strong><em>nonlinear dimensionality reduction</em></strong>?</p>
<ul>
<li>Representation learning</li>
<li>Feature extraction</li>
<li>Manifold learning</li>
</ul>
<p><strong>Autoencoder’s 4 Main keywords</strong></p>
<ol>
<li>Unsupervised Learning → 학습 방법</li>
<li>Manifold Learning → encoder : 차원 축소의 역할</li>
<li>Generative Model Learning → decoder : 생성 모델의 역할</li>
<li>ML(Maximum Likelihood) Density Estimation → Loss function : negative ML</li>
</ol>
<ul>
<li>입력과 출력이 같은 결과를 내도록 하는 구조</li>
</ul>
<h1 id="1-revisit-deep-neural-networks">1. Revisit Deep Neural Networks</h1>
<h2 id="machine-learning-problem">Machine learning problem</h2>
<p><strong><em>Classical Machine Learning</em></strong></p>
<ol>
<li><p>collecting training data</p>
</li>
<li><p>define functions</p>
<ol>
<li>output</li>
<li>Loss function</li>
</ol>
</li>
<li><p>learning/training</p>
<ol>
<li>loss가 최소화되는 optimal parameter 찾기</li>
</ol>
</li>
<li><p>predicting/testing</p>
<ol>
<li>optimal function output계산</li>
</ol>
<p>*Note. 고정된 입력값에 대한 고정된 출력값 생성</p>
</li>
</ol>
<p><strong><em>⇒ Deep Neural Networks</em></strong></p>
<ol>
<li><p>collecting training data</p>
</li>
<li><p>define function</p>
<ol>
<li>Deep Neural Net<ol>
<li>네트워크 구조</li>
<li>레이어 수</li>
</ol>
</li>
<li>Loss function<ol>
<li>MSE, CrossEntropy</li>
</ol>
</li>
</ol>
<ul>
<li><p>Backpropagation을 통해 DNN을 학습시키기 위한 조건들</p>
<p>  <strong>Assumption1.</strong> Total loss of DNN over training samples is the sum of loss for each training sample : training DB의 전체 샘플들의 각 loss의 합을 DNN의 total loss로 본다.</p>
<p>  <strong>Assumption2.</strong> Loss for each training example is a function of final output of DNN : loss function의 입력은 정답과 네트워크의 출력값 두가지로만 이루어져있다.</p>
</li>
</ul>
</li>
<li><p>learning/training</p>
<ol>
<li><p>Gradient descent</p>
<p> $$
 \theta^* = \text{argmin }<em>{\theta \in \Theta} L(f</em>{\theta}(x),y)
 $$</p>
</li>
<li><p>Iterative Method : step by step</p>
<ol>
<li>How to update $\theta → \theta+\Delta \theta$ ⇒ Only if  $L(\theta+\Delta \theta) &lt; L( \theta)$ : Loss가 줄어들 때</li>
<li>when to stop search ⇒ If $L(\theta+\Delta \theta) == L( \theta)$ : Loss의 변동이 없을 때</li>
<li>How to find $\Delta \theta$ so that $L(\theta+\Delta \theta) &lt; L( \theta)$ ⇒ $\Delta \theta = -\eta \nabla L$  where $\eta &gt; 0$ : learning rate</li>
</ol>
<ul>
<li><p>어떻게 $\theta$를 업데이트 해야 Loss 값이 줄어드는지?</p>
<p>  $\small L(\theta+\Delta\theta) = L(\theta)+\nabla L \cdot\Delta\theta + \text{second derivative} + \text{third derivative} + \dots$ → <strong><em>Taylor Expansion</em></strong></p>
<p>  $\small L(\theta+\Delta\theta) \approx L(\theta)+\nabla L \cdot\Delta\theta$  → <strong><em>Approximation</em></strong> : 더 많은 미분 차수를 사용할 수록 더 넓은 지역을 작은 오차로 표현 가능</p>
<p>  $\small L(\theta+\Delta\theta)-L(\theta) = \Delta L =  \nabla L \cdot\Delta\theta$ → $\Delta L &lt;0$  이어야함</p>
<p>  If $\Delta \theta = -\eta \nabla L$, then $\Delta L = -\eta ||\nabla L||^2 &lt; 0$, where $\eta &gt; 0$ and called learning rate</p>
<p>  *$\nabla L$ = gradient of L, steepest increasing direction of $L$</p>
</li>
</ul>
</li>
<li><p>parameter들에 대해 Loss function의 미분이 필요 → Backropagation</p>
<ol>
<li><p>Error at output layer </p>
<p> $$
 \delta^L = \nabla_aC\odot\sigma&#39;(z^L)
 $$</p>
<ul>
<li>$C$ : Cost(Loss)</li>
<li>$a$ : final output of DNN</li>
<li>$\sigma(\cdot)$ : activation function</li>
<li>가장 마지막 출력단의 error signal을 구하는 과정 → loss를 network 출력값에 대해 미분 : $\nabla_aC$ &amp; activation function의 미분에 feedfoward 값을 넣은 값 element-wise product</li>
</ul>
</li>
<li><p>Error relationship between two adjacent layers → 바로 앞레이어와의 error relationship을 통해 가장 앞 레이어의 loss까지 구함</p>
<p> $$
 \delta^l = \sigma&#39;(z^l)\odot\left( \left(w^{l+1} \right)^T\delta^{l+1}\right)
 $$</p>
</li>
<li><p>Gradient of C in terms of bias</p>
<p> $$
 \nabla_{b^l}C = \delta^l
 $$</p>
</li>
<li><p>Gradient of C in terms of weight</p>
<p> $$
 \nabla_{W^l}C = \delta^l(a^{l-1})^T
 $$</p>
</li>
</ol>
</li>
</ol>
</li>
</ol>
<pre><code>    [Neural networks and deep learning](http://neuralnetworksanddeeplearning.com/chap2.html)</code></pre><ol start="4">
<li>predicting/testing</li>
</ol>
<h2 id="loss-function-viewpoints-i--backpropagation">Loss function viewpoints I : Backpropagation</h2>
<ul>
<li>Backpropagation이 얼마나 잘 동작하는가의 관점에서는 MSE &lt; Cross Entropy Loss</li>
<li>Maximum Likelihood 관점 : output의 형태에 따라<ul>
<li>continuous value : MSE</li>
<li>discrete value : Cross Entropy Loss</li>
</ul>
</li>
</ul>
<p><strong><em>Type 1. Mean Square Error / Quadratic loss</em></strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/634ffe26-6437-4986-a824-0a95ef2ccd10/image.png" alt=""></p>
<p>$$
\begin{aligned}
&amp;C = (a-y)^2/2 = a^2/2 \ &amp;\nabla_aC = (a-y)\
&amp; \delta = \nabla_aC  \odot \sigma&#39;(z) = (a-y)\sigma&#39;(z)
\end{aligned}
$$</p>
<ul>
<li><p>Loss $C$ = MSE ⇒ (입력-정답)^2/2</p>
</li>
<li><p>$\nabla_aC$ : C를 a에 대해 미분</p>
</li>
<li><p>$\delta$ : error signal</p>
</li>
<li><p>$\frac{\partial C}{\partial w} = x\delta = \delta$ → $w = w-\eta\delta$</p>
</li>
<li><p>$\frac{\partial C}{\partial b} = \delta$ → $b=b-\eta\delta$</p>
</li>
<li><p>Gradient Vanshing problem</p>
<ul>
<li>출력 레이어에서의 에러값에 activation function 의 미분값이 곱해지는데($\sigma&#39;(z^L)$), 이때 그 값이 0에 가까워질 경우, error signal($\delta$)도 0에 가까워져 레이어간 업데이트가 전혀 이루어지지 않게 된다.</li>
<li>초기값의 영향을 크게 받는다!</li>
</ul>
</li>
</ul>
<p><strong><em>Type 2. Cross Entropy</em></strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/6a94178f-0bc4-4ef7-a168-5f5425688904/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/0818a40d-e7ca-4829-9d72-724f09a9dfbf/image.png" alt=""></p>
<ul>
<li>Cross Entropy의 출력 layer의 error signal($\delta$)는 $\sigma&#39;(z^L)$  term자체가 사라져서 gradient vanishing problem에서 자유로운 편, 초기값의 영향이 적다.<ul>
<li>btw, 레이어를 여러개 사용하면 결국 activation function 의 미분값이 계속해서
곱해지므로 gradient vanishing problem에서 완전히 자유로운건 아님.</li>
</ul>
</li>
</ul>
<h2 id="loss-function-viewpoints-ii--maximum-likelihood">Loss function viewpoints II : Maximum likelihood</h2>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/3032d3aa-9f2f-4082-8a93-d57164c1221f/image.png" alt=""></p>
<ul>
<li>x축 : 특정 값 → 모델의 출력, 정답 등,,,</li>
<li>y축 : 해당 값이 분포에서 등장할 확률</li>
<li>분포 : 가정한 분포, 특정 값이 해당 모델에서 도출될 확률 분포</li>
<li>어떤 파라미터의 모델이 있을 때, 그때의 출력값으로 정답 y의 확률을 높이는 모델인지 보고, 그 확률을 최대화하는 과정</li>
<li>결국에는 가장 높은 확률을 갖는 평균과 정답 y가 일치하게 되는 것이 목표</li>
<li>그렇게 모델의 최적 확률 분포를 찾게 되면, 그 분포에서의 sampling을 통해 y와 비슷하지만 다른 어떤 값을 생성하는 과정으로 이어지게 됨</li>
</ul>
<p>Conditional probability $p$가 어떤 분포를 따르는지 가정하에 다음을 진행 → ex. Gaussian Dist.</p>
<p>$p\left(y|f_{\theta}\left(x\right)\right)$ → Network출력값이  $f_{\theta}\left(x\right)$로 주어졌을 때, 정답 $y$가 나올 확률이 최대화 되어야함</p>
<ul>
<li>Network출력값 $f_{\theta}\left(x\right)$ : Conditional probability $p$를 추정하기 위한 parameter 개념(ex. Gaussian의 경우 평균값,,,)</li>
</ul>
<p><strong>log-likelihood</strong></p>
<p>loss : $-\log \left( p \left(y|f_{\theta}\left (x\right )\right)\right)$</p>
<p><strong>주어진 데이터를 가장 잘 설명하는 모델 찾기 →</strong> Maximum log-likelihood되는 파라미터</p>
<p>$\theta^* = \argmin_\theta[-\log \left( p \left(y|f_{\theta}\left (x\right )\right)\right)]$</p>
<p>⇒ Conditional probability $p$의 분포의 parameter를 찾은 것 ⇒ 확률 분포를 찾은 것 → sampling이 가능하다!</p>
<p><strong>*Extension. 생성모델</strong></p>
<p>확률 분포에서 sampling을 통해 새로운 input을 만들어 낼 수 있고, 새로운 출력이 나오게 된다.</p>
<p>$y_{new} \sim p(y|f_{\theta^*}\left(x_{new}\right))$</p>
<p>$\text{i.i.d Condition on }p \left(y|f_{\theta}\left (x\right )\right)$</p>
<p><strong>Assumption1. Independece</strong> : train db모두의 conditional prob가 아닌 각 sample($D_i$)의 conditional prob의 곱으로 추정</p>
<p>$$
p \left(y|f_{\theta}\left (x\right )\right) = \prod_i p_{D_i} \left(y|f_{\theta}\left (x_i\right )\right)
$$</p>
<p><strong>Assumption2. Identical Distribution</strong> : 모든 샘플의 distribution을 같다고 가정</p>
<p>$$
p \left(y|f_{\theta}\left (x\right )\right) = \prod_i p \left(y|f_{\theta}\left (x_i\right )\right)
$$</p>
<p>⇒ 결론 : 두개의 가정을 모두 만족</p>
<p>$$
-\log \left( p \left(y|f_{\theta}\left (x\right )\right)\right) = -\sum_i \log \left( p \left(y_i|f_{\theta}\left (x_i\right )\right)\right)
$$</p>
<p>분포를 다음 두가지로 가정해볼 수 있음 (일변수 - Univariate)</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/1d23ed2e-c89f-4190-9614-cf9df365d5a9/image.png" alt=""></p>
<ul>
<li>Gaussian Distribution의 경우 MSE</li>
<li>Bernoulli Distribution의 경우 Cross-Entropy</li>
</ul>
<p>각각과 같이 loss가 정리된다.</p>
<p>다변수의 경우도 마찬가지.</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/8c70f1c3-b332-46f2-8e9f-52fb665bf5f2/image.png" alt=""></p>
<ul>
<li>Autoencoder<ul>
<li>$p(x|x)$</li>
<li>network 입력 x일때 출력도 입력과 같아지는것이 목표</li>
</ul>
</li>
<li>Variational Autoencoder<ul>
<li>$p(x)$</li>
<li>training db의 확률분포 그 자체를 추정</li>
</ul>
</li>
</ul>
<h1 id="2-manifold-learning">2. Manifold Learning</h1>
<h2 id="definition">Definition</h2>
<p>Visualize의 편의성을 위해 고차원 데이터($R^m$)를 저차원 데이터($R^d$)로 차원 축소할 때, </p>
<p><strong><em>Manifold</em></strong> : 고차원 데이터 포인트들을 error없이 잘 아우르는 subspace가 있을 것. 그것을 manifold라고 하고, maifold에서 projection하게되면 저차원 데이터로 매핑할 수 있을 것.</p>
<h2 id="four-objectives">Four objectives</h2>
<ol>
<li>Data visualization</li>
<li>Curse of dimensionality<ul>
<li>차원이 증가할수록, 공간내 샘플의 수가 매우 희박해진다</li>
<li>Manifold Hypothesis(assumption)<ul>
<li>샘플을 아우르는, 잘 밀집된 저차원의 subspace(=Manifold)를 잘 찾으면, 해당 Manifold를 벗어나면 밀도가 매우 희박해진다.</li>
</ul>
</li>
</ul>
</li>
<li>Discovering most important features<ul>
<li>Manifold 좌표들이 조금씩 변화할 때 원래 데이터도 조금씩 변함을 확인</li>
<li>New distance metric → Euclidean distance ≠ Manifold의 distance ⇒ dominant한 feature representation상 가까운 sample들을 찾을 수 있음, 의미적인 interpolation이 가능하다</li>
<li>Entangled Manifold vs. Disentangled Manifold<ul>
<li>dominant feature를 잘 capture했을 경우 disentangled manifold의 형태가 됨을 확인할 수 있음</li>
</ul>
</li>
</ul>
</li>
</ol>
<h2 id="dimension-reduction">Dimension reduction</h2>
<p>Texonomy</p>
<ol>
<li>Linear<ol>
<li>PCA</li>
<li>LDA</li>
</ol>
</li>
<li>Non-linear<ol>
<li>AE</li>
<li>t-SNE</li>
</ol>
</li>
</ol>
<p>이중에서도 Non-linear dimension reduction method에 해당하는 Autoencoder에 대해 앞으로 더 자세히 알아볼 예정!</p>
]]></description>
        </item>
        <item>
            <title><![CDATA[GAN 완전 정복 - Generative Adversarial Network(GAN)]]></title>
            <link>https://velog.io/@sujin_yun_/GAN-%EC%99%84%EC%A0%84-%EC%A0%95%EB%B3%B5-1.-Generative-Adversarial-NetworkGAN</link>
            <guid>https://velog.io/@sujin_yun_/GAN-%EC%99%84%EC%A0%84-%EC%A0%95%EB%B3%B5-1.-Generative-Adversarial-NetworkGAN</guid>
            <pubDate>Sun, 01 Jan 2023 13:46:27 GMT</pubDate>
            <description><![CDATA[<p>&lt;Reference&gt;
<a href="https://www.youtube.com/watch?v=odpjk7_tGY0">https://www.youtube.com/watch?v=odpjk7_tGY0</a></p>
<h2 id="generative-model의-goal">Generative Model의 Goal</h2>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/ee03d788-cde6-4fa1-9625-520df90a7127/image.png" alt=""></p>
<ul>
<li>$p_{\text{data}}(x)$에 근사하는 $p_{\text{model}}(x)$를 찾기</li>
<li>$p_{\text{data}}(x)$ : 실제 학습 데이터의 분포</li>
<li>$p_{\text{model}}(x)$ : 모델이 생성한 데이터의 분포</li>
<li>두 분포의 차이를 최소화하기</li>
</ul>
<h2 id="brief-introduction---gangenerative-adversarial-networks">Brief Introduction - <strong>GAN</strong>(Generative Adversarial Networks)</h2>
<ul>
<li>$D$(Discriminator Model)</li>
<li>$G$(Generator Model)</li>
</ul>
<p>최종 목표는 $G$를 학습하는 것, 이를 위해  $D$를 먼저 학습시킬 필요가 있음</p>
<p><strong><em>STEP 1) $D$ 학습시키기</em></strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/ff2600a2-0c89-4e86-82f7-47a8f878be09/image.png" alt=""></p>
<ul>
<li>진짜 이미지는 1, 가짜 이미지는 0 라벨로 분류하는 것이 학습 목적</li>
<li>Input : 고정 이미지 벡터</li>
<li>Output : Binary, 1dim, sigmoid(0.5)</li>
</ul>
<p><strong><em>STEP 2) $G$ 학습시키기</em></strong></p>
<ul>
<li>랜덤한 코드(latent code $z$)를 받아 이미지를 생성</li>
<li>생성한 이미지로 $D$를 속이는 것이 목표 → $D$의 output이 1이 되도록</li>
<li>학습할 수록 진짜같은 가짜이미지를 생성하게됨</li>
</ul>
<h2 id="objectiveloss-function-of-gan"><strong>Objective(Loss) Function of GAN</strong></h2>
<p>$$
\min_{G} \max_{D} V(D, G) = E_{x\sim p_{data}(x)}[\log D(x)]+E_{z\sim p_z(z)}[\log(1-D(G(z)))]
$$</p>
<p><strong>A. <em>Discriminator</em> 관점</strong></p>
<ul>
<li>목적함수를 <strong>최대화</strong>하는 것이 목적</li>
</ul>
<ol>
<li>Left Term : $E_{x\sim p_{data}(x)}[\log D(x)]$</li>
</ol>
<ul>
<li>$x\sim p_{data}(x)$ : 확률 밀도 함수, 실제 데이터에서 샘플링,</li>
<li>$\log D(x)$ 최대화 : 실제 데이터에서 받은 데이터를 입력으로 받으면, $D$는 1에 가까운 값을 출력해야함, $D(x)$는 0~1사이 값을 출력</li>
</ul>
<ol start="2">
<li>Right Term : $E_{z\sim p_z(z)}[\log(1-D(G(z)))]$</li>
</ol>
<ul>
<li>$z\sim p_z(z)$ : z는 Generator로 들어가는 입력, 표준 정규 분포/uniform 분포에서 랜덤하게 추출된 100차원의 벡터</li>
<li>$G(z)$ : Random 하게 생성한 벡터를 입력으로 받아 Generate한 이미지, 출력은 가짜 이미지</li>
<li>$D(G(z))$ : 이를 다시 Discriminator에 넣어 Fake, Real Binary classification</li>
<li>$\log(1-D(G(z)))$ : $D(G(z))$값이 0일때 최대 = $z$로 부터 생성된 가짜 이미지를 가짜로 분류하였을때 최대값을 가짐 = 학습 목표</li>
</ul>
<p><strong>B. <em>Generator</em> 관점</strong></p>
<ul>
<li>목적함수를 <strong>최소화</strong>하는 것이 목적</li>
</ul>
<ol>
<li>Left Term : $E_{x\sim p_{data}(x)}[\log D(x)]$</li>
</ol>
<ul>
<li>실제이미지를 discriminate하는 것과 Generator는 독립</li>
</ul>
<ol start="2">
<li>Right Term : $E_{z\sim p_z(z)}[\log(1-D(G(z)))]$</li>
</ol>
<ul>
<li>가짜이미지를 입력으로 받았을 때 Discriminator가 진짜 이미지로 분류하도록 하는 것이 목적</li>
<li>$D(G(z))$ 값이 1일때 최소 = z로 부터 생성된 가짜 이미지를 진짜로 분류하였을때 최소값을 가짐 = 학습 목표</li>
</ul>
<h3 id="pytorch-implementation">Pytorch Implementation</h3>
<p><a href="https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html">DCGAN Tutorial - PyTorch Tutorials 1.13.1+cu117 documentation</a></p>
<pre><code class="language-python">import torch
import torch.nn. as nn

D = nn.Sequential(
    nn.Linear(784 ,128),
    nn.ReLU(),
    nn.Linear(128, 1),
    nn.Sigmoid())

G = nn.Sequential(
    nn.Linear(100, 128),
    nn.ReLU(),
    nn.Linear(128, 784),
    nn.Tanh()) # 생성된 값이 -1 ~ 1

criterion = nn.BCELoss() # Binary Cross Entropy Loss(h(x), y)

d_optimizer = torch.optim.Adam(D.parameters(), lr=0.01) #maximize
g_optimizer = torch.optim.Adam(G.parameters(), lr=0.01) #minimize
# 충돌하기에 2개의 optimizer를 설정

while True:
    # train D
    loss = criterion(D(x), 1) + criterion(D(G(z)), 0)
    loss.backward() # 모든 weight에 대해 gradient값을 계산
    d_optimizer.step()

    # train G
    loss = criterion(D(G(z)), 1)
    loss.backward()
    g_optimizer.step() # generator의 파라미터를 학습</code></pre>
<p>Binary Cross Entropy Loss $(h(x),y)$</p>
<p>$$
-y\log h(x) -(1-y)\log (1-h(x))
$$</p>
<pre><code class="language-python">criterion = nn.BCELoss()</code></pre>
<p>Loss function</p>
<p>$$
\min_{G} \max_{D} V(D, G) = E_{x\sim p_{data}(x)}[\log D(x)]+E_{z\sim p_z(z)}[\log(1-D(G(z)))]
$$</p>
<pre><code class="language-python">loss = criterion(D(x),1) + criterion(D(G(x)),0)</code></pre>
<ul>
<li><code>criterion(D(x),1)</code> : $-\log D(x)$</li>
<li><code>criterion(D(G(x)),0)</code> : $-\log(1-D(G(x)))$</li>
</ul>
<p>**Note : Gradient Descent로 학습되기 때문에 기존 loss function에 -를 붙여준 형태</p>
<p>**Train $G$에서 주의할 점</p>
<ul>
<li>Generator를 학습할 때 Discriminator는 고정이어야함.</li>
<li>optimizer를 $D,G$ 파라미터에 대해 각각 설정해두고, genrator학습 시 <code>g_optimizer.step()</code>만 수행</li>
</ul>
<h3 id="non-saturating-gan-loss">Non-Saturating GAN Loss</h3>
<p>$G$의 objective Function</p>
<p>$$
\min_{ G }{V(G)} = { E }<em>{ z\sim { p }</em>{ z }( z)  }[ \log { (1-D(G(z)))  }  ]
$$</p>
<ul>
<li>$log(1-x)$ 그래프</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/aa51c900-797e-41a0-b391-02b9fb06eaf5/image.png" alt=""></p>
<p>$G$는 학습 초반에 매우 평편없는 이미지를 생성하게 되고, $D$는 이를 가짜 이미지라고 확신하게됨 → $D$가 0에 매우 가까운 값을 출력</p>
<p>⚠️ 이때의 gradient가 상대적으로 작다</p>
<p>💡 $log(1-x)$를 최소화 하는 대신 $log(x)$를 최대화 하자</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/4dd22991-baf7-4c71-80a2-0f72c8d76386/image.png" alt=""></p>
<p>→ 상대적으로 큰 graident</p>
<p>⇒ 초반에 Generator가 매우 안좋은 상황을 최대한 빠르게 벗어날 수 있게됨</p>
<p><strong><em>Implementation</em></strong></p>
<pre><code class="language-python">loss = criterion(D(G(z)), 1)</code></pre>
<h2 id="why-does-gans-work">Why does GANs work?</h2>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/06ef40d5-d3b5-44bc-a0de-00491c9516d8/image.png" alt=""></p>
<p>GAN의 loss function을 최대화 하는 것이 실제 데이터와 가짜 데이터의 분포 차이를 줄이는 것이 맞는가? → O</p>
<p>$$
\begin{aligned}
&amp;\min_ { G }\max_ { D }{ V( D,G)    }\\iff &amp;\min_ {G,D} JSD(p_{\text{data}} \vert \vert p_g)\end{aligned}
$$</p>
<p>어떤식으로 GAN이 학습되는지 돌아보고 다시 아래에서 증명을 이어서 해보자! </p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/c2557705-c45c-4a3a-ba0b-21be31e46b76/image.png" alt=""></p>
<ul>
<li>파란색 점선 : $D$, discriminative distribution (판별 모델의 분포)</li>
<li>검정색 점선 : $p_x$, 데이터에서 생성된 분포 (원본 데이터의 분포)</li>
<li>초록색 실선 : $p_g(G)$ , generative distribution (생성 모델의 분포)</li>
<li>z 실선 : uniformly sampling된 z의 domain</li>
<li>z → x 화살표 : $x=G(z)$ 매핑, non-uniform 분포 $p_g$로 변환되는 과정</li>
<li>x 실선 : 매핑/변환된 x</li>
</ul>
<p>GAN은 Discriminative distribution과 동시에 실제 데이터에서 샘플링하여 생성된 분포 $p_x$와 Generator를 통해 생성된 분포에서 샘플링한 $p_g(G)$를 구분하도록 학습</p>
<p>$G$ contracts in regions of high density and expands in regions of low density of $p_g$.</p>
<p>(a) $x=G(z)$ 매핑을 통해 만들어진 가짜 분포 $p_g$</p>
<p>(b) $D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)}$을 통해 판별 모델 확률 분포 $D$ 업데이트</p>
<p>(c) $p_g$가 $p_{\text{data}}$에 가깝도록 업데이트</p>
<p>(d) 학습을 계속 반복하여 $p_g = p_{\text{data}}$ 가 되면 두 분포를 구분할 수 없어져 $D(x) = \frac{1}{2}$로 수렴</p>
<ul>
<li><p>어떻게 $P_g$가 $P_{\text{data}}$로 수렴할 수 있게 될까?</p>
<ul>
<li>Proof. Global Optimality</li>
</ul>
<ol>
<li><p>G가 고정되어있는 상황에서 D의 optimal point $D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x)+p_g(x)}$</p>
<p> <img src="https://velog.velcdn.com/images/sujin_yun_/post/02ed0592-7aae-4ede-b9bc-f1058a5bc23b/image.png" alt=""></p>
</li>
</ol>
</li>
</ul>
<pre><code>2. G의 global optimum은 $p_g = p_{\text{data}}$에 있다.

    ![](https://velog.velcdn.com/images/sujin_yun_/post/2cd3d185-baed-42a4-a301-7c1b2ebf6591/image.png)</code></pre><ul>
<li>KL divergence      <br>


</li>
</ul>
<pre><code>Note. BCE 

$$
BCE = \sum_{x\in{0, 1}}\left(-P(x)\log(Q(x))\right)
$$

- $P(x)$ = 희망하는 타겟에 대한 결괏값
- $Q(x)$ = 모델에서 출력한 출력값
- Q라는 모델의 결과에 대해 P라는 이상적인 값을 기대했을 때 그와 실제 결과의 차이에 대한 감각</code></pre><p> <a href="https://angeloyeo.github.io/2020/10/27/KL_divergence.html">KL divergence</a></p>
<p> 확률분포 $P$를 모델링한다고 할때, 이산 확률 분포 $P$와 $Q$가 동일한 샘플 공간 $x$에서 정의된다고 하면 KL divergence는 다음과 같다.</p>
<pre><code>$$
\begin{aligned}
D_{KL}(P\|Q) 
&amp;= \sum_{x\in \chi}P(x)\log_b\left(\frac{P(x)}{Q(x)}\right)\\
&amp;=-\sum_{x\in \chi}P(x)\log_b\left(\frac{Q(x)}{P(x)}\right)\\
&amp;=-\sum_{x\in\chi}P(x)\log_b Q(x) + \sum_{x\in\chi}P(x)\log_b P(x)
\end{aligned}
$$

이를 기댓값($=\sum x\times\text{prob}(x)$)으로 치환하면

$$
\Rightarrow -E_P[\log_bQ(x)]+E_P[\log_bP(x)]
$$

*여기서 $E_P$는 $P(x)$라는 확률 분포에 대한 기댓값 연산임을 의미

이를 전개하면

$$
\Rightarrow H_P(Q) - H(P)
$$

*여기서 $H_P(Q)$는 $P$를 기준으로 봤을 때 $Q$에대한 cross entropy, $H(P)$는 $P$에 대한 정보 엔트로피

$H_P(Q)$ : **어떠한 확률분포 P가 있을 때, 샘플링 과정에서 확률분포 Q를 P 대신 사용할 경우 엔트로피**

$H_P(Q) - H(P)$ : 위에서 $H(P)$를 빼주게 되면, 기존에서의 엔트로피의 **변화**를 의미하게됨

- 항상 0이상
- aysymmetric : distance개념이 아니다.</code></pre><ul>
<li><p>JSD(Jensen-Shannon Divergence)</p>
<p>  KL divergence를 distance metric으로 쓸 수 있는 방법은 없을까</p>
<p>  $M$을 확률 분포 $P$와 $Q$의 <strong>평균</strong>이라고 할 때</p>
<p>  $$
  JSD(p||q) = \frac{1}{2}KL(p||M)+\frac{1}{2}KL(q||M)\
  where, M=\frac{1}{2}(p+q)
  $$</p>
<ul>
<li>symmetric → <strong>distance개념</strong></li>
</ul>
</li>
</ul>
<h3 id="algorithm">Algorithm</h3>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/598bffcc-04e9-4ce4-a0ec-cd1786dd6472/image.png" alt=""></p>
<h2 id="variations-of-gan">Variations of GAN</h2>
<h3 id="1-dcgandeep-convolutional-gan">1. DCGAN(Deep Convolutional GAN)</h3>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/2d6bd2e7-9c81-492d-b5d5-ae9ed9e590ae/image.png" alt=""></p>
<ul>
<li>Discriminator<ul>
<li>CNN</li>
</ul>
</li>
<li>Generator<ul>
<li>deep convolutional NN</li>
<li>deconvolution, transpose convolution → upsampling</li>
</ul>
</li>
<li>No pooling layer</li>
<li>stride size&gt;2 의 convolution,deconvolution</li>
<li>BN</li>
<li>Adam optimizer<ul>
<li>Momentum = 0.5, 0.999</li>
<li>64x64이미지를 사용할때 실험적으로 위 숫자들을 사용할 때 성능이 좋은 것을 확인</li>
</ul>
</li>
<li>Generator의 입력인 Latent vector $z$간의 산술적 연산이 가능! (선형적 관계)<ul>
<li>ex. man with glasses - man without glassed + woman without glasses ⇒ woman with glasses</li>
</ul>
</li>
</ul>
<h3 id="2-lsganleast-squares-gan">2. LSGAN(Least Squares GAN)</h3>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/f841029a-2cf1-4958-ba98-a9742d4ff6cf/image.png" alt=""></p>
<ul>
<li>기존의 GAN Loss → $D$를 속이기만 하면 됨</li>
<li>파란색 선  = $D$의 decision boundary → 낮으면 진짜, 높으면 가짜</li>
<li>빨간색 점들 → 진짜 이미지</li>
<li>파란색 점들 → 가짜 이미지<ul>
<li>⇒ 빨간점에 가까이 있는 파란 점들은 잘만든 가짜 이미지</li>
</ul>
</li>
<li>핑크색 점들 → discriminator를 완벽히 속인 가짜 이미지 (Decision boundary완전 안쪽에 있어서)</li>
</ul>
<p>💡 그렇다고 핑크색 점들이 잘 만들어진 이미지인가? ⇒ NO</p>
<p>🤷 why? ⇒ 실제 이미지에 가깝게 만들어진게 잘 만들어진 이미지, discriminator를 완벽히 속였어도, 실제와 비슷하다는 보장을 할 수가 없다.</p>
<p>⇒ LSGAN에서는 핑크색 점들을 decision boundary근처로 끌어 올린다.</p>
<p>Vanilla GAN → LSGAN</p>
<ul>
<li>$D$의 마지막 레이어 sigmoid 제거</li>
<li>$G$는 동일</li>
<li>Cross entropy loss ⇒ Least squeares loss</li>
<li>LSGAN - loss of D<ul>
<li>(D(x)-1)**2 → 진짜 이미지 D(x)는 1에 가깝게</li>
<li>(D(G(z))**2 → 가짜 이미지 D(G(z))는 0에 가깝게</li>
</ul>
</li>
<li>LSGAN - loss of G<ul>
<li>(D(G(z))-1)**2 → 가짜 이미지 D(G(z))는 1에 가깝게</li>
</ul>
</li>
<li>cross entropy loss와의 차이 :<ul>
<li>1에 최대한 가까운 값이 나오도록 조정하게됨</li>
</ul>
</li>
</ul>
<p><strong>*Note. 코드로 비교해보자~!</strong></p>
<ol>
<li>Vanilla GAN</li>
</ol>
<pre><code class="language-python">import torch
import torch.nn. as nn

D = nn.Sequential(
    nn.Linear(784 ,128),
    nn.ReLU(),
    nn.Linear(128, 1),
    nn.Sigmoid())

G = nn.Sequential(
    nn.Linear(100, 128),
    nn.ReLU(),
    nn.Linear(128, 784),
    nn.Tanh()) 

#Loss of D
D_loss = -torch.mean(torch.log(D(x))) - torch.mean(torch.log(1-D(G(z))))))

#Loss of G
G_loss = -torch.mean(torch.log(D(G(z))))</code></pre>
<ol start="2">
<li>LSGAN</li>
</ol>
<pre><code class="language-python">import torch
import torch.nn. as nn

D = nn.Sequential(
    nn.Linear(784 ,128),
    nn.ReLU(),
    nn.Linear(128, 1)) #1. Remove sigmoid

G = nn.Sequential(
    nn.Linear(100, 128),
    nn.ReLU(),
    nn.Linear(128, 784),
    nn.Tanh())

#Loss of D
D_loss = -torch.mean((D(x)-1)**2) - torch.mean(D(G(z))**2))

#Loss of G
G_loss = -torch.mean((D(G(z))-1)**2)</code></pre>
<h3 id="3-sgansemi-supervised-gan">3. SGAN(Semi-Supervised GAN)</h3>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/0dbd1c06-9323-4f1e-9545-abf85eb8e24b/image.png" alt=""></p>
<ul>
<li>MNIST data</li>
<li>$D$가 진짜/가짜를 구분하는 것이 아닌 class를 구분(0~9) + Fake class를 추가해 11개의 class ⇒ softmax ⇒ one-hot vector</li>
<li>$G$는 one-hot vector + latent vector $z$를 input으로 받아 fake image생성<ul>
<li>$D$는 이 이미지는 fake로 분류해야함</li>
</ul>
</li>
<li>$D$는 라벨이 있어야 하는 supervised learning, $G$는 generator가 만든 이미지로 분류하는 unsupervised learning ⇒ Semi-Supervised GAN</li>
</ul>
<h3 id="4-acganauxiliary-classifier-gan">4. ACGAN(Auxiliary Classifier GAN)</h3>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/344525f8-22ba-400e-8e78-86f2111db5e0/image.png" alt=""></p>
<ul>
<li>$D$ → Multi-task learning<ol>
<li>진짜이미지 vs 가짜이미지 (0 or 1) → sigmoid</li>
<li>이미지의 진위 여부와 관계 없이 0~9중 어떤 숫자에 해당하는지 → softmax</li>
</ol>
<ul>
<li>노이즈가 포함된 이미지의 분류에 집중</li>
</ul>
</li>
<li>$G$<ul>
<li>input  = one-hot vector + latent vector $z$</li>
<li>여기서 생성한 가짜 이미지로 $D$는 다음 두가지 task 시행<ol>
<li>진짜이미지 vs 가짜이미지 (0 or 1)</li>
<li>이미지의 진위 여부와 관계 없이 0~9중 어떤 숫자에 해당하는지 </li>
</ol>
</li>
<li>Data augmentation의 효과 (Noise가 포함된 이미지)</li>
</ul>
</li>
</ul>
<p>⇒ Loss의 경우 두가지 task의 loss합한 것을 사용</p>
<h2 id="extensions-of-gan">Extensions of GAN</h2>
<h3 id="1-cyclegan--unpaired-image-to-image-translation">1. CycleGAN : Unpaired Image-to-Image Translation</h3>
<ul>
<li>이미지의 style, domain을 바꾸는 task</li>
</ul>
<p>💡 Pair image가 없는 unsupervised 상태에서도 이러한 task의 학습이 가능하지 않을까?</p>
<p>⇒ How does it work?</p>
<p>ex. 얼룩말 이미지를 말로 변환하기</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/1203ddf9-4c33-471a-8896-8409743d493f/image.png" alt=""></p>
<ul>
<li>$D$<ul>
<li>말 이미지만 받게 되고, 진짜라고 학습</li>
</ul>
</li>
<li>$G$<ul>
<li>latent code $z$대신 Real image입력을 받게됨</li>
<li>차원을 줄였다가 다시 복구하는 encoder decoder 구조</li>
<li>얼룩말 이미지를 받아 $D$를 속이기 위해 말 모양으로 변환</li>
</ul>
</li>
</ul>
<p>**Note. 얼룩말 이미지를 말로 변환하되, 이미지의 형태는 유지해야함!</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/9d0ea300-25bc-45ff-8c4e-a84856e25cad/image.png" alt=""></p>
<ul>
<li>$G_{\text{BA}}$로 다시 원래 이미지로 복원하려면 모양이 최대한 적게 바뀌어야함 → reconstrunction error를 줄이는 방향</li>
</ul>
<p><strong><em>Implementation</em></strong></p>
<p><a href="https://github.com/yunjey/mnist-svhn-transfer">https://github.com/yunjey/mnist-svhn-transfer</a></p>
<h3 id="2-stackgan--text-to-photo-realistic-image-synthesis">2. StackGAN : Text to Photo-realistic Image Synthesis</h3>
<ul>
<li>text를 주고 그에 해당하는 이미지 생성</li>
</ul>
<p>⚠️ 128x128, 256x256 고해상도 이미지를 $z$벡터에서 바로 생성하기 어렵다는 문제</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/6379a291-06b7-411c-a73b-4101bb23ece4/image.png" alt=""></p>
<p>💡 64x64 저해상도 이미지를 먼저 생성한 후 이를 기반으로 또다른 Generator로 upsampling하기</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/ac8f362d-3a96-419d-b75c-c1c4c2fe26a2/image.png" alt=""></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[Understanding Convolutions on Graphs]]></title>
            <link>https://velog.io/@sujin_yun_/Understanding-Convolutions-on-Graphs</link>
            <guid>https://velog.io/@sujin_yun_/Understanding-Convolutions-on-Graphs</guid>
            <pubDate>Wed, 21 Dec 2022 08:28:43 GMT</pubDate>
            <description><![CDATA[<p>&lt;References&gt;
<a href="https://distill.pub/2021/understanding-gnns/">Understanding Convolutions on Graphs</a></p>
<h2 id="the-challenges-of-computation-on-graphs"><strong>The Challenges of Computation on Graphs</strong></h2>
<ol>
<li><strong><em>Lack of Consistent Structure</em></strong></li>
</ol>
<ul>
<li>ex. molecule; 각각 다른 수/종류의 atom을 포함하고 다른 수/종류의 connection을 가짐</li>
</ul>
<ol start="2">
<li><strong><em>Node-Order Equivariance</em></strong></li>
</ol>
<ul>
<li>원래는 노드에 순서가 없지만, 임의로 부여 ⇒ node-order equivariant</li>
</ul>
<ol start="3">
<li><strong><em>Scalability</em></strong></li>
</ol>
<ul>
<li>very large graph, but sparse</li>
</ul>
<h2 id="problem-setting-and-notation"><strong>Problem Setting and Notation</strong></h2>
<ul>
<li><strong>Node Classification:</strong> Classifying individual nodes.</li>
<li><strong>Graph Classification:</strong> Classifying entire graphs.</li>
<li><strong>Node Clustering:</strong> Grouping together similar nodes based on connectivity.</li>
<li><strong>Link Prediction:</strong> Predicting missing links.</li>
<li><strong>Influence Maximization:</strong> Identifying influential nodes.</li>
</ul>
<p>→ 문제 해결에 선행하여 node representation learning이 필요</p>
<p>$$
G = (V,E)
$$</p>
<ul>
<li>Undirected Graph</li>
<li>$x_v$ : node features for node $v \in V$</li>
<li>$h_v^{(k)}$ : kth layer(iteration)을 거친 뒤 node v의 representation</li>
<li>$M_v$ : matrix M에서 node v의 property</li>
</ul>
<h2 id="extending-convolutions-to-graphs"><strong>Extending Convolutions to Graphs</strong></h2>
<p>ordinary convolutions : not node-order invariant</p>
<ul>
<li>이미지의 경우 pixel의 위치에 영향을 받음</li>
</ul>
<p>⇒ How to generalize convolutions to general graph?</p>
<h2 id="polynomial-filters-on-graphs"><strong>Polynomial Filters on Graphs</strong></h2>
<ul>
<li>CNN에서 주변 pixel에대해 localized filter를 적용하는 것처럼 주변 노드들에 대해 polynomial filter적용하기</li>
</ul>
<h3 id="the-graph-laplacian"><strong>The Graph Laplacian</strong></h3>
<ul>
<li>A : Adjacency Matrix</li>
<li>D : Degree Matrix</li>
</ul>
<p>$$
D_v = \sum_u{A_{vu}}
$$</p>
<ul>
<li>L = Graph Laplacian, $n\times n$ matrix</li>
</ul>
<p>$$
L = D-A
$$</p>
<h3 id="polynomials-of-the-laplacian"><strong>Polynomials of the Laplacian</strong></h3>
<ol>
<li>Graph Laplacian을 이해하기 위한 polynomial 만들기<ul>
<li>polynomial : CNN에서의 필터에 해당하는 느낌</li>
<li>coefficient w : 필터의 가중치</li>
</ul>
</li>
</ol>
<p>$$
p_w(L) = w_0I_n + w_1L + w_2L^2 + \dots + w_dL^d = \sum_{i=0}^d w_iL^i
$$</p>
<p>이 polynomial의 계수들을 다음의 벡터로 나타낼 수 있다. → $w = [w_0, \dots, w_d]$</p>
<ul>
<li>모든 $w$, $p_w(L)$은 $n \times n$ matrix</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/046df7e4-f907-4384-9ed6-ba0c6875343d/image.png" alt=""></p>
<p>Fixing a node order (indicated by the alphabets) and collecting all node features into a single vector <em>x</em></p>
<ul>
<li><p>node feature $x_v$가 실수라고 할때, 이를 stacking하여 single vector $x$를 만들 수 있고, 이때 $x \in \mathbb{R}^n$이다.</p>
</li>
<li><p>feature vector $x$에 대해 polynomial filter $p_w$로 convolution을 적용하면 다음과 같이 나타낼 수 있다.</p>
<p>  $$
  x&#39; = p_w(L)\ x
  $$</p>
</li>
</ul>
<p>💡 1.  $p_w(L)= \sum_{i=0}^d w_iL^i$ 에서 계수 $w$가 convolution에 어떤 영향을 미치는가?</p>
<ul>
<li>ex1. $w_0 = 1$, $w_i = 0$  for   $i$ ≥1 일때</li>
</ul>
<p>$$
x&#39; = p_w(L)\ x = \sum_{i=0}^d w_iL^ix = w_0I_nx = x
$$</p>
<ul>
<li>ex2. $w_1 = 1$, $w_i = 0$  for   $i ≠1$ 일때</li>
</ul>
<p>$$
\begin{aligned} {x&#39;}<em>v= (Lx)_v &amp;= L_vx  \ &amp;=\sum</em>{u \in G}L_{vu}x_u \&amp;= \sum_{u \in G}(D_{vu}-A_{vu})x_u \&amp;=D_vx_v - \sum_{u \in N(v)}x_u \end{aligned}
$$</p>
<ul>
<li>Adjacency matrix * x  →  이웃 노드들의 feature합계</li>
</ul>
<p>💡 2. Polynomial의 차수 d는 convolution에 어떤 영향을 미치는가?</p>
<ul>
<li><p><strong>Lemma 5.2</strong> from <strong>Wavelets on graphs via spectral graph theory</strong></p>
<p>  <a href="https://www.sciencedirect.com/science/article/pii/S1063520310000552">Wavelets on graphs via spectral graph theory</a></p>
<p>  Let $G$ be a weighted graph, $\mathcal{L}$ the graph Laplacian (normalized or non-normalized) and s &gt; 0 an integer. For any two
  vertices m and n, if  $d_G(m,n) &gt; s$  then $(\mathcal{L}^s)_{m,n} = 0$.</p>
</li>
</ul>
<pre><code>**Proof.**

![](https://velog.velcdn.com/images/sujin_yun_/post/337fcea7-7661-4256-8f1b-42e66554760a/image.png)


![](https://velog.velcdn.com/images/sujin_yun_/post/bb5e97a2-2671-438e-b584-e3454d8fadd8/image.png)

- s-1 길이의 sequence $k_1, k_2, \dots, k_{s-1}$ with $1≤k_r≤N$
- 노드 m,n사이의 Laplacian의 s제곱($(\mathcal{L}^s)_{m,n}$)은 m에서 n까지 도달하는 s-1길이의 path들의 노드들사이 Laplacian의  곱의 합(path들간의 합)이라고 할 수 있음
- 증명하려는 것과 반대로, $(\mathcal{L}^s)_{m,n}$가 non-zero이려면, sum이 진행되는 term(Laplacian matrix의 곱)들 중 적어도 하나가 non-zero이어야 한다.
- 즉, $\mathcal{L}_{m,k_1} \neq 0, \mathcal{L}_{k_1,k_2} \neq 0, \dots,\mathcal{L}_{k_{s-1},n} \neq 0.$  인 $k_1, k_2, \dots, k_{s-1}$(path)이 존재한다. ⇒ 노드 m,n사이에 길이가 s인 path가 존재한다.
- 반복되는 노드를 제거할경우, “노드 m,n사이에 길이가 s보다 작은 path가 존재한다”고 정리할 수 있다.
- 즉, $(\mathcal{L}^s)_{m,n} = 0$ 이려면, 노드 m,n사이에 길이가 s보다 짧은 path가 존재하지 않는다. ⇒ 두 노드 사이 거리는 s보다 크다.</code></pre><p>다시 돌아와서 Polynomial의 차수 d가 convolution에 미치는 영향에 대해 보면,</p>
<p>$$
\text{dist}<em>G(v,u) &gt; i \Rightarrow L</em>{vu}^i = 0
$$</p>
<p>$x&#39;$를 얻기 위해 $x$를 차수가 $d$인 polymonial $p_x(L)$로 대체하면,</p>
<p>$$
\begin{aligned} x&#39;<em>v = (p_w(L)x)_v &amp;= (p_w(L))_vx  \ &amp;=\sum</em>{i=0}^{d}w_iL_{v}^ix \&amp;= \sum_{i=0}^dw_i\sum_{u \in G}L_{vu}^ix_u \&amp;=\sum_{i=0}^dw_i \  \sum_{u \in G, \ \text{dist}_G(v,u) \le i}x_u \end{aligned}
$$</p>
<ul>
<li>노드 v에서의 convolution은 d hop보다 멀지 않은 노드들에 대해서만 적용됨<ul>
<li>localized polynomial filters, d의 크기에 따라 localization의 정도 변동</li>
</ul>
</li>
</ul>
<h3 id="chebnet">ChebNet</h3>
<p>위에서 사용했던 polynomial filter는 다음과 같이 정의됨</p>
<p>$$
p_w(L) = \sum_{i=0}^d w_iL^i
$$</p>
<p>ChebNet에서는 polynomial filter를 다음의 형태로 수정하여 사용</p>
<p>$$
p_w(L) = \sum_{i=1}^d w_iT_i(\tilde{L})
$$</p>
<ul>
<li><p>$T_i$ : i차의 1종 체비세프 다항식</p>
<ul>
<li><a href="https://freshrimpsushi.github.io/posts/chebyshev-differential-equation-and-chebyshev-polynomial/">체비세프 다항식</a></li>
</ul>
</li>
<li><p>$\tilde{L}$ : L의 가장 큰 eigen value를 사용해 정의된 normalized Laplacian</p>
<p>  $$
  \tilde{L} = \frac{2L}{\lambda_{\text{max}}(L)}-I_n
  $$</p>
<ul>
<li>L → positive semi-definite : L의 모든 eigenvalue들은 0보다 작지 않다.</li>
<li>$\lambda_{\text{max}} &gt; 1$ 이라면,  L의 제곱들은 급격하게 크기가 커지게 되는데, L을 효율적으로 scale-down한 $\tilde{L}$의 경우 eigenvalue들이 [-1,1]의 구간에 있음을 보장하여 제곱값의 크기가 끝없이 커지는 것을 막는다.<ul>
<li>unnormalized Laplacian $L$에 대해 높은 차원의 계수의 크기 제한</li>
<li>normalized Laplacian $\tilde{L}$에 대해서는 더 큰 값의 계수 허용</li>
</ul>
</li>
<li>chebyshev polynomial → interpolation을 수치적으로 안정적이게 만드는 특성</li>
</ul>
</li>
</ul>
<h3 id="polynomial-filters-are-node-order-equivariant"><strong>Polynomial Filters are Node-Order Equivariant</strong></h3>
<p>Polynomial filter</p>
<ul>
<li><p><strong>node order에 independent</strong> ← $p_w$의 차원이 1이고, x가 이웃 노드의 feature를 aggregate한 value인 경우를 떠올리면 이해하기 쉬움(ex. 합계는 순서와 상관이 없음)</p>
</li>
<li><p>proof.</p>
<p>  permutation matrix $P$ : 정사각 이진 행렬, 각 행에 값이 1인 요소가 하나 있고, 나머지는 0의 값을 가짐. 다른 matrix $A$ 를 곱해주었을 때 $A$의 각 row를 permutating해주는 것과 같은 효과라고 이해하면 됨.(=행 교환을 수행하는 행렬)</p>
<p>  $$
  PP^T =P^TP = I_n
  $$</p>
<p>  function $f$ : node-order equivariant</p>
<p>  $$
  f(Px) = Pf(x)
  $$</p>
<p>  permutation matrix $P$를 활용해 새로운 node-order를 만들어내면, 다음과 같은 변환이 수행된다.</p>
<p>  $$
  \begin{aligned}
  x &amp;\rightarrow Px\L&amp;\rightarrow PLP^T \ L^i &amp;\rightarrow PL^iP^T
  \end{aligned}
  $$</p>
<p>  $f(x) = p_w(L)x$ 와 같은 polynomial filter가 있을 때, 다음과 같이 정리할 수 있다.</p>
<p>  $$
  \begin{aligned} f(Px) &amp;= \sum^{d}<em>{i=0}w_i(PL^iP^T)(Px)\ &amp;=P\sum^{d}</em>{i=0}w_iL^ix\&amp;=Pf(x)
  \end{aligned}
  $$</p>
</li>
</ul>
<h3 id="embedding-computation">Embedding Computation</h3>
<ul>
<li>$K$ different polynomial filter layer<ul>
<li>$k^{th}$ layer의 learnable weights $w^{(k)}$</li>
</ul>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/01449a6f-9a45-489f-9b00-67146588014f/image.png" alt=""></p>
<ul>
<li>$w^{(k)}$의 weight를 가진 polynomial filter를 $L$에 적용하여 matrix $p^{(k)}$를 계산</li>
<li>$p^{(k)}$에 $h^{(k-1)}$를 곱해 $g^{(k)}$를 계산</li>
<li>$g^{(k)}$에 non-linearity $\sigma$를 적용하여 $h^{(k)}$를 계산</li>
<li>CNN에서의 weight-sharing(동일한 필터를 여러 grid에 적용)과 마찬가지로, 다른 노드들에 같은 weight를 가진 filter를 적용</li>
</ul>
<h2 id="modern-graph-neural-networks"><strong>Modern Graph Neural Networks</strong></h2>
<p>$$
p_w(L) = w_0I_n + w_1L + w_2L^2 + \dots + w_dL^d
$$</p>
<ul>
<li>$w_1 = 1$, 나머지 $w_i$들은 모두 0</li>
<li>$p_w(L) = L$</li>
<li>$p_w$의 차원 d ⇒ 얼마나 localized된 필터를 사용할 것인가</li>
</ul>
<p>$$
\begin{aligned} x&#39;<em>v  &amp;= L_vx  \ &amp;=\sum</em>{u \in G}L_{vu}x_u \&amp;= \sum_{u \in G}(D_{vu}-A_{vu})x_u \&amp;=D_vx_v - \sum_{u \in N(v)}x_u \end{aligned}
$$</p>
<ul>
<li><em>Aggregation :</em> 바로 이웃하는 노드 feature $x_u$들을 aggregate</li>
<li><em>Combination :</em> 자기자신의 feature $x_v$를 합침</li>
</ul>
<p>💡 Polynomial filter를 사용해 가능한 것과 별개로 다른 종류의 <em>“Aggregation”, “Combination”</em> 를 사용하면 어떨까?</p>
<ul>
<li>Aggregation이 node-order equivariant하다면, convolution 전체가 node-order equivariant하다.</li>
<li>바로 이웃하는 노드들 사이의 “message-passing”과정이라고 이해할 수 있다.</li>
<li>1-hop localized convolution을 K번 반복하면, K-hop만큼 멀리에 있는 노드들까지 receptive field를 늘릴 수 있다.</li>
</ul>
<h3 id="embedding-computation-1">Embedding Computation</h3>
<p>Message-passing을 backbone으로 하는 많은 GNN Architecture들</p>
<ul>
<li><a href="https://openreview.net/forum?id=SJU4ayYgl">Graph Convolutional Networks (GCN)</a></li>
<li><a href="https://openreview.net/forum?id=rJXMpikCZ">Graph Attention Networks (GAT)</a></li>
<li><a href="https://proceedings.neurips.cc/paper/2017/file/5dd9db5e033da9c6fb5ba83c7a7ebea9-Paper.pdf">Graph Sample and Aggregate (GraphSAGE)</a></li>
<li><a href="https://openreview.net/forum?id=ryGs6iA5Km">Graph Isomorphism Network (GIN)</a></li>
</ul>
<ol>
<li><p><em>Graph Convolutional Networks (GCN)</em></p>
<p> <img src="https://velog.velcdn.com/images/sujin_yun_/post/a6211434-c168-4815-abae-18239953da32/image.png" alt=""></p>
</li>
</ol>
<pre><code>- 각 k 단계별로 학습가능한 function $f^{(k)}$, matrics $W^{(k)}$, $B^{(k)}$는 모든 노드들에 걸쳐 공유됨</code></pre><ol start="2">
<li><p><em>Graph Attention Networks (GAT)</em></p>
<p> <img src="https://velog.velcdn.com/images/sujin_yun_/post/d5beb7b4-bc21-4f36-964e-f01c9f85bc73/image.png" alt=""></p>
</li>
</ol>
<pre><code>- 각 k 단계별로 학습가능한 function $f^{(k)}$, matrics $W^{(k)}$, $B^{(k)}$, Attention $A^{(k)}$는 모든 노드들에 걸쳐 공유됨
- multi-head attention</code></pre><ol start="3">
<li><p><em>Graph Sample and Aggregate (GraphSAGE)</em></p>
<p> <img src="https://velog.velcdn.com/images/sujin_yun_/post/bb4484a8-8899-41a5-8d6a-c6f7e04def54/image.png" alt=""></p>
</li>
</ol>
<pre><code>- 각 k 단계별로 학습가능한 function $f^{(k)}$, matrics $W^{(k)}$, $\text{AGG}$는 모든 노드들에 걸쳐 공유됨
- $\text{AGG}$의 선택
    - Mean(GCN과 유사)

        ![](https://velog.velcdn.com/images/sujin_yun_/post/2211fce0-b814-451c-921a-05b41e44266b/image.png)


    - Dimension-wise Maximum

        ![](https://velog.velcdn.com/images/sujin_yun_/post/6459b63b-e2dc-4f7c-9f89-cde42a54e795/image.png)


    - LSTM (after ordering the sequence of neighbours)
- neighbourhood sampling : 노드의 이웃노드 수에 관계 없이 고정된 수의 노드들을 random sampling하여 GraphSAGE가 매우 큰 그래프에도 적용될 수 있게됨, Node embedding의 variance는 증가</code></pre><ol start="4">
<li><p><em>Graph Isomorphism Network (GIN)</em></p>
<p> <img src="https://velog.velcdn.com/images/sujin_yun_/post/1ead5133-7768-426a-a748-4d6557523b30/image.png" alt=""></p>
</li>
</ol>
<pre><code>- 각 k 단계별로 학습가능한 function $f^{(k)}$, real-valued parameter $\epsilon^{(k)}$는 모든 노드들에 걸쳐 공유됨</code></pre><p><strong>Prediction</strong></p>
<ul>
<li>최종적으로 계산된 embedding을 사용해 각 노드에 대한 prediction을 만들어내는 방법은 다음과 같다.</li>
</ul>
<p>$$
\hat{y_v} = \text{PREDICT}(h_v^{(K)})
$$</p>
<ul>
<li>$\text{PREDICT}$ : 또다른 Neural Net, 각 GNN을 학습할 때 같이 학습</li>
</ul>
<h2 id="from-local-to-global-convolutions"><strong>From Local to Global Convolutions</strong></h2>
<p>message passing을 반복적으로 수행하여 그래프 전체에서 한 노드로 정보가 모일 수 있지만, 직접적으로 global convolution을 수행하는 방법이 있음</p>
<h3 id="spectral-convolutions"><strong>Spectral Convolutions</strong></h3>
<p>💡 feature vector $x$에 대해, Laplacian $L$을 사용해 $G$에 관해 $x$가 얼마나 smooth한지 quantify할 수 있음</p>
<p>$\sum_{i=1}^{n} x^2_i = 1$을 만족하는, 즉, normalize된 $x$에 대해</p>
<p><a href="https://en.wikipedia.org/wiki/Rayleigh_quotient">Rayleigh quotient</a>를 정의하면 다음과 같다.</p>
<p>$$
R_L(x) = \frac{x^TLx}{x^Tx} = \frac{\sum_{(i,j)\in E}(x_i-x_j)^2}{\sum_{i}x_i^2} = \sum_{(i,j)\in E}(x_i-x_j)^2
$$</p>
<ul>
<li><p>Laplacian matrix의 value가 0이면 두 노드는 인접하지 않음.</p>
</li>
<li><p>$L = D-A$</p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/ae9a750a-f5be-478f-9153-6ee9a8bdc647/image.png" alt=""></p>
</li>
</ul>
<ul>
<li>인접한 노드 feature의 차이의 제곱으로 정리할 수 있음</li>
<li>= Smoothness</li>
<li>인접한 노드 feature가 유사하면 $R_L(x)$ 값이 작아짐</li>
</ul>
<p>Laplacian matrix $L$</p>
<ul>
<li>Real, symmetric matrix</li>
<li>eigenvalues : $\lambda_1 ≤ \dots ≤ \lambda_n$이</li>
<li>이에 대응하는 $u_1, \dots, u_n$는 orthonormal</li>
</ul>
<p>$$
\begin{aligned}
    u_{k1}^Tu_{k2} = \Bigg{
        \begin{array}{ll}
        1 &amp; \text{if }k_1 = k_2,\\
        0 &amp; \text{if }k_1 \neq k_2.
        \end{array}
\end{aligned}
$$</p>
<p>$$</p>
<p>\text{argmin}_{x, x\perp{u_1, \dots, u{i-1}}} R_L(x) = u_i.
$$</p>
<p>$$
\text{min}_{x, x\perp{u_1, \dots, u{i-1}}} R_L(x) = \lambda_i.
$$</p>
<ul>
<li><p>L의 eigenvectors → successively less smooth</p>
</li>
<li><p>L의 eigenvalue들을 “spectrum”이라고 할때, L의 spectral decomposition은</p>
<p>  $$
  L = U\Lambda U^T
  $$</p>
<ul>
<li>$\Lambda$ : 정렬된 eigenvalue들의 대각행렬 = $\begin{bmatrix}\lambda_{1} &amp; &amp; \ &amp; \ddots &amp; \ &amp; &amp; \lambda_{n}\end{bmatrix}$</li>
<li>$U$ : eigenvector들의 matrix, 정렬된 eigenvalue에 대응 = $\begin{bmatrix}u_1 \dots u_n\end{bmatrix}$</li>
</ul>
</li>
</ul>
<p>eigenvector들은 orthonormality condition을 만족 :  $U^TU = I$</p>
<p>eigenvector들은 $\mathbb{R}^n$의 basis로 다음과 같이 linear combination으로 feature vector $x$를 나타낼 수 있음</p>
<p>$$
x = \sum_{i=1}^n \hat{x_i}u_i = U\hat{x}
$$</p>
<ul>
<li>$\hat{x}$ : $\begin{bmatrix}x_0 \dots x_n\end{bmatrix}$의 coefficient, spectral representation of vector $x$</li>
<li>orthonormality condition을 $x = U\hat{x}$에 적용하면, natural representation $x$와 spectral representation $\hat{x}$ 사이 변환식으로 정리할 수 있음</li>
</ul>
<p>$$
x = U\hat{x}\ \Longleftrightarrow \ U^Tx = \hat{x} </p>
<p>$$</p>
<h3 id="embedding-computation-2">Embedding Computation</h3>
<ul>
<li><p>$k$ layers → each layers’ learnable parameter $\hat{w}^{(k)}$ = filter weights</p>
</li>
<li><p>spectral representation을 계산하는데 필요한 eigenvector의 수 = $m$ = 각 layer에 필요한 weight의 수</p>
</li>
<li><p>spectral domain에서 convolution을 적용하면 direct convolution보다 더 적은 파라미터를 사용해도 됨</p>
</li>
<li><p>Laplacian eigenvector들의 smoothness덕분에, spectral representation을 사용하면 자연스럽게  주변 노드들이 유사한 representation을 갖도록하는 inductive vias를 강화할 수 있음</p>
</li>
<li><p>node feature가 1d라고 할 때, 각 layer의 output은 node representation $h^{(k)}$의 벡터로, 각 행은 node의 representation을 의미</p>
<p>  $$
  h^{(k)} = \begin{bmatrix}h^{(k)}<em>{1}\ \vdots \ h^{(k)}</em>{n}\end{bmatrix}  \quad \scriptsize \text{for each } k = 0,1,2,\dots \text{up to }K
  $$</p>
</li>
</ul>
<p>Graph $G$</p>
<ul>
<li>adjacency matrix $A$</li>
<li>degree matrix $D$</li>
<li>Lapalcian $L = D-A$</li>
</ul>
<p>$$
⁍
$$</p>
<ul>
<li>$\Lambda$ : 정렬된 eigenvalue들의 대각행렬 = $\begin{bmatrix}\lambda_{1} &amp; &amp; \ &amp; \ddots &amp; \ &amp; &amp; \lambda_{n}\end{bmatrix}$</li>
<li>$U$ : eigenvector들의 matrix, 정렬된 eigenvalue에 대응 = $\begin{bmatrix}u_1 \dots u_n\end{bmatrix}$</li>
</ul>
<p>$$
\scriptsize \color{#FE6100} \text{Computed node embeddings} \quad \color{#4D9DB5} \text{Learnable parameters}
$$</p>
<ol>
<li><p>Start with original feature $h^{(0)} = x$</p>
</li>
<li><p>Iterate,  for k=1,2,… upto K</p>
<ol>
<li><p>Convert previous feature $\color{#FE6100}{h}^{(k - 1)}$  to its spectral representation $\hat{h}^{(k - 1)}$ </p>
<p> : spectral representation으로 변환하기</p>
<p> $$
 \hat{h}^{(k - 1)}= U^T_mh^{(k - 1)}
 $$</p>
</li>
<li><p>Convolve with filter weights ${\color{#4D9DB5} \hat{w}^{(k)}}$ in the spectral domain to get ${\hat{g}^{(k)}}$, $\odot$  = element-wise multiplication </p>
<p> : weight가 $\hat{w}^{(k)}$인 filter로 spectral domain에서의 convolution적용</p>
<p> $$
 \hat{g}^{(k)} = \hat{w}^{(k)} \odot \hat{h}^{(k-1)}
 $$</p>
</li>
<li><p>Convert $\hat{g}^{(k)}$ back to its natural representation ${g}^{(k)}$ </p>
<p> : spectral → natural</p>
<p> $$
 g^{(k)} = U_m\hat{g}^{(k)}
 $$</p>
</li>
<li><p>Apply a non-linearity $\sigma$  to ${g}^{(k)}$ to get $\color{#FE6100} {h}^{(k)}$</p>
<p> $$
 h^{(k)} = \sigma (g^{(k)})
 $$</p>
</li>
</ol>
</li>
</ol>
<h3 id="spectral-convolutions-are-node-order-equivariant"><strong>Spectral Convolutions are Node-Order Equivariant</strong></h3>
<p>Laplacian polynomial filter의 node equivariant 증명에서 보인 것과 유사한 접근으로 증명 가능</p>
<ul>
<li><p>proof.</p>
<p>  node order의 변경 :  permutation matrix $P$( = 행 교환을 수행하는 행렬)와의 내적</p>
<p>  그에 따라 다음과 같은 식의 변경 발생</p>
<p>  $$
  \begin{aligned}
  x &amp;\rightarrow Px\A&amp;\rightarrow PAP^T\L&amp;\rightarrow PLP^T \ U_m &amp;\rightarrow PU_m
  \end{aligned}
  $$</p>
<p>  embedding computation에는 다음과 같은 변경</p>
<p>  $$
  \begin{aligned}
  \hat{x} &amp;\rightarrow(PU_m)^T(Px) = U^T_mx = \hat{x}\
  \hat{w}&amp;\rightarrow (PU_m)^T(Pw) = U^T_mw = \hat{w}\
  \hat{g}&amp;\rightarrow \hat{g} \ 
  g &amp;\rightarrow (PU_m)\hat{g} = P(U_m\hat{g}) = Pg
  \end{aligned}
  $$</p>
<p>  $\sigma$ 가 elemnetwise 방향으로 적용되므로</p>
<p>  $$
  f(Px) = \sigma(Pg) = P \sigma(g) = Pf(x)
  $$</p>
<p>  와 같이 정리할 수 있다. </p>
</li>
</ul>
<p>+) spectral의 $\hat{x}, \hat{w}, \hat{g}$는 node permutation이 되더라도 변하지 않는다.</p>
<p><strong>Spectral convolution의 단점</strong></p>
<ol>
<li>$L$로부터 eigenvector matrix $U_m$을 계산해야 하는데, 아주 큰 그래프에 대해서 이것이 불가능해질 수도 있다.</li>
<li>U_m 을 계산해내더라도, global convolution을 계산하는 것이 $U_m$, $U^T_m$ 을 반복적으로 곱해주어야해서 비효율적일 수 있다.</li>
<li>학습된 필터가 input그래프의 Laplacian L의 spectral decomposition에 관한것이기 때문에 그래프 specific해서 다른 구조를 가진 그래프에 transfer하여 적용하기 어렵다.</li>
</ol>
<h3 id="global-propagation-via-graph-embeddings"><strong>Global Propagation via Graph Embeddings</strong></h3>
<p>graph-level information을 node와 edge의 정보를 pooling함으로써 전체 그래프의 embedding을 계산하고, 그래프 embedding을 사용해 노드 embedding을 업데이트하여 전체 그래프의 embedding을 계산 → <a href="https://arxiv.org/abs/1806.01261">Relational inductive biases, deep learning, and graph networks</a></p>
<ul>
<li>spectral convolution이 잡아낼 수 있는 그래프의 topology를 무시하는 경향이 있음</li>
</ul>
<h2 id="learning-gnn-parameters"><strong>Learning GNN Parameters</strong></h2>
<p>embedding computations → completely differentiable ⇒ end-to-end training이 가능</p>
<p><strong>Task에 따른 Loss function $\mathcal{L}$</strong></p>
<p><strong><em>Node Classification</em></strong></p>
<p>$$
\mathcal{L}(y_v,\hat{y}<em>v)=−∑_c y</em>{vc}\log \hat{y}_{vc}
$$</p>
<ul>
<li><p>$\hat{y}_{vc}$ : node v가 class c로 예측될 확률</p>
</li>
<li><p>cross-entropy loss</p>
</li>
<li><p>semi-supervised setting에서는 다음과 같이 정의할 수 있음</p>
<p>  $$
  \mathcal{L}<em>G = \frac{\sum</em>{v \in \text{Lab}(G)}\mathcal{L}(y_v,\hat{y}_v)}{|\text{Lab}(G)|}
  $$</p>
<ul>
<li>$\text{Lab}(G)$ : labelled nodes에 대해서만 loss계산</li>
</ul>
</li>
</ul>
<p><strong><em>Graph Classification</em></strong></p>
<p>node representation을 aggregate하여 전체 그래프에 대한 representation생성</p>
<ul>
<li><p>Pooling</p>
<p>  $$
  h_G = \text{PREDICT}<em>G(\text{AGG}</em>{v \in G}({h_v}))
  $$</p>
<ul>
<li>SortPool (<a href="https://ojs.aaai.org/index.php/AAAI/article/view/11782">An End-to-End Deep Learning Architecture for Graph Classification</a>) : 그래프의 정점들을 sort하여 고정된 크기의 node-order invariant한 그래프 representation을 만들고, 일반적인 NN architecture에 적용</li>
<li>DiffPool (<a href="https://arxiv.org/abs/1806.08804">Hierarchical Graph Representation Learning with Differentiable Pooling</a>) : 정점을 클러스터링하고, 노드 대신 클러스터로 coarser graph를 만들고, coarser graph에 GNN을 적용한다. 하나의 클러스터만 남을때 까지 반복</li>
<li>SAGPool (<a href="https://arxiv.org/abs/1904.08082">Self-Attention Graph Pooling</a>) : GNN을 적용해 node score를 학습하고, 상위 score를 가진 노드만 남기고 나머지는 버림. 하나의 노드만 남을때까지 반복</li>
</ul>
</li>
</ul>
<p><strong><em>Link Prediction</em></strong></p>
<p>adjacent, non-adjacent한 노드 쌍을 sampling하여 이 벡터 쌍을 연결 유무를 예측하기 위해 사용</p>
<p>$$
\begin{aligned}
\mathcal{L}(y_v,y_u,e_{vu})&amp;=−e_{vu}\log (p_{vu})\ -\ (1-e_{vu})\log(1-p_{vu})\ 
p_{vu} &amp;= \sigma(y_v^Ty_u)
\end{aligned}
$$</p>
<ul>
<li>$e_{vu}$ : node v와 u사이에 edge 가 있으면 1, otherwise 0</li>
</ul>
<p><strong><em>Others</em></strong></p>
<p>NLP에서 ELMo나BERT에서 적용된 테크닉을 GNN에 적용해볼 수 있음</p>
<ul>
<li>local graph properties (eg. node degrees, clustering coefficient, masked node attributes)</li>
<li>global graph properties (eg. pairwise distances, masked global attributes)</li>
</ul>
<p>인접 노드가 비슷한 embedding을 갖도록 하기 위한 self-supervised technique 중 node2vec이나 DeepWalk등 random-walk와 유사한 접근을 하기도 함</p>
<p>$$
\mathcal{L}<em>G = ∑_v∑</em>{u \in N_R(v)} \log \frac{\exp z_v^Tz_u}{∑<em>{u&#39;}\exp z</em>{u&#39;}^Tz_u}
$$</p>
<ul>
<li>$N_R(v)$ : node v에서 시작하여 random-walk를 통해 방문한 node들의 multi-set</li>
</ul>
<p>아주 큰 그래프에 대해서는 Noise Contrastive Estimation을 적용하기도 함</p>
<ul>
<li><a href="https://www.jmlr.org/papers/volume13/gutmann12a/gutmann12a.pdf">Noise-Contrastive Estimation of Unnormalized Statistical Models, with Applications to Natural Image Statistics</a></li>
<li><a href="https://proceedings.neurips.cc/paper/2013/file/db2b4182156b2f1f817860ac9f409ad7-Paper.pdf">Learning word embeddings efficiently with noise-contrastive estimation</a></li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[A Gentle Introduction to Graph Neural Networks]]></title>
            <link>https://velog.io/@sujin_yun_/A-Gentle-Introduction-to-Graph-Neural-Networks-msk7tzik</link>
            <guid>https://velog.io/@sujin_yun_/A-Gentle-Introduction-to-Graph-Neural-Networks-msk7tzik</guid>
            <pubDate>Sun, 18 Dec 2022 05:27:37 GMT</pubDate>
            <description><![CDATA[<p>&lt;References&gt;
<a href="https://distill.pub/2021/gnn-intro/">A Gentle Introduction to Graph Neural Networks</a></p>
<h2 id="graphs-and-where-to-find-them"><strong>Graphs and where to find them</strong></h2>
<ol>
<li><p><strong><em>Images as graphs</em></strong></p>
<p> 224x224x3 floats → 1 pixel = 1 node</p>
<p> each nodes’ feature vector : 3-dimensional vector representing RGB value</p>
<p> non-border pixel은 8개의 이웃을 가지게됨 → adjacency matrix</p>
</li>
<li><p><strong><em>Text as graphs</em></strong></p>
<p> 단어/토큰/문자(=node)의 연결 = directed graph</p>
<p> ex. Graphs are all around us ⇒ (Graphs) → (are) → (all) → (around) → (us)</p>
</li>
</ol>
<p>하지만, image와 text의 encoding으로 graph를 잘 사용하지 않음</p>
<p>→ <strong><em>Since they have Regular structure!</em></strong></p>
<ul>
<li><p><strong><em>Graph-valued data in the wild</em></strong></p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/407a764f-f199-4fd5-aed8-36905dc6c40a/image.png" alt=""></p>
</li>
</ul>
<pre><code>1. **Molecules as graphs**
2. **Social networks as graphs**
3. **Citation networks as graphs**
4. **Other examples**</code></pre><h2 id="what-types-of-problems-have-graph-structured-data"><strong>What types of problems have graph structured data?</strong></h2>
<h3 id="1-graph-level-task">1. <strong>Graph-level task</strong></h3>
<p><strong>Goal : <em>predict the property of an entire graph</em></strong></p>
<p>ex. Molecule의 구조가 주어졌을 때 해당 분자의 특성 알아내기</p>
<h3 id="2-node-level-task">2. <strong>Node-level task</strong></h3>
<p><strong>Goal : <em>predict the identity or role of each node within a graph</em></strong></p>
<p>ex. 네트워크 내의 노드 특성 분류</p>
<h3 id="3-edge-level-task">3. <strong>Edge-level task</strong></h3>
<p><strong>Goal : <em>predict the property of an entire graph</em></strong></p>
<p>ex. 노드간의 연결 여부 예측, 연결 특성 분류</p>
<h2 id="the-challenges-of-using-graphs-in-machine-learning"><strong>The challenges of using graphs in machine learning</strong></h2>
<p>4 Types of information on Graph : <strong><em>nodes, edges, global-context, connectivity</em></strong></p>
<p><strong><em>nodes, edges, global-context</em></strong> → 노드에 id를 부여하고 Matrix만들기</p>
<p><strong><em>connectivity</em></strong> → Adjacency Matrix</p>
<p>👍) <em>easily tensoriable</em></p>
<p>👎) 노드수가 많고 연결수가 적을경우 아주 <em>sparse한 adjacency matrix*가 만들어져 *space-inefficient</em></p>
<p>👎) <em>같은 connectivity를 표현하는 adjacency matrix가 다양<em>하고, 이렇게 각각 다른 matrix가 deepNN에서 동일한 결과를 생성한다는 보장이 없음(=</em>not permutation invariant</em>)</p>
<p>Sparse matrix를 표현하는 memory efficient한 방법 = <strong><em>adjacency list</em></strong></p>
<h2 id="graph-neural-networks">Graph Neural Networks</h2>
<p><strong><em>GNN</em></strong> : optimizable transformation on all attributes of the graph (nodes, edges, global-context) that preserves graph symmetries (permutation invariances)</p>
<p>→ 그래프 대칭성을 보존하며 노드, 엣지 등 <strong>그래프의 모든 특성에 대한 optimizable transformation</strong></p>
<p><strong><em>GNN</em></strong> ← <strong><em>Graph Nets architecture schematics + message passing neural network</em></strong></p>
<p><strong><em>“graph-in, graph-out”</em></strong> : 노드/엣지/global-context의 정보를 입력으로 <strong>그래프의 연결성을 변화시키지 않으면서</strong> 임베딩을 점진적으로 변환</p>
<h3 id="the-simplest-gnn">The Simplest GNN</h3>
<p><strong><em>GNN Layer</em></strong> : <strong>Graph의 각 component(V = Node, E = Edge, U = Global-context)에 대해 별도의 MLP</strong>를 사용 </p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/96438bad-b054-4fd1-a0cd-c077d4303024/image.png" alt="A single layer of a simple GNN. A graph is the input, and each component (V,E,U) gets updated by a MLP to produce a new graph. Each function subscript indicates a separate function for a different graph attribute at the n-th layer of a GNN model."></p>
<p>A single layer of a simple GNN. A graph is the input, and each component (V,E,U) gets updated by a MLP to produce a new graph. Each function subscript indicates a separate function for a different graph attribute at the n-th layer of a GNN model.</p>
<p><strong>그래프를 input으로, 동일한 그래프 구조(연결)에 업데이트된 임베딩을 가진 그래프가 output으로 나오게 됨!</strong></p>
<h3 id="gnn-predictions-by-pooling-information"><strong>GNN Predictions by Pooling Information</strong></h3>
<p>각 노드의 업데이트된 임베딩에 대해 선형분류기를 적용하여 node prediction task를 수행할 수 있음</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/c39b3b76-4f2e-4107-a0cf-e0c7357ced8f/image.png" alt=""></p>
<p>cf. 노드에 대한 정보가 없고, 엣지에 대한 정보는 있는 상황에서 노드에 대한 예측 task를 수행해야할 경우 → 엣지에서 정보를 수집하여 예측을 위해 노드에게 해당 정보를 제공해야함 ⇒ <strong><em>Pooling</em></strong></p>
<p><strong><em>2 Steps of Pooling</em></strong></p>
<ol>
<li><p>For each item to be pooled, <em>gather</em> each of their embeddings and concatenate them into a matrix. : 풀링할 요소들의 임베딩을 행렬로 concat하여 gathering</p>
</li>
<li><p>The gathered embeddings are then <em>aggregated</em>, usually via a sum operation. : 모인 임베딩들을 aggregate(ex. sum)</p>
<p> <img src="https://velog.velcdn.com/images/sujin_yun_/post/4b5c3f46-eaf9-419f-b13d-20eb323021a2/image.png" alt=""></p>
</li>
</ol>
<p>$\rho$ : Pooling operation ⇒ gathering information form edges to node : $\rho_{E_n \rightarrow V_n}$</p>
<p><strong>Model for predicting binary node information using edge-level features</strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/0dc16fc2-db9d-47cf-9446-4535ea586686/image.png" alt=""></p>
<p><strong>Model for predicting binary edge-level information using node-level features</strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/65585fb0-e7ac-4ac0-8180-2f7fc4de5c99/image.png" alt=""></p>
<p><strong>Model for predicting binary global property using node-level features</strong></p>
<ul>
<li>CNN의 Global average pooling layer와 유사</li>
<li>분자특성 예측 task : atomic information + connectivity → toxicity of a molecule
  <img src="https://velog.velcdn.com/images/sujin_yun_/post/8359eb5f-c5d0-467c-94a0-724c2280fc5d/image.png" alt=""></li>
</ul>
<ul>
<li>Classification model $c$는 다른 differentiable model로 대체 가능</li>
</ul>
<p><strong>An end-to-end prediction task with a GNN model</strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/c8bd973e-c9f0-4119-8f4c-dba626997dc5/image.png" alt=""></p>
<p>An end-to-end prediction task with a GNN model.</p>
<ul>
<li>Simplest GNN에서는 <strong>각 GNN layer내 그래프 연결성 정보를 활용하지 않음</strong></li>
<li>각 노드/엣지는 <strong>독립적</strong>으로 처리됨</li>
<li>예측을 위해 정보를 <strong>pooling할 때만 connectivity를 활용</strong></li>
</ul>
<h3 id="passing-messages-between-parts-of-the-graph"><strong>Passing messages between parts of the graph</strong></h3>
<p>GNN layer안에서 Pooling을 활용해 graph connectivity를 고려한 임베딩을 만들어 낼 수 있음 ⇒ <strong><em>Message Passing</em></strong> : <strong>이웃하는 노드와 엣지들 사이 정보를 주고받으며 각각의 업데이트에 영향을 줌</strong></p>
<p><strong><em>Message Passing</em></strong></p>
<ol>
<li>For each node in the graph, <em>gather</em> all the neighboring node embeddings (or messages), which is the $g$ function described above. : $g$함수로 그래프의 각 노드에 대해 모든 인접노드의 임베딩을 모음</li>
<li>Aggregate all messages via an aggregate function (like sum). : 집계함수로 모인 모든 메세지들을 집계</li>
<li>All pooled messages are passed through an <em>update function</em>, usually a learned neural network. : 풀링된 모든 메세지는 학습된 NN인 update function으로 전달됨</li>
</ol>
<p>노드 또는 엣지에 풀링을 각각 적용하는 것과 같이 노드/엣지간의 message passing이 발생할 수 있음</p>
<ul>
<li>그래프의 connectivity 활용</li>
<li>GNN의 표현력 증가
  <img src="https://velog.velcdn.com/images/sujin_yun_/post/b69cca7b-381b-4fb1-a8a0-ed8e8ce589da/image.png" alt=""></li>
</ul>
<ul>
<li>Convolution과 비슷한 느낌<ul>
<li>Message passing과 convolution 모두 특정 요소의 값을 업데이트하기위해 이웃의 정보를 집계하여 처리하는 작업</li>
<li>차이점 : 이미지에서는 인접 요소의 수가 고정적이지만 그래프는 가변적</li>
</ul>
</li>
<li>Message passing GNN layer들을 쌓으면, 한 노드는 최종적으로 전체 그래프에 대한 정보를 통합할 수 있음<ul>
<li><strong>layer가 하나 쌓일때마다 정보를 모으는 노드수가 1,2,3,,,hop으로 증가</strong></li>
</ul>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/6dcc4245-8501-494c-8b9b-cd8374803c15/image.png" alt="Schematic for a GCN architecture, which updates node representations of a graph by pooling neighboring nodes at a distance of one degree."></p>
<p>Schematic for a GCN architecture, which updates node representations of a graph by pooling neighboring nodes at a distance of one degree.</p>
<h3 id="learning-edge-representations"><strong>Learning edge representations</strong></h3>
<p>*앞선 예시</p>
<p>node에 대한 예측을 수행해야 하는데 edge에 대한 정보만 가지고 있는경우</p>
<p>→ edge정보를 node에 대한 정보로 routing하기 위해 pooling을 해주는 방법 활용</p>
<p>👎) model의 마지막 prediction 단계에 대해서만 적용 가능</p>
<p>⇒ sol💡) message passing을 사용하여 GNN layer내에서 node와 edge사이 정보공유 활성화</p>
<p>👎) edge information과 node information이 같은 차원을 가지고 있다고 보장할 수 없음</p>
<p>⇒ sol💡) 서로의 information space로 mapping하는 <strong>linear function을 학습</strong> or <strong>concatencate</strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/fd1fcbe6-b1ba-406b-ab5c-954c3f4256e9/image.png" alt=""></p>
<p>Architecture schematic for Message Passing layer. The first step “prepares” a message composed of information from an edge and it’s connected nodes and then “passes” the message to the node.</p>
<p>GNN의 설계 요소 중 하나는 <strong>node embedding과 edge embedding 중 어떤 것을 먼저 업데이트할지</strong>에 대한 결정이 있음</p>
<p>ex. four updated representations that get combined into new node and edge representations: <strong><em>node to node (linear), edge to edge (linear), node to edge (edge layer), edge to node (node layer)</em></strong></p>
<p><a href="https://arxiv.org/abs/1603.00856">Molecular Graph Convolutions: Moving Beyond Fingerprints</a></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/d9a3d202-7362-4621-b3eb-180de3174e9d/image.png" alt=""></p>
<p>Some of the different ways we might combine edge and node representation in a GNN layer.</p>
<h3 id="adding-global-representations"><strong>Adding global representations</strong></h3>
<p>지금까지 설명한 네트워크들의 단점</p>
<ul>
<li>message passing을 여러번 적용하더라도 <strong>아주 멀리있는 노드들은 서로의 정보를 효율적으로 교환하기 어려움</strong></li>
<li>i.e. k개의 GNN layer를 쌓으면, k-hop 내의 노드들까지만 정보의 전파가 이루어짐</li>
<li>node prediction이 멀리 떨어져있는 노드들의 정보에 영향을 받는 경우 문제가 됨</li>
</ul>
<p>⇒ sol💡) Using <strong><em>global representation of graph(U), i.e. master node or context vector</em></strong></p>
<ul>
<li><strong><em>Global context vector</em></strong><ul>
<li>네트워크 모든 노드, 엣지들과 연결</li>
<li>information pass의 중간다리 역할</li>
<li>그래프 전체의 representaion을 만드는 역할</li>
<li>더 풍부하고 복잡한 그래프 representation</li>
</ul>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/99581034-6a1a-401a-a7e8-ebbdc9131b6a/image.png" alt=""></p>
<p>Schematic of a Graph Nets architecture leveraging global representations.</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/470d2daa-d68a-47ea-a20f-250289264e5c/image.png" alt=""></p>
<p>Schematic for conditioning the information of one node based on three other embeddings (adjacent nodes, adjacent edges, global). This step corresponds to the node operations in the Graph Nets Layer.</p>
<p>새로운 노드 임베딩을 만들어낼 때 neighboring nodes, connected edges, global information을 모두 활용할 수도 있지만, conditioning을 통해 일부만 활용할 수도 있음</p>
<ul>
<li>concatenate</li>
<li>learning linear mapping function</li>
<li>feature-wise modulation layer(featurize-wise attention mechanism)</li>
</ul>
<p><a href="https://distill.pub/2018/feature-wise-transformations/">Feature-wise transformations</a></p>
<h2 id="gnn-playground"><strong>GNN playground</strong></h2>
<ul>
<li>Graph-level prediction task</li>
<li><a href="https://zenodo.org/record/4085098#.Y4W-unZBxPY">Leffingwell Odor Dataset</a></li>
</ul>
<h3 id="some-empirical-gnn-design-lessons"><strong>Some empirical GNN design lessons</strong></h3>
<ol>
<li>a <strong><em>higher number of parameters</em></strong> does correlate with <strong><em>higher performance</em></strong><ul>
<li>GNNs are a very <strong><em>parameter-efficient model</em></strong> type: for even a small number of parameters (3k) we can already find models with high performance</li>
</ul>
</li>
<li>models with <strong><em>higher dimensionality</em></strong> tend to have <strong><em>better</em></strong> mean and lower bound <strong><em>performance</em></strong><ul>
<li>higher dimensionality = higher number of parameter 이기때문에, 위와 동일</li>
</ul>
</li>
<li>GNN with a <strong><em>higher number of layers</em></strong> will <strong><em>broadcast information at a higher distance</em></strong> <ul>
<li>노드 하나가 넓은 영역의 그래프의 노드들로부터 정보를 얻어 개별정보가 희석될 위험이 있음 → layer를 쌓을 수록 성능의 boundary가 큼</li>
</ul>
</li>
<li><strong><em>the more graph attributes</em></strong> are communicating, <strong><em>the better the performance</em></strong> of the average model</li>
</ol>
<p><strong>Approach</strong></p>
<ul>
<li>neighborhood-based pooling operation<ul>
<li>그래프 구조에 의존적인 node representation learning</li>
<li>stochastic graph traversals</li>
</ul>
</li>
<li>graph information을 얻는 새로운 mechanism들<ul>
<li><strong><a href="https://arxiv.org/abs/1806.03536">Representation Learning on Graphs with Jumping Knowledge Networks</a></strong><ul>
<li>jumping knowledge (JK) networks는 각 노드의 neighborhood set을 다르게 정의하여 structure-aware representation</li>
</ul>
</li>
<li><strong><a href="https://arxiv.org/abs/2102.04350">Graph Traversal with Tensor Functionals: A Meta-Algorithm for Scalable Learning</a></strong><ul>
<li>Graph Traversal via Tensor Functionals(GTTF) : 다양한 graph altorithm을 통해 큰 그래프에서의 효율적인 학습</li>
</ul>
</li>
<li><strong><a href="https://arxiv.org/abs/2102.04350">Graph Neural Tangent Kernel: Fusing Graph Neural Networks with Graph Kernels</a></strong><ul>
<li>infinitely wide multi-layer GNNs trained by gradient descent</li>
</ul>
</li>
<li><strong><a href="https://arxiv.org/abs/1910.10593">Neural Execution of Graph Algorithms</a></strong></li>
</ul>
</li>
</ul>
<h2 id="into-the-weeds"><strong>Into the Weeds</strong></h2>
<h3 id="other-types-of-graphs-multigraphs-hypergraphs-hypernodes-hierarchical-graphs"><strong>Other types of graphs (multigraphs, hypergraphs, hypernodes, hierarchical graphs)</strong></h3>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/ee9a7eb3-2713-4e5d-a1c0-554ebad3dfc7/image.png" alt=""></p>
<p>Schematic of more complex graphs. On the left we have an example of a multigraph with three edge types, including a directed edge. On the right we have a three-level hierarchical graph, the intermediate level nodes are hypernodes.</p>
<ul>
<li><em>multigraphs(multi-edge graphs)</em><ul>
<li>노드쌍이 여러 type의 edge를 공유</li>
<li>For example with a social network, we can specify edge types based on the type of relationships (acquaintance, friend, family).</li>
<li>GNN can be adapted by having <strong>different types of message passing steps for each edge type</strong>.</li>
</ul>
</li>
<li><em>hypernode graphs(nested graphs)</em><ul>
<li>node represents a graph</li>
<li>For example, we can consider a network of molecules, where a <strong>node represents a molecule and an edge is shared between two molecules</strong> if we have a way (reaction) of transforming one to the other</li>
<li>GNN that <strong>learns representations at the molecule level and another at the reaction network level</strong>, and alternate between them during training.</li>
</ul>
</li>
<li><em>hypergraph</em><ul>
<li>edge가 2개이상의 노드를 연결</li>
<li>build a hypergraph by identifying communities of nodes and <strong>assigning a hyper-edge that is connected to all nodes in a community</strong>.</li>
</ul>
</li>
</ul>
<h3 id="sampling-graphs-and-batching-in-gnns"><strong>Sampling Graphs and Batching in GNNs</strong></h3>
<p>👎그래프의 경우 노드와 엣지의 수가 고정적이지 않으므로 constant한 batchsize를 만들기 어려움</p>
<p>⇒ 💡 큰 그래프의 필수적인 속성을 보존하는 subgraph를 만들어 batching</p>
<ul>
<li><p>graph sampling operation</p>
<ul>
<li><p>그래프에서 노드와 엣지를 sub-selecting하는 과정을 포함하고 context에 매우 의존적</p>
</li>
<li><p><a href="https://arxiv.org/abs/1905.07953">Cluster-GCN</a>, <a href="https://arxiv.org/abs/1907.04931">GraphSaint</a> 같은 새로운 architecture, training strategy를 만들어내기도 함</p>
<p>⇒ Research Question : How to sample a graph? </p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/f1a3fdfb-5573-4096-8ac9-a19e4521275d/image.png" alt=""></p>
</li>
</ul>
</li>
</ul>
<pre><code>Four different ways of sampling the same graph. Choice of sampling strategy depends highly on context since they will generate different distributions of graph statistics (# nodes, #edges, etc.). For highly connected graphs, edges can be also subsampled.

- [Little Ball of Fur: A Python Library for Graph Sampling](https://dl.acm.org/doi/abs/10.1145/3340531.3412758)
- preserving structure at a neighborhood level
    - 동일한 숫자의 노드를 random sampling하여 node set을 만들고, edge를 포함해 node set에서 k-hop 이웃 노드들을 추가 ⇒ 이를 개별 그래프처럼 batch 학습에 활용
    - The **loss** can be masked to **only consider the node-set** since all neighboring nodes would have incomplete neighborhoods.
- 한 노드를 랜덤하게 샘플링한 후 그 노드의 k-hop까지 그래프를 확장한 뒤, 확장된 셋내의 다른 노드를 선택함, 원하는 수의 셋을 만들때 까지 반복
- Random walk
- Metropolis algorithm</code></pre><h3 id="inductive-biases">Inductive biases</h3>
<p><strong><em><a href="https://arxiv.org/abs/1806.01261">Relational inductive biases, deep learning, and graph networks</a></em></strong></p>
<p>How each graph component (edge, node, global) is related to each other so we seek models that have a relational inductive bias?</p>
<ul>
<li>A model should preserve <strong>explicit relationships between entities (adjacency matrix)</strong> and preserve <strong>graph symmetries (permutation invariance)</strong>.</li>
<li>node나 edge에의 operation 순서는 상관이 없어야하고, operation이 다양한 input에 작동해야함</li>
</ul>
<h3 id="comparing-aggregation-operations"><strong>Comparing aggregation operations</strong></h3>
<p>Aggregation function</p>
<ul>
<li>node ordering에 invariant해야함</li>
<li>differentiable해야함</li>
<li>비슷한 input에 대해 비슷한 aggregated output을 만들어내야함</li>
</ul>
<ol>
<li><strong><em>mean</em></strong></li>
</ol>
<ul>
<li>when nodes have a highly-variable number of neighbors or you need a <strong>normalized view of the features</strong> of a local neighborhood</li>
</ul>
<ol start="2">
<li><strong><em>max</em></strong></li>
</ol>
<ul>
<li>when you want to <strong>highlight single salient(prominent) features</strong> in local neighborhoods</li>
</ul>
<ol start="3">
<li><strong><em>sum</em></strong></li>
</ol>
<ul>
<li>provides a balance between these two, by providing a <strong>snapshot of the local distribution of features</strong>, but because it is not normalized, can also <strong>highlight outliers</strong></li>
</ul>
<p><strong>Designing new aggregation operations</strong></p>
<ul>
<li><a href="https://arxiv.org/abs/2004.05718">Principal Neighborhood aggregation</a><ul>
<li>take into account several aggregation operations by concatenating them and adding a scaling function that depends on the degree of connectivity of the entity to aggregate</li>
</ul>
</li>
</ul>
<h3 id="gcn-as-subgraph-function-approximators"><strong>GCN as subgraph function approximators</strong></h3>
<p>k layer GNN : 노드로 부터 k-hop의 subgraph에 대한 representation을 학습하는 것</p>
<p>⇒ GCN is <strong>collecting all possible subgraphs of size k</strong> and learning vector representations from the vantage point of one node or edge</p>
<p><strong><a href="https://arxiv.org/abs/1806.09206">N-Gram Graph: Simple Unsupervised Representation for Graphs, with Applications to Molecules</a></strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/40efb215-f0c8-4a0c-acc2-c1f7ed4fe474/image.png" alt=""></p>
<h3 id="edges-and-the-graph-dual"><strong>Edges and the Graph Dual</strong></h3>
<p>Edge prediction과 Node prediction task </p>
<p>: an edge prediction task on a graph $G$ can be phrased as a node-level prediction on $G$’s dual.</p>
<p>G의 dual을 얻기 위해, node→edge, edge→node로의 convert가 필요</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Dual_graph">Dual Graph</a>?</li>
<li><a href="https://arxiv.org/abs/1806.00770"><strong>Dual-Primal Graph Convolutional Networks</strong></a><ul>
<li>to solve an edge classification problem on $G$, we can think about doing graph convolutions on $G$’s dual (which is the same as learning edge representations on $G$)</li>
</ul>
</li>
</ul>
<h3 id="graph-convolutions-as-matrix-multiplications-and-matrix-multiplications-as-walks-on-a-graph"><strong>Graph convolutions as matrix multiplications, and matrix multiplications as walks on a graph</strong></h3>
<p><strong><em>Message passing</em></strong></p>
<ul>
<li>“gathering” all node features values of dimension j that share an edge with $node_i$</li>
<li>not updating the representation of the node feature, just pooling neighboring node feature</li>
</ul>
<p>$$
&lt;A_{row_i} \dot X_{column_j}&gt; \ = A_{i,1}X_{1,j}+A_{i,2}X_{2, j}+…+A_{i,n}X_{n, j}\=\sum_{A_{i,k}&gt;0} X_{k,j}
$$</p>
<ul>
<li><p>$A$ : adjacency matrix, $n_{nodes} \times n_{nodes}$</p>
</li>
<li><p>$X$ : node feature matrix, $n_{nodes} \times node_{dim}$</p>
</li>
<li><p>$A_{i,k}$ : node i와 node k사이 edge의 존재 여부</p>
</li>
<li><p>Adjacency matrix $A$의 sparsity</p>
<ul>
<li>matrix multiply-free approach : $A_{i,j}$가 0인 경우 값을 더할 필요 없음 → 양수 값 retrieval로 해결<ul>
<li>aggregation function으로 sum을 사용할 필요가 없어짐</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>위 과정을 여러번 반복하게되면 더 넓은 영역의 정보를 전파할 수 있음</p>
<p>⇒ <strong>matrix multiplication is a form of traversing over a graph</strong></p>
<p>$<strong>A^K_{ij}$ : node i와 j사이 길이가 K인 경로의 수</strong></p>
<p>$$
A^2_{ij} = &lt;A_{row_i}, A_{column_j}&gt; = A_{i,1}A_{1, j}+A_{i,2}A_{2, j}+…+A_{i,n}A{n,j}
$$</p>
<h3 id="graph-attention-networks"><strong>Graph Attention Networks</strong></h3>
<p>Node feature aggregation을 할때 이웃 노드의 중요도 weight를 만들 수 있을까?</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/42f1521a-6b48-4d56-a499-7831fae07242/image.png" alt=""></p>
<p>Schematic of attention over one node with respect to it’s adjacent nodes. For each edge an interaction score is computed, normalized and used to weight node embeddings.</p>
<ul>
<li><a href="https://arxiv.org/abs/1710.10903">Graph Attention Networks (GAT)</a></li>
<li><a href="https://arxiv.org/abs/1810.00825">Set Transformers</a></li>
</ul>
<p><strong><a href="https://thegradient.pub/transformers-are-graph-neural-networks/">Transformers are Graph Neural Networks</a></strong></p>
<ul>
<li>transformers can be viewed as GNNs with an attention mechanism</li>
<li>transformer models several elements (i.g. character tokens) as nodes in a fully connected graph and the <strong>attention mechanism is assigning edge embeddings to each node-pair</strong> which are used to compute attention weights →<strong>all possible combinations to make a_input :</strong> $[\mathbf{W}h_i||\mathbf{W}h_j]$</li>
<li>The difference lies in the assumed pattern of connectivity between entities, a GNN is assuming a sparse pattern and the Transformer is modelling all connections.<ul>
<li>GNN : adjacency matrix에 대한 연산, aggregation function으로 attention을 사용하느냐, 하지 않느냐의 차이</li>
<li>Transformer : 모든 노드들의 서로에 대한 가중치 계산 → modelling all connections</li>
</ul>
</li>
</ul>
<h3 id="graph-explanations-and-attributions"><strong>Graph explanations and attributions</strong></h3>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/e126cd7d-7f10-4303-8a90-ef9485fca201/image.png" alt=""></p>
<p>Schematic of some explanability techniques on graphs. Attributions assign ranked values to graph attributes. Rankings can be used as a basis to extract connected subgraphs that might be relevant to a task.</p>
<p><strong><a href="https://arxiv.org/abs/1903.03894">GNNExplainer</a></strong></p>
<ul>
<li>Graph concept에 따라 달라지는 그래프 explanation에 대한 해결책</li>
<li>extracting the <strong>most relevant subgraph</strong> that is important for a task</li>
<li><a href="https://openaccess.thecvf.com/content_CVPR_2019/papers/Pope_Explainability_Methods_for_Graph_Convolutional_Neural_Networks_CVPR_2019_paper.pdf">Attribution techniques</a> : task에 relevant한 그래프의 part에 대해 importance value를 ranking</li>
<li>Because realistic and challenging graph problems can be generated synthetically, <strong>GNNs can serve as a rigorous and repeatable testbed for evaluating attribution techniques</strong> : <a href="https://papers.nips.cc/paper/2020/hash/417fbbf2e9d5a28a855a11894b2e795a-Abstract.html">https://papers.nips.cc/paper/2020/hash/417fbbf2e9d5a28a855a11894b2e795a-Abstract.html</a></li>
</ul>
<h3 id="generative-modelling"><strong>Generative modelling</strong></h3>
<p><strong><em>Graph generation</em></strong></p>
<ul>
<li>Method<ul>
<li>sampling from a learned distribution</li>
<li>completing a graph given a starting point</li>
</ul>
</li>
<li>Key Point<ul>
<li><strong>modelling the topology of a graph</strong>, which can vary dramatically in size and has $N_{nodes}^2$ terms</li>
</ul>
</li>
<li>Solution<ul>
<li><strong><a href="https://arxiv.org/abs/1611.07308">Variational Graph Auto-Encoders</a></strong><ul>
<li>modelling the adjacency matrix directly like an image with an autoencoder framework</li>
<li>binary classification task : prediction of the presence or absence of an edge</li>
<li>learns to <strong>model positive patterns of connectivity</strong> and some patterns of <strong>non-connectivity</strong> in the adjacency matrix</li>
</ul>
</li>
<li><strong>build a graph sequentially</strong>, by starting with a graph and applying discrete actions such as addition or subtraction of nodes and edges iteratively<ul>
<li>Auto-regressive mode : <a href="https://arxiv.org/abs/1802.08773">GraphRNN: Generating Realistic Graphs with Deep Auto-regressive Models</a></li>
<li><a href="https://www.nature.com/articles/s41598-019-47148-x">Optimization of Molecules via Deep Reinforcement Learning</a></li>
<li>graph to sequence with grammar elements<ul>
<li><a href="https://arxiv.org/abs/1905.13741">Self-Referencing Embedded Strings (SELFIES): A 100% robust molecular string representation</a></li>
<li><a href="https://arxiv.org/abs/2001.08184">GraphGen: A Scalable Approach to Domain-agnostic Labeled Graph Generation</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Pytorch Geometric Tutorial] 3. Graph attention networks (GAT) implementation]]></title>
            <link>https://velog.io/@sujin_yun_/Pytorch-Geometric-Tutorial-3.-Graph-attention-networks-GAT-implementation</link>
            <guid>https://velog.io/@sujin_yun_/Pytorch-Geometric-Tutorial-3.-Graph-attention-networks-GAT-implementation</guid>
            <pubDate>Thu, 08 Dec 2022 06:50:18 GMT</pubDate>
            <description><![CDATA[<p>&lt;References&gt;</p>
<ul>
<li><a href="https://www.youtube.com/watch?v=CwsPoa7z2c8&amp;list=PLGMXrbDNfqTzqxB1IGgimuhtfAhGd8lHF&amp;index=2">Pytorch Geometric tutorial: Graph attention networks (GAT) implementation</a></li>
</ul>
<p>💡 target node에 대한 neighbor node의 중요도가 모두 같지 않다</p>
<p>→ 특별히 더 중요한 노드가 있다고 할 때, 그 weight를 automatic하게 학습하는 방법? </p>
<p>⇒ GAT</p>
<p><strong><em>Graph Attention Layer</em></strong></p>
<ul>
<li>Input : set of node features  $\mathbf{h} = {\bar{h_1},\bar{h_2}, \dots ,\bar{h_n}} \quad \bar{h_i} \in \mathbf{R}^F$</li>
<li>Output : a <strong>new</strong> set of node features  $\mathbf{h&#39;} = {\bar{h&#39;_1},\bar{h&#39;_2}, \dots ,\bar{h&#39;_n}} \quad \bar{h&#39;_i} \in \mathbf{R}^{F&#39;}$</li>
</ul>
<ol>
<li>apply a <strong>parameterized linear transformation</strong> to every node</li>
</ol>
<p>$$
\mathbf{W} \cdot \bar{h_i} \quad \mathbf{W} \in \mathbf{R}^{F&#39; \times F}
$$</p>
<ul>
<li>$(F&#39; \times F) \cdot F$ matrix연산 ⇒ $F&#39;$</li>
</ul>
<ol start="2">
<li>Self attention</li>
</ol>
<p>$$
a:\mathbf{R^{F&#39;}} \times \mathbf{R^{F&#39;}} \rightarrow \mathbf{R} \e_{i,j} = a(\mathbf{W}\cdot \bar{h_i},\mathbf{W}\cdot \bar{h_j})
$$</p>
<ul>
<li>$e_{i,j}$ : Specify the importance of node j’s features to node i</li>
</ul>
<ol start="3">
<li>Normalization</li>
</ol>
<p>$$
\alpha_{i,j} = softmax_j(e_{i,j}) = \frac{exp(e_{i,j})}{\sum_{k\in N(i)}exp(e_{i,k})}
$$</p>
<ol start="4">
<li>attention mechanism $a$ : <strong>a single-layer feed forward neural network</strong></li>
</ol>
<ul>
<li>주변노드 j의 임베딩과 자기 자신노드 i의 임베딩을 각각 parameter update한 후 concatenate</li>
<li>LeakyReLU</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/afe28db9-142c-4df1-b738-b24a46b9c8ed/image.png" alt=""></p>
<p>$$
\alpha_{i,j} = \frac{exp(LeakyReLU(a^{-T}[\mathbf{W}h_i||\mathbf{W}h_j]))}{\sum_{k\in N(i)}exp(LeakyReLU(a^{-T}[\mathbf{W}h_i||\mathbf{W}h_j]))}
$$</p>
<ul>
<li>$||$ : concatenate → $F&#39; + F&#39;$</li>
<li>$[\mathbf{W}h_i||\mathbf{W}h_j]$ → $(2F&#39; \times 1)$</li>
<li>$a^{-T}$ : transpose(a) → $(1\times 2F&#39;)$</li>
<li>LeakyReLU(Real number)</li>
</ul>
<ol start="5">
<li>학습한 attention 사용하기 : Node i의 이웃의 중요도를 결정하여 Input 데이터를 재정의</li>
</ol>
<p>$$
h&#39;<em>i = \sigma(\sum</em>{j\in N(i)} \alpha_{i,j} \mathbf{W}h_j)
$$</p>
<ol start="6">
<li><p>Multi-head attention($K$번 반복)</p>
<ol>
<li><p>Concatenation : in layer</p>
<p> $$
 h&#39;<em>i = ||</em>{k=1}^K\sigma(\sum_{j\in N(i)} \alpha_{i,j}^k \mathbf{W}^kh_j)
 $$</p>
</li>
<li><p>Average : on the final prediction layer of the network</p>
<p> $$
 h&#39;<em>i = \sigma(\frac{1}{K}\sum</em>{k=1}^K \sum_{j\in N(i)} \alpha_{i,j}^k \mathbf{W}^kh_j)
 $$</p>
</li>
</ol>
</li>
</ol>
<p><strong><em>👍Advantages</em></strong></p>
<ul>
<li>Computationally efficient<ul>
<li><strong>Self-attention layers</strong> can be <strong>parallelized</strong> <strong>across edges</strong></li>
<li><strong>Output features</strong> can be <strong>parallelized across nodes</strong></li>
</ul>
</li>
<li>Allows to assign <strong>different importances to nodes</strong> of a same neighborhood</li>
<li>It is applied in a <strong>shared manner</strong> to all edges in the graph<ul>
<li><strong>Not</strong> required to have the <strong>entire graph</strong></li>
</ul>
</li>
<li>Works in both<ul>
<li>Transductive learning (Cora, Citeseer, Pubmed) : Big whole graph에 접근하여 node classification을 하거나 link prediction</li>
<li>Inductive learning (PPI) : Multiple graphs, 다른 그래프셋에 대한 예측</li>
</ul>
</li>
</ul>
<p><strong><em>Message Passing Implementation</em></strong></p>
<p><a href="https://pytorch-geometric.readthedocs.io/en/latest/notes/create_gnn.html">Creating Message Passing Networks - pytorch_geometric documentation</a></p>
<p><a href="https://pytorch-geometric.readthedocs.io/en/latest/_modules/torch_geometric/nn/conv/message_passing.html">torch_geometric.nn.conv.message_passing - pytorch_geometric documentation</a></p>
<p>$$
\mathbf{x}<em>i^{(k)} = \gamma^{(k)}(\mathbf{x}_i^{(k-1)},f</em>{j\in N(i)}\phi^{(k)}(\mathbf{x}<em>i^{(k-1)},\mathbf{x}_j^{(k-1)},\mathbf{e}</em>{j,i}))
$$</p>
<ul>
<li>자기자신, 주변 노드들, 엣지 정보를 concat하여 message를 만들고, 이를 aggregate하여 자기자긴노드와 한번 더 합친 뒤, 한번 더 MLP에 먹여주면 업데이트된 노드 임베딩</li>
<li>$\mathbf{x}_i^{(k)}$ : Features representations of node i at the k-th layer (업데이트 하고싶은 것)</li>
<li>$\phi^{(k)}$ : Differentiable function, Eg. MLP</li>
<li>$\mathbf{x}_i^{(k-1)}$ : Feature representation of node i at the (k-1)-th layer</li>
<li>$<em>\mathbf{x}_j^{(k-1)}$</em> : Feature representation of node j at the (k-1)-th layer</li>
<li>$<em>\mathbf{e}_{j,i}$</em>  : [optionally] features of edge (i,j)</li>
<li>$f_{j\in N(i)}$  : Differentiable, ordering invariant function. Aggregate function. For every j in the neighbourhood of i. Eg. sum, average, etc...</li>
<li>$\gamma^{(k)}$ : Differentiable function, Eg. MLP</li>
</ul>
<p><strong><em>PyTorch Geometric MessagePassing base class</em></strong></p>
<p><a href="https://baeseongsu.github.io/posts/pytorch-geometric-message-passing1/">PyTorch Geometric 탐구 일기 - Message Passing Scheme (1)</a></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/2b936246-c90d-4eac-a699-c6b70ddaccd0/image.png" alt=""></p>
<ul>
<li>GNN의 MessagePassing Shceme에 대해, propagation을 구조적으로 연결해주는 편리한 클래스</li>
<li><code>message()</code>, <code>update()</code>, <code>aggregation</code>를 설정</li>
<li>$\phi^{(k)}$ : message()</li>
<li>$\gamma^{(k)}$ : update()</li>
<li>$f_{j\in N(i)}$ : aggregation → max, mean, add,,,</li>
<li><code>flow</code> : flow direction of message passing  : 주변 노드로부터 정보를 전달 받을지, 전달할지 결정 (either <code>&quot;source_to_target&quot;</code> or <code>&quot;target_to_source&quot;</code>)</li>
<li><code>node_dim</code> : 노드의 차원을 의미<ul>
<li>defualt 값은 int 0</li>
<li>어떤 axis로 propagate할지 결정하는 것</li>
</ul>
</li>
</ul>
<p>ex. Message Passing interface 예시</p>
<pre><code class="language-python">class MyOwnConv(MessagePassing):
    def __init__(self):
        super(MyOwnConv, self).__init__(aggr=&#39;add&#39;) # add, mean or max aggregation

    def forward(self, x, edge_index, e):
        return self.propagate(edge_index, x=x, e=e) # pass everything needed for propagation

    def message(self, x_j, x_i, e): # Node features get automatically mapped to source(_j) and target(_i) nodes
        return x_j * e</code></pre>
<ul>
<li><code>torch.nn.Module</code>이 superclass</li>
<li><code>torch.nn.Module</code> ⇒ <code>torch_geometric.nn.MessagePassing</code> ⇒ <code>OurCustomLayer</code></li>
<li>대부분의 <code>torch_geometric.nn.conv</code> layer 구현체들이 Message Passing Scheme을 따름</li>
</ul>
<p><strong><em>MessagePassing - <code>propagate()</code></em></strong></p>
<pre><code class="language-python">def propagate():
       if mp_type == &#39;adj_t&#39; and self.fuse and not self.__explain__:
              out = self.message_and_aggregate(edge_index, **msg_aggr_kwargs)

      # Otherwise, run both functions in separation.
       elif mp_type == &#39;edge_index&#39; or not self.fuse or self.__explain__:
           msg_kwargs = self.__distribute__(self.inspector.params[&#39;message&#39;],
                                             coll_dict)
           out = self.message(**msg_kwargs)
           out = self.aggregate(out, **aggr_kwargs)
      out = self.update(out, **update_kwargs)</code></pre>
<ul>
<li><code>propagate(edge_index, size=None, **kwargs)</code></li>
<li>node embedding을 업데이트하고 <strong>message를 구성하기 위한 edge index등  다양한 추가 정보를 가져옴</strong></li>
<li><code>size</code> → bipartite graph처럼 (N,M) 사이즈도 propagate 가능<ul>
<li>이 경우, <code>size = (N,M)</code> 으로 넣어줌</li>
<li><code>size = None</code> 일경우 정사각행렬</li>
</ul>
</li>
<li><code>message()</code>와 <code>update()</code> 함수를 차례로 호출</li>
<li><code>message</code>와 <code>aggregate</code> 함수는 분리되거나 합쳐져 사용</li>
<li>최종적으로 <code>update</code> 함수를 통해 출력값 생성</li>
</ul>
<p><strong><em>MessagePassing - <code>message()</code></em></strong></p>
<pre><code class="language-python">def message(self, x_j: torch.Tensor) -&gt; torch.Tensor:
    # need to construct
    return x_j</code></pre>
<ul>
<li>$\phi$, 노드 i에 대한 <strong>message구성</strong></li>
<li><code>message(**kwargs)</code><ul>
<li>각 edge마다 발생하는 <strong>“message”라는 것을 어떻게 construct할지 구체화</strong>하는 함수</li>
<li>propagate의 호출을 따르므로, propagate에 전달할 어떤 인자든 넘길 수 있음</li>
<li>주의할 점, 메세지 간의 노드를 구체화할 때는, <strong>“_i”와 “_j”를 구분해서 표현</strong>해야 mapping이 정의 가능<ul>
<li>i : central node</li>
<li>j : neighboring nodes</li>
<li>flow=’source_to_target’일 경우, $e_{ij}\in E$ 로 구분</li>
<li>flow=’target_to_source’일 경우, $e_{ji}\in E$ 로 구분</li>
</ul>
</li>
</ul>
</li>
<li>따라서, 함수의 <strong>argument naming</strong>이 중요</li>
</ul>
<p><strong><em>MessagePassing - <code>update()</code></em></strong></p>
<pre><code class="language-python">def update(self, inputs: torch.Tensor):
    # need to construct
    return inputs</code></pre>
<ul>
<li>$\gamma$, 각 노드 i에 대해서, <strong>node embedding을 업데이트</strong>하는 함수</li>
<li><code>update(aggr_out, **kwargs)</code><ul>
<li>message의 aggregation 결과값을 <code>inputs</code> 인자로</li>
<li>처음 <code>propagate()</code>에 전달한 초기 인자들도 이용 가능</li>
</ul>
</li>
</ul>
<p><strong><em>Implementing the GCN Layer</em></strong></p>
<p><a href="https://arxiv.org/abs/1609.02907">Semi-Supervised Classification with Graph Convolutional Networks</a></p>
<p>$$
\mathbf{x}<em>i^{(k)} = \sum</em>{j \in \mathcal{N}(i) \cup { i }} \frac{1}{\sqrt{\deg(i)} \cdot \sqrt{\deg(j)}} \cdot \left( \mathbf{W}^{\top} \cdot \mathbf{x}_j^{(k-1)} \right) + \mathbf{b},
$$</p>
<ul>
<li>이웃 노드들의 feature들이 weight matrix $\mathbf{W}$로 먼저 transform되고, node degree들로 normalize됨</li>
<li>bias vector $\mathbf{b}$를 적용해 output을 aggregate</li>
<li><strong>Comparison with general message passing</strong><ul>
<li>$\mathbf{x}<em>i^{(k)} = \gamma^{(k)}(\mathbf{x}_i^{(k-1)},f</em>{j\in N(i)}\phi^{(k)}(\mathbf{x}<em>i^{(k-1)},\mathbf{x}_j^{(k-1)},\mathbf{e}</em>{j,i}))$</li>
<li>$\sum_{j \in \mathcal{N}(i) \cup { i }} \frac{1}{\sqrt{\deg(i)} \cdot \sqrt{\deg(j)}}$  =  $f_{j\in N(i)}$</li>
<li>$\mathbf{W}$ = $\phi^{(k)}$</li>
</ul>
</li>
</ul>
<p><strong>Steps</strong></p>
<ol>
<li>Add <strong>self-loops</strong> to the adjacency matrix.(본인 노드 feature도 넣어줌, 대각 성분을 1로)</li>
<li>Linearly transform node feature matrix.</li>
<li>Compute normalization coefficients.</li>
<li>Normalize node features in $\phi$</li>
<li>Sum up neighboring node features (<strong><code>&quot;add&quot;</code></strong> aggregation).</li>
<li>Apply a final bias vector.</li>
</ol>
<ul>
<li>Step 1~3 : sum 기호 내부, 타겟 노드에 전달해줄, 흐르게 할 (propagating할) message를 construct하는 과정</li>
<li>Step 4~6 : 이웃인 node-pair에 대해 aggregation하고 해당 타겟 노드를 update하는 과정</li>
</ul>
<p><strong>Source Code</strong></p>
<pre><code class="language-python">import torch
from torch.nn import Linear, Parameter
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree

class GCNConv(MessagePassing):
    def __init__(self, in_channels, out_channels):
        super().__init__(aggr=&#39;add&#39;)  # &quot;Add&quot; aggregation (Step 5).
        self.lin = Linear(in_channels, out_channels, bias=False)
        self.bias = Parameter(torch.Tensor(out_channels))

        self.reset_parameters()

    def reset_parameters(self):
        self.lin.reset_parameters()
        self.bias.data.zero_()

    def forward(self, x, edge_index):
        # x has shape [N, in_channels]
        # edge_index has shape [2, E]

        # Step 1: Add self-loops to the adjacency matrix.
        edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))

        # Step 2: Linearly transform node feature matrix.
        x = self.lin(x)

        # Step 3: Compute normalization.
        row, col = edge_index #출발, 도착 노드 분리
                #도착노드에 대해 node 등장횟수 count
        deg = degree(col, x.size(0), dtype=x.dtype)
        deg_inv_sqrt = deg.pow(-0.5)
        deg_inv_sqrt[deg_inv_sqrt == float(&#39;inf&#39;)] = 0
        norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]

        # Step 4-5: Start propagating messages.
        out = self.propagate(edge_index, x=x, norm=norm)

        # Step 6: Apply a final bias vector.
        out += self.bias

        return out

    def message(self, x_j, norm):
        # x_j has shape [E, out_channels]

        # Step 4: Normalize node features.
        return norm.view(-1, 1) * x_j</code></pre>
<p><code>GCNConv</code></p>
<ul>
<li><p>“add” propagation을 사용한 MessagePassing을 상속받음</p>
</li>
<li><p><code>foward()</code></p>
<ul>
<li><p>Step 1: Add self-loops to the adjacency matrix → <code>[torch_geometric.utils.add_self_loops()]</code> : <a href="https://pytorch-geometric.readthedocs.io/en/latest/modules/utils.html#torch_geometric.utils.add_self_loops">https://pytorch-geometric.readthedocs.io/en/latest/modules/utils.html#torch_geometric.utils.add_self_loops</a></p>
</li>
<li><p>Step 2: Linearly transform node feature matrix → <code>[torch.nn.Linear]</code> : <a href="https://pytorch.org/docs/master/generated/torch.nn.Linear.html#torch.nn.Linear">https://pytorch.org/docs/master/generated/torch.nn.Linear.html#torch.nn.Linear</a></p>
</li>
<li><p>Step 3: Compute normalization → $1/(\sqrt{\deg(i)} \cdot \sqrt{\deg(j)})$ → <code>[num_edges, ]</code> 크기의 tensor <code>norm</code> output</p>
<ul>
<li><p><code>torch_geometric.utils.degree</code></p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/d84352a6-c598-4f8a-86bd-02db5a3ce3d4/image.png" alt=""></p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<pre><code>- Step 4-5: Start propagating messages. → call `propagate()` → 내부적으로 `message()`, `aggregate()`, `update()`
    - `propagate()` : node embedding을 업데이트하고 message를 구성하기 위한 edge index등 **다양한 추가 정보**를 가져옴
        - node embeddings `x`, the normalization coefficients `norm` 를 추가 전달
- Step 6: Apply a final bias vector.</code></pre><ul>
<li><code>message()</code><ul>
<li>normalize the neighboring node features <code>x_j</code> by <code>norm</code><ul>
<li><code>x_j</code> : <em>lifted tensor,</em> 각 엣지의 source node feature를 포함</li>
<li><code>x_i</code> : 각 엣지의 target node feature를 포함</li>
<li>i : central node</li>
<li>j : neighboring nodes</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><strong><em>Implementations</em></strong>
<a href="https://github.com/sujinyun999/PytorchGeometricTutorial/blob/main/Tutorial3/Tutorial3.ipynb">https://github.com/sujinyun999/PytorchGeometricTutorial/blob/main/Tutorial3/Tutorial3.ipynb</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Pytorch Geometric Tutorial] 1. Introduction to Pytorch geometric]]></title>
            <link>https://velog.io/@sujin_yun_/Pytorch-Geometric-Tutorial-1.-Introduction-to-Pytorch-geometric</link>
            <guid>https://velog.io/@sujin_yun_/Pytorch-Geometric-Tutorial-1.-Introduction-to-Pytorch-geometric</guid>
            <pubDate>Thu, 08 Dec 2022 06:40:00 GMT</pubDate>
            <description><![CDATA[<p>&lt;References&gt;</p>
<ul>
<li><a href="https://www.youtube.com/watch?v=JtDgmmQ60x8&amp;list=PLGMXrbDNfqTzqxB1IGgimuhtfAhGd8lHF&amp;index=1">Pytorch Geometric tutorial: Introduction to Pytorch geometric</a></li>
</ul>
<p><strong><em>Problems of dealing graph in deep learning</em></strong></p>
<ol>
<li>Different sizes<ul>
<li>노드 크기에 따라 adjacency matrix의 크기가 달라짐</li>
</ul>
</li>
<li>NOT invariant to node ordering<ul>
<li>그래프가 위상적으로 동일하더라도 adjacency matrix는 다를 수 있음</li>
</ul>
</li>
</ol>
<p><strong><em>Notation</em></strong></p>
<p>$$
\mathbf{G} = (V,E)
$$</p>
<p><strong><em>Computation Graph</em></strong></p>
<p>: The neighbour of a node define its computation graph</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/880edc14-6227-4342-a4d4-0c2f7fce4a75/image.png" alt=""></p>
<ul>
<li>Neighbor node들의 정보를 <strong>aggreagte</strong>하여 <strong>박스</strong>를 거쳐 target node의 representation을 만들어 냄<ul>
<li><strong>박스 :</strong> Neural Network</li>
<li><strong>Ordering invariant Aggregation</strong> : sum, average같이 노드 순서에 상관없는 노드 정보 aggregation</li>
</ul>
</li>
<li><strong>redundancy</strong> : 각 노드들에 대해 2hop의 computational graph를 만들면 중복되는 부분이 발생하게됨</li>
</ul>
<p><strong><em>Math</em></strong></p>
<ol>
<li>0번째 layer에서 node v의 representation은 node feature이다</li>
</ol>
<p>$$
H_v^0 = X_v
$$</p>
<ul>
<li>$H_v^0$ : layer0에서 노드 v의 representation</li>
<li>$X_v$ : node $v$의 feature</li>
</ul>
<ol>
<li>노드 representation update</li>
</ol>
<p>$$
h_v^{k+1} = \sigma(W_k \sum_{u \in N(v)} \frac{h_u^k}{|N(v)|}+B_kh_v^k)
$$</p>
<ul>
<li>$h_v^{k+1}$ : layer k+1에서 노드 v의 representation</li>
<li>$h_v^{k}$ : layer k에서 노드 v의 representation</li>
<li>$\sum_{v \in N(u)} \frac{h_u^k}{|N(v)|}$ : 노드 v의 neighbor $N(v)$에 대해 임베딩을 평균한 것</li>
<li>$W_k, B_k$ : Weights(박스), shared for all computation graph</li>
<li>$\sigma$ : Activation function(relu)</li>
</ul>
<ol>
<li>k번째 layer에서 node v의 representation</li>
</ol>
<p>$$
Z_v = h_v^k
$$</p>
<p><strong><em>GraphSAGE</em></strong></p>
<p><a href="https://arxiv.org/abs/1706.02216">Inductive Representation Learning on Large Graphs</a></p>
<p>위의 Math에서 <strong>간단한 수정</strong>으로 구현할 수 있음</p>
<ul>
<li>average ⇒ general aggregation function</li>
<li>주변 노드 정보를 합친 정보와 이전 layer의 자기 자신에 대한 정보를 더하는 대신, <strong>concatenate(,)</strong></li>
</ul>
<p>$$
h_v^{k+1} = \sigma([W_k \cdot AGG({h_u^{k-1},{\forall u \in N(v)}}) ,B_kh_v^k])
$$</p>
<ul>
<li>$AGG$<ul>
<li>Pool : Element-wise min/max</li>
<li>LSTM : note <strong>not order invariant</strong></li>
</ul>
</li>
</ul>
<p><strong><em>Implementations</em></strong>
<a href="https://github.com/sujinyun999/PytorchGeometricTutorial/blob/main/Tutorial1/Tutorial1.ipynb">https://github.com/sujinyun999/PytorchGeometricTutorial/blob/main/Tutorial1/Tutorial1.ipynb</a></p>
]]></description>
        </item>
        <item>
            <title><![CDATA[[Dialogue System] Persona chat 리뷰]]></title>
            <link>https://velog.io/@sujin_yun_/Dialogue-System-Persona-chat-%EB%A6%AC%EB%B7%B0</link>
            <guid>https://velog.io/@sujin_yun_/Dialogue-System-Persona-chat-%EB%A6%AC%EB%B7%B0</guid>
            <pubDate>Thu, 28 Jul 2022 08:32:45 GMT</pubDate>
            <description><![CDATA[<h1 id="abstract">Abstract</h1>
<p>chit-chat model의 문제점</p>
<ul>
<li>lack of specificity : 일관된 personality를 보여주지 않음</li>
<li>often not very captivating</li>
</ul>
<p>⇒ chit-chat model에 profile information을 conditioning함으로써 해결</p>
<ol>
<li>주어진 프로필 정보 조건에 맞는 (=condition on their given profile information)</li>
<li>이야기하고 있는 대상에 대한 정보를 포함하는 (=information about the person they are talking to)</li>
</ol>
<p>위 두가지와 관련된 데이터를 수집하여 모델을 학습시킴으로써 다음 utterance 예측을 통해 측정되는 dialogue 생성 능력 향상을 이루고자 함.</p>
<p>그중에서도 2번의 경우 처음에는 알 수 없는 정보이기때문에, 모델은 상대가 개인적인 주제를 이야기 하도록 학습되고, 그 결과인 dialogue는 interlocutor의 프로필 정보를 예측하는데 사용될 수 있다.</p>
<h2 id="1-introduction">1. Introduction</h2>
<p>현재 :  Neural model들이 chit-chat에 있어 적절히 유의미한 대답을 생성하기 위한 데이터 셋이 구축된지 얼마 되지 않았고, 여전히 그러한 모델들의 약점이 뚜렷함</p>
<p>chit-chat model이 갖고있는 문제점</p>
<ol>
<li>lack of consistent personality : 각각 다른 speaker가 이야기한 dialogue를 바탕으로 학습되기 때문</li>
<li>lack of explicit long-term memory : 최근 dialogue history 만으로 utterance를 생성</li>
<li>tendency to produce non-specific answers like “I don’t know”</li>
</ol>
<p>→ 위 세개의 문제들로 인해 대화하는 사람의 전반적인 만족도가 크게 떨어지게 됨</p>
<p>→ 저자는 이러한 문제가 general chit-chat 모델을 위한 public dataset의 부족때문이라고 주장</p>
<p>최근의 대화모델의 낮은 퀄리티와 이러한 모델을 평가하는데 있어 발생하는 어려움 때문에, chit-chat model &lt;&lt; task-oriented communication</p>
<p>btw, 사람간 대화의 대부분은 socialization, personal interests 그리고 chit-chat에 집중되어있다.</p>
<p>⇒ <strong>configurable, persistent persona를 도입</strong>함으로써 <strong>더 engaging한 chit-chat dialogue agent</strong>를 만들 수 있을 것. </p>
<p>이때, 이러한 persona는 textual descrpition과 profile에서 encoded된 것들</p>
<ul>
<li>profile은 <a href="https://www.youtube.com/watch?v=Ry1IIjLnumI&amp;t=2186s">memory-augmented NN</a>에 저장되어 persona free model보다 더 personal, specific, consistent, engaging한 답변을 생성할 수 있음 → chit-chat model의 문제 완화</li>
<li>마찬가지로, 대화 상대에 대한 정보도 같은 방식으로 활용할 수 있음</li>
</ul>
<p>⇒ Model은 personal topic에 대한 ask와 answer question모두를 활용해 학습되고, 이는 대화 상대의 persona를 modeling할 수 있도록 함</p>
<p>그러한 모델을 학습시키기 위해, persona-chat  dataset을 제시</p>
<ul>
<li>a new dialogue dataset consisting of 164,356 utterances between crowdworkers</li>
<li>each asked to act the part of a given provided persona</li>
<li>get to know each other during the conversation</li>
</ul>
<p>Next utterance prediction task during dialogue</p>
<p>→ compare generative &amp; ranking model</p>
<ul>
<li>Seq2Seq</li>
<li>Memory Networks</li>
</ul>
<p>⇒ generative &amp; ranking model 모두에 있어 persona info가 주어진 모델이 task를 더 잘 수행함</p>
<h2 id="2-related-works">2. Related works</h2>
<ul>
<li><p>Traditional dialogue systems</p>
<ul>
<li>dialogue state tracking component와 response genrator로 구성</li>
<li>user intent가 명확히 정의된 goal-oriented dialogue</li>
<li>chit-chat setting은 고려되지 않음</li>
<li>functional goal 달성에 집중</li>
<li>이에 따라 task와 dataset도 좁은 domain에 집중됨</li>
<li><a href="https://arxiv.org/abs/1506.06714">IR base models</a> : 최근 대화 기록으로 response를 matching score기반 retrieve and rank</li>
</ul>
</li>
<li><p>End-to-end neural approach</p>
<ol>
<li><p>generative recurrent system (ex. seq2seq)</p>
<ul>
<li><a href="https://proceedings.neurips.cc/paper/2014/hash/a14ac55a4f27472c5d894ec1c3c743d2-Abstract.html">Sequence to sequence learning with neural networks</a></li>
<li><a href="https://arxiv.org/abs/1506.05869">A Neural Conversational Model</a></li>
<li><a href="https://ojs.aaai.org/index.php/AAAI/article/view/10983">A hierarchical latent variable encoder-decoder model for generating dialogues</a><ul>
<li>+) produce syntactically coherent novel responses</li>
<li>-) memory-free → longterm coherence, persistent personality 부족</li>
</ul>
</li>
</ul>
</li>
<li><p>memory-augmented network</p>
<ul>
<li><a href="https://arxiv.org/abs/1511.06931">Evaluating Prerequisite Qualities for Learning End-to-End Dialog Systems</a></li>
</ul>
</li>
<li><p>chit-chat setting</p>
<ul>
<li><a href="https://arxiv.org/abs/1603.06155">A persona-based neural conversation model</a><ul>
<li>Twitter corpus에서 capture한 background history와 speaking styler과 같은 persona를 distributed embedding으로 encapsulate하여 향상된 결과 생성</li>
<li>대화 상대를 getting to know하는 과정이 없음</li>
</ul>
</li>
</ul>
<p>⇒ explicit profile information에 집중, getting to know과정 추가</p>
</li>
</ol>
</li>
</ul>
<h2 id="3-the-persona-chat-dataset">3. The PERSONA-CHAT Dataset</h2>
<p><strong>Goal</strong></p>
<ul>
<li>Facilitate more engaging and more personal chit-chat dialogue</li>
</ul>
<p><strong>Data collection stages</strong></p>
<ol>
<li>Persona<ul>
<li>1155 Possible persona</li>
<li>각각은 최소 5개의 profile sentence를 포함</li>
<li>100 never seen before peronas for validation, the other 100 for test</li>
</ul>
</li>
<li>Revised Persona<ul>
<li>trivial word overlap으로 인해 model이 advantage를 챙기는 것을 방지하기 위해, 1155개의 persona에 대해 rephrases, generalizations or specializations처리된 관련 문장을 크라우드소싱하여 얻음</li>
</ul>
</li>
<li>Persona chat<ul>
<li>164,356 utterances over 10,981 dialogs, 15,705 utterances (968 dialogs) of which are set aside for validation, and 15,119 utterances (1000dialogs) for test</li>
</ul>
</li>
</ol>
<h3 id="31-personas">3.1 Personas</h3>
<ul>
<li>persona description 5문장을 활용해 crowdsourced worker들이 character를 만들어 냄.</li>
</ul>
<p>Example.</p>
<blockquote>
<p>“I am a vegetarian. I like swimming. My father used to work for Ford. My favorite band is Maroon5. I got a new job last month, which is about advertising design.”</p>
</blockquote>
<p>→ 이러한 프로필은 사람간 대화에 있어 나올 수 있는 전형적인 관심사를 자연스럽게 묘사하는데 초점을 둠</p>
<ul>
<li>각 문장들이 최대 15단어 정도인 짧은 문장으로 구성</li>
</ul>
<h3 id="32-revised-personas">3.2 Revised Personas</h3>
<p><strong>Issue of textual persona :</strong> </p>
<ul>
<li>프로필 정보를 unwittingly 반복하게 되어 엄청난 단어 중복이 발생할 수 있음</li>
</ul>
<p>→ 이로 인해 모델이 단어 중복 만으로 답을 맞추는 상황이 발생</p>
<ul>
<li>잘 알려진 QA데이터셋인 SQuAD의 경우, 단순한 단어 overlap만으로 맞출 수 있는 케이스가 다수 있음</li>
</ul>
<p><strong>해결 :</strong> </p>
<ul>
<li>기존의 프로필 문장을 재작성 및 재구성 하도록</li>
<li>“a related characteristic that the same person may have” : 같은 것을 의미하는 것 뿐 아니라 같은 persona가 두가지 특징을 모두 포함 할 수 있음</li>
<li>generalizations or specializations</li>
<li>ex. “I like basketball” → “I am a big fan of Michael Jordan”</li>
<li>Not just trivially rephrase the sentence by copying the original word<ul>
<li>ex. “My father worked for Ford.”<ul>
<li>“My dad was employed by Ford.” (X)</li>
<li>“My dad worked in the car industry” (O)</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/6f7fb363-e252-4a35-ad66-80c828c759c5/image.png" alt=""></p>
<h3 id="33-persona-chat">3.3 Persona Chat</h3>
<ul>
<li>수집한 persona를 crowdworkers에게 랜덤하게 부여한 후, getting to know 과정의 대화를 하도록 함.</li>
<li>turn base</li>
<li>max 15 words per message</li>
<li>페르소나 프로필 내용을 조금만 변형하여 발화하지 않도록 지시</li>
<li>Minimum dialogue length : 6~8 turns</li>
</ul>
<h3 id="evaluation">Evaluation</h3>
<p><strong>Standard dialogue task</strong></p>
<ul>
<li>given the dialogue history, predict the next utterance</li>
<li>with/ without profile information</li>
</ul>
<p><strong>Goal</strong> : </p>
<ul>
<li>enabling intersting directions for future research (persona를 도입함으로써 the engaging한 대화가 만들어지는지</li>
</ul>
<p><strong>Possible Scenarios</strong></p>
<p>conditioning on</p>
<ol>
<li>No persona</li>
<li>Your own persona</li>
<li>Their persona</li>
<li>Both</li>
</ol>
<ul>
<li>original, revised ver.모두</li>
</ul>
<p><strong>Metrics</strong></p>
<ol>
<li><p>log likelihood of the correct sequence, measured via perplexity</p>
</li>
<li><p>F1 score</p>
</li>
<li><p>next utterance classification loss</p>
<p> : N개(N=19)의 random distractor(오답)와 정답들 사이에서 정답을 고를경우 1점을 부여하는 방식</p>
</li>
</ol>
<h2 id="4-models">4. Models</h2>
<p>Next utterance prediction을 수행하기 위한 두가지 class의 모델</p>
<ol>
<li>ranking model : training set의 가능한 답변 후보들을 생성하고, 각 reply에 순위를 매김</li>
<li>generative model : dialogue history와 persona에 따라 word-by-word로  novel sentence를 생성해냄<ul>
<li>특정 후보 생성 확률을 계산하고 해당 점수로 후보 순위를 매긴다는 점에서 ranking model과 유사하게 평가할 수 있음</li>
</ul>
</li>
</ol>
<h3 id="41-baseline-ranking-models">4.1 Baseline ranking models</h3>
<ol>
<li>IR baseline - 다양한 variant가 있지만, 가장 단순한 것으로 적용<ul>
<li>training set에서 가장 유사한 메세지를 찾고, 해당 exchange에서 그 응답을 output.</li>
<li>여기서 유사도는 tf-idf weighted cosine similarity between the bags
of words로 측정됨</li>
</ul>
</li>
<li>Starspace( = supervised embedding model)<ul>
<li>IR</li>
<li>margin ranking loss와 k-negative sampling을 사용해 해당 작업에 대한 임베딩을 직접 최적화하여 dialog와 next utterance의 유사성 학습</li>
<li>(dialogue+persona)와 next utterance사이 유사도를 단어 임베딩의 합 벡터의 cosine similarity( = $sim(q,c&#39;)$)를 이용해 측정 후, 제일 유사한 utterance를 선택 → $q$ : query, $c&#39;$ : candidate</li>
<li>$W$ : dictionary of $D$ word embeddings, $D$x$d$ matrix, $W_i$ indexes ith word(row)</li>
<li>$q$ , $c&#39;$를 임베딩하는 d-dimenional embedding</li>
<li>profile을 포함하기 위해 query vector bag of word에 단순 concatenate</li>
</ul>
</li>
</ol>
<h3 id="42-ranking-profile-memory-network">4.2 Ranking Profile Memory Network</h3>
<p>두가지 이전 모델들 모두 profile info를 dialogue history와 합쳐 사용</p>
<p>→ model이 다음 utterance를 결정하는데 있어 두가지를 구분하지 못함</p>
<ul>
<li>Dialogue history를 inqut query로 입력하는 memory network를 사용하고, 각 profile sentence에 대한 attention을 학습</li>
<li>유사도 : input q와 profile sentence $p_i$</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/f6a16c5f-4da7-4918-b22c-abe63b4f13c9/image.png" alt=""></p>
<ul>
<li>candidates와 $q^+$의 유사도 기반 랭킹</li>
</ul>
<h3 id="43-key-value-profile-memory-network">4.3 Key-Value Profile Memory Network</h3>
<p><a href="https://aclanthology.org/D16-1147.pdf">key-value (KV) memory network</a></p>
<ul>
<li>improvement to the memory network by performing attention over keys and outputting the values</li>
<li>Dialogue history를 keys, next dialogue utterance(=reply of speaking partner)를 value로 하는 메모리 네트워크 → 모델이 past dialogue에 대한 memory를 갖고, 직접적으로 prediction에 사용할 수 있게됨</li>
<li>Ranking profile Memory network에서 구해진 $q^+$를 이용해 각 key에 대한 attention값을 구하고, value의 가중합을 만들어 새로운 query embedding q^++를 만들어냄</li>
<li>q^++는 candidate $c&#39;$들을 유사도 기반 ranking했던 거처럼 마찬가지로 ranking하는데 사용</li>
<li>매우 큰 key-value쌍은 학습을 매우 느리게 만들 수 있어, 실험에서는 profile memory network를 학습시키고 같은 모델의 가중치를 활용해 test시 적용하였음</li>
</ul>
<h3 id="44-seq2seq">4.4 Seq2Seq</h3>
<ul>
<li>LSTM encoder, decoder를 갖는 단순 deq2seq<ul>
<li>각 timestep t에 대해 decoder는 word j의 발생 확률을 softmax로 구함</li>
<li>negative log likelihood</li>
</ul>
</li>
<li>GloVe word embedding</li>
<li>persona는 input sequence에 concat해 입력</li>
</ul>
<h3 id="45-generative-profile-memory-network">4.5 Generative Profile Memory Network</h3>
<ul>
<li>각 profile이 memory network의 individual memory representation으로</li>
<li>seq2seq 모델에서 decoding할때 각 step에서 memory(=profile sentences)에 attend하여 persona context vector를 생성하고, 이 벡터를 추가로 입력</li>
</ul>
<h2 id="5-experiments">5. Experiments</h2>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/247b282d-f127-4bb3-85b8-3e48fd2d8578/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/917274a8-06da-49ff-8a18-f4133aaeba47/image.png" alt=""></p>
<ul>
<li>persona정보를 이용했을떄 더 좋은 성능을 보임</li>
<li>original 보다 revised ver.이 더 도전적인 데이터셋</li>
<li>hits@1에 의한 성능비교시 Ranking model이 generation model보다 좋은 성능을 보임</li>
<li>사람이 직접 scoring했을 때에도 ranking model이 generation model보다 좋은 성능을 보임</li>
</ul>
]]></description>
        </item>
        <item>
            <title><![CDATA[Attention is all you need]]></title>
            <link>https://velog.io/@sujin_yun_/Attention-is-all-you-need</link>
            <guid>https://velog.io/@sujin_yun_/Attention-is-all-you-need</guid>
            <pubDate>Tue, 31 May 2022 01:52:27 GMT</pubDate>
            <description><![CDATA[<p><del>진정한 물아일체</del></p>
<h1 id=""></h1>
<h1 id="-1"></h1>
<p>다음 자료들을 참고하여 본 글을 작성하였습니다!</p>
<p><a href="https://arxiv.org/pdf/1706.03762v5.pdf">Attention is all you need</a></p>
<p><a href="https://youtu.be/Yk1tV_cXMMU">DSBA 연구실 Transformer 강의</a></p>
<p><a href="https://jalammar.github.io/illustrated-transformer/">Jay Alammar - The Illustrated Transformer</a></p>
<h1 id="transformer">Transformer</h1>
<ul>
<li>RNN처럼 순차적 데이터를 처리하지 않음, 한꺼번에 처리</li>
<li>Model that uses attention to boost the speed with which these models can be trained and easy to parallelize</li>
<li>Encoding component와 decoding component, 그리고 연결</li>
</ul>
<p>Encoding component : Encoder의 stack, 논문에서는 6개를 쌓음</p>
<p>Decoding component : Decoder의 stack, 마찬가지로 6개</p>
<p>→ seq2seq와 달리 반복적 수행</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/395f2f3c-1bea-4255-948b-d13506dbef34/image.png" alt=""></p>
<p>512개의 token활용, 문장이 더 짧으면 padding</p>
<p><strong>Encoder</strong></p>
<ul>
<li>각각 입력된 문장내 단어간의 관계를 보여주는 self-attention layer와 모든 단어들에 동일하게 적용되는 fully connected feed-foward layer</li>
<li>순차적 X, 한번에 모든 sequence를 사용하는 unmasked</li>
<li>각각의 encoder는 구조관점에서 모두 동일한 구조 → 가중치를 share하는 것은 아님</li>
<li>각 encoder는 self attention layer와 fully connected feed-foward layer로 구성</li>
</ul>
<ol>
<li><p>self attention layer</p>
<ul>
<li><strong>self-attention layer는 다른 단어를 참고해 각 단어의 vector들끼리 서로간의 관계가 얼마나 중요한지 점수화한다 (a layer helps the encoder look at other words in the input sentence as it encodes a specific word)</strong></li>
</ul>
</li>
<li><p>fully connected feed-foward layer</p>
<ul>
<li><p>self attention layer의 결과물이 input으로 들어가게됨</p>
</li>
<li><p>각 position에 대해 feed forward network이 한번에 적용되는 것이 아닌 각각 한번씩 적용되어 output이 나오게됨</p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/5e55c230-0dda-44ad-906b-04a1b6905025/image.png" alt=""></p>
</li>
</ul>
</li>
</ol>
<p><strong>Decoder</strong></p>
<ul>
<li>encoder layer의 두개의 sublayer에 더해서 세번째 sublayer인 Encoder-decoder attention layer가 두 layer 사이에 들어가 있음</li>
<li>Encoder-decoder attention layer :  최종 output을 생성할때 encoder에서 넘어온 정보를 어떻게 활용할 것인지 연산하는 layer</li>
<li>순차적인 처리가 필요, Masked self attention</li>
<li>&lt;s&gt; 토큰으로 인해 마지막 단어가 masked</li>
</ul>
<p>N = 6</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/2a8cbda0-594d-4f36-8482-25e9b47aaf5f/image.png" alt=""></p>
<h2 id="encoder">Encoder</h2>
<h3 id="1-input-embedding--처음에-들어갈-정보에-대한-vector">1. Input Embedding : 처음에 들어갈 정보에 대한 vector</h3>
<ul>
<li>The embedding only happens in the bottom-most encoder : 제일 첫번째 encoder의 입력으로써 사용됨</li>
<li>Word2vec, fasttext, gloVe와 같은 embedding algorithm활용</li>
<li>common to all the encoders is that they receive a list of <strong>vectors each of the size 512 (512차원의 word embedding : 단어 1개)</strong></li>
<li>가장 아랫단의 encoder에만 word embedding이 input으로 들어가게되고,  윗단의 encoder들은 바로 아래 encoder의 output을 input으로 받음</li>
<li>The size of this list is hyperparameter we can set – basically it would be the length of the longest sentence in our training dataset. (리스트 자체도 파라미터, 한 시퀀스의 길이를 최대 몇개로 가져갈 것인가 → 가장 긴 문장의 단어수나 상위 95%에 해당하는 단어 수) (512차원 여러개가 모여 문장 하나)</li>
</ul>
<h3 id="2-positional-encoding--어떤-단어가-몇번째-위치에-있는지에-대한-정보">2. Positional Encoding : 어떤 단어가 몇번째 위치에 있는지에 대한 정보</h3>
<ul>
<li><p>input embedding에 positional encoding을 더함(그대로 옆에 이어 붙이는 concat과는 다름!)</p>
</li>
<li><p>input embedding 512차원 + positional encoding 512차원 합 ⇒ 512차원</p>
</li>
<li><p>각각의 input embedding에 더해지는 vector</p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/a90ec66c-10d4-4e03-a60d-9f4abcdd197a/image.png" alt=""></p>
</li>
</ul>
<ul>
<li><p>transformer는 한번에 모든 sequence를 입력받아 단어의 위치정보를 고려하지 못한다 → 최소한 순서를 반영할 수 있는 장치를 마련한 것이 positional encoding</p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/e39fba78-a01d-4921-8bb8-54b07ce66a30/image.png" alt=""></p>
</li>
</ul>
<ul>
<li><p>word embedding에 똑같은 크기로 더해주어야 한다. → 단어의 위치에 따라 positional encoding 의 size가 달라져서는 안된다.</p>
</li>
<li><p>위치관계를 표현해야하므로 단어사이의 거리가 멀 경우 positional encoding vector사이의 거리도 멀어져야한다</p>
</li>
<li><p>sequence길이, n=100이고 각 단어의 차원이 512일때 positional encoding을 위의 식대로 생성한 후 L2-norm distribution을 계산한 결과</p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/4f984577-9149-456f-98c9-7f4becf454af/image.png" alt=""></p>
</li>
</ul>
<pre><code>   - 평균에 비해 표준편차가 매우 작은것을 확인할 수 있음
   - 멀면 멀수록 positional encoding사이 거리가 커야함(The further the two positions, the larger the distacne)
   - 하지만 실제로는 그렇지 않은 경우도 있긴함
   - 어떤 단어가 앞에나오고 뒤에나오고에 대한 내용은 보전하지 못해도, 얼마나 멀리 떨어져 있는지에 대한 정보는 전달될 수 있다.</code></pre><h3 id="3-multi-head-attention">3. Multi-head attention</h3>
<p>   <img src="https://velog.velcdn.com/images/sujin_yun_/post/61ed6149-31eb-45ae-a9c5-181ad680d8b8/image.png" alt=""></p>
<ul>
<li><p>the word in each position flows through its own path in the encoder</p>
</li>
<li><p>There are dependencies between these paths in the self-attention layer. The feed-forward layer does not have those dependencies → thus the various paths can be executed in parallel while flowing through the feed-forward layer.</p>
</li>
<li><p>Self attention layer : Dependency O, feed-forward layer : Dependency X</p>
</li>
<li><p>Dependency가 있다 : 서로 영향을 미친다</p>
</li>
<li><p>차원수는 그대로 유지된다.</p>
</li>
<li><p>feed foward layer는 구조가 같지만 weight를 공유하지는 않음</p>
<p>  <img src="https://velog.velcdn.com/images/sujin_yun_/post/f2de38be-7480-431c-8381-b47b726b1ae4/image.png" alt=""></p>
</li>
</ul>
<h3 id="self-attention">Self attention</h3>
<p>   Self attention의 역할 : </p>
<ul>
<li><p>The animal didn’t cross the street because it was too tired</p>
</li>
<li><p>it : the animal</p>
</li>
<li><p>it이라는 단어를 processing할때, 문장 내 다른 단어들을 살펴보면서 it과 연관된 단어가 무엇인지에 대한 정답을 얻는 과정이라고 할 수 있음</p>
</li>
<li><p>=현재 단어와 연관된 단어는 무엇인가?</p>
<p>   <img src="https://velog.velcdn.com/images/sujin_yun_/post/a844c491-40f8-4096-b24e-06031bbfaa55/image.png" alt=""></p>
</li>
</ul>
<p><strong><strong>Self-Attention in Detail</strong></strong></p>
<p>✅ Step 1. create three vectors from each of the encoder’s input vectors (각각의 input vector에 대해 Query vector, Key vector, Value vector를 생성)</p>
<ul>
<li>Query vector : 현재 보고있는 단어의 representation, 다른 단어들을 scoring하기 위한 기준이 되는 값 (We only care about the query of the tocken we’re currently processing)</li>
<li>Key vector : label, query가 주어졌을 때 이 쿼리에 대해 relevant한 단어를 찾는다고 할때 key 값을 활용해 찾음<ul>
<li>ex. it이라는 query가 주어졌을 때, key는 각 파일들에 해당하는 identity</li>
</ul>
</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/46f0243a-8ea6-4cb0-a5fa-5e7a4f39793b/image.png" alt=""></p>
<ul>
<li>Value vector : actual word representation</li>
</ul>
<p><strong>⇒ query와 key를 통해 가장 적절한 value를 찾아 연산한다!</strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/3625c6fb-14c4-499f-b015-79c341e96aa8/image.png" alt=""></p>
<p>Input Embedding에서 만들어지는 Query, key, value</p>
<ul>
<li><p>각각에 해당하는 matrix가 존재해서 계산해주면됨</p>
</li>
<li><p>ex. X1 x Wq → (1x4) x (4x3) ⇒ (1x3) ⇒ q1</p>
</li>
<li><p>Wq,Wk,Wv는 학습을 통해 찾아야하는 미지수</p>
</li>
<li><p>Notice that these new vectors are smaller in dimension than the embedding vector. <strong>Their dimensionality is 64 (Multi head attention관점에서 Multi head attention을 통과한 벡터를 concat해서 encoder, decoder를 통과하게 하기때문에 작게 잡는것이 좋음)</strong></p>
<ul>
<li>64*8 = 512 →여기서 8은 Multi-head attention의 숫자</li>
</ul>
</li>
</ul>
<p>✅ Step 2. calculate a score, i.e, how much focus to place on other parts of the input sentence as we encode a word at a certain position (query와 가장 관련성 높은 단어는 무엇인지 찾기위한 score계산)</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/af3eda1f-51a1-47ab-b612-6663d34a66df/image.png" alt=""></p>
<ul>
<li>The score is calculated by taking the dot product of the query vector with the key vector of the respective word we’re scoring.</li>
<li>현재 보고있는 토큰의 query(q1)과 자신의 key를 포함한 모든 key와 연산을 수행해 score를 계산</li>
</ul>
<p>✅ Step 3. divide the scores by the square root of the dimension of the key vectors (query, key, value 차원의 root를 씌운 숫자를 score에서 나눠준다.)</p>
<ul>
<li>This leads to having more stable gradients</li>
</ul>
<p>✅ Step 4. pass the result through a softmax operation</p>
<ul>
<li>이렇게 만들어진 score는 현재 단어에 해당 단어가 얼마나 큰 영향을 미치는지를 나타냄</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/ff00e105-83da-414b-810f-0e9d7635b77e/image.png" alt=""></p>
<p>✅ Step 5. multiply each value vector by the softmax score(실제 value와 softmax를 통과한 값을  곱해준다)</p>
<p>✅ Step 6. sum up the weighted value vectors which produces the output of the self-attention layer at this position (for the first word).</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/414c2abc-1149-4f60-9d6d-1e7aee4f0591/image.png" alt=""></p>
<p>⇒ 현재 단어의 <strong><strong>Self-Attention = weighted sum of value vectors</strong></strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/f2cdde3b-3360-4c2c-8300-befae0879792/image.png" alt=""></p>
<p><strong><strong>Matrix Calculation of Self-Attention</strong></strong></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/a7e4c29a-7093-4318-a963-3ca62b82fd65/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/912718fe-2961-43f9-8395-7bfd4af41592/image.png" alt=""></p>
<p>&lt;정리&gt;</p>
<ol>
<li>각 단어에 대한 Wq, Wk, Wv와의 연산을 통해 각각의 query, key, value를 만들어낸다.</li>
</ol>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/0bfc48d7-7b43-4c1f-a257-c7d4548cffc7/image.png" alt=""></p>
<ol start="2">
<li>첫번째 단어의 query와 모든 단어의 key value와 연산 → softmax → 가중치</li>
</ol>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/1463e76f-04a4-4ebb-9b53-5029a4a7cef9/image.png" alt=""></p>
<ol start="3">
<li>각각의 score와 value의 연산, 후 전체합계를 통해 첫번째 단어의 self attention계산 완료</li>
</ol>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/58ad22fe-5d91-4fe4-ad8c-d81ee5832606/image.png" alt=""></p>
<ol start="4">
<li>모든 단어에 대해 아래 과정을 반복해 모든 단어에 대한 self attention 계산 완료</li>
</ol>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/de051fa0-06e0-4fb6-a654-824f051718c9/image.png" alt=""></p>
<h3 id="multi-head-attention">Multi-Head Attention</h3>
<p><strong><strong>Multi-Head Attention (Expand the model’s ability to focus on different positions)</strong></strong></p>
<p>→ 8개의 서로 다른 representation subspace를 가짐으로써 single-head attention보다 문맥을 더 잘 이해할 수 있게 된다.</p>
<p>→ layer를 여러 번 조금 다른 초기 조건으로 학습시킴으로써 &#39;그것&#39;에 관련된 단어에 대해 더 많은 후보군을 제공한다.</p>
<ul>
<li>아까의 예시에서 it이 어떤 단어와 연관있는지를 1개만 결정하는 것이 아닌, 여러개를 허용한다 = Attention head를 여러개 둔다!</li>
<li>Calculating attetion seperatly in eight different attention head</li>
<li>개별적인 attention을 만든 후 concatenate</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/4526f86d-fbb2-4a6e-a31b-6cf0789cc117/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/0f0cbc47-9ef6-41ef-beb1-0d3f1d3b11ae/image.png" alt=""></p>
<ol>
<li>concatenate</li>
<li>concatenate한 벡터의 컬럼과 같은 행의수를 갖고, 원래 임베딩과 같은 차원의 열을 갖고 모델 학습과정에서 함께 학습되는 Wo를 mulitply</li>
<li>연산을 통해 처음 갖고 있었던 input embedding의 dim과 동일한 output을 만들 수 있음</li>
</ol>
<p>&lt;Multi-Head Attention 계산의 전반적인 과정&gt;
<img src="https://velog.velcdn.com/images/sujin_yun_/post/b9b6b649-9029-498f-b358-bf8df2203552/image.png" alt=""></p>
<ul>
<li>첫번째 인코더일 경우에만 input embedding X로 연산이 이루어지고, 이후의 encoder에는 직전 인코더의 output R로 해당 연산이 이루어짐</li>
<li>크기는 계속 유지됨!</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/e2d8ddd6-8dc3-4fed-9187-0062a736d87e/image.png" alt=""></p>
<ul>
<li>같은 단어에 대해 다르게 scoring되는것을 확인할 수 있음</li>
</ul>
<h3 id="residual-block--normalization">Residual block &amp; Normalization</h3>
<p>Self attention layer를 통과한 다음에는? ⇒ Residual block &amp; Normalization</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/e9bfacb5-cc02-4b82-a4d8-f227d66e0d1a/image.png" alt=""></p>
<p>f(x)+x → d → f’(x)+1</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/30e222d5-4c58-4444-b2de-45e2c18e01d9/image.png" alt=""></p>
<p>self attention의 output인 z에 x를 그대로 더해준 후  layer normalization을 진행</p>
<p>⇒ FFNN의 입력이 되는 z가 완성됨!</p>
<ul>
<li>Residual&amp; Noramlization을 Encoder하나당 2번, decoder하나당 3번 default로 계속 적용됨</li>
</ul>
<h3 id="position-wise-feed-forward-networks">Position-wise Feed Forward Networks</h3>
<ul>
<li>Fully connected feed forward network</li>
<li>Applied to each position seperatly and identically(각 postition에 대해 개별적 적용)</li>
<li>Relu function*W+b</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/d77d8f06-9878-4eaa-8dab-803e6ecc8527/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/1e9b3312-e34e-4c71-ae5c-4cbcfaeffbea/image.png" alt=""></p>
<ul>
<li>각각의 layer마다 서로다른 parameter</li>
<li>linear transformations are the same across different positions</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/3eb0670b-0935-4816-82b2-e62b03f6d924/image.png" alt=""></p>
<ul>
<li>같은 encoder블록 내 FFN은 같은 구조</li>
<li>각 encoder블록간에는 다름</li>
<li>위 그림에서 z1, z2에 대한 W1,W2는 각각 같다!</li>
</ul>
<p>kernel size= 1인 Convolution으로 생각하기</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/9551ea27-cfad-4eee-861c-e3021f683c25/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/682d962d-6a5f-427f-a0a1-588675c870c0/image.png" alt=""></p>
<h2 id="decoder">Decoder</h2>
<h3 id="masked-multi-head-attention">Masked Multi-head attention</h3>
<ul>
<li>Decoder에서의 self attention layer는 반드시 자기 자신보다 앞쪽 포지션에 해당하는 토큰들에 대해서만 attention score 참조 가능</li>
<li>이를 수학적으로 구현하기 위해 뒤에 나오는 단어의 score를 -inf로 주면, softmax를 통해 score = 0이됨</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/da54ac63-2de8-464d-8d2f-8eab20277248/image.png" alt=""></p>
<p>이를 그림으로 표현하면 다음과 같음</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/fcf2dfe5-ea44-4cd0-9024-177478a6d9ed/image.png" alt=""></p>
<p>하지만 Sequentially 시행될 필요는 없음, 한번에</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/d11f4e52-eda5-4254-9fd9-68d3f76c3f02/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/e7d69975-02cf-4d26-82f2-6715bd375f76/image.png" alt=""></p>
<ul>
<li>Masked Multihead attention은 output embedding에 대응한 부분이었다면, decoder의 두번째 sublayer인 Encoder-decoder attention layer은 Masked Multihead attention과 encoder의 output에 대응</li>
</ul>
<ol>
<li>encoder start by processing the input sequence</li>
<li>The output of the top encoder is then transformed into a set of attention vectors K and V (These are to be used by each decoder in its “encoder-decoder attention” layer which helps the decoder focus on appropriate places in the input sequence)</li>
</ol>
<p>Encoder의 최종 output인 K,V는 stacked decoder의 Encoder-decoder attention layer에서 decoder가 어떤 input에 집중해야하는지 결정하는데 사용됨</p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/2569dc03-9051-4aba-b9f2-e991b0555580/image.png" alt=""></p>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/6499d389-db9a-49b5-bed3-0bc237951147/image.png" alt=""></p>
<ul>
<li>Decoder의 input은 masking이되어야해서 sequential하게 데이터가 들어가게됨, 특정 토큰을 마주칠때까지 프로세스 반복</li>
<li>Encoder-decoder attention layer는 Encoder의 multiheaded self-attention과 동일하게 작용함</li>
</ul>
<h3 id="the-final-linear-and-softmax-layer">The Final Linear and Softmax Layer</h3>
<ul>
<li>Linear layer : FFN</li>
<li>Softmax layer : 최종 output 확률</li>
</ul>
<p><img src="https://velog.velcdn.com/images/sujin_yun_/post/5ee19213-55c4-478d-8563-6ddc1311ee43/image.png" alt=""></p>
]]></description>
        </item>
    </channel>
</rss>