<?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 Sivan Biham on Medium]]></title>
        <description><![CDATA[Stories by Sivan Biham on Medium]]></description>
        <link>https://medium.com/@sbiham?source=rss-b3aafc24ed45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fUG4DT_NAytZyB6yQcdfxA.png</url>
            <title>Stories by Sivan Biham on Medium</title>
            <link>https://medium.com/@sbiham?source=rss-b3aafc24ed45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:11:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sbiham/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[Point Cloud Registration — Classic Approaches]]></title>
            <link>https://medium.com/data-science/point-cloud-registration-classic-approaches-d6191302b0b2?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6191302b0b2</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[alignment]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[registration]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Wed, 03 Aug 2022 18:45:38 GMT</pubDate>
            <atom:updated>2022-08-05T19:21:26.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>Point Cloud Registration: Classic Approaches</h3><h4>Introduction to Iterative Closest Point (ICP) and Coherent Point Drift (CPD) Methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AqS6eEAQRtOy1oi2" /><figcaption>Photo by <a href="https://unsplash.com/@ellenqin?utm_source=medium&amp;utm_medium=referral">Ellen Qin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my work as an algorithm developer, I use point clouds as 3D representation to solve several problems. Some of my projects required aligning two sets of points with one another, which is not trivial.</p><p>This problem is called<strong> Point Cloud registration</strong>. Given several sets of points in a different coordinate system, the goal of the registration is to align them one to another. The alignment is done by finding a transformation that minimizes the difference between them.</p><p>Like many computer vision tasks, the registration problem is not easy and has many challenges. For example, in some real-world scenarios, the point clouds have different densities and limited overlap. In other scenarios, the point sets may be symmetric or incomplete. Those examples affect the accuracy and efficiency of the results. Extensive studies have been done to improve point cloud registration accuracy, efficiency, and robustness.</p><p>In this post, I will describe the two main classic and popular suggested approaches.</p><h3>Iterative Closest Points (ICP)</h3><p>Given two sets of points P and Q, ICP optimizes the <a href="https://en.wikipedia.org/wiki/Rigid_transformation">rigid transformation</a> to align P with Q:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*JG66CYXLmrwGgk3VSdq-Hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*MDiba29u_hf7gAo54PYerw.png" /></figure><p>The ICP starts with an initial alignment and iterates between two steps -</p><ul><li><strong>The correspondence step </strong>— find the closest point <em>q_i</em> in Q for each point <em>p_j</em> in P.</li><li><strong>The alignment step </strong>— update the transformation by minimizing the L2 distance between the corresponding points.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuzOCS_gdZuM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuzOCS_gdZuM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuzOCS_gdZuM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/990e361ae55ddc68bd81a85f0d48383a/href">https://medium.com/media/990e361ae55ddc68bd81a85f0d48383a/href</a></iframe><p>This is a simple and straightforward algorithm for both understanding and implementation. At the same time, it also has several limitations.</p><h4>Limitations of the ICP Algorithm</h4><ul><li>The accuracy of the results strongly relies on a good initial alignment.</li><li>Tends to converge to local minima.</li><li>Sensitive to outliers and partial overlaps.</li><li>Works only with rigid transformations.</li></ul><p>Much research was done in this area and many variants were proposed to the ICP algorithm to tackle the limitations above.</p><p>A different family of registration methods is probabilistic ones. These methods use soft-assignment of correspondences, which means assigning correspondences between all points according to some probability. This is in contrast to the ICP algorithm which uses binary assignments. One example of such an algorithm is the Coherent Point Drift (CPD).</p><h3>Coherent Point Drift (CPD)</h3><p>Coherent point drift is a probabilistic approach for the registration problen, which works on both rigid and non-rigid transforms. As the authors explain in the original paper³:</p><blockquote>“The alignment of two point sets is considered a probability density estimation problem. One point set represents the <a href="https://en.wikipedia.org/wiki/Mixture_model#Gaussian_mixture_model">Gaussian Mixture Model</a> (GMM) centroids, and the other one represents the data points. The registration is done by fitting the GMM centroids to the data by maximizing the likelihood.”</blockquote><p>The CPD is more robust to noise, outliers, and missing points than ICP.</p><h4>Limitations of the CPD Algorithm</h4><ul><li>An assumption about the amount of noise and outliers is used. Incorrect assumptions will lead to poor registration.</li><li>For data with density variations, the registration tends to converge to a local extremum (local minimum or local maximum)</li></ul><h3>Summary</h3><p>The registration task is a popular task in the computer vision field. Most methods rely on finding correspondences between the two point clouds. Two main approaches are suggested—hard correspondences like those used in ICP, and soft-assignment of correspondences like those used in CPD. Each method has many different variants with different pros and cons.</p><p>Which one is the best for you? It depends on your data, whether you need a rigid or non-rigid method, the amount of noise and outliers, density variations, and more. As I mentioned before, a lot of variants exist to those methods. I recommend finding the one that best suits your task and data.</p><h4>References</h4><p>This is the list of papers I used for this post. You can read them for more information.</p><ul><li><a href="https://ieeexplore.ieee.org/abstract/document/8490968">Iterative Global Similarity Points: A Robust Coarse-to-Fine Integration Solution for Pairwise 3D Point Cloud Registration</a></li><li><a href="https://ieeexplore.ieee.org/abstract/document/9336308">Fast and Robust Iterative Closest Point</a></li><li><a href="https://ieeexplore.ieee.org/abstract/document/5432191">Point Set Registration: Coherent Point Drift</a></li><li><a href="https://link.springer.com/article/10.1007/s11432-011-4465-7">A refined coherent point drift (CPD) algorithm for point set registration - Science China Information Sciences</a></li><li><a href="https://ieeexplore.ieee.org/abstract/document/8897021">Density-Adaptive and Geometry-Aware Registration of TLS Point Clouds Based on Coherent Point Drift</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6191302b0b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/point-cloud-registration-classic-approaches-d6191302b0b2">Point Cloud Registration — Classic Approaches</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[From Natural to Medical Image — Why Transfer Learning works?]]></title>
            <link>https://medium.com/@sbiham/from-natural-to-medical-image-why-transfer-learning-works-831b7b81d617?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/831b7b81d617</guid>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Sun, 10 Jul 2022 15:10:09 GMT</pubDate>
            <atom:updated>2022-07-10T15:10:09.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Natural to Medical Image — Why Transfer Learning works</h3><h4>What Makes Transfer Learning Work For Medical Images</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UByzYv-ThSj5jUx-" /><figcaption>Photo by <a href="https://unsplash.com/@averey?utm_source=medium&amp;utm_medium=referral">Robina Weermeijer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Transfer learning is a common technique to transfer knowledge from one domain to another. It might be easy to understand why using knowledge from one dataset to a different dataset with similar characteristics might work. But what makes transfer learning works for medical images? Medical images have totally different characteristics than natural images. Still, transfer learning is a popular approach for medical applications.</p><p>Why does it work so well? A recent paper, published in CVPR 2022, “<a href="https://arxiv.org/pdf/2203.01825.pdf">What Makes Transfer Learning Work For Medical Images: Feature Reuse &amp; Other Factors</a>” aims to answer this question. The paper’s central question is: <em>what factors determine if transferred representations are effective in the medical domain</em>. In this blog post, I will summarize the paper&#39;s main findings.</p><p>The authors made a series of experiments to study the role of feature reuse and the effectiveness of transfer learning as a function of dataset size, distance from a source domain, model capacity, and model’s inductive bias. All transferred from ImageNet.</p><p>The results are not surprising, but it&#39;s much appreciated to back up the intuition with experimental results.</p><p><strong>The main findings of the paper are demonstrated in the following figure:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*VZOW5c-247HFH6fgsL5NGQ.jpeg" /><figcaption>Image by the paper’s authors. Factors affecting the utility of transfer learning from ImageNet to medical domains. The size of each dot represents the relative increase in performance achieved transferring weights from IMAGENET compared to random initialization. The color of the dot indicates how much of the gain can be attributed to feature reuse.</figcaption></figure><h4><strong>The benefit from transfer learning increases with:</strong></h4><ul><li>Reduced data size</li><li>Smaller distance between the source and target [1]</li><li>Models with fewer inductive biases [2] (<a href="https://en.wikipedia.org/wiki/Vision_transformer">ViT</a> vs <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">CNNs</a>)</li><li>Models with more capacity, to a lesser extent.</li></ul><p>For small datasets, transfer learning shows a noteworthy gain for all models. However, the strength of the gains and the importance of feature reuse [3] depend on the inductive biases of the model and the distance between the domains.</p><p>For large datasets and ones that poorly resemble ImageNet, the gain from transfer learning is insignificant. ViTS appear to benefit far more from feature reuse than CNNs in such cases.</p><h4>Feature reuse + Inductive Bias</h4><ul><li>When transfer learning works well, the evidence for feature reuse is strongest.</li><li>Models with less inductive bias rely more heavily on feature reuse.</li><li>The pattern of feature reuse changes in models with less inductive bias. Specifically, feature reuse in ViTs is concentrated in early layers, whereas CNNs reuse features more consistently throughout the network.</li></ul><h3>Conclusions</h3><p>Although medical datasets might have significantly different characteristics from natural images, they can still benefit from transfer learning. The described paper shows that for small datasets, which is a common scenario in the medical field, the gain from transfer learning is higher. The authors also elaborate on which architectures will gain more, and analyze the transferred representations layer-wise. I recommend you to read the full paper for more information.</p><h3>Definitions</h3><p>[1] <strong>Distance from the source domain</strong> — The distance from the source domain, ImageNet in this case, is measured using <a href="https://en.wikipedia.org/wiki/Fr%C3%A9chet_inception_distance">Frechet Inception Distance</a> which compares the distributions of two datasets.</p><p>[2] <strong>Inductive Bias </strong>— Learning algorithms mostly use some mechanisms or assumptions by putting some restrictions on the space of hypotheses. This mechanism is known as Inductive Bias or Learning Bias. This mechanism encourages the learning algorithms to prioritize solutions with specific properties. Inductive bias is a set of implicit or explicit assumptions the algorithm makes to generalize a set of training data. (<a href="https://analyticsindiamag.com/top-5-inductive-biases-in-deep-learning-models/">link</a>)</p><p>[3] <strong>Feature reuse</strong> — The feature reuse hypothesis assumes that weights learned in the source domain yield features that can readily be used in the target domain. In practice, this means that weights learned on ImageNet provide useful features in the target domain, and do not change substantially during fine-tuning despite differences between the domains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831b7b81d617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Infrastructure for Training Machine Learning Models]]></title>
            <link>https://medium.com/data-science/creating-infrastructure-for-training-machine-learning-models-aec52cf37929?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/aec52cf37929</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 15:30:18 GMT</pubDate>
            <atom:updated>2022-06-08T15:30:18.532Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introducing an Automatic Pipeline for Training, Tracing, and Comparing Machine Learning Experiments</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*snKc3ZJjof1O42K1" /><figcaption>Photo by <a href="https://unsplash.com/@firmbee?utm_source=medium&amp;utm_medium=referral">Firmbee.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s imagine the following scenario: you get a new project to work on. For this project, you need to develop a machine learning model, which will require running and training several experiments. Each experiment might take several hours or even days and needs to be tracked.</p><p>You have your own laptop for the development phase, but it&#39;s not realistic to use your own laptop for training and running all of the experiments. First, your computer might not have the required hardware, for example, a GPU. Second, it’s a waste of time. Why train on one computer sequentially if you can<strong> run and train all the experiments in parallel</strong>?</p><p>If you do train in parallel, on separate machines for each experiment, how do you easily <strong>track and compare</strong> them? How do you <strong>access the training data</strong>? Can you be <strong>aware in real-time of any failure</strong> so you will be able to fix and run it again?</p><p>All of these questions are going to be answered. In this blog post, I want to describe one possible solution for all the issues above.</p><p>The solution combines different services and unites them to create a whole pipeline solution for training machine learning models.</p><p>In the image below you can find the scheme of this pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZZwm4u2umy3EGr_s7spXw.png" /><figcaption>Image by author</figcaption></figure><p>The pipeline consists of three steps- containerizing the code so we will be able to run it later, executing the code in several separate machines, and tracking all the experiments.</p><h3>(1) Containerizing</h3><p>The best way to run training experiments at scale is to build a <a href="https://www.docker.com/"><strong>docker</strong></a> image. One way to create such an image is to use <a href="https://www.jenkins.io/"><strong>Jenkins</strong></a>. An open-source automation server that enables building, testing, and deploying software. Another way is to use <a href="https://github.com/features/actions"><strong>GitHub actions</strong></a><strong>. </strong>Continuous integration and continuous delivery (CI/CD) platform that allows you to automate your build, test, and deployment pipeline. It can be done directly from your GitHub account.</p><p>Let me describe one possible scenario — each push to our <strong>git</strong> branch, triggers a Jenkins pipeline. This pipeline builds the docker image (among other things it can do), tag it, and store it in a docker registry.</p><p>Once we have this image, we can execute it and train our models at scale using virtual cloud machines.</p><h3>(2) Executing</h3><p>We have our code ready and we want to start training. Let’s say we have 10 experiments to run, and we want to run them in parallel. One option is to use 10 <strong>virtual machines</strong>, connect each one using ssh, and manually execute our code at each one. I guess you understand that it’s not optimal.</p><p>Since we already containerized our application in the previous step, we can utilize the most popular container orchestration platform to run our training — <a href="https://kubernetes.io/"><strong>Kubernetes</strong></a>. Kubernetes is an open-source system for automating the deployment, scaling, and management of containerized applications. This means, that by using it, we can take our docker image and deploy it at scale. We can run 10 experiments on 10 separate machines, using a simple bash script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb9e8237dec4011325e19be8b8fe6838/href">https://medium.com/media/cb9e8237dec4011325e19be8b8fe6838/href</a></iframe><p>You can read more about it <a href="https://kubernetes.io/docs/tasks/job/automated-tasks-with-cron-jobs/">here</a>.</p><h3>(3) Tracking</h3><h4>Training data acquisition</h4><p>To execute the training we first need access to our training data. The best way is to have direct access from the training machine to the <strong>storage </strong>with the required training files (<a href="https://aws.amazon.com/s3/">S3</a>, <a href="https://cloud.google.com/storage">GCS</a>, etc) and to the <strong>database</strong> with the required tabular information. To establish that we might need help to get access to the relevant credentials and <a href="https://cloud.google.com/secret-manager#:~:text=Secret%20Manager%20is%20a%20secure,audit%20secrets%20across%20Google%20Cloud.">secret managers </a>(a secure and convenient storage system for API keys, passwords, certificates, and other sensitive data). Once it’s configured, we are free to go.</p><h4>NFS disk — shared disk</h4><p>All the machines that are used for the training, are connected to an NFS disk (in our case, we use the managed solution by GCP, which is called <a href="https://cloud.google.com/filestore">Filestore</a>), an additional shared disk to which all machines have read and write access. We add this shared disk for three main reasons —</p><ol><li>When training on separate machines, we don’t want to download our training data over and over again for each one. Instead, we can connect all the machines to a shared file store, an additional disk which all the machines have access to. This way we can <strong>download the data only once</strong>.</li><li>Training models might take time and as such can be costly. One option to make the training cheaper is to use <a href="https://cloud.google.com/spot-vms"><strong>Spot instances</strong></a> which are available at a much lower price. However, your cloud provider might stop (preempt) these instances if it needs to reclaim the compute capacity for allocation to other VMs. Using Kubernetes, once the instance is stopped, it’s automatically replaced and execute the same experiment again. In such a case, we want to continue the training from where we stopped- loading the last saved checkpoint. This can be done only using the shared disk, without it we will not have access to the saved checkpoint in the previous machine. Other solutions like uploading all checkpoints to cloud storage and applying the logic on it, are possible but with high overhead (and costs).</li><li><a href="https://www.tensorflow.org/tensorboard#:~:text=TensorBoard%20provides%20the%20visualization%20and,as%20they%20change%20over%20time"><strong>TensorBoard</strong></a> — to compare different experiments from different machines using TensorBoard, all the information must be written to the same parent directory. We will write all the information to the same parent log directory, which TensorBoard UI will read from.</li></ol><h4>Experiment tracking</h4><p>One of the most important things in training models is to be able to track the training progress and compare different experiments. For each experiment we want to save the parameters we used, the data we trained on, the loss values, the results, and more. We will use this data for tracking, tracing, and comparing.</p><p>There are many tracking tools. I use <a href="https://mlflow.org/"><strong>MLflow</strong></a> and <strong>TensorBoard</strong> when I want advanced visualization. They are both deployed in a way that all the team can access the same instance and see all the team’s experiments.</p><p>MLflow is an open-source platform for managing the end-to-end machine learning lifecycle. It provides a simple API to be integrated with and a nice UI for tracking and comparing the results.</p><p>TensorBoard provides the visualization and tooling needed for machine learning experimentation. It provides an API that logs our information to files on the machine’s disk. TensorBoard UI reads those files from a passed input directory.</p><h4>Errors Alerts</h4><p>As the training might take time, hours, or even days, we would like to get real-time notifications if an error occurred. One way to do so is to integrate our code with <a href="https://sentry.io/welcome/"><strong>Sentry</strong></a> and integrate Sentry with <strong>Slack</strong>. This way, every error raised in the code will be sent as an event to Sentry and will trigger a Slack notification.</p><p>Now I get notifications about errors in real-time. It not only reduced my need to monitor the runs (whether they crashed or still running), but it also reduced the time between the occurrence of the error and the triggering of another run, with the fixed code.</p><h3>Summary</h3><p>When I first trained models, it was done on my laptop. Soon enough, it was not scalable, so I moved on to virtual machines using ssh. This option has pitfalls too. For each machine, I had to log in, pull the code, download the data, run the code manually, and hope that I did not mix up the parameters I pass. The data part was the easiest one to solve, we add a shared disk to all my virtual machines. But I still got confused with the parameters and passed the same ones at several machines. <strong>This was the time to move on to use a scalable and more automated infrastructure as I described in this post. </strong>Together with the DevOps team, we defined and build the great pipeline we have today. Now I have a pipeline that is scalable, easy to execute and even sends a Slack notification every time an error is raised. This pipeline saves time not only due to the experiments&#39; parallelism but also minimizes the parameter mistakes and the idle time due to errors that we don’t know about unless actively checking each machine.</p><ul><li><a href="https://www.docker.com/">Docker: Accelerated Container Application Development</a></li><li><a href="https://www.jenkins.io/">Jenkins</a></li><li><a href="https://kubernetes.io/">Production-Grade Container Orchestration</a></li><li><a href="https://mlflow.org/">MLflow - Open Source AI Platform for Agents, LLMs &amp; Models</a></li><li><a href="https://www.tensorflow.org/tensorboard">TensorBoard | TensorFlow</a></li><li><a href="https://cloud.google.com/">AI and Cloud Computing Services</a></li><li><a href="https://sentry.io/welcome/">Application Performance Monitoring &amp; Error Tracking Software</a></li><li><a href="https://docs.github.com/en/actions">GitHub Actions documentation - GitHub Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aec52cf37929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/creating-infrastructure-for-training-machine-learning-models-aec52cf37929">Creating Infrastructure for Training Machine Learning Models</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 Validate Your JSON Using JSON Schema]]></title>
            <link>https://medium.com/data-science/how-to-validate-your-json-using-json-schema-f55f4b162dce?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/f55f4b162dce</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[json-schema]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 15:22:17 GMT</pubDate>
            <atom:updated>2022-04-18T15:22:17.524Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Gentle Introduction to JSON Schema In Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LPwau8bIdlbA9SVO" /><figcaption>Photo by <a href="https://unsplash.com/@flowforfrank?utm_source=medium&amp;utm_medium=referral">Ferenc Almasi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine the following scenario: you and your teammate are working on a new feature. Your part is to create a JSON with some results and send it to your teammate. Her part is to take this JSON, parse it and save it in the database. You verbally agreed on what the keys and types should be and each one of you implemented their part. Sounds legit, and it will indeed work if the JSON structure is simple. But one day you had a bug and sent the wrong key. You learned your lesson and decided to create an API and document it in your team&#39;s favorite documentation platform. Now you can both take a look at this API to make sure you implemented it correctly.</p><p>But is it enough? Let’s say you indeed implement it correctly. Let’s say another teammate made a change, now it returns an array of numbers instead of a single number. Your teammate is not aware of your API, and everything breaks.</p><p>What if you could validate your JSON directly in the code before sending it and before parsing it? That is what we have JSON schema for!</p><p>In this post, I will introduce JSON Schema, why it is so powerful and how can we use it in different scenarios.</p><h3>What is JSON Schema?</h3><p>JSON Schema is a JSON-based format for defining the structure of JSON data. It provides a contract for what JSON data is required for a given application and how to interact with it. It can be used for validation, documentation, hyperlink navigation, and interaction control of JSON data.</p><p>The schema can be defined in a JSON file, and be loaded into your code or it can be directly created in the code.</p><h4>How to validate our JSON?</h4><p>Easy!</p><pre>validate(instance=your_json, schema=schema)</pre><p><a href="https://python-jsonschema.readthedocs.io/en/stable/">For example</a>:</p><pre><strong>from</strong> <strong>jsonschema</strong> <strong>import</strong> validate<br><br><strong>&gt;&gt;&gt; </strong><em># A sample schema, like what we&#39;d get from json.load()</em><br><strong>&gt;&gt;&gt; </strong>schema = {<br><strong>... </strong>    &quot;type&quot; : &quot;object&quot;,<br><strong>... </strong>    &quot;properties&quot; : {<br><strong>... </strong>        &quot;price&quot; : {&quot;type&quot; : &quot;number&quot;},<br><strong>... </strong>        &quot;name&quot; : {&quot;type&quot; : &quot;string&quot;},<br><strong>... </strong>    },<br><strong>... </strong>}<br><br><strong>&gt;&gt;&gt; </strong><em># If no exception is raised by validate(), the instance is valid.</em><br><strong>&gt;&gt;&gt; </strong>validate(instance={&quot;name&quot; : &quot;Eggs&quot;, &quot;price&quot; : 34.99}, schema=schema)<br><br><strong>&gt;&gt;&gt; </strong>validate(<br><strong>... </strong>    instance={&quot;name&quot; : &quot;Eggs&quot;, &quot;price&quot; : &quot;Invalid&quot;}, schema=schema,<br><strong>... </strong>)                                   <br>Traceback (most recent call last):<br>    ...<br>ValidationError: &#39;Invalid&#39; is not of type &#39;number&#39;</pre><h3>Why should I use JSON Schema?</h3><p>Each JSON object has a basic structure of key-value. The key is a string and the value can be of any <a href="http://json-schema.org/understanding-json-schema/reference/type.html">type</a> — <a href="https://json-schema.org/understanding-json-schema/reference/numeric.html">number</a>, string, array, JSON, etc.</p><p>In some cases, the value can be of only a specific type, and in other cases, the value is more flexible. Some keys in our JSON are required, and some of them are optional. There are more complicated scenarios. For example, if we got a certain key, then a second key must appear. The value of one key can be dependent on a second key value.</p><p>All those scenarios and many more can be tested and validated locally using JSON Schema. By using it, you can validate your own JSON, and make sure it meets the API requirements before integrating with other services.</p><h3>Simple JSON Schema</h3><p>In this example, our JSON contains information about dogs.</p><pre>{<br> &quot;breed&quot;: &quot;golden retriever&quot;,<br> &quot;age&quot;: 5,<br> &quot;weight&quot;: 13.5,<br> &quot;name&quot;: &quot;Luke&quot;<br>}</pre><p>Let&#39;s take a closer look at this JSON’s properties and the requirements we want to enforce on each one:</p><ul><li>Breed —we want to represent only three breeds: golden retrievers, Belgian Malinois, and Border Collie. We would like to validate that case.</li><li>Age — we want the age to be rounded to years, so our value will be represented as an integer. In this example, we also want to limit the maximum age to 15.</li><li>Weight — can be any positive number, int or float.</li><li>Name — always a string. Can be any string.</li></ul><p>Our schema will be -</p><pre>{<br> &quot;type&quot;: &quot;object&quot;,<br> &quot;properties&quot;:<br>     {<br>        &quot;breed&quot;: {&quot;type&quot;:&quot;string&quot;, &quot;enum&quot;:[<br>                                            &quot;golden retrievers&quot;, <br>                                            &quot;Belgian Malinois&quot;, <br>                                            &quot;Border Collie&quot;<br>                                         ]<br>                 },<br>        &quot;age&quot;: {&quot;type&quot;: &quot;int&quot;, &quot;maximum&quot;:15, &quot;minimum&quot;:0},<br>        &quot;weight&quot;: {&quot;type&quot;:&quot;number&quot;, &quot;minimum&quot;:0},<br>        &quot;name&quot;: {&quot;type&quot;:&quot;string&quot;}<br>     }<br>}</pre><p>This way, only age values between 0 and 15 can be added, no negative weight, and only the three specific breeds.</p><h3>Simple Array Schema</h3><p>We can also validate array values.</p><p>For example, we want an array with the following properties: between 2 to 5 items, unique values, strings only.</p><pre>[&#39;a&#39;,&#39;b&#39;,&#39;c&#39;]</pre><pre>{<br> &quot;type&quot;: &quot;array&quot;,<br> &quot;items&quot;: {&quot;type&quot;: &quot;string&quot;},<br> &quot;minItems&quot;: 2,<br> &quot;maxItems&quot;: 5,<br> &quot;uniqueItems&quot;: true<br>}</pre><h3>More complex functionality</h3><h4>Required properties</h4><p>Some of the properties are must-haves and we would like to raise an error if they are missing.</p><p>You can add the<strong>required</strong> keyword.</p><pre>{<br> &quot;type&quot;: &quot;object&quot;,<br> &quot;properties&quot;:<br>     {<br>        &quot;breed&quot;: {&quot;type&quot;:&quot;string&quot;},<br>        &quot;age&quot;: {&quot;type&quot;: &quot;int&quot;, &quot;maximum&quot;:15, &quot;minimum&quot;:0}<br>     }<br> &quot;required&quot;:[&quot;breed&quot;]<br>}</pre><p>In this case, an error will be raised when the “breed” property is missing. Other properties like “age” remain optional.</p><h4>Dependent required</h4><p>The <strong>dependentRequired</strong> keyword conditionally requires certain properties to be present if a given property is present in an object.</p><pre>{<br>  &quot;type&quot;: &quot;object&quot;,<br><br>  &quot;properties&quot;: {<br>    &quot;name&quot;: { &quot;type&quot;: &quot;string&quot; },<br>    &quot;credit_card&quot;: { &quot;type&quot;: &quot;number&quot; },<br>    &quot;billing_address&quot;: { &quot;type&quot;: &quot;string&quot; }<br>  },<br><br>  &quot;required&quot;: [&quot;name&quot;],<br><br>  &quot;dependentRequired&quot;: {<br>    &quot;credit_card&quot;: [&quot;billing_address&quot;]<br>  }<br>}</pre><p>In this case, if the “credit_card” property appears, then “billing_address” is required.</p><h4>One of / Any of</h4><p>Until now, each property is of only one type. What if our property can be of several different types?</p><p>Example 1 — <strong>anyOf</strong>— To validate against anyOf the given data must be valid against any (one or more) of the given subschemas.</p><pre>{<br>  &quot;anyOf&quot;: [<br>    { &quot;type&quot;: &quot;string&quot;},<br>    { &quot;type&quot;: &quot;number&quot;, &quot;minimum&quot;: 0 }<br>  ]<br>}</pre><p>In this case, our data can be either a string or a number bigger or equal to 0.</p><p>Example 2 — <strong>oneOf</strong>— To validate against oneOfthe given data must be valid against exactly one of the given subschemas.</p><pre>{<br>  &quot;oneOf&quot;: [<br>    { &quot;type&quot;: &quot;number&quot;, &quot;multipleOf&quot;: 5 },<br>    { &quot;type&quot;: &quot;number&quot;, &quot;multipleOf&quot;: 3 }<br>  ]<br>}</pre><p>In this case, the data can only be numbers and it can be either multiple of 5 or multiple of 3, but not both!</p><h3>Summary</h3><p>JSON Schema is a powerful tool. It enables you to validate your JSON structure and make sure it meets the required API. You can create a schema as complex and nested as you need, all you need are the requirements. You can add it to your code as an additional test or in run-time.</p><p>In this post, I introduced the basic structure and mentioned some more complex options. There is a lot to explore and use that you can read about.</p><p>I think anyone who works with JSONs as part of their work should be familiar with this package and its options. <strong>It has the potential of saving you a lot of time and easing your integration process</strong>, just by easily validating your JSON structure. I know it saved me a lot of time since I started using it.</p><p><a href="https://json-schema.org/">JSON Schema</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f55f4b162dce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-validate-your-json-using-json-schema-f55f4b162dce">How to Validate Your JSON Using JSON Schema</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[Why You Should Consider Using Generative Adversarial Networks for Medical Data]]></title>
            <link>https://medium.com/data-science/why-you-should-consider-using-generative-adversarial-networks-for-medical-data-d0fc03314b3?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0fc03314b3</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[medical]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 04:03:20 GMT</pubDate>
            <atom:updated>2022-04-05T16:30:33.385Z</atom:updated>
            <content:encoded><![CDATA[<h4>Two Advantages in Using GANs for Medical Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ReHiJydgTCneV0lj" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Supervised deep learning methods require a large amount of data which might be hard to obtain, especially in the medical domain. One reason is that it is private data that we can’t always get, use and share. The second reason is the difficulty to obtain labels for this data. Expert annotators, such as doctors and nurses, are needed, which are both costly and time-consuming. Even if we have a large amount of labeled data, we might encounter other issues, such as data balancing. Rare conditions will not appear frequently in the data and will create a bias that will affect our models’ results.</p><p><strong>So how can we overcome those issues? Is there a method that has the potential to help up? Generative Adversarial Networks.</strong></p><p>One method that has this potential is Generative Models. In this post I will describe how using generative methods, specifically Generative Adversarial Networks, we can reduce the issues mentioned above. This post will cover the data volume, balance, and privacy issues.</p><h3>Generative Adversarial Network (GAN)</h3><p>GAN models generate new data with the same statistics as the training set. It consists of two networks, the generator and the discriminator which contest with each other. <strong>The generator </strong>learns to map from a latent space to the data distribution of interest in order to generate new samples. <strong>The discriminator&#39;s</strong> goal is to distinguish candidates produced by the generator from the true data distribution. In other words, to classify each sample whether it&#39;s a true sample or a generated one. <strong>The generator&#39;s </strong>goal is to fool the discriminator, make it believe that a generated sample is a real one, and maximize the discriminator’s error rate.</p><p><strong>By using GANs we can generate new medical samples and tackle the issues of data volume, balance, and privacy.</strong></p><h3>Data Volume and Balance</h3><p>In many situations, we want to develop an algorithm for medical purposes, but we don’t have <strong>enough data</strong>, and if we have it&#39;s not <strong>balanced</strong>. Both issues can be solved by generating quality synthetic data using GAN methods.</p><p>For example, DermGAN. DermGAN is a generative network that synthesizes clinical images with skin conditions. A map encoding of the skin condition, its region of presence (orange rectangle), and the skin color (red background) is passed through the generator to produce a synthetic image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*tZMIu7SncJdqdUvP_L-T6w.png" /><figcaption>Image from the paper — <a href="https://arxiv.org/pdf/1911.08716.pdf">https://arxiv.org/pdf/1911.08716.pdf</a></figcaption></figure><p>Using DermGAN we can generate a large number of images with skin conditions. This solves the data volume issue. We can also control the balancing of the images. We can generate more samples from rare conditions, which solves the data balancing issue.</p><p>And this is only one example of a work in this field.</p><p><strong>Using generative methods can generate almost any amount of images, with the required balancing of the samples. This is a step towards overcoming the data volume and balancing issues.</strong></p><h3>Data Anonymization</h3><p>Most medical research is done using real patients&#39; private medical data. There are several open-source data sets, but they are limited to specific fields and specific data distribution, which is not enough for developing real-world systems. To overcome it, each group creates its own medical datasets for its own problem at hand. Those datasets are private and cannot be shared with colleagues outside the group. As such, knowledge sharing and results’ reproducibility become almost impossible.</p><p><strong>By using GANs to generate synthetic medical data, we will be able to create new datasets and share them in the medical community and push the research even further.</strong></p><h3>Challenges</h3><p>Although it sounds great, we need to into account several things before using synthetic data. For example -</p><ul><li>The ratio between real and synthetic data</li><li>The sampling technique used to sample images from the GAN</li><li>The distribution of the synthesized data.</li><li>The quality of the synthesized data</li><li>…</li></ul><p>It should be in our minds when we consider using synthetic data in our models.</p><h3>Summarize</h3><p>I hope I convinced you that the medical community can benefit from developing and improving GAN methods to generate quality synthetic medical data. I am not sure we have reached the point that we can use only synthesized data, especially not for all domains. But I think it is a good motivation to put the effort into developing GAN methods for medical data. I will keep investigating it on my domain, and keep you posted.</p><ul><li><a href="https://openaccess.thecvf.com/content/CVPR2021W/ISIC/html/Bissoto_GAN-Based_Data_Augmentation_and_Anonymization_for_Skin-Lesion_Analysis_A_Critical_CVPRW_2021_paper.html">CVPR 2021 Open Access Repository</a></li><li><a href="https://arxiv.org/abs/1911.08716">DermGAN: Synthetic Generation of Clinical Skin Images with Pathology</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0fc03314b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/why-you-should-consider-using-generative-adversarial-networks-for-medical-data-d0fc03314b3">Why You Should Consider Using Generative Adversarial Networks for Medical Data</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[PostGIS for Computer Vision Developers]]></title>
            <link>https://medium.com/data-science/postgis-for-computer-vision-developers-5e703e37ad55?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e703e37ad55</guid>
            <category><![CDATA[postgis]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Mon, 28 Feb 2022 07:48:23 GMT</pubDate>
            <atom:updated>2022-02-28T07:48:23.067Z</atom:updated>
            <content:encoded><![CDATA[<h4>Analyzing Geometric Objects Directly in SQL Without Additional Python Code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zj4IUaCRuMcT_Cw3" /><figcaption>Photo by <a href="https://unsplash.com/@maxboettinger?utm_source=medium&amp;utm_medium=referral">Max Böttinger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When we talk about the input and output of Computer Vision algorithms we mainly talk about two things — the images and the annotations. While the images are mostly stored in cloud storage, the annotations have a wider range of storing options. In my case, all the annotations are stored in a database.</p><p>I am a Python lover. Most of my work as a Computer Vision developer involves Python. But as I said, the annotations, which are an integral part of my data are stored in a PostgreSQL database. I used to write simple queries to extract all my data and then analyze it in Python using Pandas/OpenCV/Shapely or any other relevant library. And then one day, I was introduced to PostGIS.</p><p>In this post, I want to pass it forward and introduce PostGIS - an alternative to python, for analyzing geometric results (for PostgreSQL databases).</p><h3>PostGIS</h3><p><a href="https://postgis.net/">Home</a></p><p><a href="https://postgis.net/">PostGIS</a> is a spatial database extender for <a href="https://postgresql.org/">PostgreSQL</a> object-relational database. It adds support for geographic objects allowing location queries to be run in SQL.</p><p>In our case, Computer Vision tasks, PostGIS allows geometric objects representation such as points, lines, and polygons. Using PostGIS’s geometric representation we can easily apply geometric manipulation and transformations directly in the SQL query, without additional Python code.</p><p>Some PostGIS methods are the equivalent of <a href="https://geopandas.org/en/stable/">GeoPandas</a> and <a href="https://shapely.readthedocs.io/en/stable/">Shapely</a> in Python.</p><h3>Data Overview</h3><h4><strong>What I have in the database</strong></h4><ol><li><strong>Data annotations</strong> — all of our image annotations are stored in the database. The annotation tool is connected directly to the database, and whenever an annotation job is done, all the data is written to the database in PostGIS format.</li><li><strong>Algorithmic results</strong> — algorithmic results, like segmentation, are also stored in the database. Whether its results from the production environment or its results from our research environment.</li></ol><p>A connection between image annotations and the image algorithmic results can be done easily by joining according to image ID.</p><p>After applying a query for all the relevant data, we can easily manipulate it using PostGIS. For example, calculating the IoU for segmentation tasks. Using PostGIS we don’t need to write a Python script, the data can be analyzed directly in the query in a convenient way.</p><p>It can be even more useful when we want to add analytics layers and save the analyzed results back to the database. Instead of analyzing in Python which requires triggering a different process, and then writing to the database, it can all be done directly using SQL.</p><h4><strong>How it should be represented</strong></h4><ul><li><strong>To geometry: </strong>In order to use PostGIS, all your objects (polygons, lines, points) should be represented in PostGIS geometry format.</li></ul><pre># Point<br>SELECT <strong>ST_GeomFromGeoJSON</strong>(‘{“type”:”<em>Point</em>”,”coordinates”:[0,1]}’)</pre><pre># Line<br>SELECT <strong>ST_GeomFromGeoJSON</strong>(&#39;{&quot;type&quot;:&quot;<em>LineString</em>&quot;,&quot;coordinates&quot;:[[0,1], [15,35], [43.2,5.1]]}&#39;))</pre><pre># Polygon<br>SELECT <strong>ST_GeomFromGeoJSON</strong><br>    (<br>        &#39;{<br>            &quot;type&quot;:&quot;<em>Polygon</em>&quot;,<br>            &quot;coordinates&quot;:[[<br>                [7.7, 51.8],<br>                [3.8,48.3],<br>                [7.2,43.5],<br>                [18.6,43.8],<br>                [17.9,50.2],<br>                [13.7,54.0],<br>                [7.7, 51.8]<br>            ]]<br>        }&#39;<br>    )</pre><pre>SELECT &#39;POLYGON((0 0, 0 1000012333334.34545678, 1.0000001 1, 1.0000001 0, 0 0))&#39;::<em>geometry</em></pre><p>Other existing representations are Points, LineStrings, Polygons, MultiPoints, MultiLineStrings, MultiPolygons, and GeometryCollections.</p><p>Notice, as opposed to Python, when using a PostGIS Polygon representation, the first and last points <strong>must</strong> be the same in order to close the polygon and get a valid representation.</p><ul><li><strong>From geometry: </strong>Geometry types can be converted back to arrays and text <strong>ST_AsText</strong>, <strong>ST_AsGeoJSON</strong>,</li></ul><pre>SELECT <strong>ST_AsGeoJSON</strong>(&#39;LINESTRING(1 2, 4 5)&#39;);<br>---------------------------<br>{&quot;type&quot;:&quot;LineString&quot;,&quot;coordinates&quot;:[[1,2],[4,5]]}</pre><pre>SELECT <strong>ST_AsGeoJSON</strong>(&#39;LINESTRING(1 2, 4 5)&#39;)::json-&gt;&gt;&#39;coordinates&#39;;<br>---------------------------<br>[[1,2],[4,5]]</pre><pre>=======================</pre><pre>SELECT <strong>ST_AsText</strong>(&#39;POINT(111.1111111 1.1111111)&#39;));<br>---------------------------<br>POINT(111.1111111 1.1111111)</pre><h3>PostGIS for Computer Vision</h3><h4>Segmentation — Intersection Over Union (IoU) metric</h4><figure><img alt="Intersection Over Union" src="https://cdn-images-1.medium.com/max/247/1*cAWhcOXlrMlEFY0MW1uVVA.png" /><figcaption>Image by the author</figcaption></figure><pre># Area<br><strong>ST_Area</strong>(l.polygon)</pre><pre># Union<br><strong>ST_Union</strong>(l1.polygon, l2.polygon)</pre><pre># Intersection<br><strong>ST_Intersection</strong>(l1.polygon, l2.polygon)</pre><pre># IoU<br><strong>ST_Area</strong>(<strong>ST_Intersection</strong>(l1.polygon, l2.polygon)) /<br><strong>ST_Area</strong>(<strong>ST_Union</strong>(l1.polygon, l2.polygon))</pre><p>Done!</p><h4>Pose estimation — Percentage of Detected Joints (PDJ) metric</h4><p>A detected joint is considered correct if the distance between the predicted and the true joint is within a certain fraction of the bounding box diagonal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*eh2hLtm-dHdsony7HLo3ZA.png" /><figcaption>Photo by <a href="https://unsplash.com/@barcelocarl?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Carl Barcelo</a> on <a href="https://unsplash.com/s/photos/gymnastic?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>. Annotations were added by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*X_-l4pQeXdxYwuh2XMgvyg.png" /><figcaption>Image by the author</figcaption></figure><ul><li><em>||d_pred — d_gt||² </em>— the euclidian distance between ground truth keypoint and predicted keypoint</li></ul><pre><strong>ST_Distance</strong>(<strong>ST_Point</strong>( GTi_x,GTi_y), <strong>ST_Point</strong>( predi_x,predi_y))</pre><ul><li>diagonal — diagonal distance of the bounding box</li></ul><pre>-- create bounding box<br><strong>ST_MakeBox2D</strong>(<strong>ST_Point</strong>(x1,y1),<strong>ST_Point</strong>(x2,y2))</pre><pre>-- get diaginal as line string<br><strong>ST_BoundingDiagonal</strong>(<strong>ST_MakeBox2D</strong>(<strong>ST_Point</strong>(x1,y1),<strong>ST_Point</strong>(x2,y2)))</pre><pre>-- calculate legnth<br><strong>ST_Length</strong>(<strong>ST_BoundingDiagonal</strong>(<strong>ST_MakeBox2D</strong>(<strong>ST_Point</strong>(x1,y1),<strong>ST_Point</strong>(x2,y2))))</pre><ul><li>threshold — the fraction of the diagonal.</li></ul><p>Final query: for this example, threshold = 0.05.</p><pre><strong>ST_Distance</strong>(<strong>ST_Point</strong>( GTi_x,GTi_y), <strong>ST_Point</strong>( predi_x,predi_y)) &lt; 0.05 * <strong>ST_Length</strong>(<strong>ST_BoundingDiagonal</strong>(<strong>ST_MakeBox2D</strong>(<strong>ST_Point</strong>(x1,y1),<strong>ST_Point</strong>(x2,y2))))</pre><h4>Detection — bounding box labels from polygons</h4><figure><img alt="Detection bounding box" src="https://cdn-images-1.medium.com/max/550/1*cbIRnJ_WSIZBP-4wQa2DXA.png" /><figcaption>Image by the author</figcaption></figure><p>In my case, I don’t have bonding box annotations. I do have polygon annotations for the segmentation task. I can easily create detection annotations from the polygons using PostGIS.</p><ul><li>Option 1 — get upper left and bottom right points</li></ul><pre>SELECT <strong>Box2D</strong>(&#39;POLYGON((7.7 51.8,3.8 48.3,7.2 43.5,18.6 43.8,17.9 50.2,13.7 54,7.7 51.8))&#39;::geometry)<br>----------------------------<br>BOX(<strong>3.8 43.5,18.6 54</strong>)</pre><ul><li>Option 2 — get all four points of the bounding box</li></ul><pre>SELECT <strong>ST_Envelope</strong>(&#39;POLYGON((7.7 51.8,3.8 48.3,7.2 43.5,18.6 43.8,17.9 50.2,13.7 54,7.7 51.8))&#39;::geometry)</pre><pre>SELECT <strong>ST_AsText</strong>(<strong>ST_Envelope</strong>(&#39;POLYGON((7.7 51.8,3.8 48.3,7.2 43.5,18.6 43.8,17.9 50.2,13.7 54,7.7 51.8))&#39;::geometry))<br>----------------------------<br>POLYGON((<strong>3.8 43.5</strong>,3.8 54,<strong>18.6 54</strong>,18.6 43.5,3.8 43.5))<br>--- We have 5 coordinates and the last coordinate is always the first one as it is a polygon representation.</pre><h4>Polygon transformations</h4><p>Do you want to rotate your polygon by 30 degrees? Do you want to scale it up by 2? Easy! PostGIS has several transformation options.</p><pre># Rotate 30 degrees counter-clockwise with origin x=50, y=160<br>SELECT <strong>ST_Rotate</strong>(l.polygon, pi()/6, 50, 160));</pre><pre># Scale X,Y<br>SELECT <strong>ST_Scale</strong>(l.polygon, 0.5, 0.75)</pre><pre># Scale X,Y,Z<br>SELECT <strong>ST_Scale</strong>(l.polygon, 0.5, 0.75, 0.8)</pre><pre># Translate X, Y<br>SELECT <strong>ST_Translate</strong>(l.polygon ,1, 0);</pre><h4>Polygon visualization</h4><p>Want to show the user the great polygon you generated, but you don’t want to show all the hundreds of points? Use <strong>ST_Simplify</strong>!</p><p>ST_Simplify returns a “simplified” version, with fewer points, of the given geometry using the Douglas-Peucker algorithm.</p><pre>SELECT <strong>ST_Simplify</strong>(geom,&lt;tolerance&gt;)</pre><h4>More options</h4><p>And there are many more options:</p><ul><li>Want to calculate the convex hull of a polygon? <strong>ST_ConvexHull</strong></li><li>Want to check whether polygons are overlapping? <strong>ST_Overlaps</strong></li><li>Check if a dot is inside a polygon? <strong>ST_Within</strong></li><li>Need to calculate the distance between geometries (polygons, lines, dots)? <strong>ST_Distance</strong></li><li>Check for self-intersections? <strong>ST_IsValid.</strong></li><li>Remove self-intersections?<strong>ST_MakeValid</strong></li></ul><h3>If you insist on Python…</h3><p>If I didn’t convince you that PostGIS is great, and you still want this functionality but in Python, take a look at:</p><ul><li><a href="https://shapely.readthedocs.io/en/stable/#">Shapely - Shapely 1.8.1.post1 documentation</a></li><li><a href="https://geopandas.org/en/stable/">GeoPandas 1.1.1 - GeoPandas 1.1.1+0.ge9b58ce.dirty documentation</a></li></ul><h3>Epilogue</h3><p>I hope I convinced you that PostGIS is very a useful extension not only for data analysts but also for computer vision developers. It offers a rich variety of options and manipulations on geometries.</p><p>It helped me to upgrade my queries and spared me the overhead of using both SQL for extracting the data and Python for analyzing the data. Now I can do both in one place and directly save the results back to the database.</p><p>I hope it will help you too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e703e37ad55" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/postgis-for-computer-vision-developers-5e703e37ad55">PostGIS for Computer Vision Developers</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[Active Learning Behind The Scenes]]></title>
            <link>https://medium.com/data-science/active-learning-behind-the-scenes-7e82f024a5db?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e82f024a5db</guid>
            <category><![CDATA[evaluation]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[active-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 17:11:25 GMT</pubDate>
            <atom:updated>2022-01-22T05:43:46.528Z</atom:updated>
            <content:encoded><![CDATA[<h3>Active Learning Behind the Scenes</h3><h4>How do I evaluate my Active Learning results?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SKUFRRIoIgH52_K_" /><figcaption>Photo by <a href="https://unsplash.com/@gwenking?utm_source=medium&amp;utm_medium=referral">Gwen King</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In my previous posts, I described what is Active Learning (<a href="https://towardsdatascience.com/how-to-start-being-an-active-learner-8d311d68fb70">introduction to Active Learning and the main approaches</a>) and how one can implement such a pipeline in a simple and generic way (<a href="https://towardsdatascience.com/towards-a-fully-automated-active-learning-pipeline-29b8f4eb7d73">architecture for Active Learning pipeline</a>).</p><p>This post is based on a talk I gave at Reversim Summit 2021. I want to jump a few steps forward and talk about how I evaluate my Active Learning models’ results and how it helped me to catch a huge bug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-_ePUheaVkg3uH8piWKKEw.jpeg" /><figcaption>Image by Gilad Artzi from Reversim Summit 2021 (with permission from organizers)</figcaption></figure><h3>Active Learning = Data Selector</h3><p>In general, when we talk about Active Learning, we talk about creating a Data Selector. An automatic algorithm that will be able to choose a subset from our unlabeled data and will give our model the largest performance gain, so it will be able to learn and improve its accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*vOKIQ1LXgT7w0oqvGccTQg.png" /><figcaption>Data Selector. Image by the author.</figcaption></figure><h3>Data Selector Evolution</h3><p>Let’s say we have 1 million new unlabeled images. We can send only 1000 of them to the annotators and add them to the training set. How will we choose those 1000 images?</p><h4><strong>Random sampling</strong></h4><p>The most popular way to select unlabeled data for tagging is random sampling. Just choose randomly the number of samples you need. The assumption, in this case, is that more data results in higher accuracy of our algorithms. Using random sampling, we don’t take into consideration our current model, if we have one. We select the data regardless of the strength and weaknesses of our model.</p><p>That leads us to the second option.</p><h4><strong>Human smart selector</strong></h4><p>In this option, we leverage the knowledge we have as data scientists about our data and model. We can choose wisely the data we want to use. We know what type of data is more challenging to our model, on what kind of samples it will fail, and we can use this knowledge to choose those exact samples and put the efforts into them.</p><p>But it will not last long. It’s not scalable. A single data scientist can’t go over the huge unlabeled dataset. What we would really want is an automatic version of ourselves.</p><h4><strong>Automatic smart selector</strong></h4><p>What we actually want is to create an automatic algorithm that encapsulates the knowledge we have regarding the model and data and of course more knowledge that we currently don&#39;t have. This way, it will be easier and faster to choose wisely a subset from our unlabeled data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*r72vYIogtB_YOEY_o5FIiQ.png" /><figcaption>Data selection evolution. Image by the author. Left Lego image: Photo by <a href="https://unsplash.com/@xavi_cabrera?utm_source=medium&amp;utm_medium=referral">Xavi Cabrera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Creating such an automatic Data Selector can be done in several ways. You can read more about it in my <a href="https://towardsdatascience.com/towards-a-fully-automated-active-learning-pipeline-29b8f4eb7d73">previous posts</a>.</p><p>In this post, we will focus on evaluating the results of <a href="https://towardsdatascience.com/how-to-start-being-an-active-learner-8d311d68fb70">uncertainty methods</a>. Reminder, in uncertainty methods we aim to identify the hard samples, the ones that our model is uncertain about its output.</p><h3>Active Learning Iteration — Overview</h3><p>Before we move on to the evaluation, let’s briefly go over a single Active Learning iteration. Active learning is a continuous process in which at each iteration we apply the data selector on the current unlabeled dataset. A single iteration includes two main steps — selecting and annotating a subset from the unlabeled data, and training again the model using this newly selected data, together with the already existing training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRVX2K1QOn32Gy6NBA0JxQ.png" /><figcaption>SIngle Active Learning iteration. Image by the author</figcaption></figure><h3>Active Learning Evaluation</h3><p>Once we developed our Data Selector, we would like to evaluate our entire learning pipeline.</p><p>In the POC phase, we have a large annotated data set that we use for our research. We will use it here for the evaluations.</p><p>The validation set is fixed across all experiments. Only the training is changing.</p><h4>Smart Selection vs Random Selection</h4><p>The first and most important evaluation is to check our model&#39;s performance with and without the Data Selector. Our baseline is a model developed using random sampling of the data (without a Data Selector). We want that our new model, the one that was developed using data chosen wisely (with a Data Selector), will get better performance than the baseline when using the same amount of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*9nGhrGS0Uugfg0Sy7jIxuQ.png" /><figcaption>Models performance. Image by the author.</figcaption></figure><p>That’s great! We get higher performance than the baseline!</p><h4>Is it enough?</h4><p>What does this graph tell us about the Data Selector? How do we know that it chose the hard and uncertain samples? The answer is that we don’t. We need to look behind the scene of this graph and get a better understanding of the data selection and the learning that was done.</p><p>I tell you that because I had a bad experience. My first performance graph was perfect, too good to be true. And it was indeed the case. There was a huge bug that somehow cause the graph to be great. And I fell into the trap and thought that I nailed it and accomplished the task. But then when I investigated my Data Selector I got weird results. That’s where I found my bug. I would have never found it if I didn’t take a look behind the scenes.</p><h4>Ranking data samples to hard and easy</h4><p>To understand better our Data Selector we need to rank our samples, images in my case, into easy and hard samples so we will be able to investigate the Data Selector selections.</p><p>In my case, each image was labeled by three different annotators. I can use all the annotations to calculate the consensus between the annotators. Images with low consensus can be seen as hard samples, while images with high consensus can be seen as easy samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyxyxjPtKrnAV7pQolb42w.png" /><figcaption>Image created by the author.</figcaption></figure><h4>Data Selector Evaluation</h4><p>In this section, I will describe how I investigate my Data Selector results. Using the ranked image, from the last section, I created the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*cBILFW6lrcqX9t-8eZHejQ.png" /><figcaption>Graph created by the author.</figcaption></figure><p>Let me go over the graph.</p><ul><li>Y-axis — the average annotators’ consensus as explained in the last section. High consensus → easy sample.</li><li>X-axis — the subset our Data Selector chose at each learning iteration.</li><li>Red line — random sampling. As expected, when we sample randomly the consensus stays the same across all iterations.</li><li>Cyan line — smart selection. In this case, we expect the graph to increase monotonically. Each time the Data Selector selects a new subset, it should select the hardest examples. Thus the next subset it will choose will be an easier subset. This is because we have a finite dataset in the research phase.</li></ul><p>If we don’t get a monotonically increasing line, we need to ask ourselves why and if it makes sense. It might be a bug or it might happen because of the characteristics of the method you use. Anyway, <strong>we need this graph in order to see that our Data Selector behaves the way it should.</strong></p><h4>Learning Evaluation</h4><p>OK, great, our Data Selector works. Now we want to take a step forward and to take a look behind the scenes of our learning process. We want to see whether the better performance arises from better accuracy on easy samples, or whether we succeed and get better performance also on hard samples.</p><p>To this end, I created the following graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*OYqFJeHDjCggFKq2hslFxA.png" /><figcaption>Graph created by the author.</figcaption></figure><p>So what do we see here?</p><ul><li>Y-axis — the model&#39;s accuracy</li><li>X-axis — goes from hard to easy samples by annotator consensus. (for example —leftmost bin represents annotators consensus between 0% to 10%, while the rightmost bin represents a consensus between 90% to 100%)</li><li>Red and cyan histograms — results using random sampling and smart selection respectively.</li><li>Red and cyan lines — histogram’s trend line (one for each histogram according to the color).</li></ul><p>Now let’s see what can we learn from this graph and why it’s an important one. First, we see that the cyan trend line (smart selection) is always higher than the red trend line (random selection). Meaning, <strong>when we choose our data wisely we get higher accuracy for both easy and hard samples.</strong></p><p>But there’s more. If we look at the yellow polygon, the area between the trend lines, we can see that the area is bigger in the hard samples zone. Meaning, <strong>the accuracy gain we get relative to random sampling, comes from improvement on hard samples, more than the improvement on easy samples.</strong></p><p>That’s exactly what we want!!</p><h3>Takeaway</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*MdFP6Fk1A_vYbwh_HKa1Ew.png" /><figcaption>Image by the author.</figcaption></figure><p>Eventually, I know that not all the things I described here can be applied to your data. But it’s not the point.</p><p>The main takeaway is that we need to take a look behind the scenes, each one in its own suitable way. The performance graph alone is not enough in this case. The performance graph does not tell you the entire story (a bug in my case). We need to dig deeper and understand our Data Selector behavior, and we need to check if we indeed get improvement on the hard samples in our data, because that is where we want to put our efforts.</p><p><strong>So let&#39;s take a look together behind the scenes, and let&#39;s improve our models!</strong></p><ul><li><a href="https://towardsdatascience.com/how-to-start-being-an-active-learner-8d311d68fb70">How to start being an active learner?</a></li><li><a href="https://towardsdatascience.com/towards-a-fully-automated-active-learning-pipeline-29b8f4eb7d73">Towards a fully automated active learning pipeline</a></li></ul><p>Want to hear more about my work? Follow me on <a href="https://www.linkedin.com/in/sbiham/">Linkedin</a>, and visit my <a href="https://www.sbiham.com/">website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e82f024a5db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/active-learning-behind-the-scenes-7e82f024a5db">Active Learning Behind The Scenes</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[Towards a fully automated active learning pipeline]]></title>
            <link>https://medium.com/data-science/towards-a-fully-automated-active-learning-pipeline-29b8f4eb7d73?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b8f4eb7d73</guid>
            <category><![CDATA[active-learning]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 19:04:36 GMT</pubDate>
            <atom:updated>2021-06-08T19:04:36.008Z</atom:updated>
            <content:encoded><![CDATA[<h3>Towards a Fully Automated Active Learning Pipeline</h3><h4>Simple, modular, and generic architecture for active learning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Q3RTSDyox-z-DsrhY5WVew.jpeg" /><figcaption>Image is taken from <a href="https://www.freepik.com/free-vector/plumber-service-concept_2869860.htm">freepik</a></figcaption></figure><p>In my <a href="https://towardsdatascience.com/how-to-start-being-an-active-learner-8d311d68fb70">previous post</a>, I gave a short introduction to the theory and methods of active learning. The next step in the Active Learning journey is the implementation. In this post, I will share my journey towards a complete automated active learning pipeline.</p><h3>Step 1 — Motivation to implement</h3><p>At first, like other motivated algorithm developers, I started by implementing the chosen active learning method. I didn’t think about the next steps and the “bigger picture”. On one hand, it got me pretty fast to a working (engineering-wise) implementation. On the other hand, it made the next steps harder. In my case I had two parallel next steps, that raises three different questions:</p><ol><li>How do I build an active learning pipeline?</li><li>How to build the pipeline in a modular and generic way?</li><li>How to incorporate multiple different tasks into the pipeline?</li></ol><h3>Step 2 — active learning pipeline — semi-automatic</h3><p>My first active learning pipeline implementation was semi-automatic. Each cycle runs fully automatically but is executed manually. To this end, the main addition is the Data Selector.</p><h4><strong>Data Selector</strong></h4><p>The Data Selector encapsulates the purpose of active learning — choosing the next images to be annotated in an informed way. Its input is a set of currently non-annotated data and its output is a sub-set to be annotated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*NNHV4dvzbDgfQXFhMcug5w.png" /><figcaption>Image by Author</figcaption></figure><p>The Data Selector can be an additional neural network, classic algorithm, database query, or any other method that works for you.</p><p>At each cycle, the Data Selector is based on the best model from the previous cycle. Its output set is added to the training set of the previous cycle (after annotating it).</p><h4>Why is semi-automatic not good enough?</h4><p>Besides the overhead of executing each cycle manually, which is time-consuming, a semi-automatic pipeline requires monitoring. By monitoring, I mean that we need to remember which cycle we want to run, where we save the state of the previous cycle, manually choosing the inference model from the previous cycle, and more. This process has a high potential for errors, bugs, and confusion. Ideally we want a fully automatic pipeline, which is the topic of our next section.</p><h3>Step 3 — modular and generic active learning pipeline</h3><p>I have several models for several different tasks. One day I found myself doing copy-paste from one file to four other different files, again and again. At this point, I decided that something needs to change, and it’s time for standardization.</p><p>The training pipeline component is the most important one in the sense of software engineering. Maintaining modular and standard architecture to your training pipeline can save you a lot of trouble the next time you implement a new network.</p><p>Inspired by <a href="https://github.com/moemen95/Pytorch-Project-Template/">this</a> template, I created my own deep learning code architecture with three main components- data loader, graph, and agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55abt9QtBf3SQJHMrhkpXg.png" /><figcaption>Image by Author</figcaption></figure><p><strong>Data Loader — </strong>as<strong> </strong>implied from its name, the Data Loader encapsulates all we need to create a data loader object.</p><p><strong>Graph — </strong>The Graph contains our network model and other components needed for training, such as optimizer, scheduler, and loss.</p><p>By defining the Graph, it is easier to reuse shared components. For example, I have two segmentation tasks, using the same loss function. My Graph superclass contains the loss function implementation, and each task is implemented as a graph class that inherits from the Graph superclass.</p><p><strong>Agent — </strong>The agent is our training class. Each specific task inherits from an Agent superclass and must implement train and eval methods. A generic training loop is implemented in the agent superclass, and any other class that inherits from it can extend it.</p><h3>Step 4 — active learning pipeline — automatic</h3><p>Back to the active learning pipeline, we finally get to the last step. In order to create a fully automated pipeline, we need to close the loop. First, each cycle needs to load the state of the previous state and save its current state. Second, we need to automatically choose the best inference model to use. This is done using the Model Selector module.</p><p>Model Selector<strong>— </strong>Finishing the training pipeline, we have several saved models from different points in the training loop. The Model Selector chooses the best model, using a given criterion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*qoLKmDgbqY7rJckekp8B7Q.png" /><figcaption>Image by Author</figcaption></figure><p>This model will be used as the Data Selector model in the next cycle (for relevant methods) and as the new production model.</p><h3>Bonus step — Compare module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*rqNuMp3NEnz3k29saT3MrQ.png" /><figcaption>Image by Author</figcaption></figure><p>Do we always want to retrain our network for any new selected non-annotated batch? Probably not. We want to retrain our model when we notice a deterioration in the results. For this, we use the Compare module.</p><p>The compare module is pretty simple and works as follow:</p><ol><li>Pass the new annotated images in the Data Selector module.</li><li>Measure the quality of the results and compare them to your key performance indicator (KPI).</li><li>Meets the KPI — no need to retrain.</li><li>Does not meet the KPI — retrain.</li></ol><p>The compare module can be eliminated in the development stage. In the development stage, we want to prove that our active learning approach works. To do so, we use a known fully annotated dataset and show that we can choose our next training samples in an informed way. For more details, see my previous post.</p><p><a href="https://towardsdatascience.com/how-to-start-being-an-active-learner-8d311d68fb70">How to start being an active learner?</a></p><h3>Finish Line</h3><p>It’s time to wrap up and summarize the entire architecture. In the following scheme, you can find the automated pipeline with all its modules and their connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yx2JNSkwh_yV3Ml7tJvevg.png" /><figcaption>Active learning pipeline scheme. Image by Author.</figcaption></figure><h3>We did it!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gspsew0lca3y6jdR" /><figcaption>Photo by <a href="https://unsplash.com/@hanness?utm_source=medium&amp;utm_medium=referral">Jo Jo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now we are all familiar with the steps toward creating a great active learning pipeline.</p><p>To me, it took some time to organize all my existing code to fit this pipeline architecture. But after it’s done, adding a new task or changing my Data Selector method became much easier.</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b8f4eb7d73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/towards-a-fully-automated-active-learning-pipeline-29b8f4eb7d73">Towards a fully automated active learning pipeline</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 start being an active learner?]]></title>
            <link>https://medium.com/data-science/how-to-start-being-an-active-learner-8d311d68fb70?source=rss-b3aafc24ed45------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d311d68fb70</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[active-learning]]></category>
            <dc:creator><![CDATA[Sivan Biham]]></dc:creator>
            <pubDate>Sat, 17 Apr 2021 16:34:59 GMT</pubDate>
            <atom:updated>2021-04-17T16:34:59.016Z</atom:updated>
            <content:encoded><![CDATA[<h4>A short introduction to Active Learning for Computer Vision</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gs-91OoxjBQicsatrYhpfw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@myleon?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Leon</a> on <a href="https://unsplash.com/s/photos/education?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Deep learning (DL) models are the most common methods for many tasks in computer vision. DL achieves tremendous results by using a huge amount of labeled data. However, as computer vision tasks become more complex, the DL network gets bigger and the number of parameters increases, which requires even more labeled data to train the network.</p><p><em>Why is this a problem?</em></p><ul><li><strong>Annotation cycle</strong> — Larger dataset to be labeled → higher price + longer time to finish all annotations.</li><li><strong>Training cycle</strong> — Larger training datasets → longer training time.</li></ul><p><strong><em>Active learning is here for the rescue!</em></strong></p><p><strong>The goal of active learning in DL is to train a model with less data — cheaper annotation budget and shorter training cycle — and get similar performance.</strong></p><p>In this post, I will describe what is active learning, share some common methods, their pros, and cons, and add some personal insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1EY5Y-7aOYgE7RURkimGKQ.png" /><figcaption><strong>Fig.1-Green line </strong>— Accuracy level is higher for the same amount of data. <strong>Orange line — </strong>Same accuracy level for less amount of data. (Image created by the author)</figcaption></figure><p><em>What is active learning?</em> Active learning is a continuous training pipeline that utilizes different methods (described below) to select the next samples to be annotated. The selection process is informed, rather than a random selection process (Fig.3 (b)), as usually done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*30SqUSdxF4ahfXRXZlRZUA.png" /><figcaption><strong>Fig.2 — </strong>Active Learning general pipeline [8]</figcaption></figure><p><em>How can we do it?</em> Active learning methods aim to choose a subset of the most informative and representative images from our unlabeled set of images. In this way, we can get higher model accuracy while using smaller datasets.</p><h3>Active Learning approaches:</h3><p>Active learning methods can be divided into three main categories [1] :</p><ol><li><em>Uncertainty methods</em> — define and measure the quantity of uncertainty to select data points (Fig.3 (c) ).</li><li><em>Diversity methods</em> — select diverse data points that represent the whole distribution of unlabeled pools (Fig.3 (d)).</li><li><em>Expected model change</em> — select points that would cause the greatest change to the current model parameters or outputs if their labels were known.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*6ySNAjrDStLZuTcXKqXSrQ.png" /><figcaption><strong>Fig.3-</strong>Sampling strategies [4]. Blue and red dots represent different classes of the data.</figcaption></figure><p><em>Expected model change </em>methods<em>, a</em>pplied successfully for small models but it is computationally impractical for recent deep networks. Thus, we will be focusing on the first two categories.</p><p>In my experience, active learning methods can be also divided into<em> task-specific or task-agnostic</em>. If I have a pipeline that includes several tasks, I might prefer to find a task-agnostic method that will be used for all models. In contrast, I may have found a great method, specific to a certain task, that improves greatly my results. In this case, it might be worth maintaining several different methods.</p><h3>Uncertainty methods:</h3><p>Uncertainty methods aim to select images that the model is most unsure of its output. Thus, most uncertainty methods are model-dependent and need to be trained or adjusted for each new model.</p><h4>Uncertainty measure directly on the output (task and model specific)</h4><p>The easiest way to get uncertainty measured directly from the output is to use a dropout layer at the inference (also called Monte Carlo Dropout). Using dropout at inference, our predictions are no longer deterministic but depend on the randomly dropped nodes. Thus, the uncertainty of image output can be estimated by computing the variance of T different predictions (for more information see [9], and for example on segmentation task see [6]).</p><h4>Uncertainty measure incorporate in the network (task-specific and task-agnostic)</h4><p>A different approach for getting the uncertainty measure is to incorporate the uncertainty prediction into the network by adding additional parallel branches.</p><p>Next, I will describe two methods that use this approach, one method is task-specific and the other is task agnostic.</p><p><em>Task-specific </em>[1] — Specific for image segmentation tasks. Focuses on uncertainty in the bounding box and mask predictions.</p><p>Two parallel branches are attached to the detection head and mask head of the network (Fig.4 — in blue network branch). The output from each branch is a value that predicts the intersection-over-union (IoU) of the predicted bounding box and target box and IoU of the predicted mask and target mask. The final prediction score is a combination of the IoU predictions and the classification score. The lower the score, the higher the uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*g5JqKFH2xvGwIN2Pdb1o3w.png" /><figcaption><strong>Fig.4— </strong>Architecture illustration. In blue, the attached branched for IoU predictions and the added loss for training [1]</figcaption></figure><p><em>Task agnostic </em>[2] — Can be added to any existing network we use. The goal is to learn to predict the network’s loss. The higher the loss, the more the network is uncertain on the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*FxhUtjQe2W2MurhQlRglnw.png" /><figcaption><strong>Fig.5 </strong>[2]</figcaption></figure><h4>Takeaways from uncertainty methods</h4><ul><li>Pros: Easy to implement and can be plugged in easily to existing models.</li><li>Cons: Might contain redundant data points. Deep learning tends to be uncertain on similar images.</li><li>Personal insights: I found the uncertainty method to be straightforward to understand, both from the algorithmic side and from the implementation side.</li></ul><h3>Diversity methods:</h3><p>Diversity methods aim to select a subset from our non-annotated set, such that it will represent our data distribution. In contrast to uncertainty methods which might result in redundant instances, the diversity approach tries to spread the chosen data across the entire distribution.</p><p>Diversity methods measure the similarity between image features and output a subset of non-annotated images such that it represents the entire data distribution, with emphasis on sampling the diverse cases.</p><h4>So how do we create those image features?</h4><p>A straightforward way is to measure the distance between features extracted from convolution neural networks. Then, images that are similar to many other non-annotated images and cover diverse cases will be chosen (see [5] for more information).</p><p>A different way is to use Variational Autoencoder and learn a mapping function to a latent space with the desired probability distribution. Then, for a new batch of non-annotated data, create a subset whose mapping distribution to the latent space is similar to the learned distribution (see [3] for more information).</p><h4>Takeaways from diversity methods</h4><ul><li>Pros: Model and task-independent. Can be used to find rare cases, and deal with class imbalance.</li><li>Cons: Might be harder to understand, requires a deeper theoretical understanding</li><li>Personal insight: I like the coupling elimination between active learning and the specific task.</li></ul><h3>Enjoy both worlds — use both methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*uJzrpIwiKLRsgr3YnaYOjQ.png" /></figure><p>As can be seen, each one of the categories has its own pros and cons. Why not combine them and enjoy both? In the next post, I will elaborate on how to leverage the pros of both approaches to get even better results. For now, you can take a look at [3] and [6] and <strong>start being an active learner!</strong></p><h3>References:</h3><p>[1]<a href="https://www.bmvc2020-conference.com/assets/papers/0031.pdf"> Semi-supervised Active Learning for Instance Segmentation via Scoring Predictions</a></p><p>[2]<a href="http://openaccess.thecvf.com/content_CVPR_2019/html/Yoo_Learning_Loss_for_Active_Learning_CVPR_2019_paper.html"> Learning loss for active learning</a></p><p>[3]<a href="https://arxiv.org/pdf/1912.10493.pdf"> Active Learning for Segmentation Based on Bayesian Sample Queries</a></p><p>[4]<a href="https://arxiv.org/pdf/1909.03585.pdf"> Learning to Sample: an Active Learning Framework</a></p><p>[5]<a href="https://link.springer.com/chapter/10.1007/978-3-319-66179-7_46"> Suggestive annotation: A deep active learning framework for biomedical image segmentation</a></p><p>[6]<a href="https://arxiv.org/abs/1711.09168"> Cost-effective active learning for melanoma segmentation</a></p><p>[7]<a href="http://proceedings.mlr.press/v48/gal16.pdf"> Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning</a></p><p>[8]<a href="https://www.researchgate.net/publication/329362769_The_Relevance_of_Bayesian_Layer_Positioning_to_Model_Uncertainty_in_Deep_Bayesian_Active_Learning"> The Relevance of Bayesian Layer Positioning to Model Uncertainty in Deep Bayesian Active Learnin</a>g</p><p>[9] <a href="https://arxiv.org/pdf/1506.02142.pdf">Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d311d68fb70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-start-being-an-active-learner-8d311d68fb70">How to start being an active learner?</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>