<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Machine Intelligence and Deep Learning - Medium]]></title>
        <description><![CDATA[The MIDL (Machine Intelligence and Deep Learning) publication is a blog initiated by  ECE, UCF (University of Central Florida) directed by Dr. Ying Ma. In this blog, we are writing tutorials based on cutting-edge research published on ICML, ICLR, NIPS, CVPR, ACL, etc.. - Medium]]></description>
        <link>https://medium.com/machine-intelligence-and-deep-learning-lab?source=rss----1c927f30b301---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Machine Intelligence and Deep Learning - Medium</title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab?source=rss----1c927f30b301---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:11:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/machine-intelligence-and-deep-learning-lab" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Self Labeling Via Simultaneous Clustering and Representation Learning]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/self-labeling-via-simultaneous-clustering-and-representation-learning-6383dbf6f65e?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/6383dbf6f65e</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[deep-neural-networks]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[self-labeling]]></category>
            <category><![CDATA[representation-learning]]></category>
            <dc:creator><![CDATA[Vedant Ghate]]></dc:creator>
            <pubDate>Tue, 03 May 2022 01:39:37 GMT</pubDate>
            <atom:updated>2022-05-03T01:39:36.941Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Blog by Vedant Ghate and Ashutosh Avadhani</blockquote><blockquote>A video explanation of this blog is available:</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fd64KBkTOV_Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dd64KBkTOV_Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fd64KBkTOV_Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce18804f481ec36d7a2f6e1a01eebf8a/href">https://medium.com/media/ce18804f481ec36d7a2f6e1a01eebf8a/href</a></iframe><p>In the world of Deep Neural Networks, learning from the available data is a primary and crucial step. The learning phase can be of three types viz. Supervised, Semi-Supervised, and Unsupervised learning. Unsupervised learning has been widely studied in the Machine Learning (ML) community and algorithms for clustering, dimensionality reduction, or density estimation are regularly used in Computer Vision (CV) applications. Unsupervised learning operates on learning from unlabeled data. This can dramatically reduce the cost of deploying machine learning algorithms to new applications, thus amplifying their impact on the real world. It is possible to adapt unsupervised methods based on density estimation or dimensionality reduction (like clustering) for deep models, however, these methods offer a poor performance when they are scaled for larger datasets. Clustering methods were primarily designed for linear models on top of fixed features, and they don’t perform well when features are to be learned simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1iJf8enFKDEyCJVVLfXn_g.png" /><figcaption>Representation Learning</figcaption></figure><p>The process of learning a deep neural network while discovering the data labels can be termed simultaneous clustering and representation learning. We can perform clustering of the data by using unsupervised clustering algorithms such as k-means and use the results of the clustering to learn the data labels by using its output as feedback (cross-entropy minimization). But combining representation learning with clustering can lead to creating degenerate solutions — solutions that are feasible but at least one of its basic variables is zero. DeepCluster [1] introduced a method that achieved excellent results in unsupervised representation learning. However, it doesn’t optimize the learning, instead, it avoids the occurrence of degenerate solutions by adopting a certain style of implementation. To overcome these problems, a paper published by Yuki Asano [2] introduces us to a new method that provides a principled formulation for simultaneous clustering and representation learning.</p><p>In this approach, we proceed as follows:</p><ol><li><strong>Minimize the cross-entropy loss for learning the deep network and estimate the data labels — </strong>This step is done in semi-supervised learning, however, if we use the same concept for unsupervised learning, we might land on degenerate solutions. To solve this issue, we proceed to step 2</li><li><strong>Add a constraint that the labels must generate equipartition of the data — </strong>This maximizes the information between data indices and labels. It results in an assignment problem that is analogous to an optimal transport problem, and hence it can be solved using linear programming. The problem in question is for large datasets, where there are millions of labels and data points for which the standard transport algorithms might fail. To solve this issue, we proceed to step 3</li><li><strong>Use a faster version of the Sinkhorn-Knopp algorithm to solve the transport problem for a large number of data points — </strong>The use of matrix-vector algebra is done for faster execution</li></ol><blockquote><strong>Need for a self-labeling algorithm?</strong></blockquote><blockquote>We are using a method where class scores are mapped to the class probabilities via the softmax operator. The model and head parameters are learned by minimizing the average cross-entropy loss, and this type of model requires a labeled dataset. When labels are not available, we NEED a self-labeling algorithm.</blockquote><p>Let’s walk through the method in detail</p><h4>Self-labeling:</h4><p>We start by defining a Deep Neural Network as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQB7kkd0HdG85T2HjsaiBg.png" /><figcaption>Model Representation</figcaption></figure><p>Using a softmax operator, the class scores are mapped to class probabilities. The learning for the network is done by minimizing this cross-entropy loss. Our objective, thus comes out to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*r8u6VO1C6Xa-IOc-vKTlCQ.png" /></figure><p>In semi-supervised learning, minimizing our current objective requires labeled data, however, it is not possible to label the data when the volume is in millions. This is why we need to make use of unsupervised learning.</p><p>Minimizing the entropy loss in unsupervised learning will lead to a degenerate solution, where, the optimization will be trivially achieved by assigning all data points to a single random label.</p><p>To address this issue, the labels are encoded as a posterior distribution q(y|xᵢ). Using posterior distribution, our objective can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*4GYV7dxGiHlGfPAvOiz6UQ.png" /></figure><p>Assuming that we set the posterior distribution as deterministic, the goal is now to optimize the q, but the problem persists because optimizing q is the same as reassigning the labels. So, to avoid this issue, we add a constraint that each data point will be assigned to only one label y, thus the total number of data points N will be uniformly grouped into exactly K clusters*. So, our learning objective now is to minimize E(p, q), as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*-l5zVAPrGgEebVG9cJc6yQ.png" /></figure><p>Now that we have formalized the learning objective, we notice that even though we are selecting the elements from a large group without any regard for their arrangement, they are combinatorial, hence very difficult to optimize. So, to optimize our problem, we would be transforming the learning objective into an instance of an optimal transport problem.</p><p>*<em>This is an equipartition condition, where a constraint is set that the label assignment must partition the data into equally-sized subsets of [N/K] or [N/K]+1</em></p><blockquote><strong>The Optimal Transport Problem</strong></blockquote><blockquote>The optimal transport problem (OTP) gives us a framework where one essentially pays a cost for transporting one measure to another. In layman’s terms, we can say that OTP is basically how we transport the probability of measure A to the probability of measure B while minimizing the cost ( c ) of transporting one unit of mass from A to B.</blockquote><p>In our learning objective, we can consider Pᵧᵢ as a set of joint estimated probabilities which can be our measure ‘A’ and Qᵧᵢ as a set of joint assigned probabilities. Using the notion of the OTP (presented in [3]) we can find the matrix Q which is a set of all possible tables that will satisfy a set of given margins. Our objective will now be transformed to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*aIwOimYpmbfevCCdxfxPag.png" /></figure><p>where 〈·〉is the Frobenius dot product (a.k.a inner dot product)</p><p><a href="https://en.wikipedia.org/wiki/Frobenius_inner_product">Frobenius inner product - Wikipedia</a></p><p>By using the principles of OTP, we can reduce our objective to linear time complexity. But traditional algorithms are not able to scale large datasets. Therefore, to scale and solve the transportation problem we use a version of the Sinkhorn-Knopp algorithm using a regularization term ‘KL’ which is also known as Kullback-Leibler divergence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*MM2ZW4NIKizdpiC8AiGC9w.png" /></figure><p>where KL is the Kullback-Leibler divergence and rcᵀ can be interpreted as a K×N probability matrix. The sinkhorn-Knopp algorithm is usually used for convergence and the advantage of the KL term is for minimizing the above equation, the minimizer for that can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*smEJ1bs3eVaJwFEjbuIxzA.png" /></figure><p>The value of λ is a tradeoff between convergence speed with closeness to the OTP, therefore we keep it constant so that we can achieve the final clusters in a more optimized way. The values of α, ß (both are scaling coefficients) are chosen in such a way that the resulting matrix Q is a probability matrix. In practice the values of α, ß are retained in every cycle thus increasing the optimization of our problem.</p><p><strong><em>The algorithm core:</em></strong></p><p>The algorithm, finally, is a process of learning the model and assigning the labels by solving the optimization problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*aIwOimYpmbfevCCdxfxPag.png" /></figure><p>It is achieved by alternating between the following two steps:</p><ol><li>For a current label assignment Q, we perform updates to our model (h ◦ Φ) by minimizing our objective with respect to the parameters of our model</li><li>Given the current model (h ◦ Φ), we compute the log probabilities P and then calculate label assignment Q by iterating the below updates:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*yYOeiq6A6FgmQWXyTFabbg.png" /></figure><p>Each update involves a single matrix-vector multiplication with complexity O(N K), so it is relatively quick even for millions of data points and thousands of labels.</p><h4><strong>Implementation of the Self-Labeling (SeLa) technique and optimal configuration</strong></h4><p><strong>Architecture setup</strong></p><ul><li><strong>Linear Probes</strong>: — Linear probes is a technique where we train a linear classifier on top of a pre-trained feature representation which is kept fixed</li><li><strong>Data</strong>: — Training data consists of ImageNet LSVRC-12 and other small similar datasets</li><li><strong>Architecture</strong>: — The base encoder used for this experimentation is AlexNet and for back-propagation we use ReLU. The probes are injected after each relu layer. With 5 layers denoted as conv1 to conv5, the first two layers conv1 to conv2 can be learned easily from data augmentation, while the next 3 (deeper) layers are more impactful towards the performance analysis.</li></ul><p><strong>Optimal configuration and ablations</strong></p><ul><li><strong>Changing the value of number of clusters — </strong>Larger number of clusters (K) slightly decrease the performance</li><li><strong>Changing the number of heads — </strong>Increasing the value of heads (T) yields a performance gain, which occurs to be between 2% (for AlexNet) to 10% (for ResNet)</li><li><strong>Number of self labeling steps — </strong>Self labeling steps are essential for good performance. Varying the number of times the self labeling algorithm is run during training, the best value occurred around 80</li><li><strong>Architectures — </strong>SeLa works well with various standard architectures such as Alexnet and ResNet</li></ul><p><strong>Implementation Results</strong></p><p>All the models are trained using SGD with the initial learning rate of 0.05 for 400 epochs reducing the learning rate at 150, 300, and 350 epochs. The value of λ is kept at 25.</p><p>The following table compares clustering metrics obtained using the trained models. They are compared against the ground truths of ImageNet validation set. These metrics include the adjusted Normalized Mutual Information and adjusted Random Index. Top-1 Accuracies are obtained using the ImageNet Linear Probing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Lh_ACjE3WcQPieKEUxg-dg.png" /><figcaption>Comparison of clustering metrics</figcaption></figure><p>The following graph shows the distribution of cross-entropy of pseudo labels with regards to the ImageNet Labels changes with training time. It helps us in understanding how well the input images are getting clustered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*hleKc6QyjyvB8MxhMI7UGA.png" /><figcaption>Cross-entropy of pseudo-labels</figcaption></figure><p>We observe that at the start, for random real ImageNet labels, a high entropy is obtained but towards the end of training we arrive at a very low value of entropy. The following figures show the random samples of images associated with the lowest entropy pseudo labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*X2H-8TqXJokp0YbKZdWOBw.png" /></figure><p>The following are the visualizations of the validation sets. They have been sampled with labels having the lowest entropy pseudo-classes of the training sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*xdm81QqhNTnfT6J-dK51uw.png" /></figure><p>The next two sets of figures have been obtained for random label visualization. In these sets of images, the first is obtained through randomly sampling the ImageNet training set which is associated with random pseudo-classes. The next image is obtained through random sampling of the validation set images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Ctw-emcBcqaW71I44SSX1A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*0ahgkarJghXpb-59ENCU1w.png" /></figure><p><strong>How Self Labeling (SeLa) solves the problem?</strong></p><p>The objective of optimizing a loss equation — for the setting where feature vectors are extracted by the neural network by processing on the input data (clustering) — is to minimize the reconstruction error of the clustering algorithm. The problem is that this minimization can be obtained by flushing all the data points into one cluster, thus forcing all the means to coincide with a single feature vector. DeepCluster [1] makes use of this method, and they successfully avoid the possibility of having a degenerate solution by establishing an interaction between the representation learning and clustering steps. They do so by fixing the feature vectors such that the K-means don’t coincide to a single feature vector, and also by fixing the label assignments during the classification. In contrast to this method, where convergence cannot be guaranteed due to the lack of having a well-defined objective, SeLa uses a single, well-defined objective for both — Representation Learning and Self Labeling — by reducing the objective to an optimal transport problem.</p><p>Learning formulation of SeLa can be interpreted as maximizing the information between data indices and labels while explicitly enforcing the equipartition condition, which is implied by maximizing the information in any case. Compared to minimizing the entropy alone, maximizing information avoids degenerate solutions as the latter carry no mutual information between labels y and indices i. DeepCluster also avoids the degenerate solutions but it cannot guarantee the convergence, which is why SeLa is advantageous over DeepCluster.</p><h4>The Conclusion</h4><blockquote>Self Labeling (SeLa) is State-Of-The-Art</blockquote><ul><li>A self-supervised feature learning method that is based on clustering</li><li>Optimizes the same objective during feature learning and clustering</li><li>Resulting self-labels can be used to quickly learn features for new architectures using simple cross-entropy training</li><li>Outperforms all other feature learning approaches and achieves SOTA</li></ul><h4><strong>References:</strong></h4><p>[1] <strong>Deep Clustering for Unsupervised Learning of Visual Features, Caron et al., 2018</strong> <a href="https://doi.org/10.48550/arXiv.1807.05520">https://doi.org/10.48550/arXiv.1807.05520</a></p><p>[2] <strong>Self Labelling Via Simultaneous Clustering and Representation Learning</strong>, <strong>Yuki Asano, 2020</strong> <a href="https://doi.org/10.48550/arXiv.1911.05371">https://doi.org/10.48550/arXiv.1911.05371</a></p><p>[3] <strong>Sinkhorn Distances: Lightspeed Computation of Optimal Transportation Distances, Marco Cuturi, 2013 </strong><a href="https://doi.org/10.48550/arXiv.1306.0895">https://doi.org/10.48550/arXiv.1306.0895</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6383dbf6f65e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/self-labeling-via-simultaneous-clustering-and-representation-learning-6383dbf6f65e">Self Labeling Via Simultaneous Clustering and Representation Learning</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VoxelNet: End-To-End Learning for Point Cloud Based 3D Object Detection]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/voxelnet-end-to-end-learning-for-point-cloud-based-3d-object-detection-6bf52c3e8fc1?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/6bf52c3e8fc1</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[autonomous-driving]]></category>
            <category><![CDATA[3d-object-detection]]></category>
            <category><![CDATA[lidar]]></category>
            <dc:creator><![CDATA[Adam Cuellar]]></dc:creator>
            <pubDate>Mon, 02 May 2022 20:19:42 GMT</pubDate>
            <atom:updated>2022-05-02T20:19:42.435Z</atom:updated>
            <content:encoded><![CDATA[<p>My name is Adam Cuellar and the following is a summary on the VoxelNet architecture for 3D object detection. In addition to this blog, you can watch a video presentation on YouTube <a href="https://www.youtube.com/watch?v=LyOC2TkYnS8&amp;t=31s">here</a>.</p><p>Developed in 2017 by Yin Zhou and Oncel Tuzel, VoxelNet was the state of the art in point cloud-based 3D object detection. Unlike previous 3D object detection methods, VoxelNet uses the 3D point cloud information end to end in the learning process. Previous methods required rasterizing point clouds into a 3D voxel grid and encoding the voxel via hand-crafted features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*u5MPircumtzJLzkslZIMRw.png" /><figcaption>VoxelNet Architecture</figcaption></figure><p><strong>VoxelNet Overview</strong></p><p>The following provides an outline of the end-to-end learning process outlined by the authors:</p><p>1. Ingest LiDAR data by dividing the point cloud into equally spaced 3D voxels.</p><p>2. Encode each voxel via Voxel Feature Encoding (VFE layers) producing a 4D tensor</p><p>3. Process each tensor using the convolutional middle layers</p><p>4. Use a region proposal network (RPN) to generate a 3D detection</p><p><strong>Step 1: The Input</strong></p><p>Using a LiDAR sensor, data is collected and represented as a point cloud of individual points reflected from the surface of objects in a 3D environment. Point clouds obtained using LiDAR are sparse and can contain greater than 100k points; therefore, using all the information at once can be computationally expensive. In the past, hand-crafted features were used to reduce the data down into a useful representation. One of the previous approaches, Multi-View 3D networks (M3VD), used a multi-view encoding scheme to obtain an effective representation of the point cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*1zAeHoIKUffG8meqkhfX0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*bM6dy1uVqBVgUhzNcBLIow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*_NQu6PagLDSbdxPS7-NwsA.png" /></figure><p>For example, the images above shows the input to the M3VD network: Image A shows the hand crafted features from the birds eye view, Image B shows the features from the front view, and C is the RGB image.</p><p>However, VoxelNet divides the 3D space into equally spaced voxels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*8iH4AFkogXPmUAWMg33GaA.png" /></figure><p>Following the figure above, if we’re given a point-cloud with dimensions of we can divide that space into a grid of 3D voxels where each voxel is of size. Each voxel will now contain a variable number of points due to the sparsity of LiDAR data. To overcome this, the authors propose using random sampling to sample a fixed number of points, <em>T</em>, from each voxel prior to encoding the information via the VFE layer. For each point the authors check if the corresponding voxel already exists to avoid duplicate samples. This is done using a lookup operation which uses a hashtable where the voxel coordinate is used as the hash key. If the voxel is already initialized then the point is added to the voxel location if there are less than <em>T</em> points, otherwise the point is ignored. The random sampling and coordinate lookup can be constructed in a single pass; therefore, the complexity of this operation is <em>O(n)</em>. The number of points chosen is specific to the task. More points will allow for capturing better shape information; however, too many points would make the network computationally expensive. This approach provides an added benefit of variation in training data as well as reducing the imbalance in number of points per voxel.</p><p><strong>Step 2: The Voxel Feature Encoding Layer</strong></p><p>The Voxel Feature Encoding layer is the main contribution of the paper. This layer is what set apart VoxelNet from previous work and introduced the idea of end-to-end learning instead of using hand-crafted features. These hand-crafted features were often computed using certain characteristics of the data. For example, in the MV3D network mentioned above, the bird’s eye view representation is encoded by height, intensity, and density.</p><p>The Voxel Feature Encoding layer encodes the randomly sampled points using a fully connected network (FCN), max-pooling, and point-wise concatenation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*8pkOR-GgEynY3dnPWPkeAA.png" /></figure><p>For each voxel, the randomly sampled points (shown as the blue, green, and yellow points above) are passed into a fully connected network that is comprised of a linear layer, a batch normalization layer, and ReLU layer. Specifically, each randomly sampled point is provided to the FCN as a vector containing the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*61KLAbHU7NJofld6ES049w.png" /><figcaption>Randomly Sampled Point Vector</figcaption></figure><p>where x, y, and z are the 3D coordinates and r is the reflectance value. The mean x, y, z, and r of the voxel are subtracted from the x, y, z and r of the point and added to the vector as well. The features are then passed to an element-wise max pooling which aggregates information from all features into a single representation. The aggregated feature is then repeated and concatenated to the point-wise features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*VqUfw7_GZ9ZHD2P-xTy5Dw.png" /><figcaption>Representation of 4D Tensor</figcaption></figure><p>This process is done for each non-empty voxel and through several stacked VFE layers providing a sparse tensor representation of the point-cloud of size <em>C x D’ x H’ x W’ </em>as shown in the figure above.</p><p><strong>Step 3: Convolutional Middle Layers</strong></p><p>After the features of each voxel are encoded using the VFE they’re processed further through the Convolutional Middle Layers. Each of the layers is a 3D convolution with a batch normalization layer and a ReLU layer. The goal of these layers is to aggregate voxel-wise features while progressively expanding the receptive field. The figure below shows an outline of the Convolutional Middle Layers architecture for Car Detection using the KITTI dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*CWZvV3znSuwQa84dVvJhuQ.png" /><figcaption>Car Detection Convolutional Middle Layers</figcaption></figure><p><strong>Step 4: Region Proposal Network</strong></p><p>To generate 3D detections the features from the Convolutional Middle Layers are passed to a Region Proposal Network. For 2D images popular state of the art network, such as Faster R-CNN, have implemented RPN’s for object detection. The authors of VoxelNet adapt the same RPN used in Faster R-CNN for 3D object detection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*p7lct0U_o3Ps8yTy12ZSLg.png" /></figure><p>Prior to passing the output of the Convolutional Middle Layers to the RPN the features must be reshaped to a 3D tensor. After reshaping, the RPN uses convolutions to down sample the features which are passed using skip connections then up sampled to a fixed size for the final feature map. The final feature map is used to predict a probability score map and a regression map. The network provides an output for each voxel.</p><p><strong>Training:</strong></p><p>VoxelNet is trained on the LiDAR data obtained from the KITTI dataset for Car, Pedestrian, and Cyclist Detection. Specific parameters are used for the Car Detection task and the Pedestrian &amp; Cyclist Detection task; therefore, the authors had two variations of the network. The car detection task only required one anchor whereas the pedestrian/cyclist class requires two. The other main difference is that the RPN for pedestrian and cyclist detection is modified for finer resolution by changing the stride size of the first convolution from 2 to 1.</p><p>For data augmentation the authors had 3 seperate online methods outlined below:</p><ol><li>Rotating and shifting the bounding boxes as individual pieces within the point-cloud. To avoid physically impossible outcomes they used a collision test between boxes after the perturbation. If a collision was detected then the data is reverted to the original set up.</li><li>Global scaling which includes multiplying the entire point-cloud by some scale factor.</li><li>Global rotation of the point-cloud where the data is rotated along the Z-axis.</li></ol><p>Each network is trained using stochastic gradient descent with a learning rate of 0.01 for 150 epochs and then 0.001 for another 10 epochs.</p><p>The following image is an example of what the LiDAR data looks like along with bounding boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*Y42jUNAvi8cFvQGJh-pScA.png" /></figure><p><strong>Loss:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*GYwd3Lvi7LMpqzja5IDcJA.png" /></figure><p>The loss function for training the network is outlined above. The intention of the network should be to output a 3D bounding box of the predicted object for each voxel. It should also predict whether that object is part of the foreground or background which is considered a positive or negative prediction and is predicted as a probability for each. Specifically, the network must output the offset of the bounding box from the anchor parameterized as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*_vR5JTA8G6S5QgBMWadwSw.png" /></figure><p>which are predicted as offsets from a predefined anchor using the following equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*vcX2CNHMj6p6dAxkXkOLSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*hg0JSWmrBvf2vwFVeCN76w.png" /></figure><p>The x and y predictions are normalized using the diagonal of the bottom face of the anchor or dᵃ. The Z coordinate is normalized by the height of the anchor and the length, width, and height are the log of the prediction over the anchor measurement. The probability of being a positive or negative prediction is refined using the Binary Cross Entropy Loss with alpha and beta parameters which weight each prediction accordingly. The loss of the positive prediction is the mean of the BCE over the number of positive anchors, <em>i</em>, and the loss of the negative prediction is the mean of the BCE over the number of negative anchors <em>j. </em>This is shown as Lcls in the loss function. The bounding box is refined using the regression loss which is a SmoothL1 loss function. The loss is taken as the mean over all of the positive points <em>i. </em>It is similar to what was done with 2D object detection and Fast R-CNN. This is shown as Lreg in the loss function. The SmoothL1 loss function is used because it is less sensitive to outliers when compared to the L2 or MSE loss. It also helps prevent exploding gradients.</p><p><strong>Results</strong></p><p>Overall, VoxelNet performs well on the KITTI dataset. The KITTI dataset is split into three categories Easy, Moderate, and Hard. In order to emphasize the importance of end-to-end learning the authors also report the results of a network which they call the HC-Baseline. The HC-Baseline has a similar architecture to Voxelnet but uses hand-crafted features as the input instead of encoding the voxel information through the VFE layers. At the time VoxelNet became the new state of the art, outperforming previous 3D object detection methods and the HC-Baseline. The table shows the results of the networks on each of the categories and for each detection task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*oq0Sbgth3C8A6j3KaO4cbg.png" /></figure><p>The following shows the detections drawn onto a 2D image obtained from the KITTI data. You can see that the network accurately detects the cars, pedestrians, and cyclists in each of the respective images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*z2AOtYKPuDreryt1NHYRlw.png" /></figure><p><strong>Ideas for Improvement:</strong></p><p>Below are some thoughts I had for improving VoxelNet’s performance:</p><ol><li>I think the prediction of both positive and negative is a bit redundant. It could be replaced with a single value where a threshold determines whether the object is positive or negative. At the time, most networks for 2D and 3D object detection predicted both object or no object; however, more recent work only uses one value.</li><li>Using self-supervised representation learning which seems to be the current state of the art on the KITTI dataset. I’m curious as to how VoxelNet can benefit from something like this. Another idea I had was to replace the voxel feature encoding layers with a transformer encoder layer. I think the self-attention mechanism in the transformer encoder would help provide more insight to the network about which points are related to one another.</li><li>I believe the network can be modified to provide an output for both detection scenarios. The way it was designed was specific to either Car or Pedestrian/Cyclist detection; however, I think the network can be modified to produce a detection for both. I think this would help the network with generalization by forcing it to understand the discrepancies between the types of 3D objects.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf52c3e8fc1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/voxelnet-end-to-end-learning-for-point-cloud-based-3d-object-detection-6bf52c3e8fc1">VoxelNet: End-To-End Learning for Point Cloud Based 3D Object Detection</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Review of DeepFool: a simple and accurate method to fool deep neural networks]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/a-review-of-deepfool-a-simple-and-accurate-method-to-fool-deep-neural-networks-b016fba9e48e?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/b016fba9e48e</guid>
            <dc:creator><![CDATA[Adrian Morgan]]></dc:creator>
            <pubDate>Mon, 02 May 2022 20:17:41 GMT</pubDate>
            <atom:updated>2022-05-02T20:17:41.446Z</atom:updated>
            <content:encoded><![CDATA[<h4>By Eric Watson and Adrian Morgan</h4><h3>Project Presentation</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwSYbf_b3N14%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwSYbf_b3N14&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwSYbf_b3N14%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ace92ec7ffc564b71988bd771306f7a/href">https://medium.com/media/9ace92ec7ffc564b71988bd771306f7a/href</a></iframe><h3>Project Repository</h3><p><a href="https://github.com/ewatson2/EEL6812_DeepFool_Project">https://github.com/ewatson2/EEL6812_DeepFool_Project</a></p><h3>Introduction</h3><p>Deep neural networks (DNN) have achieved state of the art performance for image classification tasks. However, state of the art DNNs have vulnerabilities to adversarial attacks. They are susceptible to small perturbations that are made in a meaningful way, which is not random noise. From the paper <em>DeepFool: a simple and accurate method to fool deep neural networks</em>, the authors Moosavi-Dezfooli et al. <a href="https://arxiv.org/pdf/1511.04599.pdf">[1]</a> introduce an efficient method to compute the minimal perturbations necessary to cause a classifier to misclassify an image, which they call DeepFool.</p><p>The authors of DeepFool also introduce a method of evaluating the robustness of adversarial perturbations, which can be used to compare results with other adversarial attack methods. The authors also perform an experiment to improve the robustness of DNNs by training on adversarial images.</p><p>A few examples are shown below in Figure 1. In the top row, an original image is determined to be a whale by a classifier. In the middle row, the original image of a whale has been perturbed resulting in the classifier determining it to be a turtle. The perturbed image is very subtle and is imperceptible to the human eye. The last depicts a similar perturbed image, but it has been perturbed with the Fast Gradient Sign Method (FGSM) proposed by Goodfellow et al. <a href="https://arxiv.org/pdf/1412.6572.pdf">[2]</a>, which is the primary comparison method in the paper. FGSM was able to misclassify the original image as a turtle as well, but the amount of perturbations required is higher, which can be visually seen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*P6afTnBgEPUCIXYq" /><figcaption>Figure 1: Example of Adversarial Perturbations (Deepfool vs. FGSM)</figcaption></figure><h3>DeepFool for Binary Classifiers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*_MtlgwK7XbPTr_MV.png" /><figcaption>Figure 2: Adversarial Example for Binary Classifier</figcaption></figure><p>Before the authors of DeepFool explain their algorithm for multi-class classifiers, they start off using a simply binary classifier as shown in Figure 2. From observing the figure, it is seen that in order to obtain the minimal perturbation for the classifier of 𝑓 to misclassify the input image of <em>x</em>, the perturbation of <em>r*(x) </em>must project the input image of <em>x</em> orthogonal to the hyperplane of the binary classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*8dfhTzWtEWeJGUOv.png" /><figcaption>Figure 3: DeepFool Equation to Calculate the Perturbation for a Binary Classifier</figcaption></figure><p>The DeepFool algorithm computes the perturbation of <em>r*(x)</em> by having the output prediction of 𝑓<em>(x_0)</em> divided by the L2-norm of the computed gradient <em>ω</em> of the loss function, giving the scalar for the perturbation. This is then multiplied by the unit vector of <em>ω</em> using L2-norm and finally has the sign inverted so the loss of the classifier 𝑓 is increased, as shown in Figure 3. Using the idea of models being linear, the authors devised this simple algorithm, but misclassification is not guaranteed since models are non-linear in nature. To alleviate this issue, the algorithm works iteratively and adds the previous perturbation to the next perturbation, which is performed until the label changes or max iterations are reached, as shown in Figure 4. Additionally, convergence could end up close to zero, so a parameter called overshoot <em>η</em> is used as a scalar (1 + <em>η) </em>for the perturbation of <em>r*(x),</em> so it would go past zero and make the class label change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s8gWPvxIzW8bPhph.png" /><figcaption>Figure 4: Pseudocode of DeepFool Algorithm for Binary Classifier</figcaption></figure><h3>DeepFool for Multi-Class Classifiers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/0*7_JadYZXz_pHVelm.png" /><figcaption>Figure 5: Adversarial Example for Multi-Class Classifier</figcaption></figure><p>Extending from the DeepFool algorithm implemented for binary classifiers, the DeepFool algorithm for a multi-class classifier can be considered multiple binary classifiers, as shown in Figure 5. The decision boundary as shown in Figure 5 can be considered a polyhedron, which is made from the intersection of multiple hyperplanes. The minimum perturbation needed would be from the closest hyperplane to <em>x_0</em>. Given there are multiple classes, the loss and backpropagation would need to be computed for each class label allowed by the function. When finding the minimum perturbation, the difference must be taken between the computed values for each label and the computed values for the label of the original prediction. This is shown in Figure 6, in which the index for the minimum perturbation is returned as <em>l(x_0)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/0*LmauP4N7aCLEKB9Q.png" /><figcaption>Figure 6: DeepFool Equation to Find the Index for the Minimum Perturbation for a Multi-Class Classifier</figcaption></figure><p>After the index of <em>l(x_0)</em> is determined, the minimum perturbation of <em>r*(x_0)</em> is computed similarly to the binary case shown in Figure 3. The only difference to the binary case is that it requires the differences of the classifier output and the gradients of the outputs, as well as taking the absolute value of the model output, as shown in Figure 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hNw0yvksnUHFUlj5.png" /><figcaption>Figure 7: DeepFool Equation to Calculate the Minimum Perturbation for a Multi-Class Classifier</figcaption></figure><p>After the perturbation is computed, it would be added to the previous perturbation of <em>r*(x_0)</em>, which is then multiplied by the overshoot scalar of (1 + <em>η</em>) and added to the input image of <em>x_i. </em>This process is repeated until the max iterations are reached or the output prediction of <em>k_i</em> from the image of <em>x_i</em> is not equal to the original output prediction of <em>k_0 </em>from the original image <em>x_0</em>. The pseudocode for the DeepFool multi-class algorithm is shown in Figure 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A8l-sAYWe4YcWrv6.png" /><figcaption>Figure 8: Pseudocode of DeepFool Algorithm for Multi-Class Classifier</figcaption></figure><h3>Fast Gradient Sign Method (FGSM)</h3><p>The Fast Gradient Sign Method (FGSM) by Goodfellow et al. <a href="https://arxiv.org/pdf/1412.6572.pdf">[2]</a> was used as comparison in the DeepFool paper. The algorithm works by taking the inputs of the classifier 𝑓, batch images of <em>x</em>, and batch labels of <em>y</em>. The input of <em>x</em> is forwarded to the classifier of 𝑓, giving the prediction of 𝑓<em>(x)</em>, which is then used for the cross entropy loss function with the batch labels of <em>y</em>. Backpropagation of the loss function is performed, and the gradients of <em>ω</em> are obtained. The sign of the gradients are then multiplied by the scalar of <em>ε</em>, which controls the magnitude of the perturbations, which are then added to the batch images of <em>x</em>. With only using one iteration, and having the ability to compute the perturbations for a batch of images at once, this allows the FGSM method to perform faster than the DeepFool method. However the algorithm is not designed to find the minimal perturbations, so it would result in larger perturbations and also requires manual adjustment of the parameter of <em>ε</em> to get desired results.</p><h3>Datasets</h3><p>The following datasets used in the DeepFool paper are <a href="http://yann.lecun.com/exdb/mnist/">MNIST</a>, <a href="https://www.cs.toronto.edu/~kriz/cifar.html">CIFAR-10</a>, and <a href="https://www.image-net.org/challenges/LSVRC/2012/">ILSVRC2012</a>. The training and validation sets of MNIST and CIFAR-10 were used for adversarial training and evaluation, while the validation set of ILSVRC2012 was used only for adversarial evaluation. The specifications of the datasets are the following:</p><h4>MNIST Dataset</h4><ul><li>Has 28x28 grayscale images of hand-written digits</li><li>Has 60,000 training images and 10,000 validation images</li><li>10,000 images were split for validation from training, and the original validation images were used for testing</li><li>Dataset was normalized along with random horizontal flipping of images for training/validation</li></ul><h4>CIFAR-10 Dataset</h4><ul><li>Has 32x32 RGB images of airplanes, automobiles, birds, cats, deers, dogs, frogs, horses, ships, and trucks</li><li>Has 50,000 training images and 10,000 validation images</li><li>10,000 images were split for validation from training, and the original validation images were used for testing</li><li>Dataset was normalized along with random horizontal flipping and cropping of images for training/validation</li></ul><h4>ILSVRC2012 Dataset (Validation)</h4><ul><li>Has 1000 classes and 50,000 validation images</li><li>Images were resized to size of 256 and cropped to size of 224 for GoogLeNet model</li><li>Dataset was normalized</li></ul><h3>Models</h3><p>Replication was attempted for the models used in the DeepFool paper, with two different models being used for each dataset. The models used are the following:</p><h4>LeNet-5 Model for MNIST</h4><ul><li>Uses two convolutional layers with kernel size of 5 and stride of 1</li><li>Uses two max pooling layers with kernel size of 2 and stride of 2</li><li>Uses two linear hidden layers with sizes of 120 and 84</li><li>Uses ReLU for activation functions</li></ul><h4>FC-500–150 Model for MNIST</h4><ul><li>Uses two linear hidden layers with sizes of 500 and 150</li><li>Uses ReLU for activation functions</li></ul><h4>Network-In-Network Model <a href="https://arxiv.org/pdf/1312.4400.pdf">[4]</a> for CIFAR-10</h4><ul><li>Uses the following GitHub <a href="https://github.com/jiecaoyu/pytorch-nin-cifar10">[5]</a> implementation using PyTorch</li><li>This model does not use linear layers and replaces them with convolutional layers followed by global average pooling</li><li>Using a mini-network instead of linear layers helps reduce overfitting and improves accuracy</li></ul><h4>LeNet-5 Model for CIFAR-10</h4><ul><li>Uses three convolutional layers with kernel size of 5, stride of 1, and padding of 2</li><li>Uses three max pooling layers with kernel size of 2 and stride of 2</li><li>Uses three linear hidden layers with sizes of 400, 120, and 84</li><li>Uses ReLU for activation functions</li></ul><h4>GoogLeNet for ILSVRC2012</h4><ul><li>State of the art model that ranked high in object detection and classification categories for the <a href="https://image-net.org/challenges/LSVRC/2014/results">ILSVRC2014</a> challenge</li><li>Uses pre-trained weights that were trained on ImageNet</li></ul><h4>CaffeNet for ILSVRC2012</h4><ul><li>Due to time constraints, this model was not implemented for the project</li></ul><h3>DeepFool Experiment Setup</h3><p>The author devised a way to evaluate the robustness of a classifier to adversarial attacks. The average robustness ρ of a classifier 𝑓 is calculated by taking the magnitude of the minimal perturbation <em>r(x)</em> per each image <em>x</em>, taking the sum of all of those values then dividing by the absolute value of all the test images <em>D</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*F7TA2c5Wylb3j9l3" /><figcaption>Figure 9: Average Robustness Equation</figcaption></figure><p>This equation is used to evaluate multiple classifier models and datasets against other methods of adversarial attacks, shown in Table 1 below.</p><h3>DeepFool Experiment Results</h3><p>The results show that DeepFool creates adversarial images with the lowest perturbation, but requires more computation time when compared to FGSM. FGSM is able to create adversarial images fast, but it has more perturbations than DeepFool. DeepFool requires more computation time due to its iterative process in order to find the minimal perturbation. Compared to DeepFool, FGSM computes the perturbations for one iteration, which allows it to be fast in exchange for not guaranteeing full misclassification. Also shown is the methods described in the paper <em>Intriguing Properties of Neural Networks </em><a href="https://arxiv.org/pdf/1312.6199.pdf">[3]</a>, which is also able to find small perturbations that rivals DeepFool, but it requires extensive computational time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xh78-liSY4B7eh6p" /><figcaption>Table 1: Adversarial robustness comparison</figcaption></figure><p>The models were trained on the adversarial images to improve robustness of the models. In Table 2 below, the results of the test error after adversarial training is shown. The models were trained for five epochs at half of the original learning rate. The table shows a training accuracy comparison between DeepFool and FGSM. The training accuracy for DeepFool increased for all models, while FGSM accuracy decreased. The accuracy decreased for FGSM most likely due to it producing too many perturbations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ZQ604ZYI6k6ZPRQw" /><figcaption>Table 2: Adversarial training test accuracy</figcaption></figure><p>The following models of LeNet for MNIST, FC-150–50 for MNIST, NIN for CIFAR-10, and LeNet for CIFAR-10 are trained on the adversarial images computed by DeepFool and FGSM. The graph in Figure 10 below shows the result of the adversarial training on the models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E5Dijkk7l7A_OB8A.png" /><figcaption>Figure 10: DeepFool Adversarial Training Results</figcaption></figure><p>In the previous examples, it can be seen that DeepFool robustness performs much better than FGSM when training on adversarial images. This is most likely due to FGSM producing vastly more perturbations than DeepFool, which may lead to images that are not likely to appear in the dataset. To test this hypothesis, a constant scalar α is multiplied by the minimal perturbations created by DeepFool to evaluate how the robustness responds. In Figure 11 below, it depicts the robustness dropping dramatically for each increment of the value α. This result confirms that training on highly perturbed images decreases overall robustness of models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*_wwibi1d9om_5NP9" /><figcaption>Figure 11: DeepFool Adversarial Robustness Results</figcaption></figure><h3>Project Setup</h3><p>The author’s experiment was reimplemented to test the same models used in the paper, excluding CaffeNet due to time constraints. The models were trained and evaluated with a Nvidia RTX 2070 Super graphics card. A batch size of 128 for training and a batch size of 64 for evaluation was used. The MNIST and CIFAR-10 models were trained on 50 epochs, while the NIN model was trained on 100 epochs. The MNIST and CIFAR-10 models were optimized using stochastic gradient descent (SGD) with a learning rate of 0.004 and momentum of 0.9.</p><h3>Project Results</h3><p>FC-500–150 for MNIST dataset adversarial images generated from DeepFool and FGSM are shown below in Figure 12. It depicts the original image with a label of a “7” being perturbed by both methods to fool the classifier to label it as a “5”. Similarly, an image with label “3” was misclassified as an “8”. As expected, the perturbations generated from DeepFool are lower than the FGSM perturbation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ALIg3yFv_m1aE9eW" /><figcaption>Figure 12: FC-500–150 for MNIST Misclassification Examples of a “7” and “3”</figcaption></figure><p>LeNet for CIFAR-10 dataset adversarial images generated from DeepFool and FGSM are shown below in Figure 13. It depicts the original image with a label of a “horse” being perturbed by both methods to fool the classifier to label it as a “dog”. Similarly, an image with the label “dog” was misclassified as a “cat” for FGSM and a “frog” for DeepFool. As expected, the perturbations generated from DeepFool are lower than the FGSM perturbation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qcSsiQ6Yfo0dwLJV" /><figcaption>Figure 13: LeNet for CIFAR-10 Misclassification Examples of a “horse” and “dog”</figcaption></figure><p>GoogLeNet for ILSVRC2012 dataset adversarial images generated from DeepFool and FGSM are shown below in Figure 14. It depicts the original image with a label of a “ballplayer” being perturbed by both methods to fool the classifier to label it as a “baseball”. Similarly, an image with the label “four-poster” was misclassified as a “quilt” for FGSM and a “komondor” for DeepFool. As expected, the perturbations generated from DeepFool are lower than the FGSM perturbation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zmuYN4kkTpg8IzBP" /><figcaption>Figure 14: GoogLeNet for ILSVRC2012 Misclassification Examples of a “ballplayer” and “four-poster”</figcaption></figure><p>Our results for adversarial robustness are shown below in Table 3 side by side with the author’s results for comparison. It shows similar results to paper in that DeepFool produces adversarial images with less perturbations than FGSM. The time required to create each adversarial image is vastly faster than the paper’s results. This is due to using a higher performance GPU, since the hardware for the DeepFool paper was an Nvidia GTX 750 Ti graphics card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pfPWNgdgPgRSOgsK" /><figcaption>Table 3: Adversarial Robustness Re-implementation Results</figcaption></figure><p>Our results for test accuracy after training on adversarial images are shown below in Table 4. DeepFool did not perform as expected to improve adversarial robustness. This is most likely due to adversarial images being generated per each batch using the updated weights, instead of generating all adversarials at the start of each epoch using previous weights of the model. FGSM test error was shown to decrease for adversarial training, especially for the MNIST dataset. However, for a more complex dataset like CIFAR-10, it decreased test error, but also increased test error for non-perturbed images, which can be considered a downside of adversarial training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMMkq2Q8PPs17YLB" /><figcaption>Table 4: Adversarial Training Re-implementation Results</figcaption></figure><h3>Conclusion</h3><p>DeepFool finds the minimal perturbations necessary to create adversarial images to fool image classifiers. It is computed by having the minimum perturbations added to an image so the classification label changes. The results show that models can be trained on adversarial images to improve robustness. A caveat is that DeepFool requires knowledge about the model and its parameters in order to attack it, which is also known as a white-box attack. Under normal conditions, a real adversarial attack would not have any access to the model, however this method can be used to help evaluate robustness of models. Additionally, image compression algorithms, such as JPEG, can potentially compress the minimal perturbations, resulting in a failure to fool the model.</p><h3>References</h3><ol><li>S. Moosavi-Dezfooli, A. Fawzi, and P. Frossard, <em>DeepFool: a simple and accurate method to fool deep neural networks</em>. arXiv, 2015. doi: 10.48550/ARXIV.1511.04599.</li><li>I. Goodfellow, J. Shlens, and C. Szegedy, <em>Explaining and Harnessing Adversarial Examples</em>. arXiv, 2014. doi: 10.48550/ARXIV.1412.6572.</li><li>C. Szegedy, <em>Intriguing properties of neural networks</em>. arXiv, 2013. doi: 10.48550/ARXIV.1312.6199.</li><li>M. Lin, Q. Chen, and S. Yan, <em>Network In Network</em>. arXiv, 2013. doi: 10.48550/ARXIV.1312.4400.</li><li><a href="https://github.com/jiecaoyu/pytorch-nin-cifar10">https://github.com/jiecaoyu/pytorch-nin-cifar10</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b016fba9e48e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/a-review-of-deepfool-a-simple-and-accurate-method-to-fool-deep-neural-networks-b016fba9e48e">A Review of DeepFool: a simple and accurate method to fool deep neural networks</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards Transferable Targeted Attack]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/towards-transferable-targeted-attack-3a581f510fc0?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/3a581f510fc0</guid>
            <dc:creator><![CDATA[Zoran Kolega]]></dc:creator>
            <pubDate>Mon, 02 May 2022 16:47:38 GMT</pubDate>
            <atom:updated>2022-05-02T16:47:38.370Z</atom:updated>
            <content:encoded><![CDATA[<p>A high-level presentation of the CVPR 2020 paper “Towards Transferable Targeted Attack”, authored by Maosen Li, Cheng Deng, Tengjiao Li, Junchi Yan, Xinbo Gao, and Heng Huang.</p><p>Presentation Link: <a href="https://youtu.be/PQKXUNJiQOM?t=1523">https://youtu.be/PQKXUNJiQOM?t=1523</a></p><h3>Overview</h3><h4>Goals</h4><p>The goal of this paper is to design an adversarial attack method for neural networks. The aim is for it to be used to evaluate and improve the robustness of deep neural networks.</p><p>The attack has two main features which aid in accomplishing these goals:</p><ul><li>The attack conserves or improves the transferability of existing attacks.</li><li>The attack remains targeted in black-box attacks.</li></ul><h4>Problems with Existing Attacks</h4><p>There are two main flaws with existing adversarial attacks that this paper aims to address:</p><ol><li>Existing attacks suffer from noise curing.</li><li>Existing attacks do not require that the classification be far away from the true class.</li></ol><p>The paper provides two key contributions to address these issues.</p><ol><li>Introduction of the Poincare space to address noise curing.</li><li>A triplet loss to promote classification farther from the true class.</li></ol><h4>Concepts</h4><p>There are several concepts which are helpful to know to better understand this paper.</p><p><strong>Logits</strong></p><p>A logit is a simple formula:</p><blockquote>logit(x) = log(x / 1 - x)</blockquote><p>It is the inverse of the sigmoid function. It takes values in the range [0, 1] as input, and maps them onto the range [-∞, ∞].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*0_vjyB-5NCeM3kpV" /><figcaption>The graph of logit(x) = log(x / 1 - x).</figcaption></figure><p><strong>Norms</strong></p><p>Norms are used to calculate the magnitude of a vector. They are often referred to as distance metrics. This paper include three different norms:</p><p>L1 norm : Manhattan distance</p><p>L2 norm : Euclidean distance</p><p>L-∞ norm: returns the maximum magnitude element in the vector</p><p><strong>Poincare Ball</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kPlr9AbuxYBiV1am" /><figcaption>Several visualizations of the geometry of the Poincare ball [1].</figcaption></figure><p>The Poincare ball is an example of non-Euclidean geometry. In (b), the Euclidean length of each line segment in the ball is the same. The Poincare distance from any point on the ball to the edge tends to ∞. Figure (c) shows that the Poincare distance grows exponentially larger close to the surface of the ball.</p><p>The important takeaway from all of this is the geometry of the Poincare ball such that distances between points increase when moving closer to the surface of the ball.</p><p><strong>Hyperparameters</strong></p><p>These are the set of parameters for the model which are user specified.</p><p>K : a classifier</p><p>𝜖 : the maximum perturbation allowed for each pixel of an image</p><p>μ : the momentum decay factor</p><p>T : the number of iterations</p><p>𝑤 = [𝑤₁, 𝑤₂, … , 𝑤ₖ] : the ensemble weights</p><p>x : a clean, unmodified image</p><h3>Existing Methods</h3><h4>Fast Gradient Sign Method (FGSM)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*C2jQwKsf50V3ktM-" /><figcaption>Formula to generate an adversarial example using the fast gradient sign method [1].</figcaption></figure><p>The fast gradient sign method generates adversarial examples by making perturbations in the direction of the cost function. This maximizes the error of the classifier.</p><h4>Targeted Fast Gradient Sign Method (Targeted FGSM)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*RB2aP_GYwtElmeVP" /><figcaption>A modified version of the fast gradient sign method that generates a target adversarial example [1].</figcaption></figure><p>The fast gradient sign method can be modified to produce targeted adversarial examples. Instead of maximizing error, this targeted version of FGSM creates noise that reduces the loss between the instance and its target class.</p><p>This results in an adversarial example which not only produces a misclassification, but one that is targeted at a specific class.</p><h4>Momentum-Iterative Fast Gradient Sign Method (MI-FGSM)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*dFdJ0mggUaJWcZbv" /><figcaption>Formulas to generate an adversarial example using the momentum-iterative fast gradient sign method [1].</figcaption></figure><p>The momentum-iterative fast gradient sign method aims to improve the transferability and smooth the noise output of the fast gradient sign method.</p><p>MI-FGSM improves transferability by using momentum to escape poor local minima during iterations [2]. This is desirable to make the attack more effective in a black-box attack, where network architecture is unknown.</p><p>The smoother noise output due is due to more stable update direction that the momentum also provides. This has the effect of producing adversarial examples which have noise that is less perceptible to humans.</p><p>The momentum term g is calculated using the normalized gradient of the cost function and the decay factor μ.</p><p>The adversarial example is then generated by adding noise in the direction of the momentum term using a weight 𝛼. The inputs are constrained to a range of [x - 𝜖, x + 𝜖] to ensure that the noise output is minimally perceptible.</p><h3>Problems with Existing Methods</h3><h4>Vanishing Gradient</h4><p>The vanishing gradient problem describes the phenomena of the gradient tending towards zero as more iterations occur. This makes changes to weights increasingly small and can cause training to slow dramatically.</p><p>This is one factor which can lead to noise curing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*j6c9v69oBZ4OTXuk" /><figcaption>Comparison of the Poincare metric and Cross-entropy for addressing the vanishing gradient problem [1].</figcaption></figure><h4>Noise Curing</h4><p>Noise curing is the phenomena of noise developing a lack of diversity and adaptability through the dominance of historical momentum.</p><p>The top two lines in the figure below measure noise curing with the cosine similarity of two successive perturbations (modifications) to images, where a lower similarity indicates less noise curing.</p><p>The lower two lines indicate the target label probability of each method. In this test, the Poincare attack method proved to be less susceptible to noise curing and provide a higher target label probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*cLhK4STvEShNeXTp" /><figcaption>A comparison of cosine similarity and target label probability over iterations for Poincare attack (Po) and MI-FGSM (CE) [1].</figcaption></figure><h4>Transferability</h4><p>Transferability is the property of a model to be able to adapt to solve a different but related problem.</p><p>The model in the paper aims to produce a more transferable attack by not only encouraging classifications closer to the target class, but also by encouraging classifications farther from the true class.</p><p>This is done with the introduction of a triplet loss. In the figure below, both models were able to create adversarial examples that would be misclassified as the target class. However, in the case with triplet loss, the adversarial examples landed much further from the true label than in the model without triplet loss.</p><p>Increasing the distance from the adversarial examples’ classification to the true label is key in increasing transferability in the case of black-box attacks, where the network architecture is unknown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*0GgvCyBEOzTLA62f" /><figcaption>A visualization of the transferability of two models of generating adversarial examples, one with and one without triplet loss [1].</figcaption></figure><h3>Algorithm</h3><p>For each iteration of the algorithm, the model to produce the adversarial examples does the following steps.</p><h4>Obtain Classifier Logits</h4><p>The augmented image is input into the ensemble of classifiers. The output probability for the target class is used to calculate a logit for each classifier.</p><p>These logits are used to measure the distance from the target class to the classifier’s predicted class.</p><h4>Fuse the Logits</h4><p>The logits obtained in the previous step are fused in a weighted average using the ensemble weights (if the weights are equal, then this is an arithmetic mean).</p><h4>Compute Loss</h4><p>The model’s loss is calculated using the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/0*c0Ml8YoqEvR8XyeR" /><figcaption>The model’s cost function [1].</figcaption></figure><p>The cost function is a combination of a Poincare distance and a triplet loss.</p><p>The Poincare distance is measured from the clean image and the target class, and is defined as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*CxzRXAI5kYDiADVK" /><figcaption>Formula for the Poincare distance between two points, u and v [1].</figcaption></figure><p>The primary motivation to use Poincare distance instead of softmax cross entropy is its ability to preserve the magnitude of the gradient in an iterative attack.</p><p>This behavior is possible due to properties of Poincare distance:</p><ul><li>the magnitude of the gradient only grows if the data point gets closer to the target label</li><li>the target label is near the surface of the Poincare ball</li></ul><p>As the adversarial example gets closer to the target label over iterations the magnitude of the gradient would normally tend towards zero (using softmax cross entropy), instead, the Poincare distance’s exponential growth as the example gets closer to the target causes an increase in the magnitude of the gradient.</p><p>The resulting behavior is that instead of each iteration becoming less and less effective than the last, momentum is preserved and an improved final result is achieved.</p><p>Using the Poincare distance, the triplet loss is made up of the following components:</p><ul><li>The distance from the adversarial example to the target class.</li><li>The distance from the adversarial example to the true class.</li><li>γ, the margin between these two distance metrics.</li></ul><p>This combination produces a cost function that encourages both classification near the target label and away from the true label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/0*eQMAdYE5VmKScuYL" /><figcaption>Triplet loss formula [1].</figcaption></figure><h4>Compute Gradient of Loss</h4><p>The gradient of the loss in the previous step is calculated.</p><h4>Update Momentum</h4><p>The momentum term is updated using the momentum decay factor and the gradient calculated in the previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*aY0LO3wA0qU0NEuY" /><figcaption>The process for updating the momentum term [1].</figcaption></figure><h4>Update the Adversarial Example</h4><p>The adversarial example is updated by applying a sign gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/0*U1A7GX9YlzzyHAw_" /><figcaption>The process for updating the adversarial example [1].</figcaption></figure><h3>Results</h3><p>Below is a comparison of success rates of several state-of-the-art techniques for producing adversarial examples (DI²-FGSM and TI-FGSM). ‘Po’ and ‘Trip’ represent Poincare distance and Triplet loss, respectively.</p><p>TI-FGSM convolves the gradients of the images with a predefined kernel to approximate the optimization of a perturbation over an ensemble. This technique is combined with Poincare distance and Triplet loss, designated by ‘TI’.</p><p>Each of the adversarial examples were generated with an ensemble of five networks, and then tested on the ensemble network and the hold-out network. The ensemble network is a white-box setting (the architecture of the network is known) and the hold-out network is a black-box setting (the architecture of the network is unknown), hence the lower success rates of the adversarial examples on the hold-out network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/0*Y_i6r-xMANxaTseU" /><figcaption>The success rates of targeted adversarial attacks compared against two state-ot-the-art methods for generating adversarial examples, DI²-FGSM and TI-FGSM [1].</figcaption></figure><p>The below table is similar to the above one, only the models are trained to defend against adversarial attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*zWKxPr4Cxpihpxrr" /><figcaption>The success rates of targeted adversarial attacks compared against two state-ot-the-art methods for generating adversarial examples, DI²-FGSM and TI-FGSM. These models are adversarially-trained [1].</figcaption></figure><p>Perhaps the most interesting of all the results, is the perceptibility of the perturbations in the adversarial examples produced by the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*q_ZJX_qJkf0sKXZP" /><figcaption>Adversarial examples generated by the model (top), clean images (middle), and the noise added to each image (bottom) [1].</figcaption></figure><p>Above are adversarial examples generated by the model. While the changes are perceptible, they are constrained such that no human observer would reasonably classify the adversarial examples any differently than the clean images.</p><h3>Reflections</h3><p>This paper’s key contribution is the carefully crafted loss function for generating adversarial examples which combines Poincare distance and their triplet loss. While the effectiveness of these two techniques is difficult to observe in the generated adversarial examples, their results certainly prove their effectiveness.</p><p>Understanding the Poincare ball and Poincare distance is not a simple task for someone who is not acquainted with non-Euclidean geometry. Nevertheless, when boiled down to it’s core contribution: distances between points grow exponentially nearer the surface of the ball, it makes sense as a solution to the vanishing gradient problem and noise curing.</p><p>While the triplet loss function is rather intuitive, it is simultaneously rather genius as a way to promote classification farther away from the true class.</p><p>My main reservation with the paper’s contributions is not whether they accomplished their goals, but if they really had the right goals in mind. Although the authors clearly state that the intended use for such an attack is to evaluate deep neural networks and increase their robustness to such attacks, I can’t help but feel that they are simply creating problems for others to solve. It is similar to white-hat hackers, who intend to help with cybersecurity efforts by finding vulnerabilities in good faith, although those issues are often easily solved, as opposed to designing adversarially trained networks.</p><h3>Reference</h3><p>[1] M. Li, C. Deng, T. Li, J. Yan, X. Gao, and H. Huang, “Towards Transferable Targeted Attack,” 2020. [Online]. Available: <a href="https://openaccess.thecvf.com/content_CVPR_2020/papers/Li_Towards_Transferable_Targeted_Attack_CVPR_2020_paper.pdf.">https://openaccess.thecvf.com/content_CVPR_2020/papers/Li_Towards_Transferable_Targeted_Attack_CVPR_2020_paper.pdf</a>.</p><p>[2] Y. Dong, F. Liao, T. Pang, H. Su, J. Zhu, X. Hu, and J. Li, “Boosting Adversarial Attacks with Momentum,” 2018. [Online]. Available: <a href="https://openaccess.thecvf.com/content_cvpr_2018/papers/Dong_Boosting_Adversarial_Attacks_CVPR_2018_paper.pdf">https://openaccess.thecvf.com/content_cvpr_2018/papers/Dong_Boosting_Adversarial_Attacks_CVPR_2018_paper.pdf</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a581f510fc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/towards-transferable-targeted-attack-3a581f510fc0">Towards Transferable Targeted Attack</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A tutorial on MADDPG]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/a-tutorial-on-maddpg-53241ae8aac?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/53241ae8aac</guid>
            <dc:creator><![CDATA[Diego Benalcazar]]></dc:creator>
            <pubDate>Mon, 02 May 2022 16:44:41 GMT</pubDate>
            <atom:updated>2022-05-02T16:44:41.338Z</atom:updated>
            <content:encoded><![CDATA[<h4>Original article <a href="https://arxiv.org/abs/1911.10635">https://arxiv.org/abs/1911.10635</a></h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FC-DV9kNO7H8%3Fstart%3D2%26feature%3Doembed%26start%3D2&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DC-DV9kNO7H8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FC-DV9kNO7H8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/237be9271ea7330b0610dd02b38ea734/href">https://medium.com/media/237be9271ea7330b0610dd02b38ea734/href</a></iframe><p>In the last years, there have been several new efforts to address Reinforcement Learning (RL) problems. If we consider real-life scenarios, it is easy to see why many of these approaches have focused on frameworks that include more than one agent. A robot, for example, needs to consider not only its environment but also other robots or humans that are present in that same environment. These algorithms are referred to as Multi-Agent Reinforcement Learning (MARL). For a survey about MARL, we refer to [<a href="https://arxiv.org/abs/1911.10635">1</a>]. In this article, we review one of these algorithms named Multi-Agent Deep Deterministic Policy Gradient (MADDPG), developed by Lowe et al. [<a href="https://arxiv.org/abs/1706.02275">2</a>].</p><h3>The problem with MARL</h3><p>The majority of late successes in Reinforcement Learning have been limited to a single-agent scenario, where the agent takes a series of sequential actions that affect the environment. The environment returns a new state (determined by a transition probability) and an associated reward to the agent. The environment is generally modeled as a Markov Decision Process (MDP), whose solution traduces into finding a policy that maps from the state space to a distribution over the action space so that the cumulative reward is maximized. In this context, one major assumption is that the environment is stationary. This assumption cannot be extended to multi-agent frameworks because the transition of states and the reward received by each agent are affected by the actions of the other agents. Furthermore, each agent needs to optimize its own cumulative reward, which is a function of the other agents’ policies [<a href="https://arxiv.org/abs/1911.10635">1</a>]. Accordingly, a MARL problem is generally addressed as a generalization of a MDP called Markov game (MG).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*fsjmP7eUTU_AdBCw8Vfv_Q.png" /><figcaption>Models for single and multi agent reinfocement learning [<a href="https://arxiv.org/abs/1911.10635">1</a>]</figcaption></figure><p>Traditional RL approaches such as Q-Learning or policy gradient cannot be easily extended to multi-agent scenarios. Regarding Q-learning, a changing environment presents limitations in aspects like the use of a replay buffer and the learning stability as the policy previously optimized for one instance of the environment is no longer useful once the environment has changed. Regarding policy gradient, multi-agent scenarios generate high variance gradient estimates when coordination is required.</p><h4>Deep Deterministic Policy Gradient (DDPG)</h4><p>For policy gradient approaches, we update the policy directly; this policy maps the state space to a probability distribution over the action space. This is generally done using some variant of gradient ascent for a specific performance function, generally equal to the state value function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*qSgwUk171ZzeBP1CfY-wFg.png" /></figure><p>In Deterministic Policy Gradient (DPG), we extend this approach to deterministic policies (the distribution collapses to a single element in the action space). Deep Deterministic Policy Gradient is a variant of DPG where we approximate this deterministic policy and the critic using deep neural networks. This is an off-policy algorithm that employs a replay buffer that requires the action space to be continuous. MADDPG can be seen as an extension of DDPG. For DDPG, the gradient is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*h-sonylYzGndi0h9E9fMMA.png" /></figure><p>To deal with the previously described limitations, the authors propose an algorithm that <em>i.</em> uses only local information at execution time.<em> ii.</em> makes no assumption either of a differentiable model of the environment dynamics or of any communication method and <em>iii.</em> is applicable to cooperative and competitive frameworks.</p><h3><strong>Centralized training and decentralized execution</strong></h3><p>The basic idea of MADDPG is to expand the information used in actor-critic policy gradient methods. During training, a centralized critic for each agent has access to its own policy and to the policies of all the other agents. However, during execution, each agent employs only its own policy in a decentralized approach. Despite being centralized, having one critic for each agent instead of a single critic for all the agents has the advantage that we can consider different reward functions, which is necessary for competitive frameworks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*FNRZLvzRxZmG631tBmDEfA.png" /><figcaption>Figure 1: Overview of multi-agent decentralized actor, centralized critic approach [<a href="https://arxiv.org/abs/1706.02275">2</a>]</figcaption></figure><h4>Updating the Critic</h4><p>We consider <em>N </em>agents, each one with its own continuous deterministic policy and its own centralized action-value function. This function takes the actions of all the agents and information about the state (in its simplest form this corresponds to the observations of all the agents) as input and returns the agent’s Q-value as output. To update each agent’s critic, we employ a replay buffer just like in DQN [<a href="https://www.nature.com/articles/nature14236">3</a>] where the state transitions, actions, and corresponding rewards of all the agents are accessed from. Then, the loss function used to update the critic is defined in the same way as in DQN:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*Je_0PNPzdPkzfBo1xQVXZw.png" /></figure><p>This equation works only in cases where each agent has access to other agents’ policies so the actions can be calculated and used as input to the critic. When this assumption is not realistic, each agent can use approximations of the other agents’ policies. Then, the approximations of agent <em>i </em>to the parameters that define the policy of agent <em>j</em> are updated in an online fashion, using an entropy regularizer, which changes the target employed to update the critic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*BLopUv9M7t254j23k5JtkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*P4wZhTXsIhudpvPnyOxXDA.png" /></figure><p>The effect of learning the policies of other agents is analyzed in a cooperative communication scenario (described later) achieving the same success rate as with true policies without a considerable decrease in the convergence speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*le6fmcUIA883rs26A6lQ9A.png" /></figure><h4>Updating the Actor</h4><p>The real purpose of calculating the critic is using it to update the actor, which will actually be the one used during execution time. For that purpose, we can iteratively move in the direction of the negative/positive of the gradient, which for deterministic policies, whose input is the agents’ observations, is equal to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*-7UxK01_0a6ureDDYyWgcg.png" /></figure><p>In a competitive setting, non-stationarity represents a particularly challenging problem; agents may overfit the other agents’ behaviors. To deal with this problem, the authors propose training a collection of <em>K</em> sub-policies for each agent. At every episode, each agent randomly chooses one of its K sub-policies, and samples from a replay buffer specific to that sub-policy. In this case, the gradient update for the ensemble of policies becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*LcOcp4s5g-SGDxs2zAy9jg.png" /></figure><p>The authors analyze the influence of using these ensembles in three scenarios named Keep-away, Physical deception, and predator-prey and conclude that the ensemble shows a better performance especially when it is put to compete against a single policy framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*3L0K8BnVzECZbVimy0PtuQ.png" /></figure><p>Under, all the previously described considerations, the full MADDPG algorithm for N agents is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5PKYoQ7aSxvK9Tmy0ZWWQ.png" /></figure><h3>Comparative Results</h3><p>For all the considered environments, the authors use feed-forward continuous policies with the following parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*jJGN50h1GngKF2vqtgQtjw.png" /></figure><p>The authors consider competitive and cooperative games within an environment composed by <em>N</em> agents and <em>L</em> landmarks. They can take two types of actions: physical and communication. For the comparison with other RL algorithms, the authors only consider one scenario named Cooperative communication in which there are a speaker, a listener, and three landmarks. In each episode, the listener moves to one landmark and gets a reward depending on how far it is from the correct landmark. However, only the speaker, not the listener knows which the correct landmark is. The speaker can send a message to the listener. The performance, measured as the mean episode reward, of MADDPG and other algorithms, is presented in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLDYGzJT6xALmCO4bvuFLw.png" /><figcaption>Figure 2: Policies parameterized by a two-layer ReLU MLP with 64 units. Messages were sent as approximations to a discrete message using Gumbel-Softmax estimator. Left: mean episode reward vs episode Right: Percentage of target reached after 25 000 episodes</figcaption></figure><p>In Cooperative communication, the listener goes to the right landmark 84% of the time using MADDPG, while all the other algorithms fail. The authors also consider other scenarios to compare MADDPG to the centralized version DDPG. First, they consider a scenario named Cooperative navigation, in which agents must cooperate through physical actions to reach a group of landmarks while avoiding collisions among them. MADDPG agents beat DDPG agents in cooperative navigation (N=2); they present a slightly smaller average distance and half the average number of collisions per episode.</p><p>Second, the consider a scenario named Keep-away composed of a target landmark and two teams of cooperating agents; one team knows which is the target landmark and is rewarded based on their distance to the target, and another team that does not which is the target, and tries to impede the initial team from reaching the target by physically pushing the agents and occupying the landmark temporarily.</p><p>Third, they consider a scenario named physical deception where a group of agents cooperate to get to a landmark and are rewarded based on the minimum distance between any member of the team and the target. There is also one single adversary with the same objective who does not know which landmark is the target. The members of the initial team need not only one member to get to the target but also to occupy spaces so the adversary does not know which is the correct target. Under a physical deception task with two landmarks, the adversary is deceived (all landmarks are covered) 94% of the time and the success rate of the adversary is relatively low when the cooperative team employs MADDPG. In contrast, when the cooperative team employs DDPG, they fail to deceive the adversary, even when this employs DDPG and not MADDPG.</p><p>The fourth considered scenario is a predator-prey game in which a set of slower agents try to collide with a faster prey in a randomly created world. In a MADDPG predator — DDPG prey setting, the collision rate is 16.1, in comparison to 10.3 under a DDPG predator-MADDPG prey. The fifth scenario is named Covert communication. A speaker named Alice sends an encoded message to a listener Bob, both of whom have the key. There is a second listener called Eve who wants to reconstruct the message. Alice and Bob are penalized if this occurs. Results show that Bob achieves a success rate of 52.4% with MADDPG and 25.1% with DDPF. Only when Alice uses MADDPG, Eve gets almost random accuracy. The behaviour after the training process is shown in the following video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQCmBo91Wy64%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQCmBo91Wy64&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQCmBo91Wy64%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2dfe72839e6b503af50c265c10a8892/href">https://medium.com/media/b2dfe72839e6b503af50c265c10a8892/href</a></iframe><h3>Concluding remarks</h3><p>MADDPG is a suitable and relatively algorithm in cases in which we can assume that the existence of a centralized critic is reasonable. This implies that the agents shall have access to the information from all the other agents. Furthermore, relying on the information from other agents implies that the input space for the critic increases linearly with the number of agents.</p><p>In the context of multi-agent approaches to Reinforcement Learning, MADDPG represents a middle point in terms of the amount of information considered. On one hand, we have approaches like the one presented in [<a href="https://web.media.mit.edu/~cynthiab/Readings/tan-MAS-reinfLearn.pdf">4</a>] where each agent considers the other agents as part of the environment. It has been shown that these approaches are not good in several scenarios. On the other hand, we have approaches where every agent has access to the information of all the other agents and that work only for cooperative settings. MADDPG considers the information of all the agents during training but not during execution and works for both cooperative and competitive settings.</p><h3>References</h3><p>[1] K. Zhang, Z. Yang, and T. Ba¸sar, “Multi-agent reinforcement learning: A selective overview of theories and algorithms,” 2019.</p><p>[2] R. Lowe, Y. Wu, A. Tamar, J. Harb, P. Abbeel, and I. Mordatch, “Multi-agent actor-critic for mixed cooperative-competitive environments,” 2017.</p><p>[3] Mnih, V., Kavukcuoglu, K., Silver, D. <em>et al.</em> Human-level control through deep reinforcement learning. <em>Nature</em> <strong>518, </strong>529–533 (2015). <a href="https://doi.org/10.1038/nature14236">https://doi.org/10.1038/nature14236</a></p><p>[4] M. Tan, “Multi-agent reinforcement learning: Independent vs. cooperative agents,” in In Proceedings of the Tenth International Conference on Machine Learning, pp. 330–337, Morgan Kaufmann, 1993.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53241ae8aac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/a-tutorial-on-maddpg-53241ae8aac">A tutorial on MADDPG</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ViViT : A Video Vision Transformer]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/vivit-a-video-vision-transformer-5391ba295085?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/5391ba295085</guid>
            <dc:creator><![CDATA[Nitin Limhan]]></dc:creator>
            <pubDate>Mon, 02 May 2022 16:19:09 GMT</pubDate>
            <atom:updated>2023-06-01T22:07:59.765Z</atom:updated>
            <content:encoded><![CDATA[<h3>ViViT : A Video Vision Transformer</h3><blockquote><strong>Blog by Nitin Limhan and Rutuja Pisal</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPQKXUNJiQOM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPQKXUNJiQOM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPQKXUNJiQOM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/80c674d4821f4272b6813b8f8bdcf1f1/href">https://medium.com/media/80c674d4821f4272b6813b8f8bdcf1f1/href</a></iframe><p>In recent years, Pure-Transformer based models, have advanced the state-of-the-art in many standard datasets for sequence modelling and transduction problems. They were first introduced in the “Attention Is All You Need” paper and emerged as the preferred model in natural language processing (NLP), but their applications in vision domain were limited. A Google Research Team introduced the paper “An Image Is Worth 16 X 16 Words : Transformers For Image Classification At Scale”, which applied the Transformer based models to Image classification. Inspired by this, Vision Transformer was extended for video classification which is explained in the paper “ViViT : A Video Vision Transformer”.</p><p>This is the paper that we have explored in this blog wherein we will see how Video Vision Transformers work.</p><p>To fully comprehend the paper, one must first understand the ideas of Self-attention and Vision Transformers, before moving on to Video Vision Transformers.</p><blockquote><strong>What is Self Attention</strong> ?</blockquote><blockquote>Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations.</blockquote><blockquote><strong>What is Transformer ?</strong></blockquote><blockquote>Transformer is a model architecture that foregoes recurrence in favor of drawing global dependencies between input and output wholly using an attention mechanism. After only twelve hours of training on eight P100 GPUs, the Transformer allows for substantially higher parallelization and can achieve a new state of the art in translation quality.</blockquote><blockquote><strong>What is ViT ?</strong></blockquote><blockquote>The Vision Transformer, or ViT, is a model for image classification that employs a Transformer-like architecture over patches of the image. An image is split into fixed-size patches, each of them are then linearly embedded, position embeddings are added, and the resulting sequence of vectors is fed to a standard Transformer encoder. In order to perform classification, the standard approach of adding an extra learnable “classification token” to the sequence is used.</blockquote><p>Transformers were initially just used in NLP but what can be seen in ViT : Vision Transformers, that they are now challenging Convolutional Neural Networks (CNNs) which have been the backbone of Vision related problems since many years. The fundamental difference between these two is the Local Vs Global Context. Its known that the CNNs only look for dependencies in and around the pixel window which focuses on the local context whereas Transformers have the bigger picture because of pre tokenization embeddings which focuses on the global context. And therefore transformer understand complete picture quickly and perform better. In the case of videos, this implementation is little complicated. One needs to know what spatial and temporal dependencies are, in order to grasp it better. When we are trying to segment an image and trying to find out how a pixel is related to its neighbors or other pixels in the image, these are known as spatial dependencies. There are some applications in activity recognition for which we have to process multiple frames because there are dependencies on the time axis as well, and these are known as temporal dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*VFeySE4VL3Zt1Ize4akCpw.png" /><figcaption>ViViT : Pure-Transformer architecture for video classification</figcaption></figure><p>It can be observed from ViViT’s design that it uses the same transformer encoder as well as the same Position and Token Embedding mechanism as ViT: Vision Transformers. The only difference is tokenizing more than one frame in one go and also let the transformer learn the spatial and temporal dependencies. The first thought that comes to everyone’s mind is to give the entire video as input and let the transformer learn, which is actually the first model proposed by the authors, but the issue is the number of tokens because the attention mechanism requires computation between each pair of tokens. This is a very critical issue especially in videos since it requires to process more tokens for any video task.</p><p>Let’s see how these problems are resolved by the authors.</p><h3><strong>Embedding Video Clips</strong></h3><p>Two simple methods were considered for mapping a video to a sequence of tokens. Positional embeddings are added to this and then given as input to the Transformer. The two embedding methods are :</p><ul><li>Uniform Frame Sampling</li></ul><p>It’s a simple and straightforward approach for tokenizing the input video clip. First, sampling of frames from the input clip in a uniform manner is done. Second, the same mechanism as ViT: Vision Transformers to embed each 2D frame separately is used. Finally, concatenate all of these tokens together. From common sense, it can said that this process is simply constructing a very large 2D image to be tokenized following ViT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXow8ooNzYkwReU1nqtE4Q.png" /><figcaption>Uniform Frame Sampling</figcaption></figure><ul><li>Tubelet Embedding</li></ul><p>Tubelet embedding starts with extracting non-overlapping, spatio-temporal tubes from the input video clip and then linearly projects it. This method is an extension of ViT’s embedding to 3D and also corresponds to 3D convolution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*s4UfcnkUig_Pec7SQAMugA.png" /><figcaption>Tubelet embedding</figcaption></figure><p>As it can be seen from the figure, during the tokenization process, tubelet embedding method fuses the spatio-temporal information. Whereas in uniform frame sampling, only spatial information is fused during tokenization and temporal information from different frames is fused later by the transformer.</p><h3><strong>Models Proposed</strong></h3><p>In this paper, the authors proposed 4 different transformer-based models for video classification. They start with a simple modification of ViT that simulates pairwise interactions between all spatio-temporal tokens and then move on to more efficient forms that factor the input video’s spatial and temporal dimensions at various levels of the transformer architecture.</p><p><strong>Model 1: Spatio-temporal Attention</strong></p><p>All spatio-temporal tokens collected from the video are simply forwarded through the transformer encoder in this model. In contrast to CNN, each transformer layer models all pairwise interactions between spatio-temporal tokens. Now, since the first token of first image can interact with the last token of last image, this results in long-range interactions across the videos from the first layer. As a result, this model has quadratic complexity, which was then overcome in the second model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWaPRZsVvBdGRymHVZmdrA.png" /><figcaption>Model 1 : Spatio-temporal Attention 📹</figcaption></figure><p><strong>Model 2 : Factorised Encoder</strong></p><p>In this model, just as the name suggest they factorize the encoder, which means that all the frames are first passed through spatial encoder i.e every single frame is passed through a separate spatial encoder. The output features which are received from the spatial encoder are then passed through the temporal encoder. This facilitates the late fusion of temporal information, as first the spatial information is obtained and then its fused into getting temporal information. There are more parameters in this model, since there are two encoders instead of one, but there are few floating point operations as everything is not interacting with everything directly. The tokens do interact with each other at long range but they do that indirectly and thus the complexity of this model is much less as compared to the Model 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g60QNNfF0Y2h7Hezg5lXJw.png" /><figcaption>Model 2 : Factorised Encoder 📹</figcaption></figure><p><strong>Model 3 : Factorised Self-attention</strong></p><p>In this model the authors used just one encoder, but inside one encoder they used 2 self-attention blocks, which is the spatial self-attention encoder and the temporal self-attention encoder as can be seen in the below figure. This model has same number of transformer layers as Model 1 since there is just one encoder, but its complexity is same as Model 2 since everything is not interacting with everything directly. First every block calculates the spatial self-attention(among all the tokens extracted from the same temporal index) and then the temporal self-attention(among all tokens extracted from the same spatial index). In simple words, what it does is, it takes the input tokens, reshapes it as number of frames into the spatial dimension, then performs spatial attention. Then it reshapes it appropriately again so that they can be input into the temporal self-attention block and then it performs temporal self-attention, the output of which is passed onto the next transformer block. Overall, experiments with respect to the order of the blocks were also carried out, as to which block should go first. The spatial block should go first or the temporal block should go first, and they found out that it doesn’t matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dxDbhMKQMFy1M2CtxY3Gw.png" /><figcaption>Model 3 : Factorised Self-attention 📹</figcaption></figure><p><strong>Model 4 : Factorised Dot-product Attention</strong></p><p>The final model proposed is the Factorised dot-product attention, which is like the best of all worlds model. This model has the same computational complexity as Models 2 and 3, while retaining the same number of parameters as the unfactorised Model 1. This model is a bit complex in the sense that, first it gets all attention heads and divides them into 2 parts. The concept of neighborhood is very important here in the sense that, for half of the heads the dot-product attention is computed over only the spatial axis and for the other half over only the temporal axis and then keys are generated for the attention heads. The main idea here is to modify the keys and values for each query to only attend over tokens from the same spatial and temporal index. Then, for half of the attention heads, the model attends over tokens from the same spatial dimension by computing Ys = Attention(Q;Ks;Vs), and for the rest it attends over the temporal dimension by computing Yt = Attention(Q;Kt;Vt). Finally, the outputs of multiple heads is combined by concatenating them and using a linear projection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S0RgAHrNzOMPySMIYsGobg.png" /><figcaption>Model 4 : Factorised Dot-product Attention 📹</figcaption></figure><h3><strong>Initialisation by leveraging pretrained models</strong></h3><p>Because transformers lack some of the inductive biases of convolutional networks, ViT has only been proved to be effective when trained on large-scale datasets. When compared to their image counterparts, even the largest video datasets, such as Kinetics, have orders of magnitude fewer tagged samples. As a result, training large models from scratch to high accuracy is extremely challenging. To sidestep this issue and enable more efficient training the authors initialized the video models from pretrained image models.</p><p>There are 3 problems that they faced due to this, which are as follows :</p><p><strong>1. Positional Embedding</strong></p><p><em>Problem</em> : Video models have n x t times more tokens than Image model.</p><p><em>Solution</em> : Initialise the positional embeddings by “repeating” them temporally, so all the tokens with same spatial index have the same embedding.</p><p><strong>2. Transformer Weights for Model 3 : </strong>This problem arises when model 3 is used, since model 3 has 2 self-attention blocks instead of one.</p><p><em>Problem</em> : Model 3 has two MSA modules.</p><p><em>Solution</em> : Initialise the spatial MSA module from the pretrained module and initialise all weights of the temporal MSA with zeroes.</p><p><strong>3. Embedding Weights, E :</strong> The third and most important problem that was faced was of embedding weights. This problem arises because all ViT models are pretrained using images and have 2D filters, but since ViViT uses tubulet embedding it requires 3D filter.</p><p><em>Problem</em> : Pretrained model has 2D filter but tubelet embedding required 3D filter.</p><p><em>Solution</em> : 1. Inflating Filters :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*vKiVNKUr9ChD-R-7nANEYw.png" /></figure><p>2. Central Frame Initilisation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*YUzW4DKvHvnGjAQ5iiDrQA.png" /></figure><p>So there are two solutions to the above problem. The first one is inflating filters and second one is central frame initialization. Inflating filters means at every layer weights will be taken corresponding to every image, and it will be replicated t times, where t is the number of frames and then all be divided all by t. This it just like averaging based on location. The second solution was however adopted which involved keeping image weights at central frame and initializing everything to zero.</p><h3><strong>Experimental Setup</strong></h3><p>Experiments were performed using ViT Base architecture , having tubelets of size 16 x 16 x 2. The models were trained using Sychronous SGD and Cosine Learning Rate. The models were further pretrained using ImageNet-21K and JFT Datasets.</p><h3><strong>Ablation Study</strong></h3><p>1. Input Encoding Methods : Uniform Vs Tubelet Embedding</p><p>For this experiment, ViViT base architecture with a spatial temporal attention model on the kinetics 400 dataset has been used. The table below shows the results of the experiment. From the table it can be seen that for uniform frame sampling to generate embedding matrix the accuracy achieved was 78.5%. Further, when different encoding methods were tried, better results were received. Tubelet embedding using the “central frame” approach outperformed the more often used “filter inflation” method giving an accuracy of 79.2%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*dyoJkeSnMhjkzhE_xwizoQ.jpeg" /><figcaption>ViViT-B / Spatio-temporal Attention on Kinetics 400 dataset</figcaption></figure><p>2. Model Variants (1 to 4) : Comparison of Unfactorized and Factorized Models</p><p>The next experiment was performed to see which variant of transformer model performed best. On Kinetics 400 dataset, the unfactored model (Model 1) performs the best, but it overfits on smaller datasets like EK.</p><p>The authors also investigate a second baseline (last row), based on Model 2, in which they don’t employ a temporal transformer and just pool the frame-level representations from the spatial encoder before classifying. From the table below it can be observed that accuracy for the average pool baseline models drops, which means it needs better architecture to model on the EK dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Efsi9NM3g2jzBRPJU1z7-A.png" /><figcaption>Comparison of model architectures using ViViT-B as the backbone</figcaption></figure><p>Furthermore, metrics like floating point operations, params and runtime is are also used to see the performance of different model variants. For these metrics, it can be seen that unfactorized model requires high computation and hence uses more flops. For the factorized models since attention is calculated independently over spatial and temporal dimensions they use less flops. Model 4 adds no additional parameters to the unfactorised Model 1, and uses the least compute. The temporal transformer encoder in Model 2 operates on only n x t tokens, which is why there is a barely a change in compute and runtime over the average pooling baseline, even though it improves the accuracy substantially.</p><h3><strong>Comparison to state-of-the-art</strong></h3><p>On the Kinetics 400 Dataset, various ViViT variations to the various State of the Art models. First, a brief overview of the metrics used to compare the models :</p><p>· TOP 1 : So for a prediction, if we get the ground truth as the class having highest probability then we consider that as a correct prediction.</p><p>· TOP 5 : If we get the ground truth in the top 5 class having highest probabilities then we consider that as a correct prediction.</p><p>· Views : The term Views can be explained using an example of model X3D-XXL. It has 10X3 views which says that it has 10 temporal crops and 3 spatial crops</p><p>· TFLOPs — Trillion Floating point Operations per second</p><p>Now, moving on to the table, it can be seen that the ViViT-L/16X2 FE having accuracy of 92.7% and a view of 1X1 in Top 5 metric underperforms the best 3D Convolutional Neural Network model which is X3D-XXL which has an accuracy of 94.6%. The ViViT-L/16X2 FE with a view of 1x3 and accuracy of 81.7% outperforms TimeSformer-L with an accuracy of 80.7% in Top 1 metric. Finally, when these networks are trained on large pretraining dataset JFT in order to increase the accuracies, we can see that the ViViT-H/16X2 (JFT) outperforms all other state-of-the-art models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNujZo9BYYzQQHfHrPIteA.jpeg" /><figcaption>Comparison to state-of-the-art across multiple datasets</figcaption></figure><p>On the Kinetics 600 Dataset, the best variant among the 3D Convolutional Neural Network is X3D-XL which have accuracies of 81.9% and 95.5% on Top 1 and Top 5 respectively. X3D-XL is outperformed by TimeSformer-L which is a transformer-based model giving an accuracy of 95.6% for Top 5 metric. The current state-of-the-art models have been outperformed by ViViT-L/16X2 FE by a little margin of 0.7% on Top 1 metric but still lagged behind on the Top 5 metric. Finally, while leveraging the use of pre-trained image weights from JFT, ViViT-H/14X2 (JFT) performed the best with accuracies of 85.8% and 96.5% for the Top 1 and Top 5 metrics respectively.</p><p>On numerous datasets, ViViT significantly beats all state-of-the-art models, as seen in the table above.</p><h3><strong>Conclusion and Future Work</strong></h3><ul><li>ViViT is successful in implementing regularization and factorization at different levels to produce state-of-the-art models for Video tasks.</li><li>This model presents a unique way of factorising spatial and temporal dimensions which increased efficiency and scalability.</li><li>The removal of dependence on image-pretrained models is an area for clear future improvements.</li><li>For the next step, going beyond video classification towards more complex tasks should be the aim.</li></ul><p><strong>References:</strong></p><p>[1] “<em>Attention Is All You Need”, 2017, </em>Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin, <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></p><p>[2] “An image is worth 16 X 16 words: Transformers for image recognition at scale”, 2020, Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, <a href="https://arxiv.org/abs/2010.11929">https://arxiv.org/abs/2010.11929</a></p><p>[3] “ViViT : A Video Vision Transformer”, 2021, Anurag Arnab, Mostafa Dehghani, Georg Heigold, Chen Sun, Mario Lucic, Cordelia Schmid, <a href="https://arxiv.org/abs/2103.15691">https://arxiv.org/abs/2103.15691</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5391ba295085" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/vivit-a-video-vision-transformer-5391ba295085">ViViT : A Video Vision Transformer</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep InfoMax | Explanation of Mutual Information Maximization]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/deep-infomax-explanation-of-mutual-information-maximization-99cf98170138?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/99cf98170138</guid>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[mutual-information]]></category>
            <category><![CDATA[deep-infomax]]></category>
            <category><![CDATA[self-supervised-learning]]></category>
            <dc:creator><![CDATA[James Laughridge]]></dc:creator>
            <pubDate>Mon, 02 May 2022 15:46:57 GMT</pubDate>
            <atom:updated>2022-05-02T16:02:55.406Z</atom:updated>
            <content:encoded><![CDATA[<p>An Introduction of the Deep InfoMax Method for Mutual Information Maximization</p><p>This post intends to provide an explanation of the deep learning method for maximizing mutual information, known as Deep InfoMax or DIM. The information contained in this post is based on the February 2019 version of Dr. Devon Hjelm’s the 2019 International Conference on Learning Representations conference paper titled <em>Learning Deep Representations by Mutual Information Estimation and Maximization</em>. My aim is to introduce Dr. Hjelm’s method to an audience that may not have the time to analyze the entire conference paper, in a way that allows even readers with limited background in machine learning techniques to understand the concepts.</p><p><strong>What is Deep InfoMax and why do we need it?</strong></p><p>Deep InfoMax is a deep neural network architecture that improves upon some of the leading architectures of today. It resembles a traditional Convolutional Neural Network (CNN) with some additional features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*qXgAyWcmN8_eqbFimlaT3Q.png" /><figcaption>Convolutional Neural Network — This and all images below were created by the author</figcaption></figure><p>It represents an improvement in the performance and accuracy of learning of good representations without annotations. It is technically self-supervised, a form of unsupervised learning, making it another important tool for learning representations of unlabeled datasets.</p><p><strong>What makes Deep InfoMax special?</strong></p><p>I will explain each of these in detail in the coming sections, but these are the reasons why you should be learning about Deep InfoMax, and not some other method of machine learning.</p><p>▹ First, mutual information maximization. Definitely not a new concept Deep InfoMax follows examples like <em>Mutual Information Neural Estimation</em> known as MINE. Deep InfoMax differs for reasons explained in more detail below, including the eliminating the need for a generator and improvements over Kullback-Leibler regularization.</p><p>▹Second, matching representations to a prior distribution adversarially to implicitly train the system to match the noise.</p><p>▹ Third, structure matters. This is a theme consistent through Dr. Hjelm’s paper. The results demonstrate that including knowledge about locality in the input can significantly improve performance.</p><p><strong>Supervised vs Unsupervised Learning</strong></p><p>No this does not involve watching your neural network while it trains to ensure it doesn’t become self-aware and take over the world. Supervised learning pertains to the use of “labels” which are the meaningful or informative descriptions that the neural network is trying to predict.</p><p>If the data being trained on contains labels that the machine learning model tries to predict and match, this is what is thought of as supervised learning.</p><p>On the other hand, training on unlabeled data is one type of unsupervised learning. Unsupervised learning that involves training the neural network to group items it determines to be similar is considered clustering.</p><p><strong>“Self-supervised” Learning</strong></p><p>Now I’d like to take a moment to talk about something that might sound like semantics, but is actually a neat trick of Deep InfoMax. It is not supervised, but it’s not unsupervised either. One of the things that makes Deep InfoMax unique is that it generates its own labels. These labels are more simple than what we are used to, it simply labels the feature maps of all of the input samples as “real” after they have passed through the encoder. It then creates new feature map of another image and passes the feature vector of the first image and the feature map of the second image through the discriminator. Because these feature maps and feature vectors do not belong together it labels them as “fake” and then creates a new set of images by mixing patches of different images and it labels the members of this new set as “fake”.</p><p>This self supervised aspect, and the Deep InfoMax architecture as a whole, is a complicated way of answering the simple question of “do these things go together”</p><p>It knows which samples don’t go together because it put them there and by passing the “fake” image through a discriminator it maximize mutual information, which I will discuss in the next section. The end goal of this process is to train the encoder to fool the discriminator and the discriminator to know the difference.</p><p><strong>Mutual Information</strong></p><p>Self-supervision is a good lead in to our next topic, mutual information. What is mutual information? Mutual information is just like a divergence or a difference between two different distributions, one is the joint distribution between two variables and the other is the product of marginals. The joint distribution is the probability that these two things co-occur and the product of marginals is their probabilities that they occur independently of each other.</p><p>So basically mutual information is training a classifier for determining which samples go together and which samples don’t. We use mutual information to reduce uncertainty for one variable given a known value of the other variable.</p><p>By passing the samples from the joint distribution, known as the “real” samples, and samples from the product of marginal distribution, the “fake” samples, the discriminator is trained to maximize the estimation of the mutual information.</p><p>Deep InfoMax uses gradients from the discriminator to help train the encoder network. Unmitigated, this method of training would yield representations that contain noisy information, or information that would increase mutual information without providing any useful information for classification. Fortunately there is a solution for handling this noise that is discussed in the next section.</p><p><strong>Matching Representations to a Prior Distribution</strong></p><p>Pure mutual information has its limitations. Maximizing mutual information between the input image and output representation globally would result in learning features that are unrelated because their sum has more unique information than other redundant locations. Encoding separate but related pieces of information doesn’t increase mutual information as much as encoding details of the background. These irrelevant patches of information can be considered noise. In order to remove noise and lessen its effect, the discriminator is trained to estimate the divergence between a push-forward distribution, and a prior. The encoder is then implicitly trained to minimize this estimate. This technique of combining mutual information maximization with prior matching is similar to what is performed by adversarial autoencoders.</p><p><strong>Structure Matters</strong></p><p>Just like any other CNN, Deep InfoMax takes patches across the input image and encodes them. Incorporating the location of each patch and its corresponding features is important because it biases the model to learn things that are expressible structurally. The features of each patch can vary based on location and the network needs to understand why those specific patches are related. It is a trend of CNNs to classify images based on textures that correlate with the class label rather than with shape or size. Intuition tells us that depending on what else is being classified, features like texture alone would not be enough to meaningfully differentiate between classes. For example recognizing the texture of an animal’s fur might distinguish it from the texture of a food or plants, however it would be insufficient for classifying different animal species with similar fur.</p><p>Incorporating spatial locality is accomplished by the discriminator. It is the discriminator’s objective to maximize the mutual information estimation either globally or over a local subset.</p><p><strong>How it works</strong></p><p>As stated before, Deep InfoMax takes patches across the input image and encodes them using a convnet, building a feature map of all the feature vectors from each patch. This feature map is encoded further and result is a new feature map representation that reflects some structural aspect of the data, e.g. spatial locality. This feature map is summarized into a global feature vector. From here two different architectures are described, “concatenate-and-convolve” and “encode-and-dot-product”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*vOmtRxrjc9VVKTBBwSq6mw.jpeg" /><figcaption>Feature Map for local and global feature vector</figcaption></figure><p><strong>Concatenate-and-convolve</strong>: From here the global feature vector is concatenated with the lower-level feature map at every location and passed through a 1 x 1 convolutional discriminator to produce the “real” feature map. The fake feature map is paired with the global feature vector and also passed through the discriminator to produce a “fake” score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5s-WZI-X_rctpxuuhKiwA.jpeg" /><figcaption>Concatenate-and-convolve</figcaption></figure><p><strong>Encode-and-dot-product</strong>: This time the global feature vector is encoded using a fully connected network. The lower-level feature map is encoded using 1 x 1 convolutions. The dot product of the global feature vector and local feature map is taken at each location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJAK15F-PllhWZLDdQ06vg.jpeg" /><figcaption>Encode-and-dot-product</figcaption></figure><p><strong>Architecture</strong></p><p>The Deep InfoMax architecture is difficult to define because there isn’t just one, but several versions described.</p><p>In addition to the two versions of the local classifier were outlined in the previous section. Four different mutual information architectures were tested. The first was global feature only estimation, and the other three were all local feature estimation using different mutual information estimators.</p><p>1. Global only</p><p>2. Donsker &amp; Varadhan</p><p>3. Jensen-Shannon</p><p>4. Noise-Contrastive Estimation</p><p>Tests were conducted using a variety of datasets of varying sizes and classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*yo_BsWpvIx1UhArFDgZIlg.jpeg" /><figcaption>Test datasets</figcaption></figure><p>Consistent across all tests were the hidden layers of the classifiers. They were comprised of two 512 unit layers. The ReLU activation function<strong> </strong>was used for both layers.</p><p><strong>Results</strong></p><p>Knowledge of the location of each patch and its corresponding feature vector was shown to greatly improve the representation’s quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*xHzQaiZizq7aV5xR0ILctw.jpeg" /><figcaption>Test results</figcaption></figure><p>As shown in the table above, Deep InfoMax outperformed the other networks with the exception of the global only architecture. The Bidirectional GAN network was the next highest performer actually outperforming one of the Deep InfoMax local architectures in one of the datasets.</p><p><strong>Conclusions</strong></p><p>Deep InfoMax is an improvement upon existing unsupervised classification architectures. Because it uses mutual information estimation maximization on its self-supervised samples it is able to train and encoder to improve the discriminator. By matching representations to a prior distribution the system is able to eliminate noise. And finally and crucially, because the joint distribution of the mutual information estimation is dependent on feature location we can say that structure in fact matters.</p><h3>Other Resources</h3><p>Here is a short video explaining the topic: <a href="https://youtu.be/jHt4nNC6ZcA">https://youtu.be/jHt4nNC6ZcA</a></p><p>Dr. Devon Hjelm’s conference paper, <em>Learning Deep Representations by Mutual Information Estimation and Maximization</em>, which this post is based on can be found at: <a href="https://arxiv.org/abs/1808.06670">https://arxiv.org/abs/1808.06670</a></p><p>Additional resources on this topic, provided by Microsoft can be found at:</p><p><a href="https://www.microsoft.com/en-us/research/blog/deep-infomax-learning-good-representations-through-mutual-information-maximization/">https://www.microsoft.com/en-us/research/blog/deep-infomax-learning-good-representations-through-mutual-information-maximization/</a></p><p>and</p><p><a href="https://youtu.be/s-Us47zp-48">https://youtu.be/s-Us47zp-48</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99cf98170138" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/deep-infomax-explanation-of-mutual-information-maximization-99cf98170138">Deep InfoMax | Explanation of Mutual Information Maximization</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A summary of Learning Phrase Representation using RNN Encoder-Decoder for Statistical Machine…]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/a-summary-of-learning-phrase-representation-using-rnn-encoder-decoder-for-statistical-machine-c5b6dbb61f6f?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/c5b6dbb61f6f</guid>
            <dc:creator><![CDATA[Dibu Benjamin]]></dc:creator>
            <pubDate>Mon, 02 May 2022 15:12:17 GMT</pubDate>
            <atom:updated>2022-05-03T00:14:28.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>A summary of Learning Phrase Representation using RNN Encoder-Decoder for Statistical Machine Translation</h3><p><a href="https://www.youtube.com/watch?v=ptpQbZJUQjY"><strong>Presentation Link</strong></a><strong>:</strong></p><p>This report is based on the “<strong><em>Learning Phrase Representation using RNN Encoder-Decoder for Statistical Machine Translation”</em> </strong>research paper.<br>EEL 6812-course project report.</p><p><strong><em>Research Purpose</em></strong></p><p>This paper proposes a novel neural network model called RNN Encoder-Decoder, a novel neural network architecture that can be used as a part of the conventional phrase-based SMT system. That simply words a system for translating a sentence in one langue to another language.</p><p><strong><em>Overview</em><br></strong>In the field of statistical machine translation (SMT), deep neural<br>networks have begun to show promising results. This study continues the research on employing neural networks for SMT by focusing on a unique neural network design that may be utilized as a part of the traditional phrase-based SMT system. The suggested neural network design, dubbed an RNN Encoder-Decoder, is made up of two recurrent neural networks (RNNs) that operate as an encoder and decoder pair.</p><ol><li>Encoder: First RNN, maps a variable-length source sequence to a fixed-length vector.</li><li>Decoder: Second RNN, maps the vector representation back to a variable-length target sequence.</li></ol><p>The proposed encoder-decoder units are trained together to increase the probability of the target sequence given a source sequence. Ans also a new hidden unit architecture is proposed to increase the memory capacity of the network.</p><p><strong><em>Recurrent Neural Network</em><br></strong>We must first understand a few key concepts of RNN to fully understand the architecture of RNN Encoder-Decoder.</p><p>RNN will work very well on the sequence of data. For example, suppose we have a sentence and need to predict whether it is positive or negative. First of all, need to convert the text data into some vectors. Then we can apply an ML algorithm and find whether the sentence is positive or negative. But the sequence information is discarded in this. Consider the case that needs to find whether a transaction is a fraud or not. In this case, if we change the sequence of the input it doesn&#39;t affect the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*qhi9UKumu_m3UlnDUYQi0w.jpeg" /></figure><p>But if it is in the case of a translator, it will make serious damage to the output. For example, instead of saying “I ate sushi on Sunday” we change the input sequence to “I ate Sunday on sushi”. The output translation will be also something else. So in this case the sequence of data is very important. <em>This is one of the main reasons for using RNN instead of ANN in the case of a sequence of data.</em></p><p>The three major problems with using ANN for sequence problems:</p><ol><li>Available size of input/output neurons.</li><li>Too much computation</li><li>No parameter sharing.</li></ol><p><strong><em>RNN Architecture:</em><br></strong>If you are trying to watch a movie after the beginning, let&#39;s say after half an hour, probably we will not understand what is happening there. So we need to understand the previous events also. Humans always try to connect things with past events. We will not think from scratch every second. Traditional neural networks can’t do this, and it seems like a major shortcoming. RNN addresses this issue. RNN is a special kind of network with loops in between the input and output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*HYjVSVuT5OvnIbViuYd4xA.png" /><figcaption>Recurrent Neural Network General Structure</figcaption></figure><p>Here Xt is the input, A is the hidden layer and ht is the output. and along with this we also get the output with respect to time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*jZi37qdenEjYw8N_ydcvng.png" /><figcaption>RNN hidden layer in different time step</figcaption></figure><p>Will explain this differently. The image shown above is not four different hidden layers, this is a single hidden layer at 4 different time steps. Consider we have a sentence of four words. RNN at each time will process one word. Now, what will happen in the first time step? X11 will pass to the network as input and the hidden layer will give an output for the next time step whatever was the output for the last timestep, will also send to the layer For the first time step we need some previous activation function O0 as well, let say it’s a vector of all zeros. So the output of each time step can be represented as follows:</p><ul><li>O1 = f(X11w+O0w1)</li><li>O2 = f(X12w+O1w1)</li><li>Where, f is an activation function</li><li>W is some weight.</li></ul><p>So the current output will contain the previous output also that is how the sequence is kept. A recurrent neural network (RNN) is a neural network that consists of a hidden state h and an optional output y which operates on a variable-length sequence x = (x1,……,xT ). At each time step t, the hidden state h&lt;t&gt; of the RNN is updated by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*jJ1axAw7xjXlILFgxniihQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*KxrxyB10ZbOc3xjDneQdhA.gif" /></figure><p>One of the advantages of RNNs is the possibility of connecting earlier knowledge to the current activity. Sometimes this is enough, but if the need to predict something from an event takes place long before this is not enough. Consider a case of trying to predict the last word in the text “I grew up in France………I speak….”. The last word should be French, but to predict this we need the information France. The gap between the relevant information and the point where it is needed is very large. It is entirely possible that RNN may become unable to learn to connect the information as the gap grows.</p><p><strong><em>Long-Short Term Memory Network(LSTM)</em><br></strong>Long Short Term Memory networks are a special kind of RNN, capable of learning long-term dependencies. All recurrent neural networks are made up of a series of repeated neural network modules. This repeating module in ordinary RNNs will have a relatively basic structure, such as a single tanh layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*BK65E61mcgFrk7iUV_uA3w.png" /></figure><p>LSTMs also have this structure, but the repeating module is different. There are four NN layers in LSTM instead of a single one as in RNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*NghTRMnUcoAJwPmPsPQK4g.png" /><figcaption>General Structure of LSTM</figcaption></figure><p>The cell state(the upper line)and its many gates are at the heart of LSTMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*DZ-HLVuc04FeIAQVOuUSvQ.png" /><figcaption>RNN with cell state</figcaption></figure><p>The cell state is kind of like a conveyor belt that sends relative information all the way down the chain of events. The LSTM does have the ability to remove or add information to the cell state, carefully regulated by structures called gates. During training, the gates might understand whatever data is important to preserve or forget. Gates are a mechanism to selectively allow information to pass through. A sigmoid neural net layer plus a pointwise multiplication operation make them up. The sigmoid layer produces integers ranging from zero to one, indicating how much of each component should be allowed to pass. “Allow nothing through!” signifies a value of zero, whereas “let everything through!” means a value of one.</p><p>The LSTM has three gates, Forgot gate, Input gate, and Output gate.</p><ul><li>Forgot gate: This gate helps to identify whether a piece of information should be discarded or saved. The sigmoid function passes information from the previous hidden state as well as information from the current input. If the value from the function is closer to zero it means that current information should not be remembered, and whether the value is close to one then it should be remembered.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*ayddPxQG6V8P65M4wDp0sA.png" /><figcaption>Forgot Gate</figcaption></figure><ul><li>Input gate: The input gate is used to update the cell state. This step is to determine what additional data will be stored in the cell state. The previous hidden state and current input will pass through the sigmoid function first and decides which values we’ll update. 0 means not important, and 1 means important. Then again will pass the available information to the tanh function and the corresponding value will regulate the network. Then we’ll combine these two to create an update to the state.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*aJk_NCte0dA4P-QAvWTxAQ.png" /><figcaption>Input gate</figcaption></figure><ul><li>Output gate: decide what we’re going to output. This output will be based on our cell state but will be a filtered version. First, we run a sigmoid layer which decides what parts of the cell state we’re going to output. Then, we put the cell state through tanh (to push the values to be between −1−1 and 11) and multiply it by the output of the sigmoid gate, so that we only output the parts we decided to.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*O1In4Fv-G5Z2wr36T-9QIw.png" /><figcaption>Output gate</figcaption></figure><p>In this paper, they have introduced a new hidden state called GRU.</p><p><strong><em>GRU</em><br></strong>GRU is basically a structure developed from the motivation of LSTM but is simpler to compute and implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*MZl8m5yLneKH_n06FYIZrQ.png" /></figure><p>As we can see the main difference between LSTM and GRU is that GRU has only two gates. Update gate and Reset gate. GRUs also merges the cell state and hidden state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*8frtFMl49S0D1rmp2CjG_w.png" /><figcaption>Graphical representation</figcaption></figure><p>Here r is the Reset gate and z is the update gate.</p><p>LSTM Gates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*av9WgPIQ0PP-1zJ6WHTfsg.png" /><figcaption>Forgot gate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*0reoA2YfdxfseeIAlo10DQ.png" /><figcaption>Input gate</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*21FGkKq0T3PzAy-G1EAbEw.png" /><figcaption>Output gate</figcaption></figure><p>GRU gates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*5qePdZOokJSbfu4663IvVQ.png" /></figure><ul><li>Update gate: this will perform the task of forgot and input gate in LSTM. The update gate controls how much information from the previous hidden state will carry over to the current hidden state.</li><li>Reset gate: reset gate is used to decide how much past information to forget. If the value of the reset gate is close to zero the hidden state is forced to ignore the previous hidden state and reset with the current input only.</li></ul><p><strong><em>RNN Encoder-Decoder</em><br></strong>As I explained before this is a combination of two RNN units.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*ZEiFYLjSYvB4NTYIYXDyEg.png" /><figcaption>General Architecture of Encoder-decoder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*rN2AY91nEj8V67qrVcf2VA.png" /><figcaption>Graphical Representation</figcaption></figure><p>In the encoder, the output will not be present in each hidden state instead it will take in the last hidden state of the encoder. And the combined output will feed as input to the decoder. That is the hidden state of the encoder is a summary(C) of all the input sequences. This is not the same as the RNN which we discussed before. Here both the encoder output and current hidden state are conditioned to the previous output and summary. So the hidden state of the decoder at time t can be denoted as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*J5AoiDF02xdEGxMy-IsXPA.png" /></figure><p>The next symbol’s joint probability is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*ujgtZ6vKsEvjAT50kMzIQQ.png" /></figure><p>The RNN Encoder-Decoder may be utilized in two ways once it has been trained. The model may be used to construct a target sequence from an input sequence. The model, on the other hand, may be used to score a set of input and output sequences, with the score being just a probability.</p><p><strong><em>Statistical Machine Translation</em><br></strong>Statistical machine translation (SMT) is a type of machine translation that employs huge amounts of bilingual data to determine the most likely translation for a given input. Statistical machine translation systems learn to translate by examining statistical connections between original texts and human translations. The system’s purpose is to find a translation f from a source phrase e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*wdzdEvBEVEVFcssAZWoqrw.png" /></figure><p>Where we have the translation model and a language model. Most SMT systems are modeled as a logliner model with additional features and weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*-iWejqlTJaBhVvw5NZ_iew.png" /></figure><p>The translation model log p(e|f ) is factorized into the translation probabilities of matching phrases in the source and target sentences. These probabilities are weighted accordingly to optimize the BLEU score in the log-linear model and are considered extra features. For this type of model typically the data that we use to learn the models is a table with phrase translation and their probabilities. In this paper, they set up the scoring process as like, training the encoder-decoder on these pair of phrases and then feeding that score as an additional feature into the SMT decoder. They disregard the (normalized) frequencies of each phrase pair in the source corpora when training the RNN Encoder-Decoder. A new score for each phrase pair is added to the current phrase table once the RNN Encoder-Decoder has been trained. This enables the new scores to be included in the existing tuning method with no additional computational complexity.</p><p>In this paper, they put forward the possibility that it may be possible to just completely move to the neural machine. With the suggested RNN Encoder-Decoder, the present phrase table may be totally replaced. In such an instance, the RNN Encoder-Decoder will need to build a list of (excellent) target phrases for a given source phrase. This requires a lot of computation so they didn’t implement this.</p><p><strong><em>Experiment</em><br></strong>In this paper, they evaluate the approach to the English/French<br>translation task of the WMT’14 workshop. Some of the available resources are listed below.</p><ul><li>The bilingual corpora include Europarl (61M words), news commentary (5.5M), UN (421M), and two crawled corpora of 90M and 780M words respectively. The last two corpora are quite noisy.</li><li>To train the French language model, about 712M words of crawled newspaper material are available in addition to the target side of the bitexts.</li><li>A subset of 418M words is selected out of more than 2G words for language modeling and a subset of 348M out of 850M words is selected for training the RNN Encoder-Decoder.</li></ul><p>The experiment employed an RNN Encoder-Decoder with 1000 hidden units and the suggested gates at the encoder and decoder. The activation function is a hyperbolic tangent. To evaluate the use of the BLUE score, which is essentially like a token matching metric.</p><p><strong><em>Quantitative Analysis</em><br></strong>In this paper, they use different combinations of approaches to calculate the BLUE score on training and testing.</p><p>1. Baseline configuration</p><p>2. Baseline + RNN</p><p>3. Baseline + CSLM + RNN</p><p>4. Baseline + CSLM + RNN + Word penalty</p><p>The first one is the baseline. The baseline phrase-based SMT system was built using <em>Moses. </em>This is free software, an SMT engine that is used to train a statistical model of text translation from a source language to a target language. Then the second setup checks how the SMT model does with the additional score from the RNN encoder-decoder. These scores are basically the probabilities from the encoder-decoder architecture. Then they use a language model along with the previous setup. This configuration will reveal whether various neural network contributions in different portions of the SMT system add up or are redundant. Then also another setup with an additional word penalty. The results for all these setups are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*7BVya5STk0QdS4RlEf_Zug.png" /></figure><p>The evaluation result shows that the performance is high when adding the features calculated by the neural network along with the baseline.</p><p><strong><em>Qualitative Analysis</em><br></strong>The phrase pair scores computed by the RNN Encoder-Decoder are compared to the equivalent p(f |e) from the translation model to see where the performance increase comes from.</p><p>They concentrate their qualitative analysis on pairings with lengthy (greater than 3 words per source phrase) and common resource phrases. They look at intended phrases that have received high scores from the translation probability p(f j e) or the RNN Encoder-Decoder for each such source phrase. Repeat the approach for those combinations whose source phrase is lengthy but uncommon in the corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wQ9wk1h1rAS_l9QHNwgFow.png" /></figure><p>The list shows the top three intended phrases for the corresponding source phrase for both the translation model and the proposed RNN model. In almost all the cases the target phrase selected by the proposed RNN encoder-decoder model is the same as the original translation. From the above list, we can conclude one more thing that the RNN model most probably suggests shorter models.</p><p>The translation model and the RNN Encoder-Decoder rated many phrase pairs identically, but there were just as many phrase pairings that were scored significantly differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*FVs-F8L6uJihbGAzw_jaZg.png" /><figcaption>phrase pairs according to their scores</figcaption></figure><p>This might be due to the suggested method of training the RNN Encoder-Decoder on a set of unique phrase pairs, which prevents the RNN Encoder-Decoder from merely learning the frequency of the phrase pairs from the corpus.</p><p><strong><em>Conclusion</em><br></strong>The proposed RNN Encoder-Decoder model can be used in two ways. It can be used to score two input sequences or can be used to generate a target sequence from a source sequence. And also purpose a new hidden state that has only two gates reset gate and an update gate. Which will help to determine how much each hidden unit remembers or forgets when reading/generating a sequence. Also, the proposed model is evaluated against SMT, this was done by scoring each phrase in the phrase table using the RNN model. the results of this comparison show that the new model captures language patterns in phrase pairs effectively and the new proposed model can be used to suggest well-formed target phrases. In terms of BLEU scores, the RNN Encoder-Decoder scores were shown to increase overall translation performance.</p><p><strong><em>Reference</em></strong></p><p>[1] <a href="https://arxiv.org/abs/1406.1078">Here is a link to the paper</a></p><p>[2] <a href="https://www.youtube.com/watch?v=rdkIOM78ZPk&amp;t=356s">https://www.youtube.com/watch?v=rdkIOM78ZPk&amp;t=356s</a></p><p>[3] <a href="https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21">https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21</a></p><p>[4] [Hochreiter and Schmidhuber1997] S. Hochreiter and J. Schmidhuber. 1997. Long short-term memory. Neural Computation, 9(8):1735–1780.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5b6dbb61f6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/a-summary-of-learning-phrase-representation-using-rnn-encoder-decoder-for-statistical-machine-c5b6dbb61f6f">A summary of Learning Phrase Representation using RNN Encoder-Decoder for Statistical Machine…</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformer: The Self-Attention Mechanism]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/transformer-the-self-attention-mechanism-d7d853c2c621?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7d853c2c621</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[self-attention]]></category>
            <dc:creator><![CDATA[Sudipto Baul]]></dc:creator>
            <pubDate>Mon, 02 May 2022 14:59:47 GMT</pubDate>
            <atom:updated>2022-05-02T14:59:46.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>This post gives a brief overview of the popular self-attention mechanism introduced in ‘Attention is All You Need’ paper, which is a de-facto of Machine Learning tasks nowadays.</h3><blockquote>A <strong>video presentation</strong> is available at <a href="https://youtu.be/wx09PDZlLRg">this link</a>.</blockquote><blockquote>The <strong>implementation</strong> can be found at <a href="https://github.com/Sudipto153/Transformer-model-Implementation/blob/main/Attention%20is%20All%20You%20Need.ipynb">this link</a>.</blockquote><blockquote>Blog by- Zubaidah Al-Mashhadani, Sudipto Baul</blockquote><p><strong>Intuition of the paper:</strong></p><p>The transformers propose a simple network architecture that is based on the attention mechanism. With the use of parallelization, the translation tasks are superior in quality while consuming significantly less time than the sequential models such as recurrent neural networks. Moreover, the paper shows that the transformer generalizes well to other tasks with large or sparse data.</p><p><strong>So, what is the transformer?</strong></p><p>If we think of transformer in the simplest way, it is basically a Blackbox where it has input that we want to translate and output of the translation. Now, by examining the Blackbox, we see that it consists of an encoder and a decoder component.</p><p>The encoding component it is a stack of six encoders, similarly the decoding component. The encoders are designed such that they have an identical structure, every encoder has two sublayers including the Feed Forward Neural Network, and the Self- Attention layer. Hence, the input first go through the self-attention then the feed-forward layer. Likewise, the decoder also has the same layers in addition to a third layer that takes place between the previously introduced layers, this layer is called the Encoder — Decoder Attention. It helps the decoder to focus on relevant parts of the input sentence.</p><p>Let’s take a step back to see how exactly the model deals with an input sentence to output a desired translation. In natural Language Processing (NLP), generally words can be seen as distinct inputs that have a relation with one another in the sense of meanings. Thus, we transform each word into a vector as words cannot be naively passed to a model or neural network without being encoded into a numerical form, hence comes the use of the embedding algorithms. There are multiple approaches to generate words embeddings that can be mainly split into two categories: the probabilistic approaches and count-based approach. The choice of the word embedding is the most significant step in the preprocessing when performing an NLP task. Some of the widely used embedding algorithms are BERT, word2vec, GloVe … etc.</p><p>The embedding only happens in the bottom most encoder. Where all encoders receive a list of vectors in size of 512. After embedding the words of the input sentence, each vector flows through two layers of encoder. We can now observe a very important property of the transformers that is it works in parallel. In other words, the word at each position flow through its own path in the encoder. Meanwhile in RNN such as LSTM the flow of data was sequential not parallel and that consumes more time, hence, transformers are much faster using parallelization property. Figure 1 shows the architecture of the transformer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*vrSX_Ku3EmGPyqF_E-2_Vg.png" /><figcaption>Figure 1. Transformer Architecture</figcaption></figure><p><strong>The Encoder</strong>:</p><p>The encoder maps an input sequence of symbol representation (x1, x2, …, xn) to a sequence of continuous representations Z = (z1, …, z1), given Z the decoder generates an output sequence (y1, …, ym) of symbols one element at a time. The transformers apply this process using stacked self-attention and pointwise, fully connected layers for the encoder and the decoder. As explained earlier, the encoder receives a list of vectors as the input. It processes this list by passing it to self-attention layer, then to a feed-forward neural network, and sends out the output to the following encoder.</p><p>We mentioned self-attention multiple times so far, but what do we mean by self-attention? To understand this let’s explore the idea of attention first. As humans, we use our visual attention to focus on important features when looking at a picture for example, refer to the cat image shown below, we would notice the features that are detected by the red squares can make a refer about the image while not paying attention to the background for instance in the purple rectangles, moreover, if we cover those important features then we probably will not be able to make a correct inference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*2X-JJ3RamdgkZH8ayQqo4g.png" /></figure><p>In similar way, we can explain the relationship between words in a given sentence. As illustrated below, where we can see “watching” we expect an encounter as a movie, show, or a play very soon. Meanwhile, the word French describe is related to the show, however it is not directly related to “watching”. Hence, self-attention basically allows the model to look at the other positions in the input sequence while processing each word, which will lead to a better encoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*dR8i4L8tNLgML8kfbtvXUw.png" /></figure><p><strong>Self-Attention:</strong></p><p>Now that we discussed the importance and role of self-attention in transformers, it is time to explore the calculations, and the implementation of it as follows:</p><p>1- Create three vectors for each word by multiplying each token (1x512) by three matrices (Query, Key, Value) each (512x64) that were trained so we will have three vectors for each word such that each vector of size (1x64).</p><p>2- Calculate the score (weight) by using dot product of the query vector with the key vector of the words (tokens). The score will determine how much focus to place on other parts of the inputs as we encode a word at a specific position.</p><p>3- Now divide the score by the square root of the dimension of the key vector which equals 8 in this case.</p><p>4- Apply SoftMax operation to normalize the scores from 0 to 1 such that all weights will add up to 1.</p><p>5- Next, multiply each vector value with the score.</p><p>6- Finally sum up the weighted value vectors to represent the encoding of the specified token.</p><p>7- Repeat for all words, we end up having an attention map that fully encode the words using attention.</p><p><strong>Matrix calculation of Self-Attention:</strong></p><p>We start by calculating the Query, Key, and Value matrices. This is obtained by multiplying the matrix of the packed embeddings, by the weight matrices (WQ, Wk, WV) as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*aTLu4HxVUzEOIZTLHmOktw.png" /><figcaption>Figure 2. Matrix Calculations of Self-Attention</figcaption></figure><p>Where, each row in the matrix (X) corresponds to a word in the input sentence.</p><p>Next, obtaining the score, by multiplying the Query by the Key matrix, dividing by the square root of the dimension of the key, and also applying the SoftMax operation, and multiply the scores by the values, are all done in one step as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*slTLxwiFiEJ_6_vgI_BS-Q.png" /></figure><p><strong>Multi-Headed Attention:</strong></p><p>The self-attention layer is refined further by the addition of “multi-headed” attention. This does improve the performance of the attention layer by expanding the model’s ability to focus on different positions while encoding for better predictions. Moreover, it gives the attention layer multiple “representation subspaces” as in the multi-headed attention we have multiple Query, Key, Value weights matrices instead of one. The transformer uses eight attention heads, which leads to having eight sets of Q, K, V matrices and eventually, end up having eight Z-matrices. Where, the attention is calculated separately in eight different attention heads.</p><p>This arises a challenge! The feed-forward layer is not expecting eight matrices, in fact it is expecting a single matrix. To overcome this, first concatenate the Z matrices from all the attention heads. Then, multiply by a weight matrix Wo that was trained jointly with the model. Finally, this would result in Z matrix, which will capture the information from all the attention heads and this matrix is passed to the feed-forward layer.</p><p><strong>Positional Encoding:</strong></p><p>As we discussed earlier, each word is represented by a vector using embedding algorithms which yields a token. Now, since the transformers works in parallel, it is important to keep track of the words position within a sentence. The transformers overcome this issue by adding a vector to each input embedding. These vectors follow a pattern that the model learns to help determine the position of each word, or the distance between different words in the sentence. The idea behind it, is that it provides a meaningful distance between the embedding vectors once they are projected into the Query, Key, and Value vectors and during the dot-product attention. This is called positional encoding. For example, if the embedding has a dimensionality of 4, the positional encoding is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*4WS9y0PTFceqCyP8vMAsog.png" /><figcaption>Figure 3. Positional Encoding</figcaption></figure><p>It’s important to note that the positional encodings have the same dimensions as the embeddings so that both can be summed as shown in the previous example.</p><p>Sine and Cosine functions of different frequencies are used:</p><p><em>PE(pos,2i) = sin(pos / 100002i / d_model)</em></p><p><em>PE(pos, 2i+1) = cos(pos / 100002i / d_model)</em></p><p>Where <em>pos </em>is the position and <em>i </em>is the dimensions. Such that, each dimension of the positional encoding corresponds to a sinusoid.</p><p>In each sublayer, such as self-attention and FFNN, in each encoder has a residual connection around it followed by a layer-normalization step.</p><p>To put everything, we learnt about the encoder in one big picture we can see it as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*gHPy59vTzVvyERyMIwSVDw.png" /><figcaption>Figure 4. Encoder Architecture</figcaption></figure><p><strong>The Decoder:</strong></p><p>We saw that the encoder takes the input sequence and process it. The output of the top encoder is transformed into a set of attention vectors K and V. These are used by each encoder in its “encoder-decoder attention” layer that helps the decoder focus on suitable positions in the input sentence. The self-attention layers in the decoder are slightly different than the ones in the encoder, as in the decoder the self-attention layer is only allowed to attend to earlier positions in the output sequence. This is achieved by masking the future positions before the SoftMax step in the self-attention calculation. Moreover, the “Encoder — Decoder Attention” layer works similar to the multiheaded self-attention except that it creates Queries matrix from the layer below it and takes the keys and values matrix from the output of the encoder.</p><p><strong>Final Linear and SoftMax Layer:</strong></p><p>The output of the decoder is a vector of stacked outputs that we need to turn into a word. Here comes the role of the final layer that is followed by the SoftMax layer. The final layer is a fully connected neural network that projects the vector produced by the stack of decoders into a larger vector that is called a logits vector, each cell of the logits vector corresponds to the score of a unique word. Then, the SoftMax layer turn those scores into probabilities that all would add up to 1.0. Finally, the cell with the highest probability is then chosen and the output is the word that is associated with it for this time step.</p><p><strong>Experimentation:</strong></p><p>The original model in the paper [1] was trained on the standard WMT 2014 <em>English-German</em> dataset consisting of 4.5 million sentence pairs and <em>English-French</em> dataset consisting of 36M sentences. Sentence pairs batched together by approximate sequence length. Adam optimizer used with variable learning rate. Dropout was applied to the output of each sub-layer before being added to the input of the next sub-layer and normalized. Also, dropout was applied to the sums of the embeddings and the positional encodings in both the encoder and decoder stacks. Label smoothing was also applied.</p><p><strong>Modification for the project:</strong></p><p>For this course project, we applied the model on standard WMT 2014 <em>English-German</em> dataset only following the code of [2]. Also, parts of the training process were modified. Positional encoding was learned instead of static. Moreover, static learning rate was used and no label smoothing was employed.</p><p><strong>Results:</strong></p><p>The table 1 below represents the different variations of hyperparameters of the transformer model. Also, it presents the perplexity score (PPL), BLEU score and number of trainable parameters used for each version on the EN-DE dataset. At the top, with the lowest values of the hyperparameters and hence lowest number of parameters, is the base model. At the bottom, there is the big version of the transformer with highest number of parameters as a consequence of higher value of the hyperparameters although it achieves the best BLEU and PPL scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*J-VSbIRyRs3Fd3fYL4ngWg.png" /><figcaption>Table 1. Variation of the transformer model [1]</figcaption></figure><p>Comparison of transformer’s results with the other models introduced in previous works are given in the table 2 below. The BLEU score is given for <em>English-German </em>(EN-DE) and <em>English-French </em>(EN-FR) tasks. The training cost is also provided for the stated tasks in terms of Floating Point Operations (FLOPs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ihB67FIxNqb18DliubOVgA.png" /><figcaption>Table 2. Comparison of transformer with other models [1]</figcaption></figure><p><strong>Modified model’s results:</strong></p><p>We achieved BLEU score of 35.38 and perplexity (PPL) score of 5.238 for the modified version of the model on the EN-DE translation task which is comparable to 26.4 BLEU score and 4.33 PPL score for the original model. Probably, the better BLEU score for the modified version was because of the use of learned positional embedding instead of a static one.</p><p><strong>Working of the attention mechanism:</strong></p><p>Translation of a sentence from German (<em>src</em>) to English (<em>predicted trg</em>) using the modified model can be found in Figure 5 below. The true translation of the sentence (<em>trg</em>) is also given for comparison. The model could translate the sentence almost perfectly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*ZUb2yGQD3_SRD-Q0KT9CdQ.png" /><figcaption>Figure 5. Translation of a sentence using transformer</figcaption></figure><p>To understand the attention mechanism in greater depth, the attention weights of each head was extracted from the model for the above translation. The attention matrices formed by the attention weights over the translation of each word (EN-DE) for the eight heads used in the model, is given in Figure 6 (lighter color means higher value). It can be observed that mostly the attention value is higher along the diagonal showing that the model gives attention to the specific word most of the time. But there are some lightly shaded areas in some cases representing the attention given to the neighbors for translation of a particular word. Also, the attention given to the words differs over the heads showing that each head picks up the importance from different perspectives during translation. For example, true translation of German word ‘<em>ein</em>’ is ‘<em>a</em>’. From the figure, for some heads, attention is given to ‘<em>a</em>’ and not for others while translating ‘<em>ein</em>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*yf8IHhkFn26uVKNCN96NjA.png" /><figcaption>Figure 6. Attention matrices formed by the heads for a translation</figcaption></figure><p><strong>Conclusion:</strong></p><p>The Transformer model is the first sequence transduction model based entirely on attention. It replaces the recurrent layers with multi-headed self-attention. For translation tasks, it can be trained significantly faster than recurrent or convolutional architectures. It outperforms all previously reported ensembles achieving a new state of the art result on WMT 2014 English-German translation task. The model can be extended to problems involving other input/output modalities- image, audio, video. Also local, restricted attention mechanisms can be investigated.</p><p><strong>References:</strong></p><p>[1] Vaswani, Ashish, <em>et al</em>. “Attention is all you need.” <em>Advances in neural information processing systems</em> 30 (2017).</p><p>[2] <a href="https://github.com/bentrevett/pytorch-seq2seq">https://github.com/bentrevett/pytorch-seq2seq/attention</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7d853c2c621" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/transformer-the-self-attention-mechanism-d7d853c2c621">Transformer: The Self-Attention Mechanism</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is it a bird or a plane? — One Pixel Attack for Fooling Deep Neural Networks]]></title>
            <link>https://medium.com/machine-intelligence-and-deep-learning-lab/is-it-a-bird-or-a-plane-one-pixel-attack-for-fooling-deep-neural-networks-ac9459efc781?source=rss----1c927f30b301---4</link>
            <guid isPermaLink="false">https://medium.com/p/ac9459efc781</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[adversarial-attack]]></category>
            <dc:creator><![CDATA[Sanjay Gandham]]></dc:creator>
            <pubDate>Sun, 01 May 2022 20:52:16 GMT</pubDate>
            <atom:updated>2022-05-01T20:52:16.415Z</atom:updated>
            <content:encoded><![CDATA[<h3>Is it a bird or a plane? — One Pixel Attack for Fooling Deep Neural Networks</h3><p><strong>Note: You can find our video presentation on </strong><a href="https://youtu.be/3WPEhqReyC8"><strong>YouTube</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeHsXCjeFf1E-sQcPgKx0A.png" /><figcaption>Modifying a pixel in the image changes the classification prediction of a Neural Network</figcaption></figure><p>Neural networks have been used to perform various machine learning tasks, among which image classification is one such task where convolution neural networks(CNN), a class of neural networks, have found great success. With CNNs such as AlexNet and VGG16 achieving human-competitive results, deep neural networks are the current de-facto standard for image classification. With accuracy being the main criteria, robustness of such neural networks were ignored. While at first glance, such a design choice may seem inconsequential, the findings of a group of researches described in the <a href="https://arxiv.org/pdf/1710.08864.pdf">paper</a> introduces a cause for concern.</p><h3>One-Pixel Attack</h3><p>Adding upon previous works where introducing a small amount of noise that is supposedly imperceptible to the human eye causes neural networks to misclassify images, the one-pixel attack aims to achieve the same while being limited by an extreme constraint, modify only a single pixel of the image. This is a semi black-box attack as it does not need any other information of the model except the final probability labels of each class. The problem statement can be mathematically defined as an optimization problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*MxbN8gY9KdbgA1wEsyGGBw.png" /><figcaption>Optimization problem to cause misclassfication</figcaption></figure><p>Here, <em>fₜ(x) </em>is the probability of an image<em> x = (x₁, …, xₙ), </em>to be classified as class<em> t </em>and <em>e(x) = (e₁, …, eₙ) </em>is the additive perturbation to the each of the <em>n</em> pixels of the image. The constraint here is that the overall perturbation amount is limited to <em>L</em>. However, the authors used a different approach by modifying the constraint to limit the number of pixels that can be changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*sC1YGKlXxI1LUA32n7vw2A.png" /><figcaption>Modified optimization problem with constraint on number of pixels that can be perturbed</figcaption></figure><p>The modified constraint is that the <em>L1 norm</em> of the perturbation vector, <em>e</em>, is limited to a small positive integer <em>d. </em>Solving this optimization problem will allow the authors to achieve misclassification by modifying a number of pixels . While gradient descent is the most common method of solving optimization problems, given the authors use of <em>L1</em> norm in their constraint, the equation is not differentiable making the use of gradient descent unfeasible. Additionally, the authors performed a targeted attack on the CIFAR-10 dataset which tries to trick the neural network to misclassify an image as a specific class and an untargeted attack on ImageNet dataset which tricks the neural network to misclassify the image as any other class.</p><h3>Differential Evolution algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*13teMUWAdmfgF4bHKMOEBQ.gif" /><figcaption><a href="https://pablormier.github.io/2017/09/05/a-tutorial-on-differential-evolution-with-python/">Visualization</a> of DE optimizing a 2D Ackley Function</figcaption></figure><p>Differential Evolution (DE), a population-based algorithm, is a class of evolutionary algorithms that can solve complex multi-modal optimization problems. This algorithm works by initializing a population of candidate solutions and at every iteration of the algorithm, the candidate solutions are modified and compared against their corresponding parent solutions and the winner survive for the next iteration. Each candidate represents a perturbation that modifies a pixel and is a tuple holding five elements: x-y coordinates and the RGB values of the perturbation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*lYCoExCXGD3B-n-RlZBbFA.png" /><figcaption>List of candidate solutions where d is the number of candidates</figcaption></figure><p>The authors approach to find a solution for the optimization problem includes the following steps</p><ol><li>Randomly initialize the x-y coordinates of each candidate from the uniform distribution of the image dimensions in the dataset such that <em>xᵢ, yᵢ ~ U(1,32)</em> for Kaggle CIFAR-10 and <em>xᵢ, yᵢ ~ U(1,227) </em>for ImageNet.</li><li>Randomly initialize the RGB values according to the normal distribution with mean and standard deviation being 128 and 127 respectively such that <em>rᵢ, gᵢ, bᵢ ~Ν(μ = 128, σ = 127)</em></li><li>To evaluate the effectiveness of the perturbation, we use the fitness function which is the probability label of target class for targeted attack using Kaggle CIFAR -10 and probability label of the true class for a non-targeted attack using ImageNet</li><li>For each iteration, g, of the algorithm, the candidate solutions are evolved such that</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*yB9iHsEhik6IkOptcWRWmg.png" /></figure><p>5. The evolved candidates are compared to their respective parent candidates and the candidate that scores higher on the fitness function is retained while the other is eliminated</p><p>6. This process continues until either 100 iterations of the algorithm are performed or terminal conditions are reached which is <br>fitness function = probability label of target class &gt; 90% (targeted attack) or<br>probability label of true class &lt; 5% (non-targeted attack)</p><h3><strong>Datasets</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*wMlSBTnDcgrTuzVi_nUv7Q.png" /></figure><ul><li><strong>Kaggle CIFAR-10</strong>: Kaggle’s CIFAR-10 dataset is a collection of 300,000 32x32 images that spans over 10 classes and are taken from the original CIFAR-10 with modification such as duplication, rotation, clipping and blurring. These modifications were made using an undisclosed algorithm with the purpose of introducing noise and variation in the images.</li><li><strong>ImageNet</strong>: This dataset spans 1000 object classes and contains over 1,400,00 images of dimension 227x227. This dataset was used to evaluate the attacks efficacy on high resolution images.</li></ul><h3><strong>Neural Network Models</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*BVwRICc4OdAHVwtMwRlYdg.png" /><figcaption>Model architecture of Neural Networks used in the paper</figcaption></figure><ul><li><strong>Vgg16</strong>: It is a very deep convolution neural network submitted to ILSVRC-2014 and achieved a classification accuracy of 92.7% putting it in the top-5 test accuracy in ImageNet at the time of submission.</li><li><strong>Network in Network</strong>: The NiN model avoids fully connected layers and uses multiple NiN block with number of output channels equal to the number of label classes followed by global pooling layer. The main advantage of NiN’s design is that it significantly reduces the number of required model parameters at the expense of longer training time</li><li><strong>All Convolution Network</strong>: A convolution network with fewer layers whose strength lies in its simplicity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UZ8cgcDujg5LEJltmpjTg.png" /><figcaption>Illustration of AlexNet’s architecture. Image credits to Krizhevsky et al., the original authors of the AlexNet paper.</figcaption></figure><ul><li><strong>AlexNet</strong>: AlexNet was one of the first networks to use the ReLU activation and was capable of being trained on a multi-GPU setup significantly reducing the training time. In 2012 ImageNet competition, AlexNet achieved a top-5 error rate of 15.3% winning the competition with a large margin compared to second place top-5 error rate of 26.2%.</li></ul><p>Using such a diverse selection of models with varying characteristics to evaluate the efficacy of the generated adversarial images in misclassification helped the authors to properly analyze the attack and understand the pitfalls of neural network classifiers.</p><h3>Evaluation Metrics</h3><p>The metrics of highest significance used in this paper are</p><ol><li><strong>Success Rate</strong>: For non-targeted attack, it is the percentage of images that were successfully classified by the network as an arbitrary target class and for targeted attack, it is the probability of perturbing an image to a specific target class</li><li><strong>Probability Labels (Confidence)</strong>: The sum of the probability value of the target class for each successful perturbed image divided by the number of successful perturbations.</li><li><strong>Number of Target Classes</strong> : The number of images that successfully perturb to a certain number (i.e. from 0 to 9) of target classes.</li></ol><h3><strong>Findings and Discussion</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNx7ttq5WCTaBWhvwR7XbA.png" /><figcaption>Classes in black and blue are the labels predicted before and after the targeted attack on Kaggle CIFAR-10 and non-targeted attack on ImageNet respectively. The pixel that was modified is highlighted in the images</figcaption></figure><p>As seen from the figure, one-pixel attack can drastically change the prediction label and its corresponding confidence on both the datasets. Even a high resolution picture of a baby in a bassinet that is visually apparent to the human eye was misclassified as a paper towel by the BVLC AlexNet model when a single pixel of the image was perturbed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*JCc3LWs_RgffgiKdjjZKYw.png" /><figcaption>Table indicating the original accuracy, success rate of targeted and non-targeted attack and the confidence of the attack over different models trained .</figcaption></figure><p>From the table, the success rate of the targeted attack on Kaggle CIFAR-10 indicates that around 15–25% of the adversarial images, images obtained after the one-pixel attack, were misclassified into a specific class. Moreover, a large portion of the adversarial images generated from the non-targeted attack were able to cause the networks to misclassify. Additionally, the confidence metrics of the attacks on AllConv, NiN and VGG16 is higher indicating that the attack has fooled the networks to a great extent. The main takeaway from this is that the networks trained using the conventional model training paradigm are not robust enough to withstand a perturbation to even a single pixel. Moreover, the success rate for both targeted and non-targeted attack on NiN model is higher than other models, implying that some networks can be more vulnerable to adversarial images.</p><p>However, it can be argued that the high success rate of the attack is due to the low resolution of 32x32 of the Kaggle CIFAR-10 dataset. As such, the authors used higher resolution images of size 227x227 from the ImageNet data set and about found that 16.04% of the adversarial images generated by the non-targeted one-pixel attack caused misclassification in the BVLC AlexNet model. While the success rate may seem low at first glance, considering that the search space for ImageNet is 50 times larger than that of Kaggle CIFAR-10, the attack can be considered to be effective against higher resolution images. The lower confidence for BVLC AlexNet can be attributed to ImageNet having 1000 classes compared to 10 classes of Kaggle CIFAR-10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*DlUJNxP9Tgwd2WrrTNjjrQ.png" /><figcaption>Success rate and confidence scores of targeted and non-targeted attack on AllConv Network trained with the Kaggle CIFAR-10 dataset</figcaption></figure><p>The 1-pixel attack was compared with 3-pixel and 5-pixel attack using AllConv network trained on Kaggle CIFAR-10 dataset. As expected, increasing the number of pixels perturbed significantly increased the success rate for both the targeted and non-targeted attack implying more number of adversarial images caused misclassification when more pixels were modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*GzpW28FDZVEjmiQ5yulP4g.png" /><figcaption>Heatmap showing number of times the attack was successful for a pair of original-target class pair in 1-pixel attack. Red and blue classes indicate the original and target class respectively. Number 0 to 9 indicate: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck respectively. The example on the right shows the original class and the misclassified class and the confidence of classification.</figcaption></figure><p>The heatmaps of the attack on all three models AllConv, NiN, VGG16 are approximately symmetric across the diagonal. This indicates that classes have a similar number of adversarial images create to and from those classes. For example, for the 5-3 original-target class pair, the heatmaps shows that the attack was successful multiple times implying that an image of a dog can be misclassified as a cat with higher success rate. Additionally, the 3–5 original-target class pair has equal number of successful attacks indicating that image of a cat can be misclassified as a dog with higher success rate. This also indicates that the dataset contains certain original-target class pairs that are more vulnerable to the targeted attack. However, there exists some outliers to this pattern where the model can misclassify a ship as an airplane with higher success rate but an airplane cannot be misclassified as a ship with as high of a success rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*bWQVoalxUQl5nPvt-G9zGw.png" /><figcaption>Comparing Differential Evolution (DE) 1-pixel attack with Random 1-pixel attack</figcaption></figure><p>To evaluate DE’s efficacy of solving the optimization problem, the authors compared the success rate and confidence of DE 1-pixel attack and Random 1-pixel attack, where a random pixel is selected and modified to a random value, and found that the success rate for DE is significantly higher compared to the random attack. This shows that DE has found a better solution to the optimization problem for all the networks compared to random attack proving its ability to solve non differentiable optimization problems.</p><h3><strong>Conclusion</strong></h3><p>Although it has been known that neural network based classifier can be fooled by these adversarial images where noise was added to the image, this paper is the first to show that by changing just a single pixel of the image to a specific value, the neural network can be fooled. Moreover, this paper shows that evolutionary based algorithms that are computationally inexpensive, can effectively be used in the context of neural networks and deep-learning to solve optimization problems.</p><p>Written and Presented by:</p><ul><li>Sanjay Gandham</li><li>Nicholas DeSantis</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac9459efc781" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-intelligence-and-deep-learning-lab/is-it-a-bird-or-a-plane-one-pixel-attack-for-fooling-deep-neural-networks-ac9459efc781">Is it a bird or a plane? — One Pixel Attack for Fooling Deep Neural Networks</a> was originally published in <a href="https://medium.com/machine-intelligence-and-deep-learning-lab">Machine Intelligence and Deep Learning</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>