CINXE.COM
Barlow Twins for Contrastive SSL
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Keras documentation"> <meta name="author" content="Keras Team"> <link rel="shortcut icon" href="https://keras.io/img/favicon.ico"> <link rel="canonical" href="https://keras.io/examples/vision/barlow_twins/" /> <!-- Social --> <meta property="og:title" content="Keras documentation: Barlow Twins for Contrastive SSL"> <meta property="og:image" content="https://keras.io/img/logo-k-keras-wb.png"> <meta name="twitter:title" content="Keras documentation: Barlow Twins for Contrastive SSL"> <meta name="twitter:image" content="https://keras.io/img/k-keras-social.png"> <meta name="twitter:card" content="summary"> <title>Barlow Twins for Contrastive SSL</title> <!-- Bootstrap core CSS --> <link href="/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700;800&display=swap" rel="stylesheet"> <!-- Custom styles for this template --> <link href="/css/docs.css" rel="stylesheet"> <link href="/css/monokai.css" rel="stylesheet"> <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-5DNGF4N'); </script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-175165319-128', 'auto'); ga('send', 'pageview'); </script> <!-- End Google Tag Manager --> <script async defer src="https://buttons.github.io/buttons.js"></script> </head> <body> <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5DNGF4N" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> <div class='k-page'> <div class="k-nav" id="nav-menu"> <a href='/'><img src='/img/logo-small.png' class='logo-small' /></a> <div class="nav flex-column nav-pills" role="tablist" aria-orientation="vertical"> <a class="nav-link" href="/about/" role="tab" aria-selected="">About Keras</a> <a class="nav-link" href="/getting_started/" role="tab" aria-selected="">Getting started</a> <a class="nav-link" href="/guides/" role="tab" aria-selected="">Developer guides</a> <a class="nav-link" href="/api/" role="tab" aria-selected="">Keras 3 API documentation</a> <a class="nav-link" href="/2.18/api/" role="tab" aria-selected="">Keras 2 API documentation</a> <a class="nav-link active" href="/examples/" role="tab" aria-selected="">Code examples</a> <a class="nav-sublink active" href="/examples/vision/">Computer Vision</a> <a class="nav-sublink2" href="/examples/vision/image_classification_from_scratch/">Image classification from scratch</a> <a class="nav-sublink2" href="/examples/vision/mnist_convnet/">Simple MNIST convnet</a> <a class="nav-sublink2" href="/examples/vision/image_classification_efficientnet_fine_tuning/">Image classification via fine-tuning with EfficientNet</a> <a class="nav-sublink2" href="/examples/vision/image_classification_with_vision_transformer/">Image classification with Vision Transformer</a> <a class="nav-sublink2" href="/examples/vision/attention_mil_classification/">Classification using Attention-based Deep Multiple Instance Learning</a> <a class="nav-sublink2" href="/examples/vision/mlp_image_classification/">Image classification with modern MLP models</a> <a class="nav-sublink2" href="/examples/vision/mobilevit/">A mobile-friendly Transformer-based model for image classification</a> <a class="nav-sublink2" href="/examples/vision/xray_classification_with_tpus/">Pneumonia Classification on TPU</a> <a class="nav-sublink2" href="/examples/vision/cct/">Compact Convolutional Transformers</a> <a class="nav-sublink2" href="/examples/vision/convmixer/">Image classification with ConvMixer</a> <a class="nav-sublink2" href="/examples/vision/eanet/">Image classification with EANet (External Attention Transformer)</a> <a class="nav-sublink2" href="/examples/vision/involution/">Involutional neural networks</a> <a class="nav-sublink2" href="/examples/vision/perceiver_image_classification/">Image classification with Perceiver</a> <a class="nav-sublink2" href="/examples/vision/reptile/">Few-Shot learning with Reptile</a> <a class="nav-sublink2" href="/examples/vision/semisupervised_simclr/">Semi-supervised image classification using contrastive pretraining with SimCLR</a> <a class="nav-sublink2" href="/examples/vision/swin_transformers/">Image classification with Swin Transformers</a> <a class="nav-sublink2" href="/examples/vision/vit_small_ds/">Train a Vision Transformer on small datasets</a> <a class="nav-sublink2" href="/examples/vision/shiftvit/">A Vision Transformer without Attention</a> <a class="nav-sublink2" href="/examples/vision/image_classification_using_global_context_vision_transformer/">Image Classification using Global Context Vision Transformer</a> <a class="nav-sublink2" href="/examples/vision/oxford_pets_image_segmentation/">Image segmentation with a U-Net-like architecture</a> <a class="nav-sublink2" href="/examples/vision/deeplabv3_plus/">Multiclass semantic segmentation using DeepLabV3+</a> <a class="nav-sublink2" href="/examples/vision/basnet_segmentation/">Highly accurate boundaries segmentation using BASNet</a> <a class="nav-sublink2" href="/examples/vision/fully_convolutional_network/">Image Segmentation using Composable Fully-Convolutional Networks</a> <a class="nav-sublink2" href="/examples/vision/retinanet/">Object Detection with RetinaNet</a> <a class="nav-sublink2" href="/examples/vision/keypoint_detection/">Keypoint Detection with Transfer Learning</a> <a class="nav-sublink2" href="/examples/vision/object_detection_using_vision_transformer/">Object detection with Vision Transformers</a> <a class="nav-sublink2" href="/examples/vision/3D_image_classification/">3D image classification from CT scans</a> <a class="nav-sublink2" href="/examples/vision/depth_estimation/">Monocular depth estimation</a> <a class="nav-sublink2" href="/examples/vision/nerf/">3D volumetric rendering with NeRF</a> <a class="nav-sublink2" href="/examples/vision/pointnet_segmentation/">Point cloud segmentation with PointNet</a> <a class="nav-sublink2" href="/examples/vision/pointnet/">Point cloud classification</a> <a class="nav-sublink2" href="/examples/vision/captcha_ocr/">OCR model for reading Captchas</a> <a class="nav-sublink2" href="/examples/vision/handwriting_recognition/">Handwriting recognition</a> <a class="nav-sublink2" href="/examples/vision/autoencoder/">Convolutional autoencoder for image denoising</a> <a class="nav-sublink2" href="/examples/vision/mirnet/">Low-light image enhancement using MIRNet</a> <a class="nav-sublink2" href="/examples/vision/super_resolution_sub_pixel/">Image Super-Resolution using an Efficient Sub-Pixel CNN</a> <a class="nav-sublink2" href="/examples/vision/edsr/">Enhanced Deep Residual Networks for single-image super-resolution</a> <a class="nav-sublink2" href="/examples/vision/zero_dce/">Zero-DCE for low-light image enhancement</a> <a class="nav-sublink2" href="/examples/vision/cutmix/">CutMix data augmentation for image classification</a> <a class="nav-sublink2" href="/examples/vision/mixup/">MixUp augmentation for image classification</a> <a class="nav-sublink2" href="/examples/vision/randaugment/">RandAugment for Image Classification for Improved Robustness</a> <a class="nav-sublink2" href="/examples/vision/image_captioning/">Image captioning</a> <a class="nav-sublink2" href="/examples/vision/nl_image_search/">Natural language image search with a Dual Encoder</a> <a class="nav-sublink2" href="/examples/vision/visualizing_what_convnets_learn/">Visualizing what convnets learn</a> <a class="nav-sublink2" href="/examples/vision/integrated_gradients/">Model interpretability with Integrated Gradients</a> <a class="nav-sublink2" href="/examples/vision/probing_vits/">Investigating Vision Transformer representations</a> <a class="nav-sublink2" href="/examples/vision/grad_cam/">Grad-CAM class activation visualization</a> <a class="nav-sublink2" href="/examples/vision/near_dup_search/">Near-duplicate image search</a> <a class="nav-sublink2" href="/examples/vision/semantic_image_clustering/">Semantic Image Clustering</a> <a class="nav-sublink2" href="/examples/vision/siamese_contrastive/">Image similarity estimation using a Siamese Network with a contrastive loss</a> <a class="nav-sublink2" href="/examples/vision/siamese_network/">Image similarity estimation using a Siamese Network with a triplet loss</a> <a class="nav-sublink2" href="/examples/vision/metric_learning/">Metric learning for image similarity search</a> <a class="nav-sublink2" href="/examples/vision/metric_learning_tf_similarity/">Metric learning for image similarity search using TensorFlow Similarity</a> <a class="nav-sublink2" href="/examples/vision/nnclr/">Self-supervised contrastive learning with NNCLR</a> <a class="nav-sublink2" href="/examples/vision/video_classification/">Video Classification with a CNN-RNN Architecture</a> <a class="nav-sublink2" href="/examples/vision/conv_lstm/">Next-Frame Video Prediction with Convolutional LSTMs</a> <a class="nav-sublink2" href="/examples/vision/video_transformers/">Video Classification with Transformers</a> <a class="nav-sublink2" href="/examples/vision/vivit/">Video Vision Transformer</a> <a class="nav-sublink2" href="/examples/vision/bit/">Image Classification using BigTransfer (BiT)</a> <a class="nav-sublink2" href="/examples/vision/gradient_centralization/">Gradient Centralization for Better Training Performance</a> <a class="nav-sublink2" href="/examples/vision/token_learner/">Learning to tokenize in Vision Transformers</a> <a class="nav-sublink2" href="/examples/vision/knowledge_distillation/">Knowledge Distillation</a> <a class="nav-sublink2" href="/examples/vision/fixres/">FixRes: Fixing train-test resolution discrepancy</a> <a class="nav-sublink2" href="/examples/vision/cait/">Class Attention Image Transformers with LayerScale</a> <a class="nav-sublink2" href="/examples/vision/patch_convnet/">Augmenting convnets with aggregated attention</a> <a class="nav-sublink2" href="/examples/vision/learnable_resizer/">Learning to Resize</a> <a class="nav-sublink2" href="/examples/vision/adamatch/">Semi-supervision and domain adaptation with AdaMatch</a> <a class="nav-sublink2 active" href="/examples/vision/barlow_twins/">Barlow Twins for Contrastive SSL</a> <a class="nav-sublink2" href="/examples/vision/consistency_training/">Consistency training with supervision</a> <a class="nav-sublink2" href="/examples/vision/deit/">Distilling Vision Transformers</a> <a class="nav-sublink2" href="/examples/vision/focal_modulation_network/">Focal Modulation: A replacement for Self-Attention</a> <a class="nav-sublink2" href="/examples/vision/forwardforward/">Using the Forward-Forward Algorithm for Image Classification</a> <a class="nav-sublink2" href="/examples/vision/masked_image_modeling/">Masked image modeling with Autoencoders</a> <a class="nav-sublink2" href="/examples/vision/sam/">Segment Anything Model with 🤗Transformers</a> <a class="nav-sublink2" href="/examples/vision/segformer/">Semantic segmentation with SegFormer and Hugging Face Transformers</a> <a class="nav-sublink2" href="/examples/vision/simsiam/">Self-supervised contrastive learning with SimSiam</a> <a class="nav-sublink2" href="/examples/vision/supervised-contrastive-learning/">Supervised Contrastive Learning</a> <a class="nav-sublink2" href="/examples/vision/temporal_latent_bottleneck/">When Recurrence meets Transformers</a> <a class="nav-sublink2" href="/examples/vision/yolov8/">Efficient Object Detection with YOLOV8 and KerasCV</a> <a class="nav-sublink" href="/examples/nlp/">Natural Language Processing</a> <a class="nav-sublink" href="/examples/structured_data/">Structured Data</a> <a class="nav-sublink" href="/examples/timeseries/">Timeseries</a> <a class="nav-sublink" href="/examples/generative/">Generative Deep Learning</a> <a class="nav-sublink" href="/examples/audio/">Audio Data</a> <a class="nav-sublink" href="/examples/rl/">Reinforcement Learning</a> <a class="nav-sublink" href="/examples/graph/">Graph Data</a> <a class="nav-sublink" href="/examples/keras_recipes/">Quick Keras Recipes</a> <a class="nav-link" href="/keras_tuner/" role="tab" aria-selected="">KerasTuner: Hyperparameter Tuning</a> <a class="nav-link" href="/keras_hub/" role="tab" aria-selected="">KerasHub: Pretrained Models</a> <a class="nav-link" href="/keras_cv/" role="tab" aria-selected="">KerasCV: Computer Vision Workflows</a> <a class="nav-link" href="/keras_nlp/" role="tab" aria-selected="">KerasNLP: Natural Language Workflows</a> </div> </div> <div class='k-main'> <div class='k-main-top'> <script> function displayDropdownMenu() { e = document.getElementById("nav-menu"); if (e.style.display == "block") { e.style.display = "none"; } else { e.style.display = "block"; document.getElementById("dropdown-nav").style.display = "block"; } } function resetMobileUI() { if (window.innerWidth <= 840) { document.getElementById("nav-menu").style.display = "none"; document.getElementById("dropdown-nav").style.display = "block"; } else { document.getElementById("nav-menu").style.display = "block"; document.getElementById("dropdown-nav").style.display = "none"; } var navmenu = document.getElementById("nav-menu"); var menuheight = navmenu.clientHeight; var kmain = document.getElementById("k-main-id"); kmain.style.minHeight = (menuheight + 100) + 'px'; } window.onresize = resetMobileUI; window.addEventListener("load", (event) => { resetMobileUI() }); </script> <div id='dropdown-nav' onclick="displayDropdownMenu();"> <svg viewBox="-20 -20 120 120" width="60" height="60"> <rect width="100" height="20"></rect> <rect y="30" width="100" height="20"></rect> <rect y="60" width="100" height="20"></rect> </svg> </div> <form class="bd-search d-flex align-items-center k-search-form" id="search-form"> <input type="search" class="k-search-input" id="search-input" placeholder="Search Keras documentation..." aria-label="Search Keras documentation..." autocomplete="off"> <button class="k-search-btn"> <svg width="13" height="13" viewBox="0 0 13 13"><title>search</title><path d="m4.8495 7.8226c0.82666 0 1.5262-0.29146 2.0985-0.87438 0.57232-0.58292 0.86378-1.2877 0.87438-2.1144 0.010599-0.82666-0.28086-1.5262-0.87438-2.0985-0.59352-0.57232-1.293-0.86378-2.0985-0.87438-0.8055-0.010599-1.5103 0.28086-2.1144 0.87438-0.60414 0.59352-0.8956 1.293-0.87438 2.0985 0.021197 0.8055 0.31266 1.5103 0.87438 2.1144 0.56172 0.60414 1.2665 0.8956 2.1144 0.87438zm4.4695 0.2115 3.681 3.6819-1.259 1.284-3.6817-3.7 0.0019784-0.69479-0.090043-0.098846c-0.87973 0.76087-1.92 1.1413-3.1207 1.1413-1.3553 0-2.5025-0.46363-3.4417-1.3909s-1.4088-2.0686-1.4088-3.4239c0-1.3553 0.4696-2.4966 1.4088-3.4239 0.9392-0.92727 2.0864-1.3969 3.4417-1.4088 1.3553-0.011889 2.4906 0.45771 3.406 1.4088 0.9154 0.95107 1.379 2.0924 1.3909 3.4239 0 1.2126-0.38043 2.2588-1.1413 3.1385l0.098834 0.090049z"></path></svg> </button> </form> <script> var form = document.getElementById('search-form'); form.onsubmit = function(e) { e.preventDefault(); var query = document.getElementById('search-input').value; window.location.href = '/search.html?query=' + query; return False } </script> </div> <div class='k-main-inner' id='k-main-id'> <div class='k-location-slug'> <span class="k-location-slug-pointer">►</span> <a href='/examples/'>Code examples</a> / <a href='/examples/vision/'>Computer Vision</a> / Barlow Twins for Contrastive SSL </div> <div class='k-content'> <h1 id="barlow-twins-for-contrastive-ssl">Barlow Twins for Contrastive SSL</h1> <h1 id="barlow-twins-for-contrastive-ssl">Barlow Twins for Contrastive SSL</h1> <p><strong>Author:</strong> <a href="https://github.com/dewball345">Abhiraam Eranti</a><br> <strong>Date created:</strong> 11/4/21<br> <strong>Last modified:</strong> 12/20/21<br></p> <div class='example_version_banner keras_2'>ⓘ This example uses Keras 2</div> <p><img class="k-inline-icon" src="https://colab.research.google.com/img/colab_favicon.ico"/> <a href="https://colab.research.google.com/github/keras-team/keras-io/blob/master/examples/vision/ipynb/barlow_twins.ipynb"><strong>View in Colab</strong></a> <span class="k-dot">•</span><img class="k-inline-icon" src="https://github.com/favicon.ico"/> <a href="https://github.com/keras-team/keras-io/blob/master/examples/vision/barlow_twins.py"><strong>GitHub source</strong></a></p> <p><strong>Description:</strong> A keras implementation of Barlow Twins (constrastive SSL with redundancy reduction).</p> <hr /> <h2 id="introduction">Introduction</h2> <p>Self-supervised learning (SSL) is a relatively novel technique in which a model learns from unlabeled data, and is often used when the data is corrupted or if there is very little of it. A practical use for SSL is to create intermediate embeddings that are learned from the data. These embeddings are based on the dataset itself, with similar images having similar embeddings, and vice versa. They are then attached to the rest of the model, which uses those embeddings as information and effectively learns and makes predictions properly. These embeddings, ideally, should contain as much information and insight about the data as possible, so that the model can make better predictions. However, a common problem that arises is that the model creates embeddings that are redundant. For example, if two images are similar, the model will create embeddings that are just a string of 1's, or some other value that contains repeating bits of information. This is no better than a one-hot encoding or just having one bit as the model’s representations; it defeats the purpose of the embeddings, as they do not learn as much about the dataset as possible. For other approaches, the solution to the problem was to carefully configure the model such that it tries not to be redundant.</p> <p>Barlow Twins is a new approach to this problem; while other solutions mainly tackle the first goal of invariance (similar images have similar embeddings), the Barlow Twins method also prioritizes the goal of reducing redundancy.</p> <p>It also has the advantage of being much simpler than other methods, and its model architecture is symmetric, meaning that both twins in the model do the same thing. It is also near state-of-the-art on imagenet, even exceeding methods like SimCLR.</p> <p>One disadvantage of Barlow Twins is that it is heavily dependent on augmentation, suffering major performance decreases in accuracy without them.</p> <p>TL, DR: Barlow twins creates representations that are:</p> <ul> <li>Invariant.</li> <li>Not redundant, and carry as much info about the dataset.</li> </ul> <p>Also, it is simpler than other methods.</p> <p>This notebook can train a Barlow Twins model and reach up to 64% validation accuracy on the CIFAR-10 dataset.</p> <p><img alt="image" src="https://i.imgur.com/G6LnEPT.png" /></p> <h3 id="highlevel-theory">High-Level Theory</h3> <p>The model takes two versions of the same image(with different augmentations) as input. Then it takes a prediction of each of them, creating representations. They are then used to make a cross-correlation matrix.</p> <p>Cross-correlation matrix:</p> <div class="codehilite"><pre><span></span><code>(pred_1.T @ pred_2) / batch_size </code></pre></div> <p>The cross-correlation matrix measures the correlation between the output neurons in the two representations made by the model predictions of the two augmented versions of data. Ideally, a cross-correlation matrix should look like an identity matrix if the two images are the same.</p> <p>When this happens, it means that the representations:</p> <ol> <li>Are invariant. The diagonal shows the correlation between each representation's neurons and its corresponding augmented one. Because the two versions come from the same image, the diagonal of the matrix should show that there is a strong correlation between them. If the images are different, there shouldn't be a diagonal.</li> <li>Do not show signs of redundancy. If the neurons show correlation with a non-diagonal neuron, it means that it is not correctly identifying similarities between the two augmented images. This means that it is redundant.</li> </ol> <p>Here is a good way of understanding in pseudocode(information from the original paper):</p> <div class="codehilite"><pre><span></span><code>c[i][i] = 1 c[i][j] = 0 where: c is the cross-correlation matrix i is the index of one representation's neuron j is the index of the second representation's neuron </code></pre></div> <p>Taken from the original paper: <a href="https://arxiv.org/abs/2103.03230">Barlow Twins: Self-Supervised Learning via Redundancy Reduction</a></p> <h3 id="references">References</h3> <p>Paper: <a href="https://arxiv.org/abs/2103.03230">Barlow Twins: Self-Supervised Learning via Redundancy Reduction</a></p> <p>Original Implementation: <a href="https://github.com/facebookresearch/barlowtwins">facebookresearch/barlowtwins</a></p> <hr /> <h2 id="setup">Setup</h2> <div class="codehilite"><pre><span></span><code><span class="err">!</span><span class="n">pip</span> <span class="n">install</span> <span class="n">tensorflow</span><span class="o">-</span><span class="n">addons</span> </code></pre></div> <div class="codehilite"><pre><span></span><code><span class="kn">import</span> <span class="nn">os</span> <span class="c1"># slightly faster improvements, on the first epoch 30 second decrease and a 1-2 second</span> <span class="c1"># decrease in epoch time. Overall saves approx. 5 min of training time</span> <span class="c1"># Allocates two threads for a gpu private which allows more operations to be</span> <span class="c1"># done faster</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s2">"TF_GPU_THREAD_MODE"</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"gpu_private"</span> <span class="kn">import</span> <span class="nn">tensorflow</span> <span class="k">as</span> <span class="nn">tf</span> <span class="c1"># framework</span> <span class="kn">from</span> <span class="nn">tensorflow</span> <span class="kn">import</span> <span class="n">keras</span> <span class="c1"># for tf.keras</span> <span class="kn">import</span> <span class="nn">tensorflow_addons</span> <span class="k">as</span> <span class="nn">tfa</span> <span class="c1"># LAMB optimizer and gaussian_blur_2d function</span> <span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span> <span class="c1"># np.random.random</span> <span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span> <span class="c1"># graphs</span> <span class="kn">import</span> <span class="nn">datetime</span> <span class="c1"># tensorboard logs naming</span> <span class="c1"># XLA optimization for faster performance(up to 10-15 minutes total time saved)</span> <span class="n">tf</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">optimizer</span><span class="o">.</span><span class="n">set_jit</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span> </code></pre></div> <div class="k-default-codeblock"> <div class="codehilite"><pre><span></span><code>['Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.7/dist-packages (0.15.0)', 'Requirement already satisfied: typeguard>=2.7 in /usr/local/lib/python3.7/dist-packages (from tensorflow-addons) (2.7.1)'] </code></pre></div> </div> <hr /> <h2 id="load-the-cifar10-dataset">Load the CIFAR-10 dataset</h2> <div class="codehilite"><pre><span></span><code><span class="p">[</span> <span class="p">(</span><span class="n">train_features</span><span class="p">,</span> <span class="n">train_labels</span><span class="p">),</span> <span class="p">(</span><span class="n">test_features</span><span class="p">,</span> <span class="n">test_labels</span><span class="p">),</span> <span class="p">]</span> <span class="o">=</span> <span class="n">keras</span><span class="o">.</span><span class="n">datasets</span><span class="o">.</span><span class="n">cifar10</span><span class="o">.</span><span class="n">load_data</span><span class="p">()</span> <span class="n">train_features</span> <span class="o">=</span> <span class="n">train_features</span> <span class="o">/</span> <span class="mf">255.0</span> <span class="n">test_features</span> <span class="o">=</span> <span class="n">test_features</span> <span class="o">/</span> <span class="mf">255.0</span> </code></pre></div> <hr /> <h2 id="necessary-hyperparameters">Necessary Hyperparameters</h2> <div class="codehilite"><pre><span></span><code><span class="c1"># Batch size of dataset</span> <span class="n">BATCH_SIZE</span> <span class="o">=</span> <span class="mi">512</span> <span class="c1"># Width and height of image</span> <span class="n">IMAGE_SIZE</span> <span class="o">=</span> <span class="mi">32</span> </code></pre></div> <hr /> <h2 id="augmentation-utilities">Augmentation Utilities</h2> <p>The Barlow twins algorithm is heavily reliant on Augmentation. One unique feature of the method is that sometimes, augmentations probabilistically occur.</p> <p><strong>Augmentations</strong></p> <ul> <li><em>RandomToGrayscale</em>: randomly applies grayscale to image 20% of the time</li> <li><em>RandomColorJitter</em>: randomly applies color jitter 80% of the time</li> <li><em>RandomFlip</em>: randomly flips image horizontally 50% of the time</li> <li><em>RandomResizedCrop</em>: randomly crops an image to a random size then resizes. This happens 100% of the time</li> <li><em>RandomSolarize</em>: randomly applies solarization to an image 20% of the time</li> <li><em>RandomBlur</em>: randomly blurs an image 20% of the time</li> </ul> <div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">Augmentation</span><span class="p">(</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Layer</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""Base augmentation class.</span> <span class="sd"> Base augmentation class. Contains the random_execute method.</span> <span class="sd"> Methods:</span> <span class="sd"> random_execute: method that returns true or false based</span> <span class="sd"> on a probability. Used to determine whether an augmentation</span> <span class="sd"> will be run.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span> <span class="nd">@tf</span><span class="o">.</span><span class="n">function</span> <span class="k">def</span> <span class="nf">random_execute</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">prob</span><span class="p">:</span> <span class="nb">float</span><span class="p">)</span> <span class="o">-></span> <span class="nb">bool</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""random_execute function.</span> <span class="sd"> Arguments:</span> <span class="sd"> prob: a float value from 0-1 that determines the</span> <span class="sd"> probability.</span> <span class="sd"> Returns:</span> <span class="sd"> returns true or false based on the probability.</span> <span class="sd"> """</span> <span class="k">return</span> <span class="n">tf</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">uniform</span><span class="p">([],</span> <span class="n">minval</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">maxval</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="o"><</span> <span class="n">prob</span> <span class="k">class</span> <span class="nc">RandomToGrayscale</span><span class="p">(</span><span class="n">Augmentation</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""RandomToGrayscale class.</span> <span class="sd"> RandomToGrayscale class. Randomly makes an image</span> <span class="sd"> grayscaled based on the random_execute method. There</span> <span class="sd"> is a 20% chance that an image will be grayscaled.</span> <span class="sd"> Methods:</span> <span class="sd"> call: method that grayscales an image 20% of</span> <span class="sd"> the time.</span> <span class="sd"> """</span> <span class="nd">@tf</span><span class="o">.</span><span class="n">function</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""call function.</span> <span class="sd"> Arguments:</span> <span class="sd"> x: a tf.Tensor representing the image.</span> <span class="sd"> Returns:</span> <span class="sd"> returns a grayscaled version of the image 20% of the time</span> <span class="sd"> and the original image 80% of the time.</span> <span class="sd"> """</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_execute</span><span class="p">(</span><span class="mf">0.2</span><span class="p">):</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">rgb_to_grayscale</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">tile</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span> <span class="k">return</span> <span class="n">x</span> <span class="k">class</span> <span class="nc">RandomColorJitter</span><span class="p">(</span><span class="n">Augmentation</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""RandomColorJitter class.</span> <span class="sd"> RandomColorJitter class. Randomly adds color jitter to an image.</span> <span class="sd"> Color jitter means to add random brightness, contrast,</span> <span class="sd"> saturation, and hue to an image. There is a 80% chance that an</span> <span class="sd"> image will be randomly color-jittered.</span> <span class="sd"> Methods:</span> <span class="sd"> call: method that color-jitters an image 80% of</span> <span class="sd"> the time.</span> <span class="sd"> """</span> <span class="nd">@tf</span><span class="o">.</span><span class="n">function</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""call function.</span> <span class="sd"> Adds color jitter to image, including:</span> <span class="sd"> Brightness change by a max-delta of 0.8</span> <span class="sd"> Contrast change by a max-delta of 0.8</span> <span class="sd"> Saturation change by a max-delta of 0.8</span> <span class="sd"> Hue change by a max-delta of 0.2</span> <span class="sd"> Originally, the same deltas of the original paper</span> <span class="sd"> were used, but a performance boost of almost 2% was found</span> <span class="sd"> when doubling them.</span> <span class="sd"> Arguments:</span> <span class="sd"> x: a tf.Tensor representing the image.</span> <span class="sd"> Returns:</span> <span class="sd"> returns a color-jittered version of the image 80% of the time</span> <span class="sd"> and the original image 20% of the time.</span> <span class="sd"> """</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_execute</span><span class="p">(</span><span class="mf">0.8</span><span class="p">):</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">random_brightness</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mf">0.8</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">random_contrast</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mf">0.4</span><span class="p">,</span> <span class="mf">1.6</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">random_saturation</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mf">0.4</span><span class="p">,</span> <span class="mf">1.6</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">random_hue</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mf">0.2</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="k">class</span> <span class="nc">RandomFlip</span><span class="p">(</span><span class="n">Augmentation</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""RandomFlip class.</span> <span class="sd"> RandomFlip class. Randomly flips image horizontally. There is a 50%</span> <span class="sd"> chance that an image will be randomly flipped.</span> <span class="sd"> Methods:</span> <span class="sd"> call: method that flips an image 50% of</span> <span class="sd"> the time.</span> <span class="sd"> """</span> <span class="nd">@tf</span><span class="o">.</span><span class="n">function</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""call function.</span> <span class="sd"> Randomly flips the image.</span> <span class="sd"> Arguments:</span> <span class="sd"> x: a tf.Tensor representing the image.</span> <span class="sd"> Returns:</span> <span class="sd"> returns a flipped version of the image 50% of the time</span> <span class="sd"> and the original image 50% of the time.</span> <span class="sd"> """</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_execute</span><span class="p">(</span><span class="mf">0.5</span><span class="p">):</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">random_flip_left_right</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="k">class</span> <span class="nc">RandomResizedCrop</span><span class="p">(</span><span class="n">Augmentation</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""RandomResizedCrop class.</span> <span class="sd"> RandomResizedCrop class. Randomly crop an image to a random size,</span> <span class="sd"> then resize the image back to the original size.</span> <span class="sd"> Attributes:</span> <span class="sd"> image_size: The dimension of the image</span> <span class="sd"> Methods:</span> <span class="sd"> __call__: method that does random resize crop to the image.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">image_size</span><span class="p">):</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">image_size</span> <span class="o">=</span> <span class="n">image_size</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""call function.</span> <span class="sd"> Does random resize crop by randomly cropping an image to a random</span> <span class="sd"> size 75% - 100% the size of the image. Then resizes it.</span> <span class="sd"> Arguments:</span> <span class="sd"> x: a tf.Tensor representing the image.</span> <span class="sd"> Returns:</span> <span class="sd"> returns a randomly cropped image.</span> <span class="sd"> """</span> <span class="n">rand_size</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">uniform</span><span class="p">(</span> <span class="n">shape</span><span class="o">=</span><span class="p">[],</span> <span class="n">minval</span><span class="o">=</span><span class="nb">int</span><span class="p">(</span><span class="mf">0.75</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">image_size</span><span class="p">),</span> <span class="n">maxval</span><span class="o">=</span><span class="mi">1</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">image_size</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">int32</span><span class="p">,</span> <span class="p">)</span> <span class="n">crop</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">random_crop</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="p">(</span><span class="n">rand_size</span><span class="p">,</span> <span class="n">rand_size</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="n">crop_resize</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">resize</span><span class="p">(</span><span class="n">crop</span><span class="p">,</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">image_size</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">image_size</span><span class="p">))</span> <span class="k">return</span> <span class="n">crop_resize</span> <span class="k">class</span> <span class="nc">RandomSolarize</span><span class="p">(</span><span class="n">Augmentation</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""RandomSolarize class.</span> <span class="sd"> RandomSolarize class. Randomly solarizes an image.</span> <span class="sd"> Solarization is when pixels accidentally flip to an inverted state.</span> <span class="sd"> Methods:</span> <span class="sd"> call: method that does random solarization 20% of the time.</span> <span class="sd"> """</span> <span class="nd">@tf</span><span class="o">.</span><span class="n">function</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""call function.</span> <span class="sd"> Randomly solarizes the image.</span> <span class="sd"> Arguments:</span> <span class="sd"> x: a tf.Tensor representing the image.</span> <span class="sd"> Returns:</span> <span class="sd"> returns a solarized version of the image 20% of the time</span> <span class="sd"> and the original image 80% of the time.</span> <span class="sd"> """</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_execute</span><span class="p">(</span><span class="mf">0.2</span><span class="p">):</span> <span class="c1"># flips abnormally low pixels to abnormally high pixels</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">x</span> <span class="o"><</span> <span class="mi">10</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="mi">255</span> <span class="o">-</span> <span class="n">x</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="k">class</span> <span class="nc">RandomBlur</span><span class="p">(</span><span class="n">Augmentation</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""RandomBlur class.</span> <span class="sd"> RandomBlur class. Randomly blurs an image.</span> <span class="sd"> Methods:</span> <span class="sd"> call: method that does random blur 20% of the time.</span> <span class="sd"> """</span> <span class="nd">@tf</span><span class="o">.</span><span class="n">function</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""call function.</span> <span class="sd"> Randomly solarizes the image.</span> <span class="sd"> Arguments:</span> <span class="sd"> x: a tf.Tensor representing the image.</span> <span class="sd"> Returns:</span> <span class="sd"> returns a blurred version of the image 20% of the time</span> <span class="sd"> and the original image 80% of the time.</span> <span class="sd"> """</span> <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_execute</span><span class="p">(</span><span class="mf">0.2</span><span class="p">):</span> <span class="n">s</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span> <span class="k">return</span> <span class="n">tfa</span><span class="o">.</span><span class="n">image</span><span class="o">.</span><span class="n">gaussian_filter2d</span><span class="p">(</span><span class="n">image</span><span class="o">=</span><span class="n">x</span><span class="p">,</span> <span class="n">sigma</span><span class="o">=</span><span class="n">s</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="k">class</span> <span class="nc">RandomAugmentor</span><span class="p">(</span><span class="n">keras</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""RandomAugmentor class.</span> <span class="sd"> RandomAugmentor class. Chains all the augmentations into</span> <span class="sd"> one pipeline.</span> <span class="sd"> Attributes:</span> <span class="sd"> image_size: An integer represing the width and height</span> <span class="sd"> of the image. Designed to be used for square images.</span> <span class="sd"> random_resized_crop: Instance variable representing the</span> <span class="sd"> RandomResizedCrop layer.</span> <span class="sd"> random_flip: Instance variable representing the</span> <span class="sd"> RandomFlip layer.</span> <span class="sd"> random_color_jitter: Instance variable representing the</span> <span class="sd"> RandomColorJitter layer.</span> <span class="sd"> random_blur: Instance variable representing the</span> <span class="sd"> RandomBlur layer</span> <span class="sd"> random_to_grayscale: Instance variable representing the</span> <span class="sd"> RandomToGrayscale layer</span> <span class="sd"> random_solarize: Instance variable representing the</span> <span class="sd"> RandomSolarize layer</span> <span class="sd"> Methods:</span> <span class="sd"> call: chains layers in pipeline together</span> <span class="sd"> """</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">image_size</span><span class="p">:</span> <span class="nb">int</span><span class="p">):</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">image_size</span> <span class="o">=</span> <span class="n">image_size</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_resized_crop</span> <span class="o">=</span> <span class="n">RandomResizedCrop</span><span class="p">(</span><span class="n">image_size</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_flip</span> <span class="o">=</span> <span class="n">RandomFlip</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_color_jitter</span> <span class="o">=</span> <span class="n">RandomColorJitter</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_blur</span> <span class="o">=</span> <span class="n">RandomBlur</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_to_grayscale</span> <span class="o">=</span> <span class="n">RandomToGrayscale</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_solarize</span> <span class="o">=</span> <span class="n">RandomSolarize</span><span class="p">()</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_resized_crop</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_flip</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_color_jitter</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_blur</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_to_grayscale</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">random_solarize</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">clip_by_value</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="n">bt_augmentor</span> <span class="o">=</span> <span class="n">RandomAugmentor</span><span class="p">(</span><span class="n">IMAGE_SIZE</span><span class="p">)</span> </code></pre></div> <hr /> <h2 id="data-loading">Data Loading</h2> <p>A class that creates the barlow twins' dataset.</p> <p>The dataset consists of two copies of each image, with each copy receiving different augmentations.</p> <div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">BTDatasetCreator</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""Barlow twins dataset creator class.</span> <span class="sd"> BTDatasetCreator class. Responsible for creating the</span> <span class="sd"> barlow twins' dataset.</span> <span class="sd"> Attributes:</span> <span class="sd"> options: tf.data.Options needed to configure a setting</span> <span class="sd"> that may improve performance.</span> <span class="sd"> seed: random seed for shuffling. Used to synchronize two</span> <span class="sd"> augmented versions.</span> <span class="sd"> augmentor: augmentor used for augmentation.</span> <span class="sd"> Methods:</span> <span class="sd"> __call__: creates barlow dataset.</span> <span class="sd"> augmented_version: creates 1 half of the dataset.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">augmentor</span><span class="p">:</span> <span class="n">RandomAugmentor</span><span class="p">,</span> <span class="n">seed</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">1024</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">options</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Options</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">options</span><span class="o">.</span><span class="n">threading</span><span class="o">.</span><span class="n">max_intra_op_parallelism</span> <span class="o">=</span> <span class="mi">1</span> <span class="bp">self</span><span class="o">.</span><span class="n">seed</span> <span class="o">=</span> <span class="n">seed</span> <span class="bp">self</span><span class="o">.</span><span class="n">augmentor</span> <span class="o">=</span> <span class="n">augmentor</span> <span class="k">def</span> <span class="nf">augmented_version</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ds</span><span class="p">:</span> <span class="nb">list</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Dataset</span><span class="p">:</span> <span class="k">return</span> <span class="p">(</span> <span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Dataset</span><span class="o">.</span><span class="n">from_tensor_slices</span><span class="p">(</span><span class="n">ds</span><span class="p">)</span> <span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="mi">1000</span><span class="p">,</span> <span class="n">seed</span><span class="o">=</span><span class="bp">self</span><span class="o">.</span><span class="n">seed</span><span class="p">)</span> <span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">augmentor</span><span class="p">,</span> <span class="n">num_parallel_calls</span><span class="o">=</span><span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">AUTOTUNE</span><span class="p">)</span> <span class="o">.</span><span class="n">batch</span><span class="p">(</span><span class="n">BATCH_SIZE</span><span class="p">,</span> <span class="n">drop_remainder</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="o">.</span><span class="n">prefetch</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">AUTOTUNE</span><span class="p">)</span> <span class="o">.</span><span class="n">with_options</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">options</span><span class="p">)</span> <span class="p">)</span> <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ds</span><span class="p">:</span> <span class="nb">list</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Dataset</span><span class="p">:</span> <span class="n">a1</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">augmented_version</span><span class="p">(</span><span class="n">ds</span><span class="p">)</span> <span class="n">a2</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">augmented_version</span><span class="p">(</span><span class="n">ds</span><span class="p">)</span> <span class="k">return</span> <span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Dataset</span><span class="o">.</span><span class="n">zip</span><span class="p">((</span><span class="n">a1</span><span class="p">,</span> <span class="n">a2</span><span class="p">))</span><span class="o">.</span><span class="n">with_options</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">options</span><span class="p">)</span> <span class="n">augment_versions</span> <span class="o">=</span> <span class="n">BTDatasetCreator</span><span class="p">(</span><span class="n">bt_augmentor</span><span class="p">)(</span><span class="n">train_features</span><span class="p">)</span> </code></pre></div> <p>View examples of dataset.</p> <div class="codehilite"><pre><span></span><code><span class="n">sample_augment_versions</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">augment_versions</span><span class="p">)</span> <span class="k">def</span> <span class="nf">plot_values</span><span class="p">(</span><span class="n">batch</span><span class="p">:</span> <span class="nb">tuple</span><span class="p">):</span> <span class="n">fig</span><span class="p">,</span> <span class="n">axs</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="n">fig1</span><span class="p">,</span> <span class="n">axs1</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="n">fig</span><span class="o">.</span><span class="n">suptitle</span><span class="p">(</span><span class="s2">"Augmentation 1"</span><span class="p">)</span> <span class="n">fig1</span><span class="o">.</span><span class="n">suptitle</span><span class="p">(</span><span class="s2">"Augmentation 2"</span><span class="p">)</span> <span class="n">a1</span><span class="p">,</span> <span class="n">a2</span> <span class="o">=</span> <span class="n">batch</span> <span class="c1"># plots images on both tables</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span> <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span> <span class="c1"># CHANGE(add / 255)</span> <span class="n">axs</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span><span class="o">.</span><span class="n">imshow</span><span class="p">(</span><span class="n">a1</span><span class="p">[</span><span class="mi">3</span> <span class="o">*</span> <span class="n">i</span> <span class="o">+</span> <span class="n">j</span><span class="p">])</span> <span class="n">axs</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span><span class="o">.</span><span class="n">axis</span><span class="p">(</span><span class="s2">"off"</span><span class="p">)</span> <span class="n">axs1</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span><span class="o">.</span><span class="n">imshow</span><span class="p">(</span><span class="n">a2</span><span class="p">[</span><span class="mi">3</span> <span class="o">*</span> <span class="n">i</span> <span class="o">+</span> <span class="n">j</span><span class="p">])</span> <span class="n">axs1</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="n">j</span><span class="p">]</span><span class="o">.</span><span class="n">axis</span><span class="p">(</span><span class="s2">"off"</span><span class="p">)</span> <span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span> <span class="n">plot_values</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">sample_augment_versions</span><span class="p">))</span> </code></pre></div> <p><img alt="png" src="/img/examples/vision/barlow_twins/barlow_twins_21_0.png" /></p> <p><img alt="png" src="/img/examples/vision/barlow_twins/barlow_twins_21_1.png" /></p> <hr /> <h2 id="pseudocode-of-loss-and-model">Pseudocode of loss and model</h2> <p>The following sections follow the original author's pseudocode containing both model and loss functions(see diagram below). Also contains a reference of variables used.</p> <p><img alt="pseudocode" src="https://i.imgur.com/Tlrootj.png" /></p> <p>Reference:</p> <div class="codehilite"><pre><span></span><code>y_a: first augmented version of original image. y_b: second augmented version of original image. z_a: model representation(embeddings) of y_a. z_b: model representation(embeddings) of y_b. z_a_norm: normalized z_a. z_b_norm: normalized z_b. c: cross correlation matrix. c_diff: diagonal portion of loss(invariance term). off_diag: off-diagonal portion of loss(redundancy reduction term). </code></pre></div> <hr /> <h2 id="barlowloss-barlow-twins-models-loss-function">BarlowLoss: barlow twins model's loss function</h2> <p>Barlow Twins uses the cross correlation matrix for its loss. There are two parts to the loss function:</p> <ul> <li><strong><em>The invariance term</em></strong>(diagonal). This part is used to make the diagonals of the matrix into 1s. When this is the case, the matrix shows that the images are correlated(same).<ul> <li>The loss function subtracts 1 from the diagonal and squares the values.</li> </ul> </li> <li><strong><em>The redundancy reduction term</em></strong>(off-diagonal). Here, the barlow twins loss function aims to make these values zero. As mentioned before, it is redundant if the representation neurons are correlated with values that are not on the diagonal.<ul> <li>Off diagonals are squared.</li> </ul> </li> </ul> <p>After this the two parts are summed together.</p> <div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">BarlowLoss</span><span class="p">(</span><span class="n">keras</span><span class="o">.</span><span class="n">losses</span><span class="o">.</span><span class="n">Loss</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""BarlowLoss class.</span> <span class="sd"> BarlowLoss class. Creates a loss function based on the cross-correlation</span> <span class="sd"> matrix.</span> <span class="sd"> Attributes:</span> <span class="sd"> batch_size: the batch size of the dataset</span> <span class="sd"> lambda_amt: the value for lambda(used in cross_corr_matrix_loss)</span> <span class="sd"> Methods:</span> <span class="sd"> __init__: gets instance variables</span> <span class="sd"> call: gets the loss based on the cross-correlation matrix</span> <span class="sd"> make_diag_zeros: Used in calculating off-diagonal section</span> <span class="sd"> of loss function; makes diagonals zeros.</span> <span class="sd"> cross_corr_matrix_loss: creates loss based on cross correlation</span> <span class="sd"> matrix.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">batch_size</span><span class="p">:</span> <span class="nb">int</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""__init__ method.</span> <span class="sd"> Gets the instance variables</span> <span class="sd"> Arguments:</span> <span class="sd"> batch_size: An integer value representing the batch size of the</span> <span class="sd"> dataset. Used for cross correlation matrix calculation.</span> <span class="sd"> """</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">lambda_amt</span> <span class="o">=</span> <span class="mf">5e-3</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_size</span> <span class="o">=</span> <span class="n">batch_size</span> <span class="k">def</span> <span class="nf">get_off_diag</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">c</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""get_off_diag method.</span> <span class="sd"> Makes the diagonals of the cross correlation matrix zeros.</span> <span class="sd"> This is used in the off-diagonal portion of the loss function,</span> <span class="sd"> where we take the squares of the off-diagonal values and sum them.</span> <span class="sd"> Arguments:</span> <span class="sd"> c: A tf.tensor that represents the cross correlation</span> <span class="sd"> matrix</span> <span class="sd"> Returns:</span> <span class="sd"> Returns a tf.tensor which represents the cross correlation</span> <span class="sd"> matrix with its diagonals as zeros.</span> <span class="sd"> """</span> <span class="n">zero_diag</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span> <span class="k">return</span> <span class="n">tf</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">set_diag</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">zero_diag</span><span class="p">)</span> <span class="k">def</span> <span class="nf">cross_corr_matrix_loss</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">c</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""cross_corr_matrix_loss method.</span> <span class="sd"> Gets the loss based on the cross correlation matrix.</span> <span class="sd"> We want the diagonals to be 1's and everything else to be</span> <span class="sd"> zeros to show that the two augmented images are similar.</span> <span class="sd"> Loss function procedure:</span> <span class="sd"> take the diagonal of the cross-correlation matrix, subtract by 1,</span> <span class="sd"> and square that value so no negatives.</span> <span class="sd"> Take the off-diagonal of the cc-matrix(see get_off_diag()),</span> <span class="sd"> square those values to get rid of negatives and increase the value,</span> <span class="sd"> and multiply it by a lambda to weight it such that it is of equal</span> <span class="sd"> value to the optimizer as the diagonal(there are more values off-diag</span> <span class="sd"> then on-diag)</span> <span class="sd"> Take the sum of the first and second parts and then sum them together.</span> <span class="sd"> Arguments:</span> <span class="sd"> c: A tf.tensor that represents the cross correlation</span> <span class="sd"> matrix</span> <span class="sd"> Returns:</span> <span class="sd"> Returns a tf.tensor which represents the cross correlation</span> <span class="sd"> matrix with its diagonals as zeros.</span> <span class="sd"> """</span> <span class="c1"># subtracts diagonals by one and squares them(first part)</span> <span class="n">c_diff</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">linalg</span><span class="o">.</span><span class="n">diag_part</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="c1"># takes off diagonal, squares it, multiplies with lambda(second part)</span> <span class="n">off_diag</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">get_off_diag</span><span class="p">(</span><span class="n">c</span><span class="p">),</span> <span class="mi">2</span><span class="p">)</span> <span class="o">*</span> <span class="bp">self</span><span class="o">.</span><span class="n">lambda_amt</span> <span class="c1"># sum first and second parts together</span> <span class="n">loss</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_sum</span><span class="p">(</span><span class="n">c_diff</span><span class="p">)</span> <span class="o">+</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_sum</span><span class="p">(</span><span class="n">off_diag</span><span class="p">)</span> <span class="k">return</span> <span class="n">loss</span> <span class="k">def</span> <span class="nf">normalize</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">output</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""normalize method.</span> <span class="sd"> Normalizes the model prediction.</span> <span class="sd"> Arguments:</span> <span class="sd"> output: the model prediction.</span> <span class="sd"> Returns:</span> <span class="sd"> Returns a normalized version of the model prediction.</span> <span class="sd"> """</span> <span class="k">return</span> <span class="p">(</span><span class="n">output</span> <span class="o">-</span> <span class="n">tf</span><span class="o">.</span><span class="n">reduce_mean</span><span class="p">(</span><span class="n">output</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span> <span class="o">/</span> <span class="n">tf</span><span class="o">.</span><span class="n">math</span><span class="o">.</span><span class="n">reduce_std</span><span class="p">(</span> <span class="n">output</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">0</span> <span class="p">)</span> <span class="k">def</span> <span class="nf">cross_corr_matrix</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">z_a_norm</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">,</span> <span class="n">z_b_norm</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""cross_corr_matrix method.</span> <span class="sd"> Creates a cross correlation matrix from the predictions.</span> <span class="sd"> It transposes the first prediction and multiplies this with</span> <span class="sd"> the second, creating a matrix with shape (n_dense_units, n_dense_units).</span> <span class="sd"> See build_twin() for more info. Then it divides this with the</span> <span class="sd"> batch size.</span> <span class="sd"> Arguments:</span> <span class="sd"> z_a_norm: A normalized version of the first prediction.</span> <span class="sd"> z_b_norm: A normalized version of the second prediction.</span> <span class="sd"> Returns:</span> <span class="sd"> Returns a cross correlation matrix.</span> <span class="sd"> """</span> <span class="k">return</span> <span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">transpose</span><span class="p">(</span><span class="n">z_a_norm</span><span class="p">)</span> <span class="o">@</span> <span class="n">z_b_norm</span><span class="p">)</span> <span class="o">/</span> <span class="bp">self</span><span class="o">.</span><span class="n">batch_size</span> <span class="k">def</span> <span class="nf">call</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">z_a</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">,</span> <span class="n">z_b</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""call method.</span> <span class="sd"> Makes the cross-correlation loss. Uses the CreateCrossCorr</span> <span class="sd"> class to make the cross corr matrix, then finds the loss and</span> <span class="sd"> returns it(see cross_corr_matrix_loss()).</span> <span class="sd"> Arguments:</span> <span class="sd"> z_a: The prediction of the first set of augmented data.</span> <span class="sd"> z_b: the prediction of the second set of augmented data.</span> <span class="sd"> Returns:</span> <span class="sd"> Returns a (rank-0) tf.Tensor that represents the loss.</span> <span class="sd"> """</span> <span class="n">z_a_norm</span><span class="p">,</span> <span class="n">z_b_norm</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="n">z_a</span><span class="p">),</span> <span class="bp">self</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="n">z_b</span><span class="p">)</span> <span class="n">c</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cross_corr_matrix</span><span class="p">(</span><span class="n">z_a_norm</span><span class="p">,</span> <span class="n">z_b_norm</span><span class="p">)</span> <span class="n">loss</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cross_corr_matrix_loss</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="k">return</span> <span class="n">loss</span> </code></pre></div> <hr /> <h2 id="barlow-twins-model-architecture">Barlow Twins' Model Architecture</h2> <p>The model has two parts:</p> <ul> <li>The encoder network, which is a resnet-34.</li> <li>The projector network, which creates the model embeddings.<ul> <li>This consists of an MLP with 3 dense-batchnorm-relu layers.</li> </ul> </li> </ul> <p>Resnet encoder network implementation:</p> <div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">ResNet34</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""Resnet34 class.</span> <span class="sd"> Responsible for the Resnet 34 architecture.</span> <span class="sd"> Modified from</span> <span class="sd"> https://www.analyticsvidhya.com/blog/2021/08/how-to-code-your-resnet-from-scratch-in-tensorflow/#h2_2.</span> <span class="sd"> https://www.analyticsvidhya.com/blog/2021/08/how-to-code-your-resnet-from-scratch-in-tensorflow/#h2_2.</span> <span class="sd"> View their website for more information.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="nf">identity_block</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="nb">filter</span><span class="p">):</span> <span class="c1"># copy tensor to variable called x_skip</span> <span class="n">x_skip</span> <span class="o">=</span> <span class="n">x</span> <span class="c1"># Layer 1</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Conv2D</span><span class="p">(</span><span class="nb">filter</span><span class="p">,</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">padding</span><span class="o">=</span><span class="s2">"same"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">BatchNormalization</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">3</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Activation</span><span class="p">(</span><span class="s2">"relu"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="c1"># Layer 2</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Conv2D</span><span class="p">(</span><span class="nb">filter</span><span class="p">,</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">padding</span><span class="o">=</span><span class="s2">"same"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">BatchNormalization</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">3</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="c1"># Add Residue</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Add</span><span class="p">()([</span><span class="n">x</span><span class="p">,</span> <span class="n">x_skip</span><span class="p">])</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Activation</span><span class="p">(</span><span class="s2">"relu"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="k">def</span> <span class="nf">convolutional_block</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="nb">filter</span><span class="p">):</span> <span class="c1"># copy tensor to variable called x_skip</span> <span class="n">x_skip</span> <span class="o">=</span> <span class="n">x</span> <span class="c1"># Layer 1</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Conv2D</span><span class="p">(</span><span class="nb">filter</span><span class="p">,</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">padding</span><span class="o">=</span><span class="s2">"same"</span><span class="p">,</span> <span class="n">strides</span><span class="o">=</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">))(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">BatchNormalization</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">3</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Activation</span><span class="p">(</span><span class="s2">"relu"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="c1"># Layer 2</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Conv2D</span><span class="p">(</span><span class="nb">filter</span><span class="p">,</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="n">padding</span><span class="o">=</span><span class="s2">"same"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">BatchNormalization</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">3</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="c1"># Processing Residue with conv(1,1)</span> <span class="n">x_skip</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Conv2D</span><span class="p">(</span><span class="nb">filter</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="n">strides</span><span class="o">=</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">))(</span><span class="n">x_skip</span><span class="p">)</span> <span class="c1"># Add Residue</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Add</span><span class="p">()([</span><span class="n">x</span><span class="p">,</span> <span class="n">x_skip</span><span class="p">])</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Activation</span><span class="p">(</span><span class="s2">"relu"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="k">return</span> <span class="n">x</span> <span class="k">def</span> <span class="fm">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">shape</span><span class="o">=</span><span class="p">(</span><span class="mi">32</span><span class="p">,</span> <span class="mi">32</span><span class="p">,</span> <span class="mi">3</span><span class="p">)):</span> <span class="c1"># Step 1 (Setup Input Layer)</span> <span class="n">x_input</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Input</span><span class="p">(</span><span class="n">shape</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">ZeroPadding2D</span><span class="p">((</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">))(</span><span class="n">x_input</span><span class="p">)</span> <span class="c1"># Step 2 (Initial Conv layer along with maxPool)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Conv2D</span><span class="p">(</span><span class="mi">64</span><span class="p">,</span> <span class="n">kernel_size</span><span class="o">=</span><span class="mi">7</span><span class="p">,</span> <span class="n">strides</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">padding</span><span class="o">=</span><span class="s2">"same"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">BatchNormalization</span><span class="p">()(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Activation</span><span class="p">(</span><span class="s2">"relu"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">MaxPool2D</span><span class="p">(</span><span class="n">pool_size</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">strides</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">padding</span><span class="o">=</span><span class="s2">"same"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="c1"># Define size of sub-blocks and initial filter size</span> <span class="n">block_layers</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span> <span class="n">filter_size</span> <span class="o">=</span> <span class="mi">64</span> <span class="c1"># Step 3 Add the Resnet Blocks</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">):</span> <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="c1"># For sub-block 1 Residual/Convolutional block not needed</span> <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">block_layers</span><span class="p">[</span><span class="n">i</span><span class="p">]):</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">identity_block</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">filter_size</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="c1"># One Residual/Convolutional Block followed by Identity blocks</span> <span class="c1"># The filter size will go on increasing by a factor of 2</span> <span class="n">filter_size</span> <span class="o">=</span> <span class="n">filter_size</span> <span class="o">*</span> <span class="mi">2</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">convolutional_block</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">filter_size</span><span class="p">)</span> <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">block_layers</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">-</span> <span class="mi">1</span><span class="p">):</span> <span class="n">x</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">identity_block</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">filter_size</span><span class="p">)</span> <span class="c1"># Step 4 End Dense Network</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">AveragePooling2D</span><span class="p">((</span><span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="n">padding</span><span class="o">=</span><span class="s2">"same"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Flatten</span><span class="p">()(</span><span class="n">x</span><span class="p">)</span> <span class="n">model</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">(</span><span class="n">inputs</span><span class="o">=</span><span class="n">x_input</span><span class="p">,</span> <span class="n">outputs</span><span class="o">=</span><span class="n">x</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s2">"ResNet34"</span><span class="p">)</span> <span class="k">return</span> <span class="n">model</span> </code></pre></div> <p>Projector network:</p> <div class="codehilite"><pre><span></span><code><span class="k">def</span> <span class="nf">build_twin</span><span class="p">()</span> <span class="o">-></span> <span class="n">keras</span><span class="o">.</span><span class="n">Model</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""build_twin method.</span> <span class="sd"> Builds a barlow twins model consisting of an encoder(resnet-34)</span> <span class="sd"> and a projector, which generates embeddings for the images</span> <span class="sd"> Returns:</span> <span class="sd"> returns a barlow twins model</span> <span class="sd"> """</span> <span class="c1"># number of dense neurons in the projector</span> <span class="n">n_dense_neurons</span> <span class="o">=</span> <span class="mi">5000</span> <span class="c1"># encoder network</span> <span class="n">resnet</span> <span class="o">=</span> <span class="n">ResNet34</span><span class="p">()()</span> <span class="n">last_layer</span> <span class="o">=</span> <span class="n">resnet</span><span class="o">.</span><span class="n">layers</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">output</span> <span class="c1"># intermediate layers of the projector network</span> <span class="n">n_layers</span> <span class="o">=</span> <span class="mi">2</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n_layers</span><span class="p">):</span> <span class="n">dense</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Dense</span><span class="p">(</span><span class="n">n_dense_neurons</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="sa">f</span><span class="s2">"projector_dense_</span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span> <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span> <span class="n">x</span> <span class="o">=</span> <span class="n">dense</span><span class="p">(</span><span class="n">last_layer</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">x</span> <span class="o">=</span> <span class="n">dense</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">BatchNormalization</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="sa">f</span><span class="s2">"projector_bn_</span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s2">"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">ReLU</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="sa">f</span><span class="s2">"projector_relu_</span><span class="si">{</span><span class="n">i</span><span class="si">}</span><span class="s2">"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">x</span> <span class="o">=</span> <span class="n">tf</span><span class="o">.</span><span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Dense</span><span class="p">(</span><span class="n">n_dense_neurons</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="sa">f</span><span class="s2">"projector_dense_</span><span class="si">{</span><span class="n">n_layers</span><span class="si">}</span><span class="s2">"</span><span class="p">)(</span><span class="n">x</span><span class="p">)</span> <span class="n">model</span> <span class="o">=</span> <span class="n">keras</span><span class="o">.</span><span class="n">Model</span><span class="p">(</span><span class="n">resnet</span><span class="o">.</span><span class="n">input</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span> <span class="k">return</span> <span class="n">model</span> </code></pre></div> <hr /> <h2 id="training-loop-model">Training Loop Model</h2> <p>See pseudocode for reference.</p> <div class="codehilite"><pre><span></span><code><span class="k">class</span> <span class="nc">BarlowModel</span><span class="p">(</span><span class="n">keras</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="w"> </span><span class="sd">"""BarlowModel class.</span> <span class="sd"> BarlowModel class. Responsible for making predictions and handling</span> <span class="sd"> gradient descent with the optimizer.</span> <span class="sd"> Attributes:</span> <span class="sd"> model: the barlow model architecture.</span> <span class="sd"> loss_tracker: the loss metric.</span> <span class="sd"> Methods:</span> <span class="sd"> train_step: one train step; do model predictions, loss, and</span> <span class="sd"> optimizer step.</span> <span class="sd"> metrics: Returns metrics.</span> <span class="sd"> """</span> <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span> <span class="o">=</span> <span class="n">build_twin</span><span class="p">()</span> <span class="bp">self</span><span class="o">.</span><span class="n">loss_tracker</span> <span class="o">=</span> <span class="n">keras</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">Mean</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">"loss"</span><span class="p">)</span> <span class="nd">@property</span> <span class="k">def</span> <span class="nf">metrics</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">loss_tracker</span><span class="p">]</span> <span class="k">def</span> <span class="nf">train_step</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">batch</span><span class="p">:</span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">)</span> <span class="o">-></span> <span class="n">tf</span><span class="o">.</span><span class="n">Tensor</span><span class="p">:</span> <span class="w"> </span><span class="sd">"""train_step method.</span> <span class="sd"> Do one train step. Make model predictions, find loss, pass loss to</span> <span class="sd"> optimizer, and make optimizer apply gradients.</span> <span class="sd"> Arguments:</span> <span class="sd"> batch: one batch of data to be given to the loss function.</span> <span class="sd"> Returns:</span> <span class="sd"> Returns a dictionary with the loss metric.</span> <span class="sd"> """</span> <span class="c1"># get the two augmentations from the batch</span> <span class="n">y_a</span><span class="p">,</span> <span class="n">y_b</span> <span class="o">=</span> <span class="n">batch</span> <span class="k">with</span> <span class="n">tf</span><span class="o">.</span><span class="n">GradientTape</span><span class="p">()</span> <span class="k">as</span> <span class="n">tape</span><span class="p">:</span> <span class="c1"># get two versions of predictions</span> <span class="n">z_a</span><span class="p">,</span> <span class="n">z_b</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="n">y_a</span><span class="p">,</span> <span class="n">training</span><span class="o">=</span><span class="kc">True</span><span class="p">),</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="p">(</span><span class="n">y_b</span><span class="p">,</span> <span class="n">training</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="n">loss</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">loss</span><span class="p">(</span><span class="n">z_a</span><span class="p">,</span> <span class="n">z_b</span><span class="p">)</span> <span class="n">grads_model</span> <span class="o">=</span> <span class="n">tape</span><span class="o">.</span><span class="n">gradient</span><span class="p">(</span><span class="n">loss</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">trainable_variables</span><span class="p">)</span> <span class="bp">self</span><span class="o">.</span><span class="n">optimizer</span><span class="o">.</span><span class="n">apply_gradients</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">grads_model</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">model</span><span class="o">.</span><span class="n">trainable_variables</span><span class="p">))</span> <span class="bp">self</span><span class="o">.</span><span class="n">loss_tracker</span><span class="o">.</span><span class="n">update_state</span><span class="p">(</span><span class="n">loss</span><span class="p">)</span> <span class="k">return</span> <span class="p">{</span><span class="s2">"loss"</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">loss_tracker</span><span class="o">.</span><span class="n">result</span><span class="p">()}</span> </code></pre></div> <hr /> <h2 id="model-training">Model Training</h2> <ul> <li>Used the LAMB optimizer, instead of ADAM or SGD.</li> <li>Similar to the LARS optimizer used in the paper, and lets the model converge much faster than other methods.</li> <li>Expected training time: 1 hour 30 min. Go and eat a snack or take a nap or something.</li> </ul> <div class="codehilite"><pre><span></span><code><span class="c1"># sets up model, optimizer, loss</span> <span class="n">bm</span> <span class="o">=</span> <span class="n">BarlowModel</span><span class="p">()</span> <span class="c1"># chose the LAMB optimizer due to high batch sizes. Converged MUCH faster</span> <span class="c1"># than ADAM or SGD</span> <span class="n">optimizer</span> <span class="o">=</span> <span class="n">tfa</span><span class="o">.</span><span class="n">optimizers</span><span class="o">.</span><span class="n">LAMB</span><span class="p">()</span> <span class="n">loss</span> <span class="o">=</span> <span class="n">BarlowLoss</span><span class="p">(</span><span class="n">BATCH_SIZE</span><span class="p">)</span> <span class="n">bm</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">optimizer</span><span class="o">=</span><span class="n">optimizer</span><span class="p">,</span> <span class="n">loss</span><span class="o">=</span><span class="n">loss</span><span class="p">)</span> <span class="c1"># Expected training time: 1 hours 30 min</span> <span class="n">history</span> <span class="o">=</span> <span class="n">bm</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">augment_versions</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="mi">160</span><span class="p">)</span> <span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">history</span><span class="o">.</span><span class="n">history</span><span class="p">[</span><span class="s2">"loss"</span><span class="p">])</span> <span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span> </code></pre></div> <div class="k-default-codeblock"> <div class="codehilite"><pre><span></span><code>Epoch 1/160 97/97 [==============================] - 89s 294ms/step - loss: 3480.7588 Epoch 2/160 97/97 [==============================] - 29s 294ms/step - loss: 2163.4197 Epoch 3/160 97/97 [==============================] - 29s 294ms/step - loss: 1939.0248 Epoch 4/160 97/97 [==============================] - 29s 294ms/step - loss: 1810.4800 Epoch 5/160 97/97 [==============================] - 29s 294ms/step - loss: 1725.7401 Epoch 6/160 97/97 [==============================] - 29s 294ms/step - loss: 1658.2261 Epoch 7/160 97/97 [==============================] - 29s 294ms/step - loss: 1592.0747 Epoch 8/160 97/97 [==============================] - 29s 294ms/step - loss: 1545.2579 Epoch 9/160 97/97 [==============================] - 29s 294ms/step - loss: 1509.6631 Epoch 10/160 97/97 [==============================] - 29s 294ms/step - loss: 1484.1141 Epoch 11/160 97/97 [==============================] - 29s 293ms/step - loss: 1456.8615 Epoch 12/160 97/97 [==============================] - 29s 294ms/step - loss: 1430.0315 Epoch 13/160 97/97 [==============================] - 29s 294ms/step - loss: 1418.1147 Epoch 14/160 97/97 [==============================] - 29s 294ms/step - loss: 1385.7473 Epoch 15/160 97/97 [==============================] - 29s 294ms/step - loss: 1362.8176 Epoch 16/160 97/97 [==============================] - 29s 294ms/step - loss: 1353.6069 Epoch 17/160 97/97 [==============================] - 29s 294ms/step - loss: 1331.3687 Epoch 18/160 97/97 [==============================] - 29s 294ms/step - loss: 1323.1509 Epoch 19/160 97/97 [==============================] - 29s 294ms/step - loss: 1309.3015 Epoch 20/160 97/97 [==============================] - 29s 294ms/step - loss: 1303.2418 Epoch 21/160 97/97 [==============================] - 29s 294ms/step - loss: 1278.0450 Epoch 22/160 97/97 [==============================] - 29s 294ms/step - loss: 1272.2640 Epoch 23/160 97/97 [==============================] - 29s 294ms/step - loss: 1259.4225 Epoch 24/160 97/97 [==============================] - 29s 294ms/step - loss: 1246.8461 Epoch 25/160 97/97 [==============================] - 29s 294ms/step - loss: 1235.0269 Epoch 26/160 97/97 [==============================] - 29s 295ms/step - loss: 1228.4196 Epoch 27/160 97/97 [==============================] - 29s 295ms/step - loss: 1220.0851 Epoch 28/160 97/97 [==============================] - 29s 294ms/step - loss: 1208.5876 Epoch 29/160 97/97 [==============================] - 29s 294ms/step - loss: 1203.1449 Epoch 30/160 97/97 [==============================] - 29s 294ms/step - loss: 1199.5155 Epoch 31/160 97/97 [==============================] - 29s 294ms/step - loss: 1183.9818 Epoch 32/160 97/97 [==============================] - 29s 294ms/step - loss: 1173.9989 Epoch 33/160 97/97 [==============================] - 29s 294ms/step - loss: 1171.3789 Epoch 34/160 97/97 [==============================] - 29s 294ms/step - loss: 1160.8230 Epoch 35/160 97/97 [==============================] - 29s 294ms/step - loss: 1159.4148 Epoch 36/160 97/97 [==============================] - 29s 294ms/step - loss: 1148.4250 Epoch 37/160 97/97 [==============================] - 29s 294ms/step - loss: 1138.1802 Epoch 38/160 97/97 [==============================] - 29s 294ms/step - loss: 1135.9139 Epoch 39/160 97/97 [==============================] - 29s 294ms/step - loss: 1126.8186 Epoch 40/160 97/97 [==============================] - 29s 294ms/step - loss: 1119.6173 Epoch 41/160 97/97 [==============================] - 29s 293ms/step - loss: 1113.9358 Epoch 42/160 97/97 [==============================] - 29s 294ms/step - loss: 1106.0131 Epoch 43/160 97/97 [==============================] - 29s 294ms/step - loss: 1104.7386 Epoch 44/160 97/97 [==============================] - 29s 294ms/step - loss: 1097.7909 Epoch 45/160 97/97 [==============================] - 29s 294ms/step - loss: 1091.4229 Epoch 46/160 97/97 [==============================] - 29s 293ms/step - loss: 1082.3530 Epoch 47/160 97/97 [==============================] - 29s 294ms/step - loss: 1081.9459 Epoch 48/160 97/97 [==============================] - 29s 294ms/step - loss: 1078.5864 Epoch 49/160 97/97 [==============================] - 29s 293ms/step - loss: 1075.9255 Epoch 50/160 97/97 [==============================] - 29s 293ms/step - loss: 1070.9954 Epoch 51/160 97/97 [==============================] - 29s 294ms/step - loss: 1061.1058 Epoch 52/160 97/97 [==============================] - 29s 294ms/step - loss: 1055.0126 Epoch 53/160 97/97 [==============================] - 29s 294ms/step - loss: 1045.7827 Epoch 54/160 97/97 [==============================] - 29s 293ms/step - loss: 1047.5338 Epoch 55/160 97/97 [==============================] - 29s 294ms/step - loss: 1043.9012 Epoch 56/160 97/97 [==============================] - 29s 294ms/step - loss: 1044.5902 Epoch 57/160 97/97 [==============================] - 29s 294ms/step - loss: 1038.3389 Epoch 58/160 97/97 [==============================] - 29s 294ms/step - loss: 1032.1195 Epoch 59/160 97/97 [==============================] - 29s 294ms/step - loss: 1026.5962 Epoch 60/160 97/97 [==============================] - 29s 294ms/step - loss: 1018.2954 Epoch 61/160 97/97 [==============================] - 29s 294ms/step - loss: 1014.7681 Epoch 62/160 97/97 [==============================] - 29s 294ms/step - loss: 1007.7906 Epoch 63/160 97/97 [==============================] - 29s 294ms/step - loss: 1012.9134 Epoch 64/160 97/97 [==============================] - 29s 294ms/step - loss: 1009.7881 Epoch 65/160 97/97 [==============================] - 29s 294ms/step - loss: 1003.2436 Epoch 66/160 97/97 [==============================] - 29s 293ms/step - loss: 997.0688 Epoch 67/160 97/97 [==============================] - 29s 294ms/step - loss: 999.1620 Epoch 68/160 97/97 [==============================] - 29s 294ms/step - loss: 993.2636 Epoch 69/160 97/97 [==============================] - 29s 295ms/step - loss: 988.5142 Epoch 70/160 97/97 [==============================] - 29s 294ms/step - loss: 981.5876 Epoch 71/160 97/97 [==============================] - 29s 294ms/step - loss: 978.3053 Epoch 72/160 97/97 [==============================] - 29s 295ms/step - loss: 978.8599 Epoch 73/160 97/97 [==============================] - 29s 294ms/step - loss: 973.7569 Epoch 74/160 97/97 [==============================] - 29s 294ms/step - loss: 971.2402 Epoch 75/160 97/97 [==============================] - 29s 295ms/step - loss: 964.2864 Epoch 76/160 97/97 [==============================] - 29s 294ms/step - loss: 963.4999 Epoch 77/160 97/97 [==============================] - 29s 294ms/step - loss: 959.7264 Epoch 78/160 97/97 [==============================] - 29s 294ms/step - loss: 958.1680 Epoch 79/160 97/97 [==============================] - 29s 295ms/step - loss: 952.0243 Epoch 80/160 97/97 [==============================] - 29s 295ms/step - loss: 947.8354 Epoch 81/160 97/97 [==============================] - 29s 295ms/step - loss: 945.8139 Epoch 82/160 97/97 [==============================] - 29s 294ms/step - loss: 944.9114 Epoch 83/160 97/97 [==============================] - 29s 294ms/step - loss: 940.7040 Epoch 84/160 97/97 [==============================] - 29s 295ms/step - loss: 942.7839 Epoch 85/160 97/97 [==============================] - 29s 295ms/step - loss: 937.4374 Epoch 86/160 97/97 [==============================] - 29s 295ms/step - loss: 934.6262 Epoch 87/160 97/97 [==============================] - 29s 295ms/step - loss: 929.8491 Epoch 88/160 97/97 [==============================] - 29s 294ms/step - loss: 937.7441 Epoch 89/160 97/97 [==============================] - 29s 295ms/step - loss: 927.0290 Epoch 90/160 97/97 [==============================] - 29s 295ms/step - loss: 925.6105 Epoch 91/160 97/97 [==============================] - 29s 294ms/step - loss: 921.6296 Epoch 92/160 97/97 [==============================] - 29s 294ms/step - loss: 925.8184 Epoch 93/160 97/97 [==============================] - 29s 294ms/step - loss: 912.5261 Epoch 94/160 97/97 [==============================] - 29s 295ms/step - loss: 915.6510 Epoch 95/160 97/97 [==============================] - 29s 295ms/step - loss: 909.5853 Epoch 96/160 97/97 [==============================] - 29s 294ms/step - loss: 911.1563 Epoch 97/160 97/97 [==============================] - 29s 295ms/step - loss: 906.8965 Epoch 98/160 97/97 [==============================] - 29s 294ms/step - loss: 902.3696 Epoch 99/160 97/97 [==============================] - 29s 295ms/step - loss: 899.8710 Epoch 100/160 97/97 [==============================] - 29s 294ms/step - loss: 894.1641 Epoch 101/160 97/97 [==============================] - 29s 294ms/step - loss: 895.7336 Epoch 102/160 97/97 [==============================] - 29s 294ms/step - loss: 900.1674 Epoch 103/160 97/97 [==============================] - 29s 294ms/step - loss: 887.2552 Epoch 104/160 97/97 [==============================] - 29s 295ms/step - loss: 893.1448 Epoch 105/160 97/97 [==============================] - 29s 294ms/step - loss: 889.9379 Epoch 106/160 97/97 [==============================] - 29s 295ms/step - loss: 884.9587 Epoch 107/160 97/97 [==============================] - 29s 294ms/step - loss: 880.9834 Epoch 108/160 97/97 [==============================] - 29s 295ms/step - loss: 883.2829 Epoch 109/160 97/97 [==============================] - 29s 294ms/step - loss: 876.6734 Epoch 110/160 97/97 [==============================] - 29s 294ms/step - loss: 873.4252 Epoch 111/160 97/97 [==============================] - 29s 294ms/step - loss: 873.2639 Epoch 112/160 97/97 [==============================] - 29s 295ms/step - loss: 871.0381 Epoch 113/160 97/97 [==============================] - 29s 294ms/step - loss: 866.5417 Epoch 114/160 97/97 [==============================] - 29s 294ms/step - loss: 862.2125 Epoch 115/160 97/97 [==============================] - 29s 294ms/step - loss: 862.8839 Epoch 116/160 97/97 [==============================] - 29s 294ms/step - loss: 861.1781 Epoch 117/160 97/97 [==============================] - 29s 294ms/step - loss: 856.6186 Epoch 118/160 97/97 [==============================] - 29s 294ms/step - loss: 857.3196 Epoch 119/160 97/97 [==============================] - 29s 294ms/step - loss: 858.0576 Epoch 120/160 97/97 [==============================] - 29s 294ms/step - loss: 855.3264 Epoch 121/160 97/97 [==============================] - 29s 294ms/step - loss: 850.6841 Epoch 122/160 97/97 [==============================] - 29s 294ms/step - loss: 849.6420 Epoch 123/160 97/97 [==============================] - 29s 294ms/step - loss: 846.6933 Epoch 124/160 97/97 [==============================] - 29s 295ms/step - loss: 847.4681 Epoch 125/160 97/97 [==============================] - 29s 294ms/step - loss: 838.5893 Epoch 126/160 97/97 [==============================] - 29s 294ms/step - loss: 841.2516 Epoch 127/160 97/97 [==============================] - 29s 295ms/step - loss: 840.6940 Epoch 128/160 97/97 [==============================] - 29s 294ms/step - loss: 840.9053 Epoch 129/160 97/97 [==============================] - 29s 294ms/step - loss: 836.9998 Epoch 130/160 97/97 [==============================] - 29s 294ms/step - loss: 836.6874 Epoch 131/160 97/97 [==============================] - 29s 294ms/step - loss: 835.2166 Epoch 132/160 97/97 [==============================] - 29s 295ms/step - loss: 833.7071 Epoch 133/160 97/97 [==============================] - 29s 294ms/step - loss: 829.0735 Epoch 134/160 97/97 [==============================] - 29s 294ms/step - loss: 830.1376 Epoch 135/160 97/97 [==============================] - 29s 294ms/step - loss: 827.7781 Epoch 136/160 97/97 [==============================] - 29s 294ms/step - loss: 825.4308 Epoch 137/160 97/97 [==============================] - 29s 294ms/step - loss: 823.2223 Epoch 138/160 97/97 [==============================] - 29s 294ms/step - loss: 821.3982 Epoch 139/160 97/97 [==============================] - 29s 294ms/step - loss: 821.0161 Epoch 140/160 97/97 [==============================] - 29s 294ms/step - loss: 816.7703 Epoch 141/160 97/97 [==============================] - 29s 294ms/step - loss: 814.1747 Epoch 142/160 97/97 [==============================] - 29s 294ms/step - loss: 813.5908 Epoch 143/160 97/97 [==============================] - 29s 294ms/step - loss: 814.3353 Epoch 144/160 97/97 [==============================] - 29s 295ms/step - loss: 807.3126 Epoch 145/160 97/97 [==============================] - 29s 294ms/step - loss: 811.9185 Epoch 146/160 97/97 [==============================] - 29s 294ms/step - loss: 808.0939 Epoch 147/160 97/97 [==============================] - 29s 294ms/step - loss: 806.7361 Epoch 148/160 97/97 [==============================] - 29s 294ms/step - loss: 804.6682 Epoch 149/160 97/97 [==============================] - 29s 294ms/step - loss: 801.5149 Epoch 150/160 97/97 [==============================] - 29s 294ms/step - loss: 803.6600 Epoch 151/160 97/97 [==============================] - 29s 294ms/step - loss: 799.9028 Epoch 152/160 97/97 [==============================] - 29s 294ms/step - loss: 801.5812 Epoch 153/160 97/97 [==============================] - 29s 294ms/step - loss: 791.5322 Epoch 154/160 97/97 [==============================] - 29s 294ms/step - loss: 795.5021 Epoch 155/160 97/97 [==============================] - 29s 294ms/step - loss: 795.7894 Epoch 156/160 97/97 [==============================] - 29s 294ms/step - loss: 794.7897 Epoch 157/160 97/97 [==============================] - 29s 294ms/step - loss: 794.8560 Epoch 158/160 97/97 [==============================] - 29s 294ms/step - loss: 791.5762 Epoch 159/160 97/97 [==============================] - 29s 294ms/step - loss: 784.3605 Epoch 160/160 97/97 [==============================] - 29s 294ms/step - loss: 781.7180 </code></pre></div> </div> <p><img alt="png" src="/img/examples/vision/barlow_twins/barlow_twins_35_1.png" /></p> <hr /> <h2 id="evaluation">Evaluation</h2> <p><strong>Linear evaluation:</strong> to evaluate the model's performance, we add a linear dense layer at the end and freeze the main model's weights, only letting the dense layer to be tuned. If the model actually learned something, then the accuracy would be significantly higher than random chance.</p> <p><strong>Accuracy on CIFAR-10</strong> : 64% for this notebook. This is much better than the 10% we get from random guessing.</p> <div class="codehilite"><pre><span></span><code><span class="c1"># Approx: 64% accuracy with this barlow twins model.</span> <span class="n">xy_ds</span> <span class="o">=</span> <span class="p">(</span> <span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Dataset</span><span class="o">.</span><span class="n">from_tensor_slices</span><span class="p">((</span><span class="n">train_features</span><span class="p">,</span> <span class="n">train_labels</span><span class="p">))</span> <span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="o">.</span><span class="n">batch</span><span class="p">(</span><span class="n">BATCH_SIZE</span><span class="p">,</span> <span class="n">drop_remainder</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="o">.</span><span class="n">prefetch</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">AUTOTUNE</span><span class="p">)</span> <span class="p">)</span> <span class="n">test_ds</span> <span class="o">=</span> <span class="p">(</span> <span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">Dataset</span><span class="o">.</span><span class="n">from_tensor_slices</span><span class="p">((</span><span class="n">test_features</span><span class="p">,</span> <span class="n">test_labels</span><span class="p">))</span> <span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="o">.</span><span class="n">batch</span><span class="p">(</span><span class="n">BATCH_SIZE</span><span class="p">,</span> <span class="n">drop_remainder</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="o">.</span><span class="n">prefetch</span><span class="p">(</span><span class="n">tf</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">AUTOTUNE</span><span class="p">)</span> <span class="p">)</span> <span class="n">model</span> <span class="o">=</span> <span class="n">keras</span><span class="o">.</span><span class="n">models</span><span class="o">.</span><span class="n">Sequential</span><span class="p">(</span> <span class="p">[</span> <span class="n">bm</span><span class="o">.</span><span class="n">model</span><span class="p">,</span> <span class="n">keras</span><span class="o">.</span><span class="n">layers</span><span class="o">.</span><span class="n">Dense</span><span class="p">(</span> <span class="mi">10</span><span class="p">,</span> <span class="n">activation</span><span class="o">=</span><span class="s2">"softmax"</span><span class="p">,</span> <span class="n">kernel_regularizer</span><span class="o">=</span><span class="n">keras</span><span class="o">.</span><span class="n">regularizers</span><span class="o">.</span><span class="n">l2</span><span class="p">(</span><span class="mf">0.02</span><span class="p">)</span> <span class="p">),</span> <span class="p">]</span> <span class="p">)</span> <span class="n">model</span><span class="o">.</span><span class="n">layers</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">trainable</span> <span class="o">=</span> <span class="kc">False</span> <span class="n">linear_optimizer</span> <span class="o">=</span> <span class="n">tfa</span><span class="o">.</span><span class="n">optimizers</span><span class="o">.</span><span class="n">LAMB</span><span class="p">()</span> <span class="n">model</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="n">optimizer</span><span class="o">=</span><span class="n">linear_optimizer</span><span class="p">,</span> <span class="n">loss</span><span class="o">=</span><span class="s2">"sparse_categorical_crossentropy"</span><span class="p">,</span> <span class="n">metrics</span><span class="o">=</span><span class="p">[</span><span class="s2">"accuracy"</span><span class="p">],</span> <span class="p">)</span> <span class="n">model</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">xy_ds</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="mi">35</span><span class="p">,</span> <span class="n">validation_data</span><span class="o">=</span><span class="n">test_ds</span><span class="p">)</span> </code></pre></div> <div class="k-default-codeblock"> <div class="codehilite"><pre><span></span><code>Epoch 1/35 97/97 [==============================] - 12s 84ms/step - loss: 2.9447 - accuracy: 0.2090 - val_loss: 2.3056 - val_accuracy: 0.3741 Epoch 2/35 97/97 [==============================] - 6s 62ms/step - loss: 1.9912 - accuracy: 0.4867 - val_loss: 1.6910 - val_accuracy: 0.5883 Epoch 3/35 97/97 [==============================] - 6s 62ms/step - loss: 1.5476 - accuracy: 0.6278 - val_loss: 1.4605 - val_accuracy: 0.6465 Epoch 4/35 97/97 [==============================] - 6s 62ms/step - loss: 1.3775 - accuracy: 0.6647 - val_loss: 1.3689 - val_accuracy: 0.6644 Epoch 5/35 97/97 [==============================] - 6s 62ms/step - loss: 1.3027 - accuracy: 0.6769 - val_loss: 1.3232 - val_accuracy: 0.6684 Epoch 6/35 97/97 [==============================] - 6s 62ms/step - loss: 1.2574 - accuracy: 0.6820 - val_loss: 1.2905 - val_accuracy: 0.6717 Epoch 7/35 97/97 [==============================] - 6s 63ms/step - loss: 1.2244 - accuracy: 0.6852 - val_loss: 1.2654 - val_accuracy: 0.6742 Epoch 8/35 97/97 [==============================] - 6s 62ms/step - loss: 1.1979 - accuracy: 0.6868 - val_loss: 1.2460 - val_accuracy: 0.6747 Epoch 9/35 97/97 [==============================] - 6s 62ms/step - loss: 1.1754 - accuracy: 0.6884 - val_loss: 1.2247 - val_accuracy: 0.6773 Epoch 10/35 97/97 [==============================] - 6s 62ms/step - loss: 1.1559 - accuracy: 0.6896 - val_loss: 1.2090 - val_accuracy: 0.6770 Epoch 11/35 97/97 [==============================] - 6s 62ms/step - loss: 1.1380 - accuracy: 0.6907 - val_loss: 1.1904 - val_accuracy: 0.6785 Epoch 12/35 97/97 [==============================] - 6s 62ms/step - loss: 1.1223 - accuracy: 0.6915 - val_loss: 1.1796 - val_accuracy: 0.6776 Epoch 13/35 97/97 [==============================] - 6s 62ms/step - loss: 1.1079 - accuracy: 0.6923 - val_loss: 1.1696 - val_accuracy: 0.6785 Epoch 14/35 97/97 [==============================] - 6s 62ms/step - loss: 1.0954 - accuracy: 0.6931 - val_loss: 1.1564 - val_accuracy: 0.6795 Epoch 15/35 97/97 [==============================] - 6s 63ms/step - loss: 1.0841 - accuracy: 0.6939 - val_loss: 1.1454 - val_accuracy: 0.6807 Epoch 16/35 97/97 [==============================] - 6s 62ms/step - loss: 1.0733 - accuracy: 0.6945 - val_loss: 1.1356 - val_accuracy: 0.6810 Epoch 17/35 97/97 [==============================] - 6s 62ms/step - loss: 1.0634 - accuracy: 0.6948 - val_loss: 1.1313 - val_accuracy: 0.6799 Epoch 18/35 97/97 [==============================] - 6s 63ms/step - loss: 1.0535 - accuracy: 0.6957 - val_loss: 1.1208 - val_accuracy: 0.6808 Epoch 19/35 97/97 [==============================] - 6s 63ms/step - loss: 1.0447 - accuracy: 0.6965 - val_loss: 1.1128 - val_accuracy: 0.6813 Epoch 20/35 97/97 [==============================] - 6s 62ms/step - loss: 1.0366 - accuracy: 0.6968 - val_loss: 1.1082 - val_accuracy: 0.6799 Epoch 21/35 97/97 [==============================] - 6s 62ms/step - loss: 1.0295 - accuracy: 0.6968 - val_loss: 1.0971 - val_accuracy: 0.6821 Epoch 22/35 97/97 [==============================] - 6s 63ms/step - loss: 1.0226 - accuracy: 0.6971 - val_loss: 1.0946 - val_accuracy: 0.6799 Epoch 23/35 97/97 [==============================] - 6s 62ms/step - loss: 1.0166 - accuracy: 0.6977 - val_loss: 1.0916 - val_accuracy: 0.6802 Epoch 24/35 97/97 [==============================] - 6s 63ms/step - loss: 1.0103 - accuracy: 0.6980 - val_loss: 1.0823 - val_accuracy: 0.6819 Epoch 25/35 97/97 [==============================] - 6s 62ms/step - loss: 1.0052 - accuracy: 0.6981 - val_loss: 1.0795 - val_accuracy: 0.6804 Epoch 26/35 97/97 [==============================] - 6s 63ms/step - loss: 1.0001 - accuracy: 0.6984 - val_loss: 1.0759 - val_accuracy: 0.6806 Epoch 27/35 97/97 [==============================] - 6s 62ms/step - loss: 0.9947 - accuracy: 0.6992 - val_loss: 1.0699 - val_accuracy: 0.6809 Epoch 28/35 97/97 [==============================] - 6s 62ms/step - loss: 0.9901 - accuracy: 0.6987 - val_loss: 1.0637 - val_accuracy: 0.6821 Epoch 29/35 97/97 [==============================] - 6s 63ms/step - loss: 0.9862 - accuracy: 0.6991 - val_loss: 1.0603 - val_accuracy: 0.6826 Epoch 30/35 97/97 [==============================] - 6s 63ms/step - loss: 0.9817 - accuracy: 0.6994 - val_loss: 1.0582 - val_accuracy: 0.6813 Epoch 31/35 97/97 [==============================] - 6s 63ms/step - loss: 0.9784 - accuracy: 0.6994 - val_loss: 1.0531 - val_accuracy: 0.6826 Epoch 32/35 97/97 [==============================] - 6s 62ms/step - loss: 0.9743 - accuracy: 0.6998 - val_loss: 1.0505 - val_accuracy: 0.6822 Epoch 33/35 97/97 [==============================] - 6s 62ms/step - loss: 0.9711 - accuracy: 0.6996 - val_loss: 1.0506 - val_accuracy: 0.6800 Epoch 34/35 97/97 [==============================] - 6s 62ms/step - loss: 0.9686 - accuracy: 0.6993 - val_loss: 1.0423 - val_accuracy: 0.6828 Epoch 35/35 97/97 [==============================] - 6s 62ms/step - loss: 0.9653 - accuracy: 0.6999 - val_loss: 1.0429 - val_accuracy: 0.6821 <keras.callbacks.History at 0x7f4706ef0090> </code></pre></div> </div> <hr /> <h2 id="conclusion">Conclusion</h2> <ul> <li>Barlow Twins is a simple and concise method for contrastive and self-supervised learning.</li> <li>With this resnet-34 model architecture, we were able to reach 62-64% validation accuracy.</li> </ul> <hr /> <h2 id="usecases-of-barlowtwinsand-contrastive-learning-in-general">Use-Cases of Barlow-Twins(and contrastive learning in General)</h2> <ul> <li>Semi-supervised learning: You can see that this model gave a 62-64% boost in accuracy when it wasn't even trained with the labels. It can be used when you have little labeled data but a lot of unlabeled data.</li> <li>You do barlow twins training on the unlabeled data, and then you do secondary training with the labeled data.</li> </ul> <hr /> <h2 id="helpful-links">Helpful links</h2> <ul> <li><a href="https://arxiv.org/abs/2103.03230">Paper</a></li> <li><a href="https://github.com/facebookresearch/barlowtwins">Original Pytorch Implementation</a></li> <li><a href="https://colab.research.google.com/github/sayakpaul/Barlow-Twins-TF/blob/main/Barlow_Twins.ipynb#scrollTo=GlWepkM8_prl">Sayak Paul's Implementation</a>.</li> <li>Thanks to Sayak Paul for his implementation. It helped me with debugging and comparisons of accuracy, loss.</li> <li><a href="https://www.analyticsvidhya.com/blog/2021/08/how-to-code-your-resnet-from-scratch-in-tensorflow/#h2_2">resnet34 implementation</a><ul> <li>Thanks to Yashowardhan Shinde for writing the article.</li> </ul> </li> </ul> </div> <div class='k-outline'> <div class='k-outline-depth-1'> <a href='#barlow-twins-for-contrastive-ssl'>Barlow Twins for Contrastive SSL</a> </div> <div class='k-outline-depth-1'> <a href='#barlow-twins-for-contrastive-ssl'>Barlow Twins for Contrastive SSL</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#introduction'>Introduction</a> </div> <div class='k-outline-depth-3'> <a href='#highlevel-theory'>High-Level Theory</a> </div> <div class='k-outline-depth-3'> <a href='#references'>References</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#setup'>Setup</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#load-the-cifar10-dataset'>Load the CIFAR-10 dataset</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#necessary-hyperparameters'>Necessary Hyperparameters</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#augmentation-utilities'>Augmentation Utilities</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#data-loading'>Data Loading</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#pseudocode-of-loss-and-model'>Pseudocode of loss and model</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#barlowloss-barlow-twins-models-loss-function'>BarlowLoss: barlow twins model's loss function</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#barlow-twins-model-architecture'>Barlow Twins' Model Architecture</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#training-loop-model'>Training Loop Model</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#model-training'>Model Training</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#evaluation'>Evaluation</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#conclusion'>Conclusion</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#usecases-of-barlowtwinsand-contrastive-learning-in-general'>Use-Cases of Barlow-Twins(and contrastive learning in General)</a> </div> <div class='k-outline-depth-2'> ◆ <a href='#helpful-links'>Helpful links</a> </div> </div> </div> </div> </div> </body> <footer style="float: left; width: 100%; padding: 1em; border-top: solid 1px #bbb;"> <a href="https://policies.google.com/terms">Terms</a> | <a href="https://policies.google.com/privacy">Privacy</a> </footer> </html>