<?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 Stephen Lau on Medium]]></title>
        <description><![CDATA[Stories by Stephen Lau on Medium]]></description>
        <link>https://medium.com/@stephenllh?source=rss-e9968809fb86------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*k20DU7-egNWiaMaIUeWEag.jpeg</url>
            <title>Stories by Stephen Lau on Medium</title>
            <link>https://medium.com/@stephenllh?source=rss-e9968809fb86------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:01:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stephenllh/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[So … I finished training my model, now what?]]></title>
            <link>https://medium.com/@stephenllh/so-i-finished-training-my-model-now-what-51680f613eb3?source=rss-e9968809fb86------2</link>
            <guid isPermaLink="false">https://medium.com/p/51680f613eb3</guid>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Stephen Lau]]></dc:creator>
            <pubDate>Sun, 12 Mar 2023 07:56:50 GMT</pubDate>
            <atom:updated>2023-03-12T07:56:50.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>So … I finished training my model, now what?</h3><p>Let’s say you trained a machine learning model. What do you do next? If your answer is “leave it somewhere where I won’t touch anymore and move on to the next project,” you are doing what most ML practitioners do — not showcasing your work to the world.</p><blockquote>“87 percent of ML models never make it into production.”</blockquote><blockquote>- VentureBeat</blockquote><p>This is very ironic because I think the point of machine learning is solving problems that we humans are not good at. So, by leaving the models to rot on hard disks, we greatly diminish the value of machine learning.</p><p>In this tutorial, I am going to show you what to do. Let’s set our objective. Since we already have a model, we need to find a way for us to interactively send inputs to it and get the predictions. Not only that, we want this application to be accessible to anyone, not just ourselves.</p><p><strong>Train, Save, and Upload Model</strong></p><p>I would be using the MNIST training code provided by PyTorch. You can check out the complete code in my <a href="https://github.com/stephenllh/mnist-mlops">repo</a>. After training the model, we save it as a .pt file.</p><p>We then upload the model to cloud storage. There are a lot of options available. Cloud services like Google Drive and Dropbox work, even though they lean towards general usage. All we need to do is get a download link to the storage file. For more professional uses, there are Amazon S3, Google Cloud Storage, and Azure Blob Storage. These cloud storages have their own API to upload and retrieve stored files.</p><p>I will be using the GitHub Release. GitHub Release is a feature that allows us to package software. We can use it as a free storage for our models. There is no need to worry about storage limit, as we can upload our models as long as each file is under 2 GB.</p><p><strong>Create a Streamlit App</strong></p><p><a href="https://streamlit.io/">Streamlit</a> is an application framework that makes it easy for us to create powerful user interfaces that interact with machine learning models. For our case, we want to create an app that allows us to draw a number and let the model predict what the number is. The complete code can be found <a href="https://github.com/stephenllh/mnist-mlops/blob/main/streamlit/st_app.py">here</a>.</p><p>To see this in action locally, we just have to run this on the terminal:</p><pre>streamlit run streamlit/app.py</pre><p>We will see something like this on the terminal. Copy and paste the local URL to the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*17bXs0qbPXbdPF9OExlN4g.png" /></figure><p>A webpage will load. At first, we will see a black box. That is for us to draw. Anything we draw will be converted into an image and sent to the model. Let’s try to draw a number 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*E1aQKjO4UGCti8Rz2SB2mw.png" /></figure><p>It works! After we ensure that it works on our local machine, let’s try to deploy it on a remote server.</p><p><strong>Deploy to Heroku</strong></p><p><a href="https://www.heroku.com/">Heroku</a> is a Platform as a Service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud. You need to have a Heroku account before you continue. At this point, it is also assumed that you have pushed everything to your GitHub repo. Or, you can fork my <a href="https://github.com/stephenllh/mnist-mlops">repository</a> and try it out on your own.</p><p>Heroku offers three deployment methods. We are going to use the second option, in which we connect our GitHub repository to Heroku.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ug2Pgf-P8fafVRPxLPiBRQ.png" /></figure><p>We can choose to automatically deploy our app whenever the branch we choose to deploy is updated. My suggestion is to turn this off until we get everything right. Instead, we use the manual deployment option below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfTCOf4ecyQ3FuWkeVE8Eg.png" /></figure><p>Cool! We have successfully deployed a model on a serverless platform which anyone can play around with. And we did this without spending anything! Although I used an MNIST model as a toy example, the principle is the same for other models! All you have to do is ensure that your model loads properly, then you tweak the prediction function to suit your needs.</p><p><strong>We can do better than this …</strong></p><p>If you only want to learn about model deployment, you can stop right here. We have achieved our goal: upload our model to a remote server, create a user interface that allows anyone to enter model inputs, and finally, output the model prediction.</p><p>But we can go further. Consider this …</p><p>What if there is a bug in the code? Sure, it does not show up when we deploy the model. But it can come back to haunt us, especially if this is a long-term project. So, we want to create some sort of code test to catch any hidden bugs in our code.</p><p><strong>Testing your code</strong></p><p>The Python module, pytest works well for this purpose. There are a lot of things we can do with pytest, and I am going to show you one example.</p><pre>def test_net(net):<br>    BATCH_SIZE = 2<br>    x = torch.zeros(BATCH_SIZE, 1, 28, 28)<br>    out = net(x)<br>    assert out.shape == (BATCH_SIZE, 10)</pre><p>This is a simple test for the model. Here we want to test if the output is what we expect to be (BATCH_SIZE, 10). To start the test, just type pytest on the terminal. (<em>Note: you might need to configure pytest. For reference, see the “pyproject.toml” file in my repo.)</em></p><p>The test will pass if the assert passes, and vice versa. You will see something like this if the test passes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qm1qIjTKUXmA-HEOPtsHSQ.png" /><figcaption>All 2 tests have passed.</figcaption></figure><p>If not, you see red indicators instead of green, and it will show you where it fails.</p><p>You can test for anything you want, as long as you can clearly define the inputs and their expected outputs. Because of this, it is ideal to structure your code into functions and classes that serve a singular purpose, so that they are easy to test. (This is also consistent with the <em>Single Responsibility Principle</em>, one of the design principles of Python.)</p><p>In this testing script, I have only included a limited number of tests that don’t cover all of the codes available. Please feel free to add in more tests (this might require you to restructure the code for some features to be testable, but try it out!)</p><p><strong>Makefile</strong></p><p>This is more like a quality of life. Basically, the purpose of this file is providing shortcuts for shell commands we will need to execute. For example, if I want to install the packages, I will need to type these:</p><pre>pip install — upgrade pip<br>pip install -r requirements.txt</pre><p>But with Makefile, we can do something like this:</p><p>make install</p><p>And the two shell commands will run all the same. Isn’t it convenient? Feel free to be creative and add whatever shortcuts you need.</p><p><strong>GitHub Actions</strong></p><p>This feature provided by GitHub can streamline our development process by ensuring our code works on a different machine than ours. To use GitHub Actions, we need to prepare a <a href="https://github.com/stephenllh/mnist-mlops/blob/main/.github/workflows/python_ubuntu_ci.yml">YAML</a> file and put it inside “.github/workflows” folder. Below is an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bb021eeb745768d38b7c02437c6f536/href">https://medium.com/media/8bb021eeb745768d38b7c02437c6f536/href</a></iframe><p>In this case, we have specified GitHub Actions to establish a workflow. When we push to the “beta” branch (I’ll explain later why it’s not “main” or “master”), the following actions will be triggered:</p><ol><li>Create a virtual environment that runs on the latest version of Ubuntu.</li><li>Setup Python of version 3.7.</li><li>Install dependencies, run tests, and run formatting via the make command. (I told you Makefile is convenient)</li></ol><p>When the workflow is running, we can monitor the process to see if each action passes or fails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*ebG4aa6rPkrage-uTD27dQ.png" /><figcaption>All actions passed in this build</figcaption></figure><p>We can also view all the previous workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0nZKo23ndMgfcEPe0cBmA.png" /><figcaption>All previously run workflows</figcaption></figure><p><strong>Git Branching</strong></p><p>You might notice that even if the build fails, the code is still pushed to our working branch. This is bad if automatic deployment is enabled for the main/master branch. So, the best practice is to never push directly to the main branch, but to another branch first. After we passed all the tests, only then we merge it to the main remote branch. This might be inconvenient especially if you are the sole contributor, but it ensures that no faulty code is deployed.</p><p>To create a new branch, simply type this command:</p><pre>git branch {branch-name}</pre><p>This will copy everything from your previous working branch to the new branch.</p><p>To create a remote branch of the same name and push to it:</p><pre>git push -u origin {branch-name}</pre><p>After each build passes, you will see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_Nl3QkzWKapLOEmJ-t1xw.png" /></figure><p>The “beta” branch is 1 commit ahead of the main branch because we have not merged it. To do so, we need to open a pull request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*qPk1akCSekqsjco2gR8pCw.png" /></figure><p>Optionally, you can leave any comment about the pull request. After that, you press the button “Create pull request”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8mkC8qLBJd1Oc-o06g3_dQ.png" /></figure><p>GitHub will tell you whether or not all checks have passed and there is no merge conflict. If so, you can safely merge the pull request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A8k8q5qkxFPTA009HrGsUQ.png" /></figure><p>Now, your main branch is up-to-date with the “beta” branch. If you have enabled Heroku’s automatic deployment feature, then your latest app will automatically be built.</p><p><strong>MLOps — The Best Practice for Machine Learning Production</strong></p><p>What we are doing here, so far, is applying a set of good practices of deploying and maintaining machine learning models. Whether you are aware or not, we have covered some of its components:</p><ol><li>Model registry: GitHub Releases allows us to upload models and update them if we need to. We can also assign tags to each model version for version control.</li><li>Continuous integration: GitHub Actions allows us to automate the testing and building of our app. By using the branching feature that Git provides, we ensure a smooth integration of the work from each contributor of the project.</li><li>Continuous delivery: Platforms like Heroku allows for an automated deployment whenever a new change is pushed to a specific branch.</li></ol><p>There are other components that I haven’t covered, such as data versioning and performance monitoring. Nonetheless, for a simple project like MNIST classification, what we have here is a good starting point.</p><p>I want to provide a tiny disclaimer here. The tools I have used might not be of the industrial standard. For instance, instead of Heroku, companies normally use Amazon Web Services or Google Cloud Platform.</p><p><strong>Conclusion</strong></p><p>Model deployment is an important skill to learn as we can create value with machine learning and showcase our work. In this tutorial, I show you how to serve a model on a remote server and how to automate the process. To automate this process, there are some good practices we can follow. For instance, create tests for our code, make use of GitHub actions to test our build, and Git branching. There are a lot of different tools out there to help us do the same thing, if not better, but I believe these fundamental skills can bring us far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51680f613eb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand Your Model’s Prediction with Grad-CAM]]></title>
            <link>https://heartbeat.comet.ml/understand-your-models-prediction-with-grad-cam-9f7c3b0f518c?source=rss-e9968809fb86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f7c3b0f518c</guid>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[model-interpretability]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[grad-cam]]></category>
            <dc:creator><![CDATA[Stephen Lau]]></dc:creator>
            <pubDate>Thu, 07 Apr 2022 13:34:32 GMT</pubDate>
            <atom:updated>2022-04-07T13:34:32.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning models have begun to infiltrate crucial industries such as health care, justice, and the financial sector. As a result, figuring out how the models make decisions and ensuring that the decision-making process is in line with ethnic or legal standards becomes a must.</p><p>Meanwhile, the rapid evolution of deep learning models increases the need for complex model interpretation. People are keen to fully utilize AI’s capabilities in essential facets of daily life. However, given that deep neural networks are created as black boxes, it is difficult to do so without sufficient faith in the models or an efficient mechanism to explain unexpected behavior.</p><p>Consider the following scenarios:</p><p>1. The financial industry is heavily regulated and loan issuers are expected by law to make reasonable judgments and explain their credit models when rejecting loan applications.</p><p>2. Medical diagnosis models are responsible for human life. How can we be sure we’ll be able to treat a patient according to a black-box model’s instructions?</p><p>3. When using a criminal decision model to forecast the likelihood of recidivism in court, we must ensure that the model is fair, honest, and nondiscriminatory.</p><p>4. Will we be comfortable enough to use self-driving cars in actual traffic on a broad scale if they suddenly act erratically, and we don’t know why?</p><p>Hence, it is not only important to create models that give an accurate prediction but also an explainable one so that we can be assured that the models make decisions that are based on valid reasoning.</p><h3>Can a computer vision model’s decisions be explained?</h3><p>In this article, we will narrow our scope to just a simple image classification model. Let’s first define our problem statement: Given a model that works reliably well, we want to know what makes the model make the prediction. In other words, we want to find out the model’s “thought process.”</p><p>Perhaps we can walk through the process ourselves. Take this image, for example. Can you guess what type of animal is in it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yurxJTTSlyd-IQf6.jpg" /></figure><p>You might point out that these are elephants without much hesitation. But<em> </em>can you explain how you arrive at that conclusion? It might be a bit weird to answer this question since it’s so apparent that these are elephants. But let’s try it anyway.</p><p>Well, you were asked what type of <em>animal</em> is in the picture. So, the two grey objects in the middle of the picture should be the focus, not the sky in the background and the green pasture. And you’re right that these objects are the animals we are interested in. You also noticed that they have a relatively large size, grayish color, long nose, and big ears. Based on your experience, they are likely elephants. There you go! This is exactly what we should expect from our model when we probe its “thought process.” Ideally, it should return the parts of the image that are responsible for the prediction it made.</p><h3>Visualizing what vision models learned</h3><p>As you might know, convolutional neural networks (CNNs) are the dominant model type in computer vision, ever since their remarkable achievement in the ImageNet Large Scale Visual Recognition Competition (ILSVRC) in 2012¹. Even though deep learning models like CNNs are generally considered “black boxes,” visualizing CNN layers is not a new technique. In 2013, Zeiler and Fergus already proposed a method that allows us to gain insight into what the CNN learns after training. Below are some examples from the paper regarding the feature maps of various layers in a pre-trained AlexNet model. They found that different layers learn different aspects of an image. Earlier layers are likely to learn simpler features such as edges and corners, whereas the latter layers learn the more complicated features that might sometimes resemble tiny images on their own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*osL9gnWUD0BQsSq-V2fXtA.png" /><figcaption>Visualization of feature maps of layer 1 and layer 2 of AlexNet</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*xj6U4h4_i6uMqBHb_JVHOQ.png" /><figcaption>Visualization of feature maps of layer 1 and layer 2 of AlexNet</figcaption></figure><p>From these findings, we know that it is possible to gain insight of what a computer vision model actually learns. This brings us closer to what we want, which is determining which part of the image is responsible for the prediction.</p><h3>Grad-CAM</h3><p>Remember that this model is pre-trained on ImageNet, an image dataset with 1000 different classes. How do we obtain the activations that are responsible for the prediction of one particular class?</p><p>Let me introduce you to the Gradient-Weighted Class Activation Mapping (Grad-CAM) algorithm². Grad-CAM proposes to use the gradients that are backpropagated from the prediction layer all the way to the activations we are interested in. We typically choose the last convolutional layers to have the best compromise between high-level semantics and detailed spatial information. Perhaps the figure below will illustrate better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0btrKYK6zAXduzqnWcXCw.png" /><figcaption>A simplified illustration of Grad-CAM</figcaption></figure><p>The figure above shows a simplified illustration of Grad-CAM. In this example, an image is passed through a CNN, which consists of multiple convolutional layers. After the final convolutional layer, a global average pooling (denoted by “GAP” in the figure) is applied to the tensor. The final layer is a vector that denotes the probability of each possible class. The bolded node is the class we are interested in.</p><p>Grad-CAM works like this: We obtain the gradient with respect to the class we are interested in (most of the time, we want the class predicted by the model). This is denoted by the symbol “dy/dw.” Then we multiply this gradient to the each feature map before it is globally pooled (shown in the figure as the colored rectangles).</p><blockquote>Isolating difficult data samples? Comet can do that. <a href="https://www.comet.ml/site/debugging-your-machine-learning-models-with-comet-artifacts/">Learn more with our PetCam scenario and discover Comet Artifacts.</a></blockquote><h3>TensorFlow implementation</h3><p>The complete code can be found in this official Keras <a href="https://keras.io/examples/vision/grad_cam/">tutorial</a>. This article only focuses on the Grad-CAM implementation. First, we create a Keras Model that maps the input image to both the activations of the last convolutional layer and the output predictions. This model can be any of Tensorflow’s pre-trained model, such as the Xception network. The relevant code snippet is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57d14b03f48891d0633b19c27b8b14ff/href">https://medium.com/media/57d14b03f48891d0633b19c27b8b14ff/href</a></iframe><p>Then, we compute the gradient of the class with the highest probability for our input image (which corresponds to “African elephant,” one of the classes in the ImageNet dataset) with respect to the activations of the last convolutional layer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6f8821d2f1329dd5651b851b76d6554/href">https://medium.com/media/e6f8821d2f1329dd5651b851b76d6554/href</a></iframe><p>Then, we obtain a 1-dimensional vector where each entry is the mean intensity of the gradient over a specific feature map channel. It means “how important this channel is” with regard to the top predicted class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/393615ca972f28a6c1220f5b288d4af0/href">https://medium.com/media/393615ca972f28a6c1220f5b288d4af0/href</a></iframe><p>We then multiply each channel in the feature map array by this vector, then sum all the channels to obtain the heatmap class activation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d57ec869bb9a3ca06ba035d1252f65a/href">https://medium.com/media/6d57ec869bb9a3ca06ba035d1252f65a/href</a></iframe><p>The complete TensorFlow implementation for Grad-CAM:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/865aa94f34797b79552af13b78746b1f/href">https://medium.com/media/865aa94f34797b79552af13b78746b1f/href</a></iframe><p>When we overlay the heatmap to the image, we get this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y_ttQLUePYO9xz2d.jpg" /></figure><p>We obtained a colored heatmap that indicates that the model indeed detects the elephants as those regions have the highest heatmap intensities.</p><h3>Why does it matter?</h3><p>Trying to rationalize the model’s decision is important because the model can make the correct prediction while being wrong about why. This <a href="https://arxiv.org/abs/1602.04938">paper</a>³ titled “‘Why Should I Trust You?’ — Explaining the Predictions of Any Classifier” shows us an excellent example through one of their experiments.</p><p>First, the researchers collected an image dataset of wolves and huskies. The images were hand-selected such that all pictures of wolves had snow in the background, while images of huskies did not. Then, these images were used to fine-tune a pre-trained Inception network. When they analyzed the feature maps of the first max-pooling layer of the trained model, they realized that the model classified the animals correctly during training but for the wrong reasons. Take a look at one example shown in the paper, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*89cxV0n594Yy3O_-61rg2A.png" /><figcaption>Figure reproduced from the paper.</figcaption></figure><p>This picture of a husky was wrongly classified as a wolf. The model explanation: the image has snow in it. This is not too surprising because all wolf images in the training dataset have snow in the background, so the model is inclined to correlate the presence of snow to a wolf. Although the researchers designed this experiment to train a bad classifier on purpose, this finding shows that models cannot be fully trusted. We need to know how a model obtains the conclusion before considering using it to make important decisions.</p><h3>Conclusion</h3><p>In this article, we discussed the importance of model interpretability. For computer vision models, we can use Grad-CAM to understand the model’s decisions. This algorithm works by showing the degree to which each pixel of an image influences the model decision. This allows our model to have more interpretability and therefore gives more assurance when we make decisions based on the model’s prediction.</p><h3>References</h3><ol><li>Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. “Imagenet classification with deep convolutional neural networks.” <em>Advances in neural information processing systems</em> 25 (2012).</li><li>Selvaraju, Ramprasaath R., Michael Cogswell, Abhishek Das, Ramakrishna Vedantam, Devi Parikh, and Dhruv Batra. “Grad-cam: Visual explanations from deep networks via gradient-based localization.” In <em>Proceedings of the IEEE international conference on computer vision</em>, pp. 618–626. 2017.</li><li>Ribeiro, Marco Tulio, Sameer Singh, and Carlos Guestrin. “‘Why should I trust you?’ Explaining the predictions of any classifier.” In <em>Proceedings of the 22nd ACM SIGKDD international conference on knowledge discovery and data mining</em>, pp. 1135–1144. 2016.</li></ol><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f7c3b0f518c" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/understand-your-models-prediction-with-grad-cam-9f7c3b0f518c">Understand Your Model’s Prediction with Grad-CAM</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caption Your Images with a CNN-Transformer Hybrid Model]]></title>
            <link>https://heartbeat.comet.ml/caption-your-images-with-a-cnn-transformer-hybrid-model-a980f437da7b?source=rss-e9968809fb86------2</link>
            <guid isPermaLink="false">https://medium.com/p/a980f437da7b</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[image-captioning]]></category>
            <category><![CDATA[heartbeat]]></category>
            <dc:creator><![CDATA[Stephen Lau]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 14:19:05 GMT</pubDate>
            <atom:updated>2022-02-15T14:19:05.712Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say we have an image and we want to give it a suitable description. This task is known as image captioning and is by no means an easy one. To see why that is the case, let’s look at the picture below and try to give it a suitable caption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ypLOudamW8wPQ1kI.jpg" /><figcaption>Source: <a href="https://www.earth.com/news/kids-playing-indoors-outdoors/">https://www.earth.com/news/kids-playing-indoors-outdoors/</a></figcaption></figure><p>Done? The caption you gave actually does not matter, but the process in which your brain goes through is the one we are more interested in.</p><p>Most likely, when you see this image, your brain needs to identify certain key features in the image such as “kids,” “playing,” “ball,” and “grass.” You might even identify subtle things like the emotions of the kids and what they are wearing. Then, your brain needs to somehow come up with a coherent sentence that combines all the visual information it captures.</p><p>For example, the sentence will be something like “There are four kids playing soccer in the grass field.” Since our brain is so good at doing this, it likely takes us mere seconds to do so. With training, we can even produce fancier sentences that better describe this picture.</p><p>However, this is not easy for computer models. After all, deep learning models are just a bunch of numbers in the form of matrices and high-dimensional tensors. We might take our ability to quickly and accurately process visual and textual information for granted, but we need to remember that our brain is a result of millions of years of the evolutionary process, whereas computer models do not have that luxury.</p><p>However, there is one thing that computer models can do better than us: they can do things faster. We can create a computer model in such a way that it mimics how a human brain would likely to tackle this task: extract visual information from the image before generating a coherent text sentence out of it.</p><p>To do that, we can combine a model that excels in image recognition and another that is designed for text generation. There are plenty of research papers that propose methods in line with this framework. For instance, this paper¹ proposes to use an object detector to draw regions of an image, then caption each region separately. Later on, people² ³ realized that the convolutional layers of a convolutional neural network (CNN) can be used to derive the semantic features for the visual attention that is used later in the text generation process.</p><p>The development of the text generation model is rather straightforward as we typically just use the state-of-the-art approach in natural language processing. For instance, the Transformer model and its variant such as GPT are the best at text generation so far. This paper⁴ is one that proposed a method in line with this idea.</p><h3>CNN-Transformer</h3><p>In a nutshell, one way to get a good image captioning model is by combining a convolutional neural network (CNN) and a Transformer network. To explain why this works, we need to first understand the original motivation of the Transformer architecture. The Transformer is originally designed for machine translation, i.e. translating sentences from one language into another. To achieve this, it has an encoder that handles the inputs of the source language, and a decoder that handles the generation of sentences in the target language. For more details, please refer to the original <a href="https://arxiv.org/abs/1706.03762">paper</a>.</p><p>We can borrow the idea of machine translation for image captioning. We can frame the problem from “translating a sentence from language X to language Y” into “translating an image into a sentence.” We know that image data can be well represented by CNNs, so we just need to replace the Transformer encoder with a CNN. The figure below illustrates the overall architecture of our model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*W4knw57_Nx4_G4CDCrjLrQ.png" /><figcaption>The architecture for our image captioning model</figcaption></figure><p>This is the approach we are going to use: replace the encoder part of the Transformer with a CNN backbone. The input is the image that we send into the CNN. The text generation part can be handled by a Transformer decoder, which is able to generate the next word of a sentence sequentially, provided that we feed it the previous part of the sentence.</p><p>However, different from recurrent neural networks where we send the words of a sentence one by one into the model, here we send the whole sentence to the decoder altogether. Using this figure as an example, the input sent to the decoder consists of the tokens that make up &lt;bos&gt; this is a corgi .and the model is expected to output this is a corgi . &lt;eos&gt; . To summarize, this model architecture actually has two different sources of input: one is the image we want to caption, and the other one is the very sentence that we want it to generate, but shifted one word to the left.</p><p>I am going to show you how to implement it using PyTorch. The full code is available in my <a href="https://github.com/stephenllh/image-captioning-transformer">repo</a>.</p><h3>Data Processing</h3><h4>Download data</h4><p>We can use the Flickr dataset that contains images with their respective captions. We can download the dataset from this <a href="https://github.com/jbrownlee/Datasets/releases/">link</a>. There are 8091 images in total and each of them has 5 text captions. Let’s look at an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*LO2YGullmHu-iFUtVWL_EA.jpeg" /><figcaption>An image from the Flickr dataset</figcaption></figure><p>The given text captions are:</p><ol><li>A child in a pink dress is climbing up a set of stairs in an entry way.</li><li>A girl going into a wooden building.</li><li>A little girl climbing into a wooden playhouse.</li><li>A little girl climbing the stairs to her playhouse.</li><li>A little girl in a pink dress going into a wooden cabin.</li></ol><h4>Creating the caption data</h4><p>All captions in the .txt file are loaded and we create a dictionary that maps each filename to its captions. We also need to tokenize every word in the captions. This is done by gathering all unique words using collections.Counter. After that, we convert every word into their respective tokens using the get_tokenizer function from the torchtext.data.utils module.</p><p>Then, we use torchtext.vocab.vocab to create a vocabulary object from the dictionary we just created using the collections.Counter module. By the way, we also need to insert four special tokens with their special indices:</p><ol><li>&lt;unk&gt; : The “unknown” token. This is for the case where any word not in the vocab is encountered (especially during inference). Its index is 0.</li><li>&lt;pad&gt; : The padding token. These tokens are added at the end of a sentence that is shorter than the maximum allowed length. Its index is 1.</li><li>&lt;bos&gt; : Stands for the beginning of a sentence. Added before the first word token in a sentence. Its index is 2.</li><li>&lt;eos&gt;: Stands for the end of a sentence. Added before the last word token in a sentence. Its index is 3.</li></ol><p>Here, the dictionary is output as a Pandas Dataframe for the ease of visualization and debugging, but it is optional.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5e0fc8bf8e19ef3c6f8cd7e533a6e08/href">https://medium.com/media/f5e0fc8bf8e19ef3c6f8cd7e533a6e08/href</a></iframe><h4>PyTorch Dataset</h4><p>We now create a PyTorch Dataset that outputs an image and its respective captions when given an index. First, we initialize the attributes that will be used later, such as the dataframe, tokenizer, torchtext vocab object, the maximum sequence length, and the image transforms (using the albumentations library).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ddc5ff69b1e080db0f05fbf143768ae/href">https://medium.com/media/9ddc5ff69b1e080db0f05fbf143768ae/href</a></iframe><p>Next, in the __getitem__ method, we open each image with cv2 after retrieving the filename from the dataframe we saved as an attribute before. We then use apply the transforms defined before to the image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1afceaa69383b6b6e8ee760ec4290b51/href">https://medium.com/media/1afceaa69383b6b6e8ee760ec4290b51/href</a></iframe><p>We first define the sequence length. Any sentences shorter than that are padded with the pad token, and any sentences longer are truncated. The value is set to 20. We also need to prepare the attention masks, which are related to how the sentences are padded.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cb294c0bfaaee5015d008e1d692d73c/href">https://medium.com/media/2cb294c0bfaaee5015d008e1d692d73c/href</a></iframe><p>The Transformer decoder accepts sentence inputs of a fixed sequence length. Hence, we need to pad the sentences that are shorter than that. We can do that by simply assigning the logical True to the position that we need to mask, and False if otherwise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d9df8714a34ec2e48848b86f27117dd/href">https://medium.com/media/0d9df8714a34ec2e48848b86f27117dd/href</a></iframe><p>Finally, we return a dictionary that has 4 keys: the image, the arrays of tokens, the captions (for visualization), and the attention masks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db828e92a5b3487d9c94d3019d7f3489/href">https://medium.com/media/db828e92a5b3487d9c94d3019d7f3489/href</a></iframe><blockquote>Want to get the most up-to-date news on all things Deep Learning? <a href="https://www.deeplearningweekly.com/about">Subscribe to Deep Learning Weekly</a> for the latest research, resources, and industry news, delivered to your inbox.</blockquote><h3>Model</h3><h4>Init — Encoder</h4><p>For the encoder, we use a pretrained CNN model to output a reasonable representation of the input image. I used a pretrained EfficientNet-B0 backbone provided by the timm library since the EfficientNet models are fairly strong baselines. Feel free to test out with the other variants of EfficientNet models that are larger, or even other CNN models. The final pooling layer and linear classifier layer are replaced with a linear layer with an output dimension of d_model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a09ecad8710634d55308e55da869fd5/href">https://medium.com/media/4a09ecad8710634d55308e55da869fd5/href</a></iframe><h4>Init — Decoder</h4><p>Next, we implement the Transformer decoder. You can use libraries like HuggingFace to simplify the model building process, but here I want to show you what happens underneath the hood. (Yes, this is secretly a Transformer tutorial.)</p><p>First, we add an nn.Embedding layer to map each unique token to its respective embedding vector. We add another nn.Embedding layer for the positional embeddings for each token in a sentence. Unlike the sinusoidal positional embedding implemented in the original Transformer, these embeddings are learnable instead.</p><p>PyTorch provides us with the implementation of each Transformer block. For this, we use the nn.TransformerDecoderLayer class which consists of a masked self-attention module, a cross attention module, and a layer normalization layer. We then connect multiple of these Transformer blocks before adding a linear layer at the end of the last Transformer block by passing the instance of the decoder layer and num_decoder_layers to the nn.TransformerDecoder class. The value of num_decoder_layers indicates the number of repeating Transformer decoder blocks, and is set to 1 here to create a smaller model, but feel free to try out different values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92512bc2fed75bad6246f39d99c77231/href">https://medium.com/media/92512bc2fed75bad6246f39d99c77231/href</a></iframe><h4>Forward pass</h4><p>In the forward pass, we need to provide it the image, caption, and the padding mask (a binary tensor where 1 denotes there is a “pad” token). Following the original implementation of Transformer, we multiply the token embeddings with the square root of the d_model. The output is added with the position embeddings. Then, the tensor is permuted to have a shape of (sequence, batch, embedding) .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c240a96a3b99d45689be8d6637f19c40/href">https://medium.com/media/c240a96a3b99d45689be8d6637f19c40/href</a></iframe><p>Then, we obtain the image feature tensor by passing the image to the pretrained EfficientNet-B0 model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0bf07d34e1081d1827922013519cc7d/href">https://medium.com/media/f0bf07d34e1081d1827922013519cc7d/href</a></iframe><p>The image feature tensor is then passed to a linear layer before being passed to the cross attention module in each Transformer block. Besides the image feature, we also need to pass the padding mask and another thing called “subsequent mask.” This is the mask that “pads” or “covers up” the future tokens to prevent the model from cheating by looking into the future. For instance, since we pass “&lt;bos&gt; this is a corgi” to the model, the part where the model should predict the next word after “&lt;bos&gt;” should have a subsequent mask that covers the tokens “this”, “is”, “a”, and “corgi”. The nn.Transformer class provides a static method called generate_square_subsequent_mask for this purpose. After that, we pass everything to the final linear layer that acts as a classifier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/348ecb30403cbfdc9251352dd4079665/href">https://medium.com/media/348ecb30403cbfdc9251352dd4079665/href</a></iframe><h4>Training</h4><p>I am going to use PyTorch Lightning for the training loop. By inheriting the LightningModule class from PyTorch Lightning, we can implement the training loop, validation loop, test loop, optimizer customization, metric logging, etc. I am going to show you the most important part of this article: the training loop.</p><p>From each batch of the dataloader, we obtain the image tensor, a list of 5 token arrays (for 5 different captions), and a list of 5 attention masks. Then, we iterate through each token array and its corresponding attention mask. In each iteration, we pass the image, token array, and the attention mask to the model. The loss function is then calculated using the caption predicted by the model and the caption that is shifted by one position to the left. Using our prior example, when we pass the corgi image and the tokenized caption of [‘&lt;bos&gt;’, ‘this’, ‘is’, ‘a’, ‘corgi’, ‘.’] , the caption that serves as the ground truth should be [‘this’, ‘is’, ‘a’, ‘corgi’, ‘.’, &lt;eos&gt;] , which matches what the model should predict.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eea8101427806b2df81f28132740955/href">https://medium.com/media/7eea8101427806b2df81f28132740955/href</a></iframe><h4>Prediction</h4><p>During prediction, we need to tweak the code slightly from the training script. This is because during the prediction stage, we do not have the ground truth for the generated tokens. Remember the example we saw in the beginning, where the tokens containing “&lt;bos&gt; this is a corgi .” are sent to the input and the expected generated tokens are “this is a corgi . &lt;eos&gt;”? During training, we can do this because we already have the ground truth: &lt;bos&gt; this is a corgi . &lt;eos&gt; , so we can just send the whole sentence (bar the last &lt;eos&gt; token) into the model, and the model is trained using teacher forcing and will output the tokens autoregressively.</p><p>However, for prediction on images without ground truth, we need to create our own “ground truth” for the prediction of next token. For example, when we send the corgi image into the encoder, we first send the &lt;bos&gt; token into the decoder. We keep the maximum sentence length, so the rest of the sentence is padded. The model will ideally output the this token. We then add this predicted token to the input just now to make it &lt;bos&gt; this . The process is repeated until the model decides to output the &lt;eos&gt; token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76e96198efaee0f368fac44977408b5e/href">https://medium.com/media/76e96198efaee0f368fac44977408b5e/href</a></iframe><h3>Results</h3><p>I served my trained model on Heroku, which you can access from this <a href="https://image-captioning-transformer.herokuapp.com/">website</a>. Here I will show you a few of my (totally not cherry-picked) examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*fIdU8AH8o0cuKPMPJ-CL4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*-KkHtpz_whgUkfXjvBQMsg.png" /></figure><p>They look pretty decent for me. Granted that the captions are not perfect, the model still manages to capture the gist of the images. With a better dataset and a larger model, the performance will surely improve.</p><h3>Conclusion</h3><p>Image captioning algorithms can be used in various applications. One good example in my opinion is a visual aid for blind people. Ideally, this technology can help them describe everything around them. Besides, content creators might find this tool useful to generate ideas for their catchy captions. In general, I think the combination of image and text has a lot of potential. What other applications can you think of? Feel free to share it in the comments.</p><h3>References</h3><ol><li>A. Karpathy and L. Fei-Fei. Deep visual-semantic alignments for generating image descriptions. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 3128–3137, 2015.</li><li>K. Xu, J. Ba, R. Kiros, K. Cho, A. Courville, R. Salakhudinov, R. Zemel, and Y. Bengio. Show, attend and tell: Neural image caption generation with visual attention. In International Conference on Machine Learning, pages 2048–2057, 2015.</li><li>Q. You, H. Jin, Z. Wang, C. Fang, and J. Luo. Image captioning with semantic attention. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pages 4651–4659, 2016.</li><li>S. Herdade, A. Kappeler, K. Boakye, J. Soares. Image captioning: Transforming objects into words. In Proceedings of the Neural Information Processing Systems. 2019.</li></ol><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a980f437da7b" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/caption-your-images-with-a-cnn-transformer-hybrid-model-a980f437da7b">Caption Your Images with a CNN-Transformer Hybrid Model</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Brain Tumor Diagnosis with Computer Vision]]></title>
            <link>https://heartbeat.comet.ml/brain-tumor-diagnosis-with-computer-vision-f7b17bb8eda8?source=rss-e9968809fb86------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7b17bb8eda8</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[heartbeat]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Stephen Lau]]></dc:creator>
            <pubDate>Tue, 11 Jan 2022 15:33:05 GMT</pubDate>
            <atom:updated>2022-01-11T15:33:05.115Z</atom:updated>
            <content:encoded><![CDATA[<p>Conventionally, doctors use magnetic resonance imaging (MRI) scans to help with the diagnosis of various medical conditions such as cancer. However, in certain cases, accurate diagnosis cannot be performed based on the images alone. For instance, glioblastoma, the most common form of brain cancer, has an analysis procedure that involves the extraction of a tissue sample from the patient through surgery. Moreover, the characterization of the tumor can take weeks. So, a computer-aided solution is welcome to aid doctors in not only producing more accurate diagnoses but providing them at a faster rate.</p><p>Deep learning has been successful in solving computer vision problems. This method has been extended to the medical field. In this article, I will show you how to build a classifier that predicts the presence of a tumor from MRI scans. I will be using the data from the RSNA-MICCAI Brain Tumor Radiogenomic Classification competition hosted by Kaggle. For the implementation, I will be referencing the top solution of the competition, which can be found in this <a href="https://github.com/FirasBaba/rsna-resnet10">repository</a>.</p><h3><strong>Understanding the Data</strong></h3><p>We are given a training dataset with a folder structure of this:</p><pre>train<br>|---00000<br>    |---FLAIR<br>        |Image-1.dcm<br>        |Image-1.dcm<br>        |...<br>    |---T1w<br>    |---T1wCE<br>    |---T2w<br>|---00001<br>|---00002<br>|---...</pre><p>This means that for each patient ID (such as “00000”), we are given 4 different cases or scans obtained from different pulse sequences. In each case, there are DICOM files that have a format of .dcm . From the additional CSV file provided to us, each patient ID is mapped to a binary value that signifies the presence of the brain tumor.</p><h4>DICOM files</h4><p>DICOM stands for “Digital Imaging and Communications in Medicine.” It is a standard, internationally accepted format to view, store, retrieve, and share medical images. Typically, a special medical DICOM viewer needs to be installed to access DICOM files. Luckily, we can use the PyDicom package that allows us to read the files in Python. We can do this using the read_file function:</p><pre>dicom = pydicom.read_file(path)</pre><p>If we print out the dicom object, we will be shown the metadata. Some elements of the metadata are useful for understanding the data we are dealing with. Let’s inspect them.</p><h4>Metadata</h4><p><strong>Rows and columns</strong>: These parameters define the image size. Their values are both 512. So, each image size has a size of 512 pixels by 512 pixels.</p><p><strong>Samples per pixel</strong>: Defines the number of color channels. The value of 1 here means the image is grayscale.</p><p><strong>Photometric interpretation</strong>: The value is “MONOCHROME2,” meaning the image is grayscale and a pixel value of 0 indicates a black pixel. This is the opposite of “MONOCHROME1,” where a pixel value of 0 indicates a white pixel. Hence, knowing the value of this metadata is important, or it will affect our image processing.</p><p><strong>Pixel spacing</strong>: Indicates the physical distance between the centers of each pixel in mm. The value shown is [0.5, 0.5], which means the physical distances between each pixel in both x and y directions are both 0.5 mm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74MLbOEBHe1GzUih2e66UA.png" /><figcaption>A sample image extracted from a DICOM file</figcaption></figure><p>Let’s apply this piece of information to one of the brain slices. Referring to the figure above, the maximum length across the brain slice is approximately 200 pixels, which translates to 200 x 0.5 mm = 100 mm = 10 cm. The length of 10 cm makes sense for a normal brain size.</p><p><strong>Series description</strong>: For each patient, we are provided with 4 different folders of DICOM files, namely “FLAIR,” “T1w,” “T1wCE,” and “T2W.” These are scans obtained using different MRI<strong> </strong>pulse sequences. An MRI pulse sequence is a programmed set of changing magnetic gradients. Each sequence is defined by multiple parameters, such as time to echo (TE), time to repetition (TR), inversion pulse, and diffusion weighting. Different combinations of these parameters affect tissue contrast and spatial resolution. We can make use of this piece of information to decide what to do with the data. We can choose to include every pulse sequence in a single dataset, or train the model separately on different pulse sequences.</p><p><strong>Bits allocated</strong>: Defines the amount of space allocated for every sample in bits. Not all allocated bits are used to define the pixel value. Hence, the bits stored (0028,0101) can be fewer than the bits allocated. In our case, they are both 16 bits. This means it has a pixel range of 2¹⁶ = 65536. However, the 8-bit monitor which we typically use can only display 256 shades of gray. What radiologists normally do is <em>windowing</em>. Windowing allows us to view the part of the brain that is more relevant for diagnosis. By adjusting two parameters called the window center and window width, we are able to accentuate the appearance of different components of the brain, such as bone, soft tissues, water, fat, lung, and air.</p><p><strong>Window center</strong> and <strong>window width</strong>: This is for the purpose of windowing. For instance, if the window center and window width are 71 and 142, respectively, then:</p><ul><li>The lowest visible pixel value = 71 -(142/2) = 0</li><li>The highest visible pixel value = 71-(142/2) =142</li></ul><p>The pixel values between 0 and 142 are displayed as-is. Any pixel value below 0 will show up as black, whereas any pixel value above 142 will show up as white.</p><p><strong>Patient orientation</strong>: It is [1, 0, 0, 0, 0, -1] for every file. It should be read as two separate vectors: [1, 0, 0] and [0, 0, -1], which represent x-axis and the negative z-axis, respectively. The coordinate system and the directions of XYZ axes are illustrated in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7xsPTmd7MF3bTD4J7O9XQ.png" /><figcaption>The convention of the coordinate system</figcaption></figure><p>Let us compare the image position of the first and the last DICOM file of the patient with the ID “00000.”</p><p>Image position of the first DICOM file: [-125.094, 90.3865, 127.74]</p><p>Image position of the last DICOM file: [-125.094, -137.013, 127.74]</p><p>The y-coordinate value decreases while the other two coordinates remain the same. According to the coordinate system defined by DICOM, it implies that the scans were performed along the y-axis from the back of the head to the front of the head. To further confirm this, let us analyze the orientation of each DICOM image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ou4JJasjSD4cfUGxTOlhcQ.png" /></figure><p>From the coordinate system above, we can infer that we are viewing the brain image from the patient’s front, with the forehead facing us.</p><blockquote>The most important thing to keep in mind when building and deploying your model? Understanding your end-goal. <a href="https://www.comet.ml/site/industry-qa-where-most-machine-learning-projects-fail/">Read our interview with ML experts from Stanford, Google, and HuggingFace to learn more</a>.</blockquote><h3><strong>Data Processing</strong></h3><p>We now understand the data we are given. For each patient, each DICOM file contains an image of a cross-section of the brain taken from the posterior to the anterior. We can combine these images into a 3-dimensional array structure that represents a brain before sending it to the model to output a binary prediction of whether or not the tumor exists.</p><p>Read a DICOM file and extract the image array. Then, we can choose to apply windowing using the apply_voi_lut function provided in the PyDicom package.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d012307f89d035a9bf018464fe8c1a3b/href">https://medium.com/media/d012307f89d035a9bf018464fe8c1a3b/href</a></iframe><p>Let us inspect some of the images. What we are seeing here are cross-sections (slices) of a brain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*mGeFc3XHUtnlvq-sgCx1tw.png" /><figcaption>Samples of the brain slices</figcaption></figure><p>We then create a PyTorch Dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3df0436406efc4a4efc2a1595ad0bda/href">https://medium.com/media/d3df0436406efc4a4efc2a1595ad0bda/href</a></iframe><p>Now, there is a slight problem with creating a 3-dimensional representation of the image. First of all, the number of slices for every DICOM image is different. Besides, due to computation costs, we might need to limit the number of slices sent to the model.</p><p>One solution that is intuitive and straightforward is to select the middle <em>n</em> number of slices. However, this might not be the ideal solution. This is because the middle slice might not be the exact center of the brain. The solution author offered a better solution: obtain the slice that has the largest brain area, then grab the (n-1)/2 slices before and after it. This solution assumes the slice with the largest brain area is the center of the brain. According to the solution author, it did help him get better performance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b699eda41ff64a5e6d6b03494e40b71/href">https://medium.com/media/1b699eda41ff64a5e6d6b03494e40b71/href</a></iframe><h3><strong>Model</strong></h3><p>For 2D images, we use a 2-dimensional convolutional neural network as the deep learning model. This is no longer applicable in our case since our images are now represented in 3 spatial dimensions. Instead, we use a 3-dimensional convolutional neural network (3D CNN). The concept is similar to 2D CNNs, just that the kernel filter slides in 3 dimensions instead of 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*-sKYKuRHo2e6WgcT.png" /><figcaption>A simplistic overview of a 3D CNN</figcaption></figure><p>To create a 3D CNN, we are going to use the MONAI framework. MONAI is a freely available, community-supported, PyTorch-based framework for deep learning in healthcare imaging. It supports a lot of modules and utilities catered for this purpose. We can use a pre-trained model such as ResNet-10 using just one line of code:</p><pre>model = monai.networks.nets.resnet10(<br>    spatial_dims=3, n_input_channels=1, n_classes=1<br>)</pre><p>The model is trained similarly as one would with 2D CNNs. Since we have a binary classification problem, we can use binary cross-entropy loss. The training loop is similar to the one we normally use. The solution author used Adam as the optimizer with a learning rate of 1e-4. The scheduler is MultiStepLR , which decays the learning rate of each parameter group by gamma once the number of epoch reaches one of the milestones.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b66e3784458020c2d6684511a544221e/href">https://medium.com/media/b66e3784458020c2d6684511a544221e/href</a></iframe><p>This approach got the solution author top of the leaderboard, with an AUROC score of 0.62174. However, the solution author acknowledges that the leaderboard is rather noisy, and judging from the relatively low AUROC score (just slightly above 0.5), I believe that more data will help improve the performance.</p><h3>Conclusion</h3><p>In this article, we learned about DICOM files for medical images and how to interpret the metadata. By doing so, we understand how the data are obtained, and thus we are able to make informed decisions about how the data should be represented. In addition, we also learned about representing a 3-dimensional brain structure using a series of 2D images. By combining these techniques, we can certainly get at least a good baseline model for a classification task on MRI-based medical data.</p><p>However, this is by no means a replacement for actual doctors because deep learning models lack interpretability no matter how good they can be. Consider this, if a computer diagnoses you of brain cancer without telling you how it comes up with this prediction, how much will you trust its judgment? I certainly would be skeptical! Therefore, it might be wise for computer vision to act as a tool to further aid doctors’ diagnosis rather than work toward replacing them completely.</p><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7b17bb8eda8" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/brain-tumor-diagnosis-with-computer-vision-f7b17bb8eda8">Brain Tumor Diagnosis with Computer Vision</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Supervised Vision with Masked Autoencoder]]></title>
            <link>https://heartbeat.comet.ml/self-supervised-vision-with-masked-autoencoder-9e2372138142?source=rss-e9968809fb86------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2372138142</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[self-supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[heartbeat]]></category>
            <dc:creator><![CDATA[Stephen Lau]]></dc:creator>
            <pubDate>Thu, 09 Dec 2021 14:15:19 GMT</pubDate>
            <atom:updated>2021-12-09T16:42:33.931Z</atom:updated>
            <content:encoded><![CDATA[<p>Supervised learning is the conventional way of training machine learning models, which requires labels for every data observation. Data is relatively easy to collect, given how accessible everything is through the internet. For example, if we want to collect dog images, we can scrap photos from the web using just a script. But labeling is often the bottleneck that slows down the data collecting process.</p><p>What if we have a way of training machine learning models without going through the hassle of collecting labels? What if, instead, we extract labels from the same data we collected? This type of learning algorithm is known as <em>self-supervised learning</em>. This approach has worked well in natural language processing. One example is BERT¹, which Google has been using for their search engine since 2019. Unfortunately, the same could not be said for computer vision.</p><p>However, there might be a breakthrough in self-supervised vision. In their recent paper, He et al. from Facebook AI Research proposed a masked auto-encoder (MAE)² that follows the Vision Transformer (ViT)³ architecture. The authors claimed that their approach performed better on ImageNet than a Vision Transformer that was trained from scratch. In this article, we will dive into their approach and see how it can be implemented in code.</p><h3>Masked Autoencoder</h3><p>Like other self-supervised methods, MAE has a pretext task: reconstruct the missing patches in an image. An image is divided into patches with a portion masked out. The rest of the patches are converted into token embeddings via linear projection, similar to ViT. Then, a portion of the token embeddings is removed (masked out) before being sent to the encoder. After that, those masked token embeddings are all converted into the same mask embedding, before being appended to the encoder output according to their original position. After a linear projection, the encoder output, together with the mask embeddings, are sent to a decoder that predicts the pixel values of the masked patches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2detiL9GQmEYEyUTaYJoLA.png" /><figcaption>Masked autoencoder architecture for pretraining. Adapted from the MAE paper.</figcaption></figure><p>This stage is called <em>pretraining,</em> as the MAE model will be later used for downstream tasks, such as image classification. The performance of the model on pretext tasks is not crucial in self-supervision. The point of these tasks is to allow the model to learn an intermediate representation that is expected to contain good semantic meanings. After the pretraining stage, the decoder will be replaced by a multilayer perceptron (MLP) head or a linear layer, which acts as a classifier that outputs a prediction for the downstream tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YsV80gl4HliKRN5JgccROg.png" /><figcaption>MAE architecture for downstream tasks</figcaption></figure><h3>Model Architecture</h3><h4>Encoder</h4><p>The encoder is a ViT. It accepts an image with a tensor shape of (batch_size, RGB_channels, height, width). A patch embedding is obtained for each patch by performing a linear projection. This can be done with a 2D convolutional layer. The tensor is then flattened at the last dimension to become (batch_size, encoder_embed_dim, num_visible_patches). Transpose into a tensor with a shape of (batch_size, num_visible_patches, encoder_embed_dim).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93aee65e2266ddcf288395f3465b3936/href">https://medium.com/media/93aee65e2266ddcf288395f3465b3936/href</a></iframe><p>As mentioned in the original Transformer paper, the positional encoding adds information about the position of each patch. The authors use the “sine-cosine” version instead of learnable positional embeddings. This implementation below is the 1-D version.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e653c4230bb130c15148a2c707573ff/href">https://medium.com/media/6e653c4230bb130c15148a2c707573ff/href</a></iframe><p>Similar to Transformer, each block consists of norm layers, a multi-head attention module, and a feed-forward layer. The intermediate output shape is (batch_size, num_visible_patches, encoder_embed_dim). The code for the multi-head attention module is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce5816e7fbe60388c88b631375f5b6ea/href">https://medium.com/media/ce5816e7fbe60388c88b631375f5b6ea/href</a></iframe><p>The code for the Transformer block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c11ab0e67caa85feba230367c77ae9f/href">https://medium.com/media/3c11ab0e67caa85feba230367c77ae9f/href</a></iframe><p>This part is for fine-tuning only. The authors follow the ViT architecture which has a class token (patch) for classification. Hence, they added a dummy token. But they claimed that their method worked well without it, as they performed an average pooling on the other tokens. Here, I included the average pooling version of the implementation. After that, a linear layer is added as a classifier. The final tensor shape is (batch_size, num_classes).</p><blockquote>Want to get the most up-to-date news on all things Deep Learning? <a href="https://www.deeplearningweekly.com/about">Subscribe to Deep Learning Weekly</a> and get the latest news delivered right to your inbox.</blockquote><p>Putting it all together, the encoder is implemented as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59b1cefcebf2acc07a49f5ae55647e36/href">https://medium.com/media/59b1cefcebf2acc07a49f5ae55647e36/href</a></iframe><h4>Decoder</h4><p>Similar to the encoder, the decoder consists of a series of transformer blocks. At the end of the decoder, there is a classifier that consists of a norm layer and a feed-forward layer. The input tensor has a shape of batch_size, num_patches, decoder_embed_dim)whereas the final output tensor has a shape of (batch_size, num_patches, 3 * patch_size ** 2).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/058609ef2a9bdac4aedb7ba150155ba2/href">https://medium.com/media/058609ef2a9bdac4aedb7ba150155ba2/href</a></iframe><h4>Put Everything Together — MAE architecture</h4><p>The MAE is used for pretraining on masked images. First, the masked inputs are fed to the encoder. Then, they are passed to a feed-forward layer to change the embedding dimension to match the decoder. Before being passed to the decoder, the masked patches are inserted back. Position encoding is applied again to the full set of image patches, both visible and masked. In the paper, the authors unshuffle the list containing all the patches so that the masked patches are inserted correctly. This is not done here as it is not straightforward to implement on PyTorch. Instead, the positional encodings are shuffled accordingly before being added to the patches.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a97c463326115f6b7469b4785a5d9270/href">https://medium.com/media/a97c463326115f6b7469b4785a5d9270/href</a></iframe><h3>Training Procedure</h3><p>For self-supervised pretraining, the authors found that a simple pixel-wise mean absolute loss works well as the objective function. The dataset they used is the ImageNet-1K training set.</p><p>In the fine-tuning stage, the decoder is removed and the encoder is trained on the same dataset. The data is slightly different from pretraining as the encoder is now fed with the complete set of image patches (without masking). As a result, the number of patches now is different from the pretraining stage.</p><p>In case you wonder if the model used for pretraining can still be used in fine-tuning, the answer is yes. Allow me to explain. The encoder mainly consists of an attention module, a norm layer, and a feed-forward layer. To check if a change in the number of patches (the second dimension, index 1) affects the forward pass, we need to see the shape of the parameter tensors of each layer.</p><ul><li>The parameter in the norm layer has a shape of (batch, 1, encoder_embed_dim). It can broadcast along the patch dimension (index 1) during forward pass, so it does not depend on the size of the patch dimension.</li><li>The feed-forward layer has a weight matrix of a shape of (in_channels, out_channels)and a bias matrix of a shape of (out_channels,), both of which do not depend on the number of patches.</li><li>The attention module essentially performs a series of linear projections. So, for the same reason, the number of patches does not affect the shape of the parameter tensor.</li></ul><p>However, the number of patches in a batch still needs to be consistent due to how parallel processing allows data to be put in batches.</p><h3>Results</h3><p>Let’s look at the reconstruction images from the pretraining stage as reported in the original paper. It looks like MAE did a decent job at reconstructing images even when 80% of the pixels are masked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rohk0KZZSEYIwXng-NKYYg.png" /><figcaption>Example results on ImageNet validation images. From left to right: Masked image, reconstructed image, ground truth image. The masking ratio is 80%. Figure adapted from the paper.</figcaption></figure><p>MAE also performs well on fine-tuned downstream tasks, such as image classification on the ImageNet-1K dataset. The baseline that the authors used, ViT-Large, actually performed better when trained using MAE pretraining compared to the supervised manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrrjtzhtkPjZm3RMHUp4ag.png" /><figcaption>Benchmark results on ImageNet-1K. Table adapted from the paper.</figcaption></figure><p>The paper also included benchmark results of transfer learning experiments on downstream tasks and various ablation studies. I encourage you to take a look at the paper for more details.</p><h3>Discussion</h3><p>If you are familiar with BERT, you might notice the similarities between the approaches of BERT and MAE. In the pretraining of BERT, we mask out a portion of the text, and the model is tasked to predict them. Moreover, since we are now using a Transformer-based architecture, it would not be inappropriate to suggest that this approach is the BERT equivalent in vision.</p><p>However, the authors of the paper argued that such an approach predates BERT. For instance, past attempts on image self-supervision have used stacked denoising autoencoders and image inpainting as the pretext task. MAE itself also uses an autoencoder as the model and a pretext task similar to image inpainting.</p><p>If that is the case, what makes MAE work while previous works did not? I believe the key lies in the ViT architecture. In their paper, the authors mentioned that convolutional neural networks have a problem with integrating “indicators” such as mask tokens and positional embeddings into them, whereas ViT addresses this architectural gap. If that is the case, then we are seeing yet another idea developed in natural language processing successfully implemented in computer vision. Before that, it was the attention mechanism, then the Transformer concept was borrowed into computer vision in the form of Vision Transformers, and now the whole BERT pretraining process.</p><h3>Conclusion</h3><p>I am excited about what self-supervised vision has to offer in the future. Given how successful BERT is for natural language processing, I am tempted to think that a masked modeling approach like MAE will benefit computer vision. As I mentioned at the beginning of this post, image data is easy to obtain but labeling them can be time-consuming. With this approach, one can potentially scale up the pretraining process by curating a much larger dataset than ImageNet without worrying about the labeling. The potential is limitless. Whether we will witness another renaissance in computer vision, only time will tell.</p><h3>References</h3><ol><li>Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. BERT: Pretraining of deep bidirectional transformers for language understanding. In NAACL, 2019.</li><li>Kaiming He, Xinlei Chen, Saining Xie, Yanghao Li, Piotr Dollár, and Ross Girshick. Masked autoencoders are scalable vision learners. <em>arXiv:2111.06377</em>, 2021.</li><li>Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, and Neil Houlsby. An image is worth 16x16 words: Transformers for image recognition at scale. In ICLR, 2021.</li></ol><p><em>Editor’s Note: </em><a href="https://heartbeat.comet.ml/"><em>Heartbeat</em></a><em> is a contributor-driven online publication and community dedicated to providing premier educational resources for data science, machine learning, and deep learning practitioners. We’re committed to supporting and inspiring developers and engineers from all walks of life.</em></p><p><em>Editorially independent, Heartbeat is sponsored and published by </em><a href="http://comet.ml/?utm_campaign=heartbeat-statement&amp;utm_source=blog&amp;utm_medium=medium"><em>Comet</em></a><em>, an MLOps platform that enables data scientists &amp; ML teams to track, compare, explain, &amp; optimize their experiments. We pay our contributors, and we don’t sell ads.</em></p><p><em>If you’d like to contribute, head on over to our</em><a href="https://heartbeat.fritz.ai/call-for-contributors-october-2018-update-fee7f5b80f3e"><em> call for contributors</em></a><em>. You can also sign up to receive our weekly newsletters (</em><a href="https://www.deeplearningweekly.com/"><em>Deep Learning Weekly</em></a><em> and the </em><a href="https://info.comet.ml/newsletter-signup/"><em>Comet Newsletter</em></a><em>), join us on</em><a href="https://join.slack.com/t/fritz-ai-community/shared_invite/enQtNTY5NDM2MTQwMTgwLWU4ZDEwNTAxYWE2YjIxZDllMTcxMWE4MGFhNDk5Y2QwNTcxYzEyNWZmZWEwMzE4NTFkOWY2NTM0OGQwYjM5Y2U"><em> </em></a><a href="https://join.slack.com/t/cometml/shared_invite/zt-49v4zxxz-qHcTeyrMEzqZc5lQb9hgvw"><em>Slack</em></a><em>, and follow Comet on </em><a href="https://twitter.com/Cometml"><em>Twitter</em></a><em> and </em><a href="https://www.linkedin.com/company/comet-ml/"><em>LinkedIn</em></a><em> for resources, events, and much more that will help you build better ML models, faster.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2372138142" width="1" height="1" alt=""><hr><p><a href="https://heartbeat.comet.ml/self-supervised-vision-with-masked-autoencoder-9e2372138142">Self-Supervised Vision with Masked Autoencoder</a> was originally published in <a href="https://heartbeat.comet.ml/">Heartbeat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>