<?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 Ivan Panshin on Medium]]></title>
        <description><![CDATA[Stories by Ivan Panshin on Medium]]></description>
        <link>https://medium.com/@ivan-panshin?source=rss-6253d2421d72------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ltx30ToFgtVDxYCAIoh0Pg.png</url>
            <title>Stories by Ivan Panshin on Medium</title>
            <link>https://medium.com/@ivan-panshin?source=rss-6253d2421d72------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:38:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivan-panshin/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[How to use metric learning: embedding is all you need]]></title>
            <link>https://medium.com/data-science/how-to-use-metric-learning-embedding-is-all-you-need-f26e01597375?source=rss-6253d2421d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/f26e01597375</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[metric-learning]]></category>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ivan Panshin]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 17:42:57 GMT</pubDate>
            <atom:updated>2021-02-08T19:49:07.813Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>Find out what’s the difference between regular classification and metric learning, and try it for yourself with my implementation of Supervised Contrastive Loss in PyTorch</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*je2OhipTv-4Mpekb" /><figcaption><a href="https://unsplash.com/@writecodenow">Boitumelo Phetla</a> via unsplash</figcaption></figure><p>One of the most simplest and common tasks in machine learning is classification. For instance, in computer vision you want to be able to fine-tune the last layers of common convolutional neural networks (CNN) to correctly classify samples into some categories (classes). However, there are several fundamentally different ways to achieve that.</p><p>Metric learning is one of them, and today I would like to share with you how to correctly use it. In order to make things practical we’re going to look at <a href="https://arxiv.org/abs/2004.11362">Supervised Contrastive Learning</a> (SupCon), which is a part of Contrastive Learning, which, in turn, is a part of Metric Learning, but more on that later.</p><p>The <strong>complete code</strong> can be found in the <a href="https://github.com/ivanpanshin/SupCon-Framework">GitHub repo</a>.</p><h3>How classification is usually done</h3><p>Before we dive into metric learning, it’s actually a good idea to first understand how the task of classification is usually solved. One of the most important ideas of practical computer vision today is convolutional neural networks, and they consist of 2 parts: encoder and head (in this case — classifier).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*vJdb_TVhDGjrMg_X.png" /><figcaption><a href="https://neurohive.io/en/author/muneeb/">Hassan</a> via neurohive</figcaption></figure><p>First — you take an image and compute a set of features that captures the important qualities of that image. This is done using convolution and pooling operations (that’s why it’s called convolutional neural networks). After that — you unsqueeze those features into the single vector, and use a regular fully-connected neural network to perform the classification. In practice, you take some model (for example, ResNet, DenseNet, EfficientNet, etc) that is pretrained on a big dataset (like ImageNet), and fine-tune it on your task (either just the last layers, or the whole model).</p><p>However, there are several things to note here. First of all, <em>usually</em> you only care about the outputs of FC part of the network. That is, you take its outputs, and supply them to the loss function in order to keep the model learning. In order words, you don’t really care what happens in the middle of the network (for example, with features from the encoder). Second of all, <em>(again, usually)</em> you train this whole thing with some basic loss function like Cross-Entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/0*UHmue29pv_Zkek_E.png" /><figcaption><a href="https://medium.com/@skolluru?source=post_page-----29d89edfe200--------------------------------">Kolluru</a> via Medium</figcaption></figure><p>In order to gain a better intuition about this 2 step process (encoder + FC) you can think about it as follows: encoder maps an image into some high dimensional space (for example, in case of ResNet18 we’re talking about 512 dimensions, and for Resnet101– 2048). After that, the objective of FC is to draw a line between these dots that represent samples in order to map them to classes. And these 2 things are trained at the same time. So you’re trying to optimize features and “drawing the line in high dimensional space” jointly.</p><p>What’s wrong with that approach? Well, nothing, really. It actually works just fine. But it doesn’t mean that there isn’t another way.</p><h3>Metric Learning</h3><p>One of the most interesting ideas (at least personally for me) in the modern machine learning is called metric learning (or deep metric learning). In simple terms: what if, instead of going for the outputs of FC layer, we take a closer look at features that are generated by the encoder. What if we manage to optimize those features with some loss function, rather that the logits from the end of the network. And this is actually what metric learning is about: generating good features (embeddings) with an encoder.</p><p>But what does it mean — “good”? Well, if you think about it, in case of computer vision you want to have similar features for images that are similar, and very distinct features for images that are nothing alike.</p><h3>Supervised Contrastive Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*wcC-bdrTZoiSny_KnlcRNg.png" /><figcaption><a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Khosla%2C+P">Prannay Khosla</a> via arxiv</figcaption></figure><p>Okay, suppose in Metric Learning all we care about is good features. But what’s the deal with Supervised Contrastive Learning? To be honest, there is nothing that special about this specific approach. It’s just a fairly recent paper that proposed some nice tricks, and an interesting 2 step approach:</p><ol><li>Train a good encoder, that is capable of generating good features for images.</li><li>Freeze the encoder, add a FC layer, and train just that.</li></ol><p>You might be wondering what’s the difference with regular classifier training then. The difference is that in regular training you train encoder and FC at the same time. On the other hand, here, you first train a decent encoder, then freeze it (<em>don’t train anymore</em>), and train only FC. The intuition behind that logic is that if we manage to first generate really good features for images, it should be easy to optimize FC (whose objective, as we noted earlier, is to optimize the line that separates the samples).</p><h3>Details of the training process</h3><p>Let’s dig into the details of SupCon implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*feLJFQh9djzZvFQeCFheeQ.png" /><figcaption><a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Khosla%2C+P">Prannay Khosla</a> via arxiv</figcaption></figure><p>Before checking the training loop, one thing you should understand about SupCon is what model is being trained. That’s quite simple: encoder (like ResNet, DenseNet, EffNet, etc), but without regular FC layers for classification.</p><p>Instead of classification head, here we have a projection head. Projection head is a sequence of 2 FC layers that maps encoder features to a lower dimensional space (usually 128 dimensional, you can even see that value on the picture above). The reason for projection head is that it’s simply easier for model to learn with 128 carefully selected features rather than all several thousand features that come from the encoder.</p><p>All right, time to finally check the training loop.</p><ol><li>Construct a batch of N images. Unlike other Metric Learning approaches, you don’t need to care too much about the choice of those samples. Just take as many as you can, the rest will be handled by the loss.</li><li>Forward those images thought the network in pairs, where a pair is constructed as [<em>augmentation(image_i)</em>, <em>augmentation(image_i)</em>], get embeddings. Normalize them.</li><li>Take some image as an anchor. Find all the images of the same class in the batch. Use them as positive samples. Find all the images of difference classes. Use them as negative samples.</li><li>Apply SupCon loss to the normalized embeddings, making positive samples closer to each other, and at the same time — more apart from negative samples.</li><li>After the training is done, delete projection head, and add FC on top of encoder (just like in the regular classification training). Freeze the encoder, and fine-tune the FC.</li></ol><p>Several thing to keep in mind here. First, after the training is done, it’s more profitable to get rid of the projection head, and use features before it. Authors explain this fact due to the loss of information in the head, since we lower the embedding’s size. Second, the choice of augmentations is important. Authors propose a combination of cropping and color jittering. Third, Supcon deals with all the images in the batch at once (so, no need to construct pairs or triplets). And the more images are in the batch, the easier it is for model to learn (since SupCon has a quality of implicit positive and negative hard mining). Fourth, you can actually stop at step 4. Meaning that it’s possible to do classification just with embeddings, without any FC layers. In order to do that, compute embeddings for all the train samples. Then, at validation time, for each sample compute an embedding, compare it to every train embedding <em>(compare = cosine distance)</em>, take the most similar, take its class.</p><h3>PyTorch implementation</h3><p>There is actually a semi-official <a href="https://github.com/HobbitLong/SupContrast">implementation</a> of SupCon in PyTorch. Unfortunately, it contains very irritating hidden bugs. One of the most serious ones: the creator of the repo used his own implementations of ResNets, and due to some bugs in it, the batch size is twice lower than it can be with regular torchvision models. On top of that — the repo has no validation or visualizations, so you have no idea when to stop training. In my repo I fix all these issues, and add more tricks for a stable training.</p><p>To be more precise, in my implementation you have access to:</p><ol><li>Augmentations with <a href="https://github.com/albumentations-team/albumentations">albumentations</a></li><li>Yaml configs</li><li><a href="https://github.com/DmitryUlyanov/Multicore-TSNE">t-SNE</a> visualizations</li><li>2-step validation (for features before and after the projection head) using metrics like AMI, NMI, mAP, precision_at_1, etc <a href="https://github.com/KevinMusgrave/pytorch-metric-learning">PyTorch Metric Learning</a>.</li><li><a href="https://github.com/fadel/pytorch_ema">Exponential Moving Average</a> for a more stable training, and Stochastic Moving Average for a better generalization and just overall performance.</li><li>Automatic Mixed Precision training in order to be able to train with a bigger batch size (roughly by a factor of 2).</li><li>LabelSmoothing loss, and <a href="https://github.com/davidtvs/pytorch-lr-finder">LRFinder</a> for the second stage of the training (FC).</li><li>Support of <a href="https://github.com/rwightman/pytorch-image-models">timm models</a> and <a href="https://github.com/jettify/pytorch-optimizer">jettify optimizers</a></li><li>Fixing the seeds in order to make the training deterministic.</li><li>Saving weights based on validation, logs — to regular .txt files, as well as TensorBoard logs for future examination.</li></ol><p>From the box the repo has support for Cifar10, and Cifar100. However, it’s quite trivial to add your own datasets. In order to run the whole pipleline, do the following:</p><pre>python train.py --config_name configs/train/train_supcon_resnet18_cifar10_stage1.yml</pre><pre>python swa.py --config_name configs/train/swa_supcon_resnet18_cifar100_stage1.yml</pre><pre>python train.py --config_name configs/train/train_supcon_resnet18_cifar10_stage2.yml</pre><pre>python swa.py --config_name configs/train/swa_supcon_resnet18_cifar100_stage2.yml</pre><p>After that you can check t-SNE visualizations in the corresponding Jupyter notebook. For example, for Cifar10 and Cifar100 you can expect something as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*wy0fOFaapqTfyYeHfM56WA.png" /><figcaption>Cifar10 with t-SNE, validation and training (SupCon), Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*leYV6Nh-Xf8yTkyvF0h_ug.png" /><figcaption>Cifar10 with t-SNE, validation and training (Cross Entropy), Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*l7PyggBJ_sBOAqq3nC9uxA.png" /><figcaption>Cifar100 with t-SNE, validation and training (SupCon), Image by Author</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*8WIcbE8tA8W4y50XFE96Bw.png" /><figcaption>Cifar100 with t-SNE, validation and training (Cross Entropy), Image by Author</figcaption></figure><h3>Final thoughts</h3><p>Metric Learning is a very powerful thing. However, it’s been quite hard for me to reach the level of accuracy that regular CE/LabelSmoothing can provide. Moreover, it also may be computationally expensive and unstable during training. I tested SupCon and other metric losses on variety of tasks (classification, out of distribution predictions, generalization to new classes, etc), and the advantage of using something like SupCon is unclear.</p><p>Wait a minute, what’s the point then? I personally see 2 things here. First — SupCon (and other Metric Learning approaches) still can provide more structured clusters, than CE, since it directly optimizes that property. Second — it’s still very beneficial to have one more skill/tool that you might try. So it’s possible that with a better set of augmentations, or a different dataset (maybe with more fine-grained classes) SupCon can yield better results, not just on par with regular classification training.</p><p>So we just have to try and experiment. No free lunch, right?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f26e01597375" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-use-metric-learning-embedding-is-all-you-need-f26e01597375">How to use metric learning: embedding is all you need</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deploy ML models using Flask + Gunicorn + Nginx + Docker]]></title>
            <link>https://medium.com/data-science/how-to-deploy-ml-models-using-flask-gunicorn-nginx-docker-9b32055b3d0?source=rss-6253d2421d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b32055b3d0</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ivan Panshin]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 21:52:37 GMT</pubDate>
            <atom:updated>2020-04-30T21:52:37.986Z</atom:updated>
            <content:encoded><![CDATA[<h4>A template for configuring Flask + Gunicorn + Nginx + Docker with a detailed explanation, that should bring you a bit closer to working with microservices, building MVPs, and so on.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*No_PfHiKia5YW1Z2dpvFcw.jpeg" /><figcaption><a href="https://www.flickr.com/photos/appleboy/">Bo-Yi Wu</a> via flickr</figcaption></figure><p>It might be tricky to develop a good Machine Learning model, but even if one manages to do that, it’s still pretty much useless until you deploy it, so that other people can access it.</p><p>There are many ways to deploy a model, and I would like to talk about a pretty simple solution that works for a basic MVP — write an API for your model with Flask, use Gunicorn for the app server, Nginx — for the web server, and wrap it up in Docker, so that it’s easier to deploy on other machines (in particular, AWS and GCP).</p><p>The <strong>complete code</strong> can be found in the <a href="https://github.com/ivanpanshin/flask_gunicorn_nginx_docker">GitHub repo</a>.</p><h3>Set-up a server</h3><p>I prefer to do experiments with new configurations on servers that I rent specifically for that, instead of using my personal or work hardware. That way, if you break something badly, it’s no big deal. I recommend using for those purposes <a href="https://www.linode.com/">Linode</a>, since I personally use them for my experiments and their hardware works just fine. But feel free to use any other service, as long as it’s on Ubuntu 18.04 LTS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZQx2LIo0PSP0Zu9IfIW4Q.jpeg" /><figcaption><a href="https://www.pexels.com/@artunchained">Manuel Geissinger</a> via pexels</figcaption></figure><p>If you decide to use Linode, then this section is for you. Navigate to Linodes and click “Add a Linode”. There are several things you should fill-in. In distributions I recommend to select Ubuntu 18.04 LTS image, the region — whatever is closer to you (I use Frankfurt, DE), Linode plan — Nanode (which costs only 5$ a month, but that’s enough for our purposes), root password — your password, and then click “Create”. After some time (about a couple of minutes) you can go to “Networking”, where you can find info for accessing your server via SSH.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R-yGZPjQAYU5YLD9xqXByA.png" /></figure><p>The next thing that I recommend to do is connect to the server and create non-root user with sudo privileges. The logic behind that action is fairly simple: you don’t want messing around the server with running everything as root, since it makes it easier to break stuff.</p><pre>adduser username</pre><pre>usermod -aG sudo username</pre><p>Finally, switch to your new user:</p><pre>su — username</pre><h3>Create app container</h3><p>The whole system config is split into 2 parts: app container (Flask + Gunicorn), and web container (Nginx web server). Let’s start with the first one.</p><h4>Step 0 — install Docker and Docker Compose</h4><p>Docker and docker-compose installations are extremely easy. They’re done in 4 and 2 lines respectively. So, I recommend following these pages:</p><blockquote><a href="https://docs.docker.com/engine/install/ubuntu/">Docker installation</a></blockquote><blockquote><a href="https://docs.docker.com/engine/install/linux-postinstall/">Make Docker run without root</a></blockquote><blockquote><a href="https://docs.docker.com/compose/install/">Docker Compose installation</a></blockquote><h4>Step 1 — create Flask App and WSGI entry point</h4><p>Inside your main directory create <em>flask_app</em> directory and place the following files there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74a86d703eacc9f7b35b7f15706339c3/href">https://medium.com/media/74a86d703eacc9f7b35b7f15706339c3/href</a></iframe><p>This is the most basis Flask app without pretty much any functionality. We don’t load any models, don’t add any GET/POST requests and stuff. That will come later. For now, we just have an app that displays “hello world” on the main page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77e9b31f6a594ee006c42384fd931490/href">https://medium.com/media/77e9b31f6a594ee006c42384fd931490/href</a></iframe><p>An extremely easy part — we just create a separate file for Gunicorn to run on port 8000.</p><h4>Step 2 — create a Docker image for Flask</h4><p>Now we need to create a Dockerfile that will use these files and create an image that we will be able to run later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b8dab56e7cadedd23a72ff68518102b/href">https://medium.com/media/8b8dab56e7cadedd23a72ff68518102b/href</a></iframe><p>For those who aren’t familiar with Docker, what this script does is the following: imports Python 3.6.7 images, sets up the work directory for all files, copies the requirements file that contains Flask, Gunicorn, and everything else you need for your Flask app to run. After that, all packages from requirements are installed via RUN command, and at the end we copy all the files from flask dir to <em>usr/scr/flask_app</em> inside the container.</p><p>Now you only need to place this file inside the same flask_app directory and add <em>requirements.txt</em>. In this particular case it’s very basic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d35ed9f01972c0b5f63d20660efb7a21/href">https://medium.com/media/d35ed9f01972c0b5f63d20660efb7a21/href</a></iframe><p><em>P.S.</em> Remember, that if you’re ever a bit lost regarding the directories and stuff, feel free to check complete project structure at the end of the article, or just visit the GitHub repo.</p><h4>Step 3 — create Nginx files</h4><p>There are several things you need to configure in order to run Nginx. But before we continue, create nginx directory inside your main directory (at the same level as <em>flask_app</em>). After that, the first file that we need — is <em>nginx.conf</em> that pretty much contains all fundamental Nginx info and variables. One example of quite basic Nginx set-up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ed0160f5477e8d25516dacfc105f871/href">https://medium.com/media/9ed0160f5477e8d25516dacfc105f871/href</a></iframe><p>The second file — a configuration for our particular app. There are 2 popular ways to do that. The first one is to create a configuration file in <em>/etc/nginx/sites-available/your_project</em>, and then create a symlink to <em>/etc/nginx/sites-enabled/your_project</em>. The second one is to just create a <em>project.conf</em> inside your main Nginx directory. We are going with the second approach.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a246f403c4fe1dfec7727d161f1a00b0/href">https://medium.com/media/a246f403c4fe1dfec7727d161f1a00b0/href</a></iframe><p>There are several things you should note. First of all, take a look at <em>listen 80. </em>That command specifies what port your app will run at. As default port, we choose 80. Second of all, server name. You can either specify your IP address that you got from Linode, or you can just use your docker image name. And last but not least, <em>proxy pass</em> command that should point your Nginx configuration to the flask project. Since the flask container is called flask_app (we’ll get to that later), we just use the name of the container, and the port that we specified inside the Flask project.</p><h4>Step 4 — create a Docker image for Nginx</h4><p>This particular Docker image is fairly simple. As in the case of Flask, it also contains just 5 lines and does only 2 things: imports nginx image, copies our files, and replaces them with default ones.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d746ea8d7c5f84fd648eb65922f9dfee/href">https://medium.com/media/d746ea8d7c5f84fd648eb65922f9dfee/href</a></iframe><h4>Step 5 — combine Dockerfiles with docker-compose</h4><p>So, now we have 2 Dockerfiles: one for Flask + Gunicorn, and another for Nginx. It’s time to make them talk to each other and run the whole system. In order to do that we need docker-compose.</p><p>The only fundamental change we need to do is create docker-compose.yml file in the main directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46a32017ea484c5641c0a47d9ea9bd1f/href">https://medium.com/media/46a32017ea484c5641c0a47d9ea9bd1f/href</a></iframe><p>There are several important things that we should address in order to understand how it works. First of all, <em>docker-compose</em> is split into 2 parts (2 services): <em>flask_app</em> and <em>nginx</em>. As you can see by the following lines, the flask_app container executes Gunicorn that runs the Flask app and translates it to 8000 port with 1 worker. And the second container just runs Nginx on 80 port. Plus, note the <em>depends_on</em> section. It tells the docker-compose to first launch <em>flask_app</em> container, and only then — the <em>nginx</em> one, because one depends on the other.</p><p>Actually, there is one more thing that we should add, so that it’s even easier to run this docker set-up. And that is <em>run_docker.sh</em> file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5eb277fcbbdce2ea59efa3612a41c090/href">https://medium.com/media/5eb277fcbbdce2ea59efa3612a41c090/href</a></iframe><p>It simply runs the docker-compose, but first makes sure that there are no old docker processes active at this time.</p><h4>Step 6 — put it all together</h4><p>All right, keep in mind, that the current project structure should look like this:</p><pre>.<br>├── flask_app <br>│   ├── app.py          <br>│   ├── wsgi.py<br>│   └── Dockerfile<br>├── nginx<br>│   ├── nginx.conf          <br>│   ├── project.conf<br>│   └── Dockerfile<br>├── docker-compose.yml<br>└── run_docker.sh</pre><p>After you made sure everything is in place, it’s time to run docker:</p><pre>bash run_docker.sh</pre><p>And see the main page in the browser by navigating to the IP that you got from Linode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*PvN0bh118RsrYVLf5_zlOA.png" /></figure><h4>Step 7 — I didn’t get anything. What should I do?</h4><p>Well, first of all, rent a server at Linode, install docker and docker-compose, then clone the git repository, and just run <em>bash run_docker.sh. </em>After you made sure it runs successfully, start changing stuff. Play around with Flask, or Dockerfiles, or docker-compose, until you break something. After that, try to figure out what went wrong and fix it.</p><p>Moreover, if you’re not proficient with Flask, Gunicorn, Nginx, or Docker, I highly recommend these tutorials:</p><blockquote><a href="https://docker-curriculum.com/">Docker for beginners</a></blockquote><blockquote><a href="https://www.tutorialspoint.com/flask/index.htm">Learn Flask</a></blockquote><blockquote><a href="https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04-ru">Flask + Gunicorn + Nginx</a></blockquote><h4>Step 8 — all right, I get it. What’s next?</h4><p>The next thing to add is POST requests support in Flask App. That way, you can send requests to your model, and get responses. So, we need 2 things. First — a model that will handle requests. Second — POST requests support itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e99723e08d80038233236124e23260d7/href">https://medium.com/media/e99723e08d80038233236124e23260d7/href</a></iframe><p>For simplicity, the model in this case just returns the i-th element of list of colors. But it really doesn’t matter what kind of model is running, just create an instance of your model above all methods (<em>pretty much where you have server = Flask(__name__)</em> ), and you’re good to go.</p><p>Now, if you navigate to your IP address, you will see a message “<em>The model is up and running. Send a POST request”, </em>since<em> </em>just going to the IP qualifies as a GET request. However, let’s try to send a POST request with a json file that contains index for our model. Personally, I use Postman for that, but you can use whatever you like (i.e., Curl).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*zSTjW6ILhvFXJx7QYg7zBA.png" /></figure><p>Hey, it works! Now you can add additional routes with ability to receive GET/POST requests. The reason behind the idea is that you can load several models, and send requests to a particular model based on URLs.</p><h4>Step 9 — how about taking it further?</h4><p>There is actually one big thing left to do. In order to deploy this docker set-up big time, it might be a good idea to deploy it in cloud. For instance, I recommend taking a look at <a href="https://medium.com/underscoretec/deploy-your-own-custom-docker-image-on-amazon-ecs-b1584e62484">deploying Docker to Amazon ECS</a>. One of the main advantages of such approach is that AWS will take care of cluster management infrastructure.</p><h3>Conclusion</h3><p>We have taken a look at running a model inside a Flask App with Gunicorn + Nginx + Docker. Note that if you have any questions, feel free to contact me in the comments, GitHub issues, or my e-mail address: ivan.panshin@protonmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b32055b3d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-deploy-ml-models-using-flask-gunicorn-nginx-docker-9b32055b3d0">How to deploy ML models using Flask + Gunicorn + Nginx + Docker</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get top 1% on Kaggle and help with Histopathologic Cancer Detection]]></title>
            <link>https://medium.com/data-science/how-to-get-top-1-on-kaggle-and-help-with-histopathologic-cancer-detection-af729dc3e6f7?source=rss-6253d2421d72------2</link>
            <guid isPermaLink="false">https://medium.com/p/af729dc3e6f7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[cancer]]></category>
            <dc:creator><![CDATA[Ivan Panshin]]></dc:creator>
            <pubDate>Mon, 13 Apr 2020 20:43:42 GMT</pubDate>
            <atom:updated>2020-04-29T17:54:59.958Z</atom:updated>
            <content:encoded><![CDATA[<h4>A story about my first Kaggle competition, and the lessons that I learned during that competition. Moreover, tons of code, model weights, and just ideas that might be helpful to other researchers.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0YHaGNOMIhZaHkZ7RR-FFQ.jpeg" /><figcaption><a href="https://commons.wikimedia.org/wiki/User:Nephron">Nephron</a> via Wikimedia Commons</figcaption></figure><p>Almost a year ago I participated in my first Kaggle competition about cancer classification. Since then I’ve taken part in many more competitions and even published a paper on CVPR about this particular one with my team. However, I feel that we lose most of the knowledge after a competition ends, so I would like to share my approach as well as <a href="https://github.com/ivanpanshin/hist_canser"><strong>publish the code</strong></a> and <a href="https://www.kaggle.com/ivanpan/histopathologic-cancer-detection-weights"><strong>model weights</strong></a> (better late than never, right?).</p><p>I hope that my ideas (+PyTorch solution that implements them) will be helpful to researchers, Kaggle enthusiasts and just people, who want to get better at computer vision.</p><p><strong>Disclaimer: </strong>I’m not a medical professional and only a ML engineer. That said, take all my medical related statements with a huge grain of salt. However, I’m open to criticism, so if you find an error in my statements or general methodology, feel free to contact me and I will do my best to fix it.</p><h3>What is Histopathologic Cancer and why it matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*-u9DfFKNFbVOcK5Q6lFdFg.jpeg" /><figcaption><a href="https://memepedia.ru/users/neverov/">neverov</a> via memepedia</figcaption></figure><p>In simple terms, you take a large digital pathology scan, crop it pieces (patches) and try to find metastatic tissue in these crops. In this particular case we have patches from large scans of lymph nodes (PatchCamelyon dataset). Keep in mind, that metastasis is a spread of cancer cells to new parts of a body. Usually, it’s done via bloodstream of the lymph system.</p><p>The importance of such work is quite straightforward: building machine learning-powered systems might and should help people, who are unable to get accurate diagnoses. Maybe they don’t have access to good specialists or just want to double-check their diagnosis.</p><p><em>However, remember that it’s not a wise idea to self-medicate and also that many ML medical systems are flawed (</em><a href="https://towardsdatascience.com/detecting-covid-19-with-97-accuracy-beware-of-the-ai-hype-9074248af3e1"><em>recent example</em></a><em>).</em></p><h3>What’s under the hood</h3><h4>Objective</h4><p>The main challenge is solving classification problem whether the patch contains metastatic tissue or not. A positive label indicates that the center 32x32px region of the patch contains at least one pixel of tumor tissue. Tumor tissue in the outer region of the patch does not influence the label.</p><p>All solutions are evaluated on the area under the ROC curve between the predicted probability and the observed target.</p><h4>EDA</h4><p>The first thing that it’s done in any ML project is exploratory data analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc66b16ea873f5f77ce4051fd4714e2a/href">https://medium.com/media/bc66b16ea873f5f77ce4051fd4714e2a/href</a></iframe><pre>Train/Test images: 220025/57458</pre><pre>Value counts: <br>0    130908<br>1     89117</pre><pre>Image size: (96, 96)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*ydoAbzLdqDUHW5tXimFRtQ.png" /></figure><h4>Validation</h4><p>The most important thing when it comes to building ML models, without a doubt, is validation. One might think it’s okay to simply split data randomly in 80/20 proportions for training and validation, or do it in a stratified fashion, or apply k-fold validation. But actually, the best way to validate such model is GroupKFold. How can we build groups, and why it’s the best validation technique in this case? Let’s back up a bit.</p><p>As I said before, patches that we work with are a part of some bigger images (scans). That said, we can’t send a part of the scan to training and the remaining part to validation, since it will lead to leakage. So, each scan should be either in training or validation entirely. That’s why we construct groups, so that there is no intersection of scans between groups.</p><p>In order to do that, we need to match each patch to its corresponding scan. We did that as a part of Kaggle challenge, you can find the file <em>(patch_id_wsi_full.csv)</em> in the GitHub repo with a complete matching.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf98dd133000509d9d216080de8f2f55/href">https://medium.com/media/cf98dd133000509d9d216080de8f2f55/href</a></iframe><h4>Data preparation</h4><p>The key step is resizing, since training on original size produces mediocre results. And even worse — with training just on center crops (32). <em>The complete table with a comparison of models is at the end of the article.</em></p><p>Based on an examination of the training set by hand, I thought it’s a good idea to focus my augmentations on flips and color changes. Notice that I don’t use albumentations and instead use default pytorch transforms. That’s just legacy, since I wrote this part of the code about a year ago, and didn’t want to break it while transfering it to albumentations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15eaee526d39801d0d264372dac763ca/href">https://medium.com/media/15eaee526d39801d0d264372dac763ca/href</a></iframe><h4>Model and optimization details</h4><p>The backbone of the models is either EfficientNet-B3 or SE_ResNet-50 with a modified head with the concatenation of adaptive average and maximum poolings + additional FC layers with intensive dropout (3 layers with a dropout of 0.8). The main reason for using EfficientNet and SE_ResNet is that they are good default go to backbones that work great for this particular dataset.</p><p>The optimizer is Adam without any weight decay + ReduceLROnPlateau (factor = 0.5, patience = 2, metric = validation AUROC) for scheduling and the training is done in 2 parts: fine-tuning the head (2 epochs) and then unfreezing the rest of the network and fine-tuning the whole thing (15–20 epochs). The learning rate for both stages is 0.01 and was calculated using LR range test (learning rate was increased in an exponential manner with computing loss on the training set):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*Wxeab9PUMCZuwjTlultTqA.png" /><figcaption>Learning rate range test for stage 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*pK2nbQV7g9LXSFI5aHuPyw.png" /><figcaption>Learning rate range test for stage 2</figcaption></figure><p>Keep in mind that it’s actually better to use <a href="https://arxiv.org/pdf/1803.09820">original idea</a> proposed by Leslie Smith, where you increase the learning rate linearly and compute the loss on validation set. That way, you get more reliable results, but it just takes longer to finish.</p><p>The training is done using the regular BCEWithLogitsLoss without any weights for classes (the reason for that is simple — it works).</p><h4>Additional tricks (+ things to add + things that didn’t work)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*zRoZBo499SbmpJSsN7H7Bw.jpeg" /><figcaption><a href="https://www.flickr.com/photos/tofu_mugwump/">Topher McCulloch</a> via flickr</figcaption></figure><p>In order to achieve better performance, TTA is applied. In particular, 4-TTA (all rotations by 90 degrees + original) for validation and testing with mean average. Also, all folds of EfficientNet-B3 and SE_ResNet-50 are blended together with a simple mean.</p><p>If you want to increase the quality of the final model even more and don’t want to bother with original ideas (like advanced pre and post-processing) you can easily apply SWA. In order to do that, the repo supports SWA (which is not memory consuming, since weights of EfficientNet-B3 take about 60 Mb of space and SE_ResNet-50 weights take 40 Mb more), which makes it easy to average model weights (keep in mind, SWA is not about averaging model predictions, but its weights).</p><p>I tried to add more sophisticated losses (like FocalLoss and Lovasz Hinge loss) for last-stage training, but the improvements were marginal. Also, I implemented progressive learning (increasing image size during training), but for some reason, it didn’t help. Perhaps, my implementation is flawed, since it’s usually a fairly safe approach to increase the model’s performance.</p><h3>Model comparison</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebff9aa3469174f7f0193f7f48e9e58e/href">https://medium.com/media/ebff9aa3469174f7f0193f7f48e9e58e/href</a></iframe><p>Note that there are no CV scores for ensembles. The reason for that is that it’s easy to compare single models based on single fold scores (but you need to freeze the seed), but in order to compare ensembles (like blending, stacking, etc.) you need an additional holdout set. In other words, you take (for example) 20% of all data for holdout, and the rest 80% split into folds as usual. It’s quite straightforward, the only reason why I didn’t implement it in this solution — I had no computational resources to retrain 10 folds from scratch.</p><p>That’s also the reason why I don’t publish weighted ensembles scores: you need to fine-tune weights based on holdout from validation.</p><h3>Final thoughts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*jX8qGZC3WOIm1LFvBNL5jA.png" /><figcaption><a href="https://memepedia.ru/users/olegmont/">Mememaster</a> via memepedia</figcaption></figure><p>It’s been a year since this competition has completed, so obviously a lot of new ideas have come to light, which should increase the quality of this model. Personally, I can recommend the following.</p><p>If you’re not low on resources, just train more models with different backbones (with focus on models like SE_ResNet, SE_ResNeXt, etc) and different pre-processing (mainly image size + adding image crops) and blend them with even more intensive TTA (adding transforms regarding colors), since ensembling works great for this particular dataset. But remember, that in order to evaluate ensembles (and reliably compare folds) it’s a necessary to make a separate holdout set aside from folds.</p><p>If you want something more original than just blending neural networks, I would certainly advise working on more sophisticated data augmentation techniques with regard to domain knowledge (that is, work with domain specialists and ask for thoughts on how to augment images so that they still make sense). Moreover, obviously, I used pretrained EfficientNets and ResNets, which were trained on ImageNet. Running additional pretraining (or even training from scratch) on some medical-related dataset that resembles this one should be a profitable approach.</p><h3>Contacts</h3><p>If you have any questions regarding this solution, feel free to contact me in the comments, GitHub issues, or my e-mail address: ivan.panshin@protonmail.com</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af729dc3e6f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-get-top-1-on-kaggle-and-help-with-histopathologic-cancer-detection-af729dc3e6f7">How to get top 1% on Kaggle and help with Histopathologic Cancer Detection</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>