<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kevin Musgrave on Medium]]></title>
        <description><![CDATA[Stories by Kevin Musgrave on Medium]]></description>
        <link>https://medium.com/@tkm45?source=rss-f1bc1d8e67b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*o4ZLUxupBXvCDbsiFeKFQQ.png</url>
            <title>Stories by Kevin Musgrave on Medium</title>
            <link>https://medium.com/@tkm45?source=rss-f1bc1d8e67b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:14:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tkm45/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Customizing Domain Adaptation Algorithms with PyTorch Adapt]]></title>
            <link>https://medium.com/@tkm45/customizing-domain-adaptation-algorithms-with-pytorch-adapt-d11ec1a8463c?source=rss-f1bc1d8e67b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d11ec1a8463c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[domain-adaptation]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Kevin Musgrave]]></dc:creator>
            <pubDate>Tue, 07 Dec 2021 15:40:51 GMT</pubDate>
            <atom:updated>2021-12-07T15:40:51.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIyPfLkMBwJczW6yQZrdqA.png" /></figure><p>Domain adaptation algorithms come in many forms. Some use a GAN architecture. Some require features from one domain, but not the other. Some require features to be detached from the autograd graph. And so on. This makes it difficult to design code that:</p><ul><li>is easy to customize</li><li>doesn’t perform unnecessary computations</li></ul><p>To solve this problem, <a href="https://github.com/KevinMusgrave/pytorch-adapt"><strong>PyTorch Adapt</strong></a> uses key-based lazily evaluated hooks. In a nutshell, each hook follows these steps:</p><ol><li>Determine the required data (e.g. source features, target logits).</li><li>Check if the required data is already available in the current context. If it is available, then go to step 4.</li><li>Compute the required data and add it to the context.</li><li>Use the required data.</li></ol><p>This system makes it easy to combine hooks and build complex algorithms. Let’s look at a few examples.</p><h3>Example 0: Setup</h3><p>First we need to create some models and data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agHOu4fM-_dvdJ8EVblZOw.png" /></figure><p>We’ll also add a PyTorch forward hook to count the number of times each model is used. (In between each example, we’ll manually reset the count to zero.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8CHXbTdi-II16f2msEyUZA.png" /></figure><h3>Example 1: Source Classifier</h3><p>The ClassifierHook applies a cross entropy loss to the source data, so it requires source logits to be computed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ShbMRYMCNRErIQhQrI0ctA.png" /></figure><p>Therefore, models G and C should both be used once. This is confirmed by running the code below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTStbDD5u8WyuLxmCR12mA.png" /></figure><h3>Example 2: Source Classifier + BSP + BNM</h3><p>Now we’ll use the same ClassifierHook but add some hooks that are useful for domain adaptation.</p><p>The BSPHook requires source and target features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpQCx_s7WwOZI2JN34Nuhg.png" /></figure><p>The BNMHook requires target logits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fw1CKCMzffaxdTtPCoZ5OQ.png" /></figure><p>The source logits still need to be computed for the source classification loss. So in total, each model should be used twice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuH513YHoh3eCGGHpHoWtw.png" /></figure><p>Notice that the hooks obtain the data they need, and without doing any redundant computations, i.e. BSPHook did not recompute the source features. (If it did, then G.count would be 3.)</p><h3>Example 3: MCD</h3><p>MCD is an adversarial method with 3 optimization steps that are run independently of one another, so all required tensors have to be recomputed in each step. The steps are:</p><ol><li>Classification loss on source data. Like in example 1, G and C will be used once.</li><li>Classification loss + adversarial loss on target logits. Both source and target logits need to be computed, so G and C will be used twice.</li><li>Advesarial loss on target logits, repeated N times. Target logits need to be computed N times, so G and C will be used N times.</li></ol><p>The default value of N is 4. Therefore, G and C should be used a total of 7 times:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yc8cWSe4YMPJ5-oC9VBDA.png" /></figure><h3>Example 4: MCD + AFN + MMD</h3><p>Here we’ll add two hooks:</p><ul><li>AFNHook requires source and target features. We&#39;ll place this in step 1 of MCDHook. Step 1 already computes source features, but not target features, so the model count for G should increase by 1.</li><li>AlignerHook (which computes MMD) requires source and target features. We&#39;ll place this in step 3 of MCD. Step 3 already computes target features, but not source features, so the model count for G should increase by N.</li></ul><p>In total, the count for G should be 7 + 1 + N = 12 (where N = 4 by default).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8PG1bxui6cZ8GB2ulCHewQ.png" /></figure><p>It looks like the hooks are working as intended: easy customization of algorithms, with no unnecessary computations!</p><h3>Running these examples</h3><p>These snippets come from <a href="https://github.com/KevinMusgrave/pytorch-adapt/blob/main/examples/getting_started/CustomizingAlgorithms.ipynb"><strong>this Jupyter notebook</strong></a>, which you can also <a href="https://colab.research.google.com/github/KevinMusgrave/pytorch-adapt/blob/main/examples/getting_started/CustomizingAlgorithms.ipynb">run on Google Colab</a>.</p><p>Interested in learning more about PyTorch Adapt hooks? Take a look at the <a href="https://github.com/KevinMusgrave/pytorch-adapt/blob/main/examples/in_depth/Hooks.ipynb"><strong>Hooks In Depth notebook</strong></a>.</p><h3>Other links</h3><ul><li><a href="https://github.com/KevinMusgrave/pytorch-adapt"><strong>PyTorch Adapt on GitHub</strong></a></li><li><a href="https://kevinmusgrave.github.io/pytorch-adapt/"><strong>Documentation (in progress)</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d11ec1a8463c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Domain Adaptation using PyTorch Adapt]]></title>
            <link>https://medium.com/@tkm45/deep-domain-adaptation-using-pytorch-adapt-c020ae596e25?source=rss-f1bc1d8e67b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c020ae596e25</guid>
            <category><![CDATA[domain-adaptation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Kevin Musgrave]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 14:04:09 GMT</pubDate>
            <atom:updated>2022-01-16T13:23:45.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIyPfLkMBwJczW6yQZrdqA.png" /></figure><p>Consider the scenario where you’ve trained a model on MNIST digits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*x8EAAO-BHRbPBEtb_cbKXQ.png" /><figcaption>MNIST dataset</figcaption></figure><p>And you’ve been told that your model must also work on a dataset of randomly colored digits:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*KZ-xf-QGw8z4z3H3rgdefQ.png" /><figcaption>MNIST-M dataset (<a href="https://arxiv.org/abs/1505.07818">https://arxiv.org/abs/1505.07818</a>)</figcaption></figure><p>It turns out that you don’t have the labels for this dataset, so you can’t use supervised learning to retrain your model. But you can use domain adaptation, which is a type of algorithm for repurposing existing models to work in different domains.</p><p>Enter <a href="https://github.com/KevinMusgrave/pytorch-adapt"><strong>PyTorch Adapt</strong></a>, a new modular library for domain adaptation. You can use it with vanilla PyTorch, or with a provided framework wrapper. Let’s see how it works on the MNIST → MNIST-M task.</p><h3>Using PyTorch Adapt for the MNIST → MNIST-M task</h3><p>The following snippets are from <a href="https://github.com/KevinMusgrave/pytorch-adapt/blob/main/examples/getting_started/DANNIgniteWithViz.ipynb"><strong>this Jupyter notebook</strong></a>.</p><ol><li>Download the datasets and initialize a dataloader creator.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*UhzdVuZLLCTNeSDmgFPfng.png" /></figure><p>2. Setup the models (G and C), the domain adaptation algorithm (DANN), and the validator (IMValidator). We move much of the classifier model (C) to the trunk (G) because this tends to work better for DANN. To simplify our code, we’ll use the PyTorch Ignite wrapper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*atyf2necB2CuLb6X5vvspQ.png" /></figure><p>3. Setup the visualization hook. For this demo I’ve written a simple function to visualize the features during training. (See the notebook for the function definition.) Since we’re using the PyTorch Ignite wrapper, we can use Ignite’s event handling system to add the visualizer hook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*QNIp4AGVGLhOWUeBJpBW6g.png" /></figure><p>4. Train the model. Here we train for only 4 epochs, though typically many more are needed for the best performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*BagUq9DLTE8QXfvmh8y-Ig.png" /></figure><p>5. Compare the feature visualizations. Before training, the MNIST (blue) features are well clustered, but there is little overlap with the MNIST-M (orange) features. After 4 epochs of training, the overlap between the two domains has increased, indicating that the model is adapting to the new domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0tEdYNQ70cB_cCIAtJ1WQ.png" /><figcaption>Features before training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuUyWTAmftaq5r1EFdtQAQ.png" /><figcaption>Features after 4 epochs</figcaption></figure><p>6. Compute accuracy on MNIST-M… or not? In a real-world application, you wouldn’t be able to compute accuracy because the target data doesn’t come with labels. But for the purpose of this demo, we’ll cheat and check the accuracy anyway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*YatqxkLqn9qvhpwWP2Gs7w.png" /></figure><p>The best accuracy after 4 epochs is 65.6%, compared to the starting accuracy of 57.4%. So training seems to be headed in the right direction.</p><h3>To be continued</h3><p>This post provides a brief overview of PyTorch Adapt. In my next post, I’ll explain how to easily customize algorithms using the pytorch_adapt.hooks module.</p><p>For more info, check out these links:</p><ul><li><a href="https://github.com/KevinMusgrave/pytorch-adapt"><strong>PyTorch Adapt on GitHub</strong></a></li><li><a href="https://github.com/KevinMusgrave/pytorch-adapt/tree/main/examples"><strong>Example Jupyter notebooks</strong></a></li><li><a href="https://kevinmusgrave.github.io/pytorch-adapt/"><strong>Documentation</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c020ae596e25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch Metric Learning: What’s New]]></title>
            <link>https://medium.com/@tkm45/pytorch-metric-learning-whats-new-15d6c71a644b?source=rss-f1bc1d8e67b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/15d6c71a644b</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kevin Musgrave]]></dc:creator>
            <pubDate>Wed, 16 Sep 2020 14:26:15 GMT</pubDate>
            <atom:updated>2020-09-16T21:44:50.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48EYCz9WC_ECK-05A7tgBA.png" /></figure><p><a href="https://github.com/KevinMusgrave/pytorch-metric-learning"><strong>PyTorch Metric Learning</strong></a> has seen a lot of changes in the past few months. Here are the highlights.</p><h3>Distances, Reducers, and Regularizers</h3><p>Loss functions are now highly customizable with the introduction of distances, reducers, and regularizers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QzZ6DLebN0vrE17d" /></figure><h4>Distances</h4><p>Consider the TripletMarginLoss in its default form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*1xarBy6Crbb45Bn-p3Ypzw.png" /></figure><p>This loss function attempts to minimize:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*UwB7rXXI6gZx8SC6_xIGnQ.png" /></figure><p>where “d” represents L2 distance. But what if we want to use a different distance metric like unnormalized L1, or signal-to-noise ratio? With the distances module, you can try out these ideas easily:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*IT39W88CPE02OpG0l7fsSQ.png" /></figure><p>You can also use similarity measures rather than distances, even though similarities are inversely related to distances:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*BewwjZ1v9SnuvUWH8Me7HQ.png" /></figure><p>With a similarity measure, the TripletMarginLoss internally swaps the anchor-positive and anchor-negative terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*iGY-46vIJaFXlNeT97ht_w.png" /></figure><p>where “s” represents similarity.</p><h4>Reducers</h4><p>Losses are typically computed per element, pair, or triplet, and then are reduced to a single value by some operation, such as averaging. Many PyTorch loss functions accept a reduction parameter, which is usually “mean”, “sum”, or “none”.</p><p>In PyTorch Metric Learning, the reducer parameter serves a similar purpose, but instead takes in an object that performs the reduction. Here is an example of a ThresholdReducer being passed into a loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*aR8RHFvKb8_q8tL4FcTFpw.png" /></figure><p>This ThresholdReducer will discard losses that fall outside of the range (10, 30), and then return the average of the remaining losses.</p><h4>Regularizers</h4><p>It’s common to add embedding or weight regularization terms to the core metric learning loss. Thus, every loss function has an optional embedding regularizer parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*gePOndOarKBfEKJplwZFgA.png" /></figure><p>And classification losses have an optional weight regularizer parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*m4w6Zw0Gm8f32f02fq0Qhg.png" /></figure><h3>Flexible MoCo for Self-Supervised Learning</h3><p><a href="https://arxiv.org/pdf/2003.04297.pdf">Momentum Contrastive Learning</a> (MoCo) is a state-of-the-art self-supervision algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Bdun_z2KjbKWs4s3m0JZag.png" /><figcaption>Figure 1 from the <a href="https://arxiv.org/pdf/1911.05722.pdf">original paper</a></figcaption></figure><p>In a nutshell, it consists of the following steps:</p><ol><li>Initialize two convnets, Q and K, that have identical weights.</li><li>At each iteration of training, set the weights of K to (m)*K + (1-m)*Q, where m is the momentum.</li><li>Retrieve a batch of images, X, and a randomly augmented version, X`.</li><li>Pass X into Q, and X` in K, and store K’s output in a large queue.</li><li>Apply the InfoNCE loss (a.k.a NTXent), using [Q_out, K_out] as positive pairs, and [Q_out, queue] as negative pairs.</li><li>Backpropagate and update Q.</li></ol><p>This simple procedure works amazingly well for creating good feature extractors. You might be wondering if it’s possible to use a different loss function, distance metric, or reduction method. And what about mining hard negatives from the queue?</p><p>With this library, it’s very easy to try these ideas by using <a href="https://arxiv.org/pdf/1912.06798.pdf">CrossBatchMemory</a>. First, initialize it with any tuple-based loss, and optionally supply a miner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*LRspsEkQEMvFQr_yHuYImg.png" /></figure><p>Create “labels” to indicate which elements are positive pairs, and specify which part of the batch to add to the queue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*ikianuaZzgadk_suWBFOiw.png" /></figure><p>Compute the loss and step the optimizer. CrossBatchMemory takes care of all the mining, loss computation, and bookkeeping for the queue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*5pJn8sstkpjIxAi0vyuKSQ.png" /></figure><p>To confirm that CrossBatchMemory works with MoCo, I wrote a notebook demonstrating that it achieves accuracy equivalent to the official implementation on CIFAR10 (using InfoNCE and no mining). You can <a href="https://colab.research.google.com/github/KevinMusgrave/pytorch-metric-learning/blob/master/examples/notebooks/MoCoCIFAR10.ipynb"><strong>run the notebook on Google Colab</strong></a>.</p><h3>AccuracyCalculator</h3><p>If you need to compute accuracy based on k-nearest-neighbors and k-means clustering, AccuracyCalculator is a convenient tool for that. By default, it computes 5 standard accuracy metrics when you pass in query and reference embeddings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*GED6wEZetePfljPJi_t8yw.png" /></figure><p>Adding your own accuracy metrics is straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*kj8R07yQp67OFczH4PZRIw.png" /></figure><p>Now when you call “get_accuracy”, the returned dictionary will include “some_amazing_metric”. Check out <a href="https://kevinmusgrave.github.io/pytorch-metric-learning/accuracy_calculation/">the documentation</a> for details on how this works.</p><h3>Distributed Wrappers</h3><p>To make losses and miners work in multiple processes, use the distributed wrappers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*PFT6HesmYd9LXIHhjKh2HQ.png" /></figure><p>Why are these wrappers necessary? Under the hood, metric losses and miners usually have to access all tuples in a batch. But if your program is running in separate processes, the loss/miner in each process doesn’t get to see the global batch, and thus, will see only a fraction of all tuples. Using the distributed wrappers fixes this problem. (Thanks to John Giorgi who figured out how to implement this in his project on constrastive unsupervised textual representations, <a href="https://github.com/JohnGiorgi/DeCLUTR">DeCLUTR</a>.)</p><h3>Examples on Google Colab + Documentation</h3><p>To see how this library works in actual training code, take a look at the <a href="https://github.com/KevinMusgrave/pytorch-metric-learning/blob/master/examples/README.md"><strong>example notebooks on Google Colab</strong></a>. There’s also a lot of <a href="https://kevinmusgrave.github.io/pytorch-metric-learning/">documentation</a> and an accompanying <a href="https://arxiv.org/abs/2008.09164">paper</a>.</p><p>As a final note, here’s a long and narrow view of this library’s contents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*LE5oMhtrM8B9MDJclHSazw.png" /></figure><p>Hope you find it useful!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*Iz4YsqsdEfaHYhqA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15d6c71a644b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updates to “A Metric Learning Reality Check”]]></title>
            <link>https://medium.com/@tkm45/updates-to-a-metric-learning-reality-check-730b6914dfe7?source=rss-f1bc1d8e67b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/730b6914dfe7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Kevin Musgrave]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 14:21:30 GMT</pubDate>
            <atom:updated>2020-08-05T14:21:30.095Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently uploaded a new version of <a href="https://arxiv.org/abs/2003.08505"><strong>A Metric Learning Reality Check</strong></a> to arXiv. Here are the highlights:</p><h3>Unfair Comparisons: Concrete Examples</h3><p>People were asking for examples to back up my claims about unfair comparisons, so I created a list of examples. See the screenshots below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osjpPr4cN0rUphvKjyFTAw.png" /><figcaption>Click <a href="https://kevinmusgrave.github.io/powerful-benchmarker/papers/mlrc/#papers-that-use-a-better-architecture-than-their-competitors-but-dont-disclose-it"><strong>here to view the list with working links</strong></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YutRlWP9JT9UFpMP6iBAOA.png" /><figcaption>Click <a href="https://kevinmusgrave.github.io/powerful-benchmarker/papers/mlrc/#papers-that-use-a-higher-dimensionality-than-their-competitors-but-dont-disclose-it"><strong>here to view the list with working links</strong></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBgANzW9_hz3gubz_6ODRA.png" /><figcaption>Click <a href="https://kevinmusgrave.github.io/powerful-benchmarker/papers/mlrc/#papers-that-claim-to-do-a-simple-256-resize-and-227-or-224-random-crop-but-actually-use-the-more-advanced-randomresizedcrop-method"><strong>here to view the list with working links</strong></a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vR0fw0BheZvd9idzezQu9w.png" /><figcaption>Click <a href="https://kevinmusgrave.github.io/powerful-benchmarker/papers/mlrc/#papers-that-omit-details"><strong>here to view the list with working links</strong></a></figcaption></figure><h3>Bayesian Optimization Plots</h3><p>The supplementary material comes with bayesian optimization plots, like the one below. Each plot shows how the validation accuracy changes with respect to hyperparameters. Click <a href="https://kevinmusgrave.github.io/powerful-benchmarker/papers/mlrc/#optimization-plots"><strong>here to view the plots</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*D7GDwKAd8WOeHZho_5ZhCA.png" /></figure><h3>Comprehensive “Papers vs Reality” Figure</h3><p>We updated the “trend according to papers” to include more algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ci1GLvs6sPrrIjXNIocvAw.png" /></figure><h3>Large Batch Experiment Results on CUB200</h3><p>We added results for CUB200 with a batch size of 256. The increase in batch size gives FastAP a significant boost in accuracy, and as a result, it performs on par with the rest of the methods, rather than underperforming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsq05AZMzMyyUd6F7vdBFA.png" /></figure><h3>Better Explanation of MAP@R and its Benefits</h3><p>We explained in more detail why MAP@R is preferable to Recall@1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1fmMTw6OOvuHZloc0ysNQ.png" /></figure><h3>Related links</h3><p>Finally, here are some links you might find interesting:</p><ul><li><a href="https://github.com/KevinMusgrave/powerful-benchmarker/"><strong>Powerful Benchmarker</strong></a><strong> </strong>(the code used to run the experiments)</li><li><a href="https://docs.google.com/presentation/d/1KnLDFzMKLYlnMzMDc7wyKHVAh5dJ9z6Fs1qto4OqQFY/edit?usp=sharing"><strong>Powerpoint Slides</strong></a><strong> </strong>(summarizes the paper)</li><li><a href="https://kevinmusgrave.github.io/powerful-benchmarker/papers/mlrc/"><strong>Supplementary material</strong></a><strong> </strong>(contains lots of goodies)</li><li><a href="https://github.com/KevinMusgrave/pytorch-metric-learning"><strong>PyTorch Metric Learning</strong></a><strong> </strong>(the algorithm implementations)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VJrhr8Dr3_4ofCPKHxWvw.png" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Thats_all_folks.svg">https://commons.wikimedia.org/wiki/File:Thats_all_folks.svg</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=730b6914dfe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking Metric Learning Algorithms the Right Way]]></title>
            <link>https://medium.com/@tkm45/benchmarking-metric-learning-algorithms-the-right-way-90c073a83968?source=rss-f1bc1d8e67b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/90c073a83968</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[metric-learning]]></category>
            <dc:creator><![CDATA[Kevin Musgrave]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 20:19:26 GMT</pubDate>
            <atom:updated>2020-05-07T22:08:48.576Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Go </strong><a href="https://github.com/KevinMusgrave/powerful-benchmarker"><strong>here</strong></a><strong> for the code and latest updates, and check out the associated paper, </strong><a href="https://arxiv.org/abs/2003.08505"><strong>A Metric Learning Reality Check</strong></a><strong>.</strong></p><p>The typical metric learning paper presents a new loss function or training procedure, and then shows results on a few datasets, like CUB200, Stanford Cars, and Stanford Online Products. Every couple of months, we see the accuracy improve like clockwork.</p><p>Great, but there are a few caveats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*Nf5Mzy9OowdTWlB3K_IQAQ.png" /><figcaption>Here’s a random graph to keep your attention</figcaption></figure><h3><strong>Some papers do not compare apples to apples</strong></h3><p>In order to claim that a new algorithm outperforms existing methods, it’s important to keep as many parameters constant as possible. That way, we can be certain that it was the new algorithm that boosted performance, and not one of the extraneous parameters. This has not been the case with metric learning papers:</p><ol><li><strong>Network architectures have not been kept constant</strong>. Some papers use <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43022.pdf">GoogleNet</a>. Many recent papers have been using <a href="https://arxiv.org/pdf/1502.03167.pdf">BN-Inception</a>, sometimes referred to as “Inception with Batch Normalization”. One widely-cited paper from 2017 used <a href="https://arxiv.org/pdf/1512.03385.pdf">ResNet50</a>, and then claimed huge performance gains. This is questionable, because the competing methods used GoogleNet, which is a less powerful architecture. Thus, much of the performance gain likely came from the choice of network architecture, and not their proposed method.</li><li><strong>Image augmentations have not been kept constant. </strong>Most papers claim to apply the following transformations: Resize the image to 256 x 256, randomly crop to 227 x 227, and do a horizontal flip with 50% chance. But the official open-source implementations of some recent papers, show that they are actually using the more sophisticated cropping method described in the original <a href="https://arxiv.org/pdf/1409.4842.pdf">GoogleNet paper</a> (see “Training Methodology”).</li><li><strong>Performance-boosting tricks have been used without being mentioned in the paper.</strong> In the official open-source code for a recent 2019 paper, the trunk-model’s BatchNorm parameters are frozen during training. This can help reduce overfitting, and the authors explain that it results in a 2-point performance boost on the CUB200 dataset. Yet this is not mentioned in their paper.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*r8ljV4NH-bQcIruReAGGWA.png" /><figcaption>Accuracy (Recall@1) of models pretrained on ImageNet. Output embedding sizes were reduced to 512 using PCA. For each image, the smaller side was scaled to 256, followed by a center-crop to 227x227.</figcaption></figure><h3>Most papers are using a simple train/test split</h3><p>They train on a portion of the data, find the model that performs best on the test set, and report that number. In other words, <strong>they do not use a validation set. </strong>So hyperparameters have been tuned and entire algorithms have been created with direct feedback from the test set. This breaks the most basic rule of Machine Learning 101. Moreover, the <strong>same single train/test split has been used for years</strong>. Over time, these two factors have likely lead to overfitting on the test set.</p><h3>So let’s benchmark these algorithms correctly</h3><p>This is where the <a href="https://github.com/KevinMusgrave/powerful_benchmarker">powerful_benchmarker</a> comes in.</p><h4>Why use this tool?</h4><p><strong>Transparency. </strong>Every experiment you run comes with detailed config files that show exactly what models, losses, transforms (and more) were used. So now we can compare methods fairly.</p><p><strong>Better performance metrics. </strong>Use metrics that are more informative than Recall @ 2, 4, 8, 100, 1000 etc.</p><p><strong>Measure accuracy the correct way. </strong>Measure accuracy on multiple class-based train/val/test splits. Or you can use the old 50/50 train/test split for comparison purposes.</p><p><strong>Detailed record keeping.</strong> View in-depth information about the training process on Tensorboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*WZTGims6IgTQ1fHr" /></figure><p><strong>Flexibility with config files. </strong>Control most aspects of your experiment via config files. Extend existing config files by merging them with new ones. Here’s an example of how models are specified:</p><pre>models:<br>   trunk:<br>      bninception:<br>         pretrained: imagenet<br>   embedder:<br>      MLP:<br>         layer_sizes: <br>            - 512</pre><p>And here’s how you merge 3 config_general files:</p><pre>python run.py \<br>--experiment_name test \<br>--config_general default daml train_with_classifier </pre><p><strong>Flexibility at the command line. </strong>Specify complex config options using standard Python dictionary notation:</p><pre>python run.py \<br>--experiment_name test \<br>--optimizers {metric_loss_optimizer: {SGD: {lr: 0.01}}} </pre><p><a href="https://github.com/KevinMusgrave/powerful_benchmarker#override-config-options-at-the-command-line">See this</a> for more details.</p><p><strong>Flexibility with algorithms. </strong>Mix and match losses, mining functions, samplers, and training methods. Want to use the multi-similarity loss with the batch-hard miner? No problem:</p><pre>loss_funcs:<br>  metric_loss: <br>    MultiSimilarityLoss:<br>      alpha: 0.1<br>      beta: 40<br>      base: 0.5</pre><pre>mining_funcs:<br>  post_gradient_miner: <br>    BatchHardMiner: {}</pre><p><strong>Access to all models in the torchvision and pretrainedmodels packages. </strong>In your config_models file, just specify the function name as it appears in <a href="https://pytorch.org/docs/stable/torchvision/models.html#id1">torchvision </a>or <a href="https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/__init__.py#L19">pretrainedmodels</a>.</p><p><strong>Access to all losses in torch.nn and pytorch_metric_learning. </strong>In your config_loss_and_miners file, just specify the class name as it appears in <a href="https://pytorch.org/docs/stable/nn.html">torch.nn</a> or <a href="https://github.com/KevinMusgrave/pytorch_metric_learning">pytorch_metric_learning</a>.</p><h3>Does it matter?</h3><p>In the table below are the results from a selection of metric learning papers published in CVPR 2019 and ICCV 2019. Each color represents a different model and embedding size configuration. Because there is no standard way of running experiments, it is difficult to compare the performance of the various algorithms. This impedes research progress, because we don’t know which method really works best. Hence, it’s important to have a benchmarking tool that enables us to do fair comparisons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*aPgRiHnTYkqWa7kvEB9z9w.png" /><figcaption><strong>Green</strong>: BN-Inception, 512. <strong>Blue</strong>: Resnet50, 128. <strong>Yellow</strong>: Resnet50, 512. <strong>Red</strong>: GoogleNet, 512.<strong> The numbers for the first 8 rows come from the respective papers.</strong></figcaption></figure><p>In the bottom part of the table are results that were obtained using the benchmarking tool. Both the triplet loss and contrastive loss come close to the state-of-the-art. Yet these two are often left out of results tables, or are purported to be among the worst performing methods. The powerful benchmarker makes it easy to check these baseline algorithms.</p><p>(To view the config files for these experiments and others, see <a href="https://docs.google.com/spreadsheets/d/1kiJ5rKmneQvnYKpVO9vBFdMDNx-yLcXV2wbDXlb-SB8/edit?usp=sharing">this spreadsheet</a>, which I’ll be adding to over time.)</p><h3>Thoughts?</h3><p>Let me know what you think about this tool and the state of metric learning. If you have any questions or want to add features, visit the GitHub repos for <a href="https://github.com/KevinMusgrave/powerful_benchmarker">powerful_benchmarker</a> and <a href="https://github.com/KevinMusgrave/pytorch_metric_learning">pytorch_metric_learning</a>.</p><h3>Acknowledgements</h3><p>Thank you to Ser-Nam Lim at Facebook AI, and my research advisor, Professor Serge Belongie. This project began during my internship at Facebook AI where I received valuable feedback from Ser-Nam, and his team of computer vision and machine learning engineers and research scientists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90c073a83968" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The New PyTorch Package that makes Metric Learning Simple]]></title>
            <link>https://medium.com/@tkm45/the-new-pytorch-package-that-makes-metric-learning-simple-5e844d2a1142?source=rss-f1bc1d8e67b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e844d2a1142</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[metric-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[computer-inventory]]></category>
            <dc:creator><![CDATA[Kevin Musgrave]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 20:17:47 GMT</pubDate>
            <atom:updated>2020-01-31T22:36:03.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you thought of using a metric learning approach in your deep learning application? If not, this is an approach you may find useful, especially if your deployed model will encounter unseen classes of data.</p><p>With the release of <a href="https://github.com/KevinMusgrave/pytorch-metric-learning"><strong>pytorch-metric-learning</strong></a>, it’s easier than ever to give metric learning a try!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*cY9AOTe3vjlerL73ItnfTg.jpeg" /><figcaption><a href="http://www.vision.caltech.edu/visipedia/CUB-200.html">Samples from the CUB200 dataset</a>, a commonly-used metric learning benchmark</figcaption></figure><h3>What is Metric Learning?</h3><p>Metric Learning refers to the task of learning distances or dissimilarities over a set of observations. We want to find a function that returns a small distance for similar observations and a large distance for different ones.</p><h3>Why use this package?</h3><p><strong>Ease of use</strong></p><ul><li>Add metric learning to your application with just 2 lines of code in your training loop.</li><li>Mine pairs and triplets with a single function call.</li></ul><p><strong>Flexibility</strong></p><ul><li>Mix and match losses, miners, and trainers in ways that other libraries don’t allow.</li></ul><h3>Usage:</h3><p>Let’s try the vanilla triplet margin loss. In all examples, embeddings is assumed to be of size (N, embedding_size), and labels is of size (N).</p><pre>from pytorch_metric_learning import losses<br>loss_func = losses.TripletMarginLoss(margin=0.1)<br>loss = loss_func(embeddings, labels)</pre><p>Loss functions typically come with a variety of parameters. For example, with the TripletMarginLoss, you can control how many triplets per anchor to use in each batch. You can also use all possible triplets within each batch:</p><pre>loss_func = losses.TripletMarginLoss(triplets_per_anchor=&quot;all&quot;)</pre><p>Sometimes it can help to add a mining function:</p><pre>from pytorch_metric_learning import miners, losses<br>miner = miners.MultiSimilarityMiner(epsilon=0.1)<br>loss_func = losses.TripletMarginLoss(margin=0.1)<br>hard_pairs = miner(embeddings, labels)<br>loss = loss_func(embeddings, labels, hard_pairs)</pre><p>In the above code, the miner finds positive and negative pairs that it thinks are particularly difficult. Note that even though the TripletMarginLoss operates on triplets, it’s still possible to pass in pairs. This is because the library automatically converts pairs to triplets and triplets to pairs, when necessary.</p><p>For more complex approaches, like deep adversarial metric learning, use one of the <a href="https://kevinmusgrave.github.io/pytorch-metric-learning/trainers"><strong>trainers</strong></a>. And to check the accuracy of your model, use one of the <a href="https://kevinmusgrave.github.io/pytorch-metric-learning/testers"><strong>testers</strong></a><strong>.</strong><br><br>Also check out the <a href="https://github.com/KevinMusgrave/pytorch-metric-learning/tree/master/examples"><strong>example scripts</strong></a><strong>. </strong>Each one shows how to set up models, optimizers, losses etc for a particular trainer.</p><p>Do you want an easy solution for saving models and recording data on tensorboard (as shown below)? Try the <a href="https://kevinmusgrave.github.io/pytorch-metric-learning/utils/#hookcontainer"><strong>ready-to-use hooks</strong></a> that can be passed into any trainer or tester object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*pAHRP86EC12TxKYahViDyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-sYhAK9bUE1jdU_aMX5Fcg.png" /></figure><p>To learn more about all of the above, <a href="https://kevinmusgrave.github.io/pytorch-metric-learning/"><strong>see the documentation</strong></a><strong>.</strong></p><h3>Installation:</h3><p>Install with conda:</p><pre>conda install pytorch-metric-learning -c metric-learning</pre><p>Or pip:</p><pre>pip install pytorch-metric-learning</pre><h3>Suggestions are welcome</h3><p>If you’re looking for an easy way to integrate metric learning algorithms into your code, then try <a href="https://github.com/KevinMusgrave/pytorch_metric_learning"><strong>pytorch-metric-learning</strong></a><strong>. </strong>And if you have any suggestions, or would like to add a function to the library, please make a GitHub issue or pull-request.</p><h3>Acknowledgements</h3><p>Thank you to Ser-Nam Lim at Facebook AI, and my research advisor, Professor Serge Belongie. This project began during my internship at Facebook AI where I received valuable feedback from Ser-Nam, and his team of computer vision and machine learning engineers and research scientists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e844d2a1142" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>