<?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 Hannah Peterson on Medium]]></title>
        <description><![CDATA[Stories by Hannah Peterson on Medium]]></description>
        <link>https://medium.com/@hbpeters?source=rss-d47c7e37bf13------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_e0aiEDRcbmypUT-UEwG8g.png</url>
            <title>Stories by Hannah Peterson on Medium</title>
            <link>https://medium.com/@hbpeters?source=rss-d47c7e37bf13------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:24:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hbpeters/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[My Data Science Internship Experience]]></title>
            <link>https://medium.com/gsi-technology/my-data-science-internship-experience-e4fc7b3cf002?source=rss-d47c7e37bf13------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4fc7b3cf002</guid>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hannah Peterson]]></dc:creator>
            <pubDate>Thu, 17 Sep 2020 17:13:21 GMT</pubDate>
            <atom:updated>2020-09-18T13:21:48.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xyebyMLkE38J5cA3uVY4w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@richtervet?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Rich Tervet</a> on <a href="https://unsplash.com/s/photos/desk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Coming into it, I wasn’t sure what to expect from a remote internship experience—in light of the pandemic, I was grateful to still have an internship with GSI Technology at all. Now, a quick three months later, it’s almost over! So to wrap-up, I thought I’d share some of my takeaways from my data science internship at GSI.</p><p>I knew I was going to be writing blogs for GSI from seeing the past interns’ work but I wasn’t sure how to even begin that process. Luckily, I began with a pretty focused topic for my first blog and my mentor helped me make an outline to guide my research. A writing process that ended up working for me was to do a bit of preliminary, general research on the topic of interest such that I could jot down an outline, and then to focus my research further based on the outline; otherwise, the sheer amount of articles and papers covering these data science concepts could quickly get overwhelming.</p><p>Speaking of research papers, I got a lot of experience reading them this summer! Specifically, I gained confidence in knowing that if I spend enough time grappling with papers I’ll generally be able to make sense of them, something that’s important to keep in mind when faced with all of the technical jargon and complex equations in data science literature—it can be pretty intimidating initially.</p><p>I quickly came to terms with the fact that there was no way for me to fully grasp any of these data science topics within a matter of weeks, as they are subjects people spend their entire careers researching, and I learned to be okay with developing a decent surface level understanding of things, so long as I understood enough to write effectively about them. After all, I wasn’t writing to experts in the field necessarily but to people who were at similar experience levels to myself prior to when I began researching, which brings me to perhaps my most important takeaway from blog writing: know your intended audience. Knowing my audience and keeping in mind the central messages I wanted to convey to them helped me keep my research focused and avoid going down unnecessary rabbit holes (not to say that didn’t still happen, occasionally 🙂).</p><p>I also learned to refer to outside resources for direction when I couldn’t find the answers I was looking for online: the authors of papers or GitHub repositories, industry experts, etc. Most of the time, I found people are very willing to provide advice and suggestions — the worst thing that can happen is they don’t reply, and the best thing is that they share information that saves you a lot of time and/or strife in the long run.</p><p>In sum, I learned a lot about current state-of-the-art research in various realms of data science over the course of my internship at GSI. I did a deep dive into satellite image processing and image segmentation, scratched the surface of reinforcement learning, and researched techniques for model compression and task retention in neural networks. And blogging about these topics really helped solidify my knowledge of them and gave me practice communicating technical concepts in an easily interpretable way to people who may be less familiar with them—a skill that will definitely be of use in future workplaces. Finally, I’m really grateful to my mentor, <a href="https://medium.com/@georgewilliams">George</a> (gwilliams@gsitechnology.com), for his expertise, patience, and guidance along the way.</p><p>With that, the following is a list of the blogs I’ve published during my internship at GSI, marking the end of a great summer and a valuable learning experience!</p><ul><li><a href="https://medium.com/gsi-technology/getting-started-with-satellite-data-processing-7653dbd4fc1e?source=friends_link&amp;sk=b7b69f429154e8ed6d1c327ee58738c1">Getting Started with Satellite Data Processing</a></li><li><a href="https://medium.com/gsi-technology/a-beginners-guide-to-segmentation-in-satellite-images-9c00d2028d52?source=your_stories_page---------------------------">A Beginner’s Guide to Segmentation in Satellite Images</a></li><li><a href="https://medium.com/gsi-technology/demystifying-markov-decision-processes-cd8f119aa3d1?source=your_stories_page---------------------------">Demystifying Markov Decision Processes</a></li><li><a href="https://medium.com/gsi-technology/core-concepts-in-reinforcement-learning-by-example-dc8e839f6a2c?source=your_stories_page---------------------------">Core Concepts in Reinforcement Learning By Example</a></li><li><a href="https://medium.com/gsi-technology/an-overview-of-model-compression-techniques-for-deep-learning-in-space-3fd8d4ce84e5?source=your_stories_page---------------------------">An Overview of Model Compression Techniques for Deep Learning in Space</a></li><li><a href="https://levelup.gitconnected.com/your-neural-network-will-forget-what-its-learned-39b7f578f24a?source=your_stories_page---------------------------">Your Neural Network Will Forget What It’s Learned!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4fc7b3cf002" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gsi-technology/my-data-science-internship-experience-e4fc7b3cf002">My Data Science Internship Experience</a> was originally published in <a href="https://medium.com/gsi-technology">GSI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Neural Network Will Forget What It’s Learned!]]></title>
            <link>https://medium.com/gsi-technology/your-neural-network-will-forget-what-its-learned-39b7f578f24a?source=rss-d47c7e37bf13------2</link>
            <guid isPermaLink="false">https://medium.com/p/39b7f578f24a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Hannah Peterson]]></dc:creator>
            <pubDate>Thu, 10 Sep 2020 21:30:22 GMT</pubDate>
            <atom:updated>2020-09-17T00:03:31.367Z</atom:updated>
            <content:encoded><![CDATA[<h4>This can be catastrophic, but you can fix it</h4><p><em>By Hannah Peterson and </em><a href="https://medium.com/@georgewilliams"><em>George Williams</em></a><em> (gwilliams@gsitechnology.com)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEImESJuQA-lS76C5JrOag.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brucemars?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">bruce mars</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is Catastrophic Forgetting?</h3><p>Our brains are ever-evolving objects, continuously revising their structures to retain new information and get rid of the old based on our interactions with the environment. As we know, artificial neural networks with their webs of activations and connections were originally modeled after the brain. Most ANNs, however, are made to be static in structure, relying on <em>batch learning</em> in which they are fed many batches of independent identically distributed (IID) data at training time and their learned parameters are fixed upon deployment, which is inconsistent with the way our brains learn: We do not learn by processing random batches of data all at once, but by processing the continuous streams of causally related information we receive about our environment from our senses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeYH5cQahLAbIUfgmcvj2A.png" /><figcaption><a href="https://medinform.jmir.org/2017/2/e12/">Source</a></figcaption></figure><p>While batch learning works fine for tasks in which the precise nature of the data a model will encounter at inference is known beforehand, like in classifying specific classes of random photos, this is an unrealistic precedent in many real-world applications where a model may encounter new data after deployment. In such instances, we would want the model to adapt to deal with the new data on the fly, a process known as <em>online learning. </em>Additionally, in most cases the data encountered is not random but occurs in sequences of related instances, such as frames of a video or fluctuations in a stock’s price—a property that must also be taken into account when developing online learning solutions.</p><p>There have been several attempts to create evolving neural networks for online learning but they inevitably run into the problem of what is known as <em>catastrophic forgetting </em>(sometimes called<em> catastrophic interference</em>), where adapting to perform new tasks causes the network to “forget” those it previously learned. This phenomenon was first discovered by researchers <a href="https://experts.illinois.edu/en/publications/catastrophic-interference-in-connectionist-networks-the-sequentia">McCloskey and Cohen</a> all the way back in 1989 when testing a network’s ability to sequentially learn associate list tasks. In their experiment, the first task consisted of learning pairs of arbitrary words from two sets <em>A</em> and <em>B</em>, such as “locomotive - dishtowel, window - reason, bicycle - tree, etc.” The network was trained until it could perfectly recall the <em>B</em> associate for each <em>A</em> item. It then began learning a second task in which set <em>A</em> was paired with different words from set <em>C</em>, such as “locomotive - cloud, window - book, bicycle - couch, etc.” and it was tested on its ability to remember pairings from the <em>AB</em> list after 1, 5, 10 and 20 iterations of learning the <em>AC </em>list. The following graph<em> b)</em> shows how the network rapidly forgets the <em>AB </em>task after beginning to learn the <em>AC</em> task, as compared to human performance in the same experimental setup, which demonstrates that our brains are able to retain knowledge of previous tasks much more effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2oUscvvCJqRAiIzJzGHUA.png" /><figcaption><a href="https://grey.colorado.edu/CompCogNeuro/index.php/CCNBook/Memory">Source</a></figcaption></figure><p>It’s undoubtedly challenging to construct a network that is finite in structure but that can retain knowledge of past experiences given a continuous stream of data. Initial tactics for overcoming catastrophic forgetting relied on allocating progressively more resources to networks as new classes were learned, an approach that is ultimately unsustainable for most real-world applications. Let’s now take a look at some more recent strategies for compelling networks to remember.</p><h3>Strategies for Remembering</h3><h4>Regularization</h4><p>One heavily researched mechanism for dealing with catastrophic forgetting is regularization. As we know, a network adapts to learn new tasks by adjusting the weights of its connections, and regularization involves varying the changeability, or <em>plasticity</em>, of weights based on how important they are determined to be for previous tasks.</p><p>In a highly cited <a href="https://arxiv.org/pdf/1612.00796.pdf">2017 paper</a>, Kirkpatrick et al. introduced a regularization technique called Elastic Weight Consolidation (EWC). EWC maintains the fidelity of connections important for previously learned tasks by constraining weights to stay close to their learned values as new tasks are encountered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9ysCFn45S0caYaEJtwCXA.png" /></figure><p>To illustrate how EWC works, let’s say we are learning some classification task <em>A</em>, for which our network is learning a set of weights <em>θ</em>. There are, in fact, multiple configurations of <em>θ </em>that will yield good performance on <em>A</em>—a general ballpark of weights represented by the gray ellipse in the diagram above. Catastrophic forgetting occurs when the network moves on to learn a different task <em>B</em> associated with a different ballpark of weights—the cream ellipse—and its weights are consequently adjusted such that they fall outside the ballpark for good performance on <em>A</em>, as illustrated by the blue arrow.</p><p>In EWC, a quadratic penalty is introduced to constrain the network parameters to stay within the low error region for task <em>A</em> when learning to perform <em>B</em>, depicted by the red arrow. The quadratic penalty acts as a “spring” of sorts to anchor the parameters to previously learned solutions, hence the name <em>Elastic </em>Weight Consolidation. The spring’s degree of elasticity, i.e. the degree of the quadratic penalty, differs between weights depending on how “important” the weights are determined to be for prior tasks. In the diagram, for example, task <em>A</em>’s 2D weight ellipsoid is longer along the <em>x</em> dimension than the <em>y</em> dimension, indicating the <em>x</em> weight is more important for <em>A</em> and thus will be afforded less elasticity than the <em>y </em>weight when adjusting to learn <em>B</em>. Failing to make the spring adaptable in this way and applying the same elasticity coefficient to each weight would result in weights not very well suited to either task, as indicated by the green arrow in the diagram.</p><p>The EWC model is trained on a sequence of tasks, each task consisting of a batch of data. A task is a fixed random shuffling of pixels in the handwritten MNIST digit images. Once the model trains on data for one task, it moves on to the batch for the next task and data for previous tasks is not encountered again, which allows testing of how well EWC “remembers” how to perform previously learned tasks. The following plot shows EWC’s test performance on a sequence of three tasks <em>A</em>, <em>B,</em> and <em>C </em>as it proceeds through training on them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnuh_GuMErcgeDHwfshpTw.png" /></figure><p>We can see how the performance of EWC remains fairly stable across previously learned tasks even as it learns new ones, as opposed to an approach that uses the same quadratic penalty for all weights (the green line) and one that doesn’t include a penalty at all, just using standard stochastic gradient descent (the blue line)—these both demonstrate catastrophic forgetting of task <em>A</em>, for example, as tasks <em>B</em> and<em> C</em> are learned.</p><h4>Replay</h4><p>Replay is another popular method for mitigating forgetting that involves storing some representation of previously encountered training data. The data is stored in what is referred to as a <em>replay buffer</em>. This technique was first proposed in the paper <a href="https://arxiv.org/pdf/1611.07725.pdf">“iCaRL: Incremental Classifier and Representation Learning”</a> by Rebuffi et al. in late 2016. In its replay buffer, iCaRL stores sets of images for each class encountered during training, referred to as “exemplar” images. The goal is for these images to be as representative of their respective classes as possible. For training, iCaRL processes batches of classes at a time. As a new class is encountered, a simulated training set is created with all the stored exemplars and the new data. All of this data is run through the network and its outputs for the previously learned classes are stored for the next step, in which the network’s parameters are updated. The network is updated by minimizing a loss function that integrates both <em>classification loss</em> and <em>distillation loss—</em>classification loss to prompt it to output correct labels for the newly encountered class and distillation loss to encourage it to reproduce the labels stored for the previously learned classes.</p><p>The network determines how to classify a given image by consulting the stored sets of exemplar images. Specifically, at inference time the exemplar images for a particular class are passed through the network to yield a set of feature vectors, which are averaged to produce a representative feature vector for that class. This is repeated for all classes and the feature vector for the test instance is compared to them all and assigned the label of the class it is most similar to. Importantly, a limit is imposed on the number of exemplar images that are stored such that if a new class is encountered after the limit is reached, images are removed from the sets of the other classes to accommodate for learning the new one. This prevents the computational requirements and memory footprint of the model from increasing unbounded as new classes are encountered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceGRVtMj6AUesh61yZI6eg.png" /></figure><p>With this strategy, we can see evidence of iCaRL’s retention of previous classes (<em>a</em>) among the confusion matrices above. Illuminated pixels on the diagonal represent correct class predictions, and we can see that iCaRL achieves the most correct predictions as well as an even distribution of incorrect predictions as compared to other networks that are biased towards predicting initial classes (<em>c</em>) or more recently encountered classes (<em>b</em> and <em>d</em>).</p><h4>REMIND</h4><p>iCaRL introduced the idea of storing training instances for replay to remember learned tasks and sparked a lot of research on different applications of this technique; however, all relied on storing <em>raw</em> representations of the training data in replay buffers, whereas the brain is known to store and replay memories as <em>compressed</em> representations of neocortical activity patterns. <a href="https://arxiv.org/abs/1910.02509">REMIND</a>, standing for Replay using Memory INDexing, is a streaming learning model introduced by Hayes et al. in late 2019 that aims to mimic this functionality of the brain by storing <em>feature maps </em>of image data for replay, the first of its kind to do so. Further, many models for streaming learning involve processing input data in batches—for example, training on a batch of cat images and then on a batch of dog images—which is neither representative of how the brain works nor of most real-world deployment scenarios, where data is encountered one instance at a time in a continuous stream. Batch processing is also more resource intensive, making it unsuitable for many mobile applications, so for these reasons REMIND classifies instances one-by-one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfo_ETLc2Yh-t3hYaSu1ZA.png" /></figure><p>The REMIND network is split into two parts, as depicted in the diagram above: a series of frozen layers followed by a series of plastic layers, with a replay buffer in between. Training of the network begins with a “base initialization period,” in which all layers are trained on a certain number of classes in a normal offline manner to initialize their weights. After this, the weights of the frozen layers are, effectively, frozen—they remain unchanged for the remainder of training. The idea behind this is that initial neural network layers are made to generalize well across variable inputs, so it’s not necessary to update their weights as new data is encountered as they would not change significantly anyway. The feature map representations of the input images produced by the frozen layers of the network are used to train a vector quantization model that compresses the feature maps and learns how to faithfully reconstruct them. The compressed representations are what get stored in REMIND’s replay buffer, mimicking the brain’s mechanisms for storing memories as well as decreasing the size of the data so that more training instances can be stored in the buffer.</p><p>After the base initialization period, each new training instance is run through the frozen layers of the network and combined with a number of instances that have been uniformly selected from the replay buffer and reconstructed via the learned quantization model. The mixture is then used to train the plastic layers of the network. Quantized training examples and their labels are stored in the replay buffer until it reaches its maximum capacity, at which point each time a new example is added, an example from the class with the most instances is randomly removed; this allows the model to learn new classes without expanding unbounded.</p><p>In the following plot, we can see how the test accuracy of REMIND’s online learning technique compares to others as it progresses to learn classes in an image classification task. We see that it achieves the best accuracy among the online approaches and is second only to the offline batch learning approach, where the network is retrained on random batches of all the previously encountered data as each new class is learned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7Wd87eXtq6Frl8Rzp6DNw.png" /></figure><p>REMIND’s superior results indicate that mimicking the brain’s means of storing compressed memory representations in neural networks may be a key factor in compelling them to remember.</p><h4>Bi-level Continual Learning</h4><p><a href="https://arxiv.org/abs/2007.15553">Bi-level Continual Learning (BCL)</a> is another online learning technique modeled after the way our brains operate. Proposed by Pham et al. in 2020, it involves two different models—a “fast-weight” model and a base model—which mirror the functionality of the hippocampus and neocortex, respectively. In our brains, the hippocampus is responsible for “rapid learning and acquiring new experiences” and the neocortex is tasked with “capturing common knowledge of all observed tasks.” To facilitate this in their model, Pham et al. employ both a generalization memory and an episodic memory buffer. The small episodic memory’s purpose is to store data from recent tasks for training the fast weight model, while the generalization memory stores data across all encountered tasks. The job of the fast weight model is to consolidate information from new samples for transfer to the base model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svBWoX1kp9nV2PdBR-3Jaw.png" /></figure><p>For BCL, data arrives in mini-batches corresponding to a particular class and a sample of it is put in generalization memory while most of it goes on to train the fast weight model. The fast weight model is initialized with the weights <em>θ </em>of the base model and is trained on the current batch of data for the particular class mixed with recently seen data from the episodic memory to arrive at a new set of weights<em> Φ</em>. The base model’s weights are then adjusted to factor in those from the fast weight model. While the fast weight model’s job is to quickly adapt to learn new tasks, a knowledge distillation regularizer is employed to encourage it to minimize the distance between new weights <em>Φ</em> it learns and its initial weights <em>θ </em>from the base model so that updates to the base model won’t cause it to lose too much generalization ability across tasks. After a mini batch is processed, the fast weights are discarded and re-initialized with the base model’s weights for learning the next batch of data.</p><p>Pham et al. compare their BCL technique against several other continual learning models on a series of classification tasks and find that it generally outperforms them all. On the CIFAR100 dataset, a typical offline batch learning approach achieves 74.11% test accuracy and BCL achieves 67.75%, compared to the next best performing model that reaches 64.36%, and iCARL that achieves only 48.43% accuracy. The following graph shows how BCL and other replay techniques generally improve in performance on the CIFAR task as their episodic memory size increases, which makes sense given that a larger memory allows for a more accurate representation of the original dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oo-l1hGm3mDePVNeNwHA1A.png" /></figure><p>Unlike REMIND, though, BCL stores the raw, uncompressed data in its memory buffers. It would therefore be interesting to compare the performances of these two different approaches to modeling the brain’s structures for memory on the same task.</p><h3>Conclusion</h3><p>Even among the incremental learning scenarios discussed here, the conditions for training are still not very representative of real-world scenarios—there aren’t many situations in which arriving data is so clearly delineated into incremental batches for each class. Given this, a new research direction is to investigate online learning with more realistic streaming scenarios where training instances stream with variable distributions. Such research would be particularly relevant for, for example, space-based applications of online learning where spacecraft may have to learn collision avoidance of previously unseen objects on the fly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39b7f578f24a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gsi-technology/your-neural-network-will-forget-what-its-learned-39b7f578f24a">Your Neural Network Will Forget What It’s Learned!</a> was originally published in <a href="https://medium.com/gsi-technology">GSI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Overview of Model Compression Techniques for Deep Learning in Space]]></title>
            <link>https://medium.com/gsi-technology/an-overview-of-model-compression-techniques-for-deep-learning-in-space-3fd8d4ce84e5?source=rss-d47c7e37bf13------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd8d4ce84e5</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[satellite-technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Hannah Peterson]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 19:34:06 GMT</pubDate>
            <atom:updated>2020-09-10T23:25:50.019Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leveraging data science to optimize at the extreme edge</h4><p><em>By Hannah Peterson and </em><a href="https://medium.com/@georgewilliams"><em>George Williams</em></a><em> (gwilliams@gsitechnology.com)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2b65kbmwoBrxwe-HC75rg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NASA</a> on <a href="https://unsplash.com/s/photos/satellite?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Computing in space</h3><p>Every day we depend on extraterrestrial devices to send us information about the state of the Earth and surrounding space—currently, there are about 3,000 satellites orbiting the Earth and this number is growing rapidly. Processing and transmitting the wealth of data these devices produce is not a trivial task, given that resources in space such as on-board memory and downlink bandwidth face tight constraints. In the case of satellite images, the data at hand can be extremely large, sometimes as large as 8,000×8,000 pixels. For most practical applications, only part of the great amount of detail encoded in these images is of interest—such as the footprints of buildings, for example—but the current standard approach is to transmit the entire images back to Earth for processing. It seems a more efficient solution would be to process the data <em>on board</em> the spacecraft, arriving at a compressed representation that occupies fewer resources—something that could be achieved using a machine learning model.</p><p>Unfortunately, running machine learning models tends to be a resource-intensive process even here on Earth. State-of-the-art networks typically consist of many millions of parameters and limited uplink bandwidth makes uploading such large networks to satellites impractical/infeasible. And even if they were pre-loaded prior to launch, they require significant memory bandwidth to fetch weights and compute dot products at runtime. Energy consumption of these networks is dominated by memory accesses, and they typically rely on hardware accelerators for timely inference. Spacecraft, however, face very strict weight and power requirements, which means that a satellite can’t be loaded with an unlimited number of GPUs for the purpose of running a model.</p><p>In this way, the topic of <em>model compression</em> is particularly relevant to space-based applications, as there is an evident need to reduce the size and complexity of neural networks for deployment in highly constrained extraterrestrial environments. Luckily, many effective techniques for model compression exist thanks to a rapidly growing body of research on the topic. In this blog, I’ll be going over a few common approaches.</p><h3>What is model compression?</h3><p>The goal of model compression is to achieve a model that is simplified from the original without significantly diminished accuracy. A simplified model is one that is reduced in size and/or latency from the original. Specifically, a <strong>size reduction</strong> means that the compressed model has fewer and/or smaller parameters and, thus, uses less RAM when run, which is desirable because it frees up memory for other parts of the application to use. A <strong>latency reduction</strong> is a decrease in the time it takes for the model to make a prediction, or <em>inference</em>, based on an input to the trained model, typically translating to lower energy consumption at runtime. Model size and latency often go hand-in-hand because larger models require more memory accesses to be run. As we can see, both types of reduction are desirable for deploying models in space, where computing resources face both strict size and power constraints.</p><p>The following are some popular, heavily researched methods for achieving compressed models:</p><ul><li>Pruning</li><li>Quantization</li><li>Low-rank approximation and sparsity</li><li>Knowledge distillation</li><li>Neural Architecture Search (NAS)</li></ul><p>Let’s take a look at each technique individually. In practice, a complete model compression pipeline might integrate several of these approaches, as each comes with its own benefits and drawbacks.</p><h3>Pruning</h3><p>Pruning involves removing connections between neurons or entire neurons, channels, or filters from a trained network, which is done by zeroing out values in its weights matrix or removing groups of weights entirely; for example, to prune a single connection from a network, one weight is set to zero in a weights matrix, and to prune a neuron, all values of a column in a matrix are set to zero. The motivation behind pruning is that networks tend to be over-parametrized, with multiple features encoding nearly the same information. Pruning can be divided into two types based on the type of network component being removed: <em>unstructured pruning</em> involves removing individual weights or neurons, while <em>structured pruning</em> involves removing entire channels or filters. We’ll look at these two types individually, as they differ in their implementations and outcomes.</p><h4>Unstructured Pruning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3rR1-qzZfgYE_QA7WvLOQ.png" /><figcaption><a href="https://arxiv.org/abs/1907.02124">Source</a></figcaption></figure><p>By replacing connections or neurons with zeros in a weights matrix, unstructured pruning increases the <strong>sparsity</strong> of the network, i.e. its proportion of zero to non-zero weights. There exist various hardware and software, such as <a href="https://www.tensorflow.org/model_optimization/guide/pruning">TensorFlow Lite</a> and <a href="https://caffe.berkeleyvision.org/">Caffe</a>, that are specialized to efficiently load and perform operations on sparse matrices and, thus, that can facilitate significant latency reductions in pruned models as compared to their original dense representations. For example, Caffe can be used to apply a mask to pruned parameters that causes them to be skipped over during network operation, reducing the amount of FLOPs and, thus, the power and time, required to make an inference. Depending on the degree of sparsity and the method of storage used, pruned networks can also take up much less memory than their dense counterparts.</p><p>But what is the criteria for deciding which weights should be removed? One common method known as <em>magnitude-based pruning</em> compares the weights’ magnitudes to a threshold value. A highly cited <a href="https://medium.com/r?url=https%3A%2F%2Farxiv.org%2Fpdf%2F1506.02626.pdf">2015 paper</a> by Han et al. prompted widespread adoption of this approach. In their implementation, pruning is applied layer-by-layer. First, a predetermined “quality parameter” is multiplied by the standard deviation of a layer’s weights to calculate the threshold value and weights with magnitudes below the threshold are zeroed. After all layers are pruned, the model is retrained so that the remaining weights can adjust to compensate for those that were removed, and the process is repeated for several iterations. The researchers used this method to prune four different model architectures, two pre-trained on the MNIST dataset and two on the ImageNet dataset. We can see the effects of their unstructured pruning approach visualized in the following image, which shows the sparsity pattern of the first fully-connected layer for one of the MNIST networks, where the blue dots represent non-zero parameters:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFR6BwUmX0elASKIhJO_3g.png" /><figcaption><a href="https://arxiv.org/pdf/1506.02626.pdf">Source</a> (modified)</figcaption></figure><p>The MNIST dataset consists of 28×28 pixel images of handwritten digits from 0–9 like the one above and models are trained to classify these digits. To be inputted into a neural network, the image is flattened by concatenating the rows of pixels end-to-end from top to bottom, resulting in a vector of 784 values. The first layer of the network is fully-connected with 300 neurons. As we can see, the digits tend to be oriented in the center of the image, thus pixels around the edges are less consequential to the classification task and connections to them get pruned more heavily. For the entire network, pruning caused both the number of non-zero weights and FLOPs required to decrease by a factor of 12 with no drop in predictive performance. Similarly, for the AlexNet and VGG-16 models trained on ImageNet, the numbers of parameters were reduced from 61 million to 6.7 million and from 138 million to 10.3 million, respectively, with no decrease in classification accuracy.</p><p>Han et. al showed that when implemented correctly, unstructured pruning can yield some truly impressive degrees of compression, as they note “the storage requirements of AlexNet and VGGNet are are small enough that all weights can be stored on chip, instead of off-chip DRAM which takes orders of magnitude more energy to access.” However, they also acknowledge the “limitation of general purpose hardware on sparse computation” and, thus, use specialized software to work around this problem. Indeed, unstructured pruning’s reliance on specially designed software or hardware to handle network sparsity to speed up computations is a significant limitation, one that is not faced by taking a structured approach.</p><h4>Structured Pruning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apCAWcTdSgLaWaNnq3-7PA.png" /><figcaption>Three types of structured pruning. <a href="https://arxiv.org/abs/1907.02124">Source</a></figcaption></figure><p>Unlike unstructured pruning, structured pruning does not result in weight matrices with problematic sparse connectivity patterns because it involves removing entire blocks of weights within given weight matrices. This means the pruned model can be run using the same hardware and software as the original. While we are now looking at groups of weights to remove at the channel or filter level, magnitude-based pruning can still be applied by ranking them according to their L1 norms, for example. But there are also more intelligent, “data-driven” approaches that have been proposed which can achieve better results.</p><p>Huang et al., for example, were the first to integrate into the pruning process a means of controlling the tradeoff between network performance and size in their <a href="https://arxiv.org/pdf/1801.07365.pdf">2018 paper</a>. Their algorithm outputs a set of filter “pruning agents”—each a neural network corresponding to a convolutional layer of the network—and an alternative, pruned version of the original model, which is initialized to be the same as the original. The pruning agents work to maximize an objective that is parametrized by a “drop bound” value, which is defined as the maximum allowed drop in performance between the original and the pruned model, forcing the agents to keep performance above a specified level. For each convolutional layer, a pruning agent is trained by evaluating the effects of pruning combinations of different filters within that layer. To do so, it removes certain filters from the alternative model and compares this model’s performance on an evaluation set to that of the original, learning which modifications will increase the network’s efficiency while still adhering to accuracy constraints. Once the agent for one layer is trained and filters for that layer have been optimally removed, the entire pruned model is retrained to adjust for the changes and the process repeats for the next convolutional layer.</p><p>The following plot shows the degree of pruning achieved with this approach with drop bound <em>b</em> = 2<em> </em>on the layers of a VGG-16 model trained on the CIFAR 10 dataset. The greater degree of pruning of higher layers indicates they tend to contain more unnecessary filters than initial ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byGnKTYfibQy8TU3IUiK1Q.png" /><figcaption><a href="https://arxiv.org/pdf/1801.07365.pdf">Source</a></figcaption></figure><p>We can also see the quantitative compression results of pruning this model using different drop bound values. The accuracy values in parentheses correspond to models pruned to the same ratio but with a magnitude-based approach instead, and we see that the “data-driven” implementation has superior performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piOzpIBwARHArvOE_LZkkQ.png" /><figcaption><a href="https://arxiv.org/pdf/1801.07365.pdf">Source</a></figcaption></figure><p>Similarly impressive results have been achieved through a variety of structured pruning methods, establishing it as a popular model compression technique. But pruning in general still has a few potential drawbacks. For example, it’s generally unclear how well given methods generalize across different architectures, and the pruning process tends to involve a lot of fine-tuning that can act as a barrier both to implementation and generalization. Further, in many cases it may be more effective to simply use a more efficient architecture than to prune a suboptimal one. If you’re interested in taking a closer look at the diverse range of approaches currently being taken to prune models, I suggest checking out <a href="https://heartbeat.fritz.ai/research-guide-pruning-techniques-for-neural-networks-d9b8440ab10d">this blog</a> or the paper <a href="https://arxiv.org/pdf/2003.03033.pdf">“What is the State of Neural Network Pruning?”</a>, both written in 2019.</p><h3>Quantization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPun-QDJsoy1u2piBUJ3iw.png" /><figcaption><a href="https://www.tutorialspoint.com/dip/concept_of_quantization.htm">Source</a></figcaption></figure><p>While pruning compresses models by reducing the number of weights, quantization consists of decreasing the size of the weights that are there. Quantization in general is the process of mapping values from a large set to values in a smaller set, meaning that the output consists of a smaller range of possible values than the input, ideally without losing too much information in the process. We can think about this in the context of image compression, as with the images of Einstein above. In the leftmost representation, each pixel value is represented by 8 bits and thus can take on 256 varying shades of gray. The number of possible shades is halved in each successive image. Notice, however, that we really aren’t able to detect much difference between the first four images or so, and this represents the goal of model quantization: to reduce the precision of network components to the extent that it is more lightweight but without a “noticeable” difference in efficacy. Intuitively, it makes sense that neural networks should be able to deal with some information loss, as they are trained to cope well with high levels of noise in their inputs, and lower precision calculations can essentially be seen as another source of noise.</p><p>So, how might a mapping between different precisions (i.e. a <em>quantization scheme</em>) work? In a neural network, the weights or activation outputs of a particular layer tend to be normally distributed within a certain range, so ideally a quantization schema takes advantage of this fact and adapts to fit each layer’s individual distribution. For example, models weights are typically stored as 32-bit floating point numbers and a common approach is to reduce these to 8-bit fixed points (though some techniques have even gone as far as to represent them with <a href="https://arxiv.org/pdf/1609.07061.pdf">single bits</a>!), for which there are 2⁸ = 256 possible values: in the simplest case, we can take the min and max weights of a layer, divide the range between the two into 255 evenly-spaced intervals, and bin the weights according to the interval edge they are closest to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NH0PuB_oxyTdP7st78mFw.png" /><figcaption><a href="https://sahnimanas.github.io/post/quantization-in-tflite/#deep_compression">Source</a> (modified)</figcaption></figure><p>We can see how quantizing the weights in this way would reduce their memory footprint by 4x. And there are many other, more complex techniques that achieve lower information loss, such as an <a href="https://arxiv.org/pdf/1510.00149.pdf">implementation</a> by Han et. al that involves k-means clustering. Specifically, their compression pipeline combines weight pruning, quantization, and <a href="https://www.techiedelight.com/huffman-coding/">Huffman coding</a>, and we can see in the following graph how pruning and quantization of AlexNet trained on ImageNet work together to achieve a model that is 3.7% of its original size with no loss in accuracy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbLOVEjgGPSfEDzHhP42FA.png" /><figcaption><a href="https://arxiv.org/pdf/1510.00149.pdf">Source</a></figcaption></figure><p>In addition to weights, neural networks also consist of operators such as matrix multiplication, convolution, activation functions and pooling that must also be quantized to deal with lower precision weights. While the general idea is the same, quantizing operators is a bit trickier than quantizing pre-trained weights because they have to deal with potential bit overflows and unseen inputs, which can make determining a schema difficult. Luckily, many deep learning softwares, such as <a href="https://www.tensorflow.org/lite/performance/post_training_quantization">TensorFlow</a>, <a href="https://github.com/pytorch/glow/blob/master/docs/Quantization.md">PyTorch</a>, and <a href="https://mxnet.apache.org/versions/1.6/api/python/docs/tutorials/performance/backend/mkldnn/mkldnn_quantization.html">MXNet</a>, have functionality for quantizing commonly-used operators (if you’re interested, <a href="https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/">this blog</a> provides high level explanation of TensorFlow’s process), which can yield networks with significantly diminished latency given the increased efficiency of lower precision operations.</p><p>In practice, quantization can be difficult to actually implement because it requires having a decent understanding of hardware and bit-wise computations. It turns out that deciding upon the degree of precision to compress a model to is not as simple as picking a random number of bits: you have to make sure the hardware you’re using is even capable of handling numbers of that size, let alone of doing so efficiently. In reviewing the literature, I found that the savings offered by many state-of-the-art quantization implementations are tied to the features of the hardware being used, although here exist other means of compression that generalize well across many kinds of hardware, such as low-rank factorization.</p><h3>Low-rank approximation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JoECwTgczh4mfptY2gM6g.png" /><figcaption>Convolutional filter bank (a) learned for the extraction of linear structures in retinal scan images, along with its separable low-rank approximation (b). <a href="https://www.cv-foundation.org/openaccess/content_cvpr_2013/papers/Rigamonti_Learning_Separable_Filters_2013_CVPR_paper.pdf">Source</a></figcaption></figure><p>We’re aware that deep neural networks tend to be over-parametrized, with a lot of similarity—or redundancy—occurring <em>between</em> different layers and/or channels. For example, image <em>a</em> above shows filters of a convolutional layer learned for an image segmentation task, many of which look nearly the same. The goal of low-rank approximation is to approximate the numerous, redundant filters of a layer using a linear combination of fewer filters, such as those represented in image <em>b</em>. Compressing layers in this way reduces the network’s memory footprint as well as the computational complexity of convolutional operations and can yield significant speedups.</p><p>Specifically, the filters in <em>b </em>are of lower rank than those in <em>a</em>. The <strong>rank </strong>of a matrix is defined as the dimension of the vector space spanned by its columns, which is equal to its number of linearly-independent columns. To illustrate, say we have the following matrix:</p><pre>[[1, 0, -1],<br>[-2, -3, 1],<br>[3, 3, 0]]</pre><p>If we look at just the first two columns, we see that they are linearly independent because neither can be computed from the other using linear operations, so the matrix has to have a rank of at least 2. But if we look at all three columns, we see that if we subtract the first from the second, we get the third, thus all three are not linearly independent and the matrix only has a rank of 2.</p><p>Intuitively, we get the sense that if an element of a matrix can be computed using others that are present, there is some redundancy of information occurring in the matrix. While individual filters and channels in a network tend to be full rank, indicating no redundancy within themselves, there <em>is </em>typically significant redundancy <em>between</em> different filters or channels. And since low-rank matrices encode redundant information, it makes sense that we can use them to approximate these redundant layers of a network, which is exactly what low-rank approximation does. To understand the intuition behind how this might be achieved, let’s take a look at a relatively simple approach from <a href="http://www.bmva.org/bmvc/2014/files/paper073.pdf">Jaderberg et al.</a> that takes advantage of cross-filter redundancy.</p><p>The following represents a convolution operation with N 2D filters, W, on a single channel feature map, Z, to output an N-channel feature map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*rUCEmy7wKuHyrBEGP55o1A.png" /><figcaption><a href="http://www.bmva.org/bmvc/2014/files/paper073.pdf">Source</a> (modified)</figcaption></figure><p>The goal is to reduce the computational complexity of these operations by approximating the N full rank filters with a linear combination of M lower rank filters where M&lt;N, based on the assumption that there is redundancy between the N filters. Specifically, Jadenberg et al. impose that the new filters be of rank 1. If a matrix has rank 1, it means that if we select one of its columns, all the other columns will be some multiple of that column. Thus, rank 1 matrices can be <em>factorized</em> or <em>decomposed</em> to be products of a column vector and a row vector—a property called <em>separability—</em>for example:</p><pre>[[1, 4, 5],          [[1],   [[1, 4, 5]]<br>[2, 8, 10],     =     [2], * <br>[3, 12, 15]]          [3]]</pre><p>By imposing separability of the M basis filters and adding a layer to approximate the N output channels of the original convolution operation from the compressed basis, we arrive at a transformed operation that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAYTI3vxUlcsUG3gUPG6UA.png" /><figcaption><a href="http://www.bmva.org/bmvc/2014/files/paper073.pdf">Source</a> (modified)</figcaption></figure><p>While it may look more complex, it is actually a more computationally efficient operation if M is made to be sufficiently small. The separable bases for these modified layers are optimized asynchronously by minimizing the reconstruction error between the output of the original layer and the output of the approximation layer. Jaderberg et al. use a similar approach to exploit redundancy between channels, with which they achieve 4.5× speedup of a shallow network trained for a text classification task with only a 1% drop in classification accuracy.</p><p>If you take a look at the literature on low-rank approximation, it’s likely you’ll come across the terms SVD (“Singular Value Decomposition”), Tucker decomposition and CP (“Canonical Polyadic”) decomposition, so it bears briefly explaining the designation between these. <a href="https://en.wikipedia.org/wiki/Singular_value_decomposition#Low-rank_matrix_approximation">SVD</a> stands for “Singular Value Decomposition” and is a<em> matrix</em> factorization. In the context of approximating a matrix <em>M</em> with another matrix <em>M’ </em>of a lower rank <em>r </em>as we’ve discussed, the optimal <em>M’ </em>is equal to the SVD of <em>M </em>constrained by <em>r</em>. <a href="https://en.wikipedia.org/wiki/Tucker_decomposition">Tucker</a> and <a href="https://en.wikipedia.org/wiki/Tensor_rank_decomposition">CP decomposition</a> are ways of generalizing SVD to <em>tensors</em>. As you likely know, a tensor is a multi-dimensional array. Tucker decomposition decomposes a tensor into a set of matrices and one small core tensor. CP is actually a special case of Tucker decomposition that decomposes a tensor into a sum of rank-1 tensors, though they are often referred to in the literature as two separate approaches. We can see how they both work in 3D space below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cT1o8fOoqGd-77R0-_234A.png" /><figcaption><a href="https://www.researchgate.net/publication/321902217_A_novel_nonconvex_approach_to_recover_the_low-tubal-rank_tensor_data_when_t-SVD_meets_PSSV/figures?lo=1">Source</a></figcaption></figure><p>Both have their benefits and drawbacks, which you can read more about <a href="http://alexhwilliams.info/pdf/cpd_notes_janelia_2016.pdf">here</a>, and are popular approaches to low-rank approximation of deep neural networks. <a href="https://arxiv.org/pdf/1511.06530.pdf">Kim et al.</a>, for example, achieve substantial compression using Tucker decomposition. They take a data-driven approach to determining the ranks that the compressed layers should have and then perform Tucker decomposition according to these ranks. They apply this compression to various models for image classification tasks and run them on both a Titan X and Samsung Galaxy S6 smartphone, which, notably, has a GPU with 35× lower computing ability and 13× smaller memory bandwidth than Titan X. The following table shows the compressed models’ drops in performance and reductions in size and FLOPs from the original, as well as their time and energy consumption to process a single image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uViTv1fcUcz_CgmYbWSByw.png" /></figure><p>With these results, Kim et al. demonstrate that low-rank approximation is an effective means of compression to achieve significant size and latency reductions in deep neural networks for their potential deployment on mobile devices. And as I mentioned before, a large upside to low-rank approximation as a compression technique is that, since it simplifies model structure just by reducing parameter count, it does not require specialized hardware to implement.</p><h3>Knowledge distillation</h3><p>If we think about it, the need to compress neural networks arises from the fact that training and inference are two fundamentally different tasks. During training, for example, a model does not have to operate in real time and does not necessarily face restrictions on computational resources, as its primary goal is simply to extract as much structure from the given data as possible, but latency and resource consumption do become of concern if it is to be deployed for inference. As a result, trained models are often larger and slower than what would be ideal for inference and, hence, we have to develop ways compress them. To address this problem, Cornell researchers <a href="https://www.cs.cornell.edu/~caruana/compression.kdd06.pdf">proposed</a> in 2006 the idea of transferring the knowledge from a large trained model (or ensemble of models) to a smaller model for deployment by training it to mimic the larger model’s output, a process that Hinton et al. <a href="https://arxiv.org/pdf/1503.02531.pdf">generalized</a> in 2014 and gave the name <em>distillation</em>. In short, knowledge distillation is motivated by the idea that training and inference are different tasks such that a different model should be used for each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgPx4ADFZCKjN0Zs-1WlVg.png" /><figcaption>A visualization of the student-teacher network paradigm. <a href="https://arxiv.org/pdf/2004.05937.pdf">Source</a></figcaption></figure><p>In Hinton et al.’s implementation, the small “student” network learns to mimic the large “teacher” network by minimizing a loss function in which the target is based on the distribution of class probabilities outputted by the teacher’s softmax function. To understand this, let’s review how the softmax function works: it takes in a a logit for a particular class, <em>z_i</em>, and converts it to a probability by dividing it by the sum of logits of all <em>j</em> classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0NHo5wNt33UfOLt8c1MRA.png" /></figure><p>Here, the term <em>T</em> is the temperature, of which higher values correspond to “softer” outputs. <em>T</em> is usually set to 1, which results in “hard” outputs in which the correct class label is assigned a probability close to 1, indicating near certainty in this prediction, while the others are assigned probabilities close to 0. Hinton et al. suggest, however, that the distribution of the incorrect class labels holds valuable information about the data that can to be learned from, as they describe in the context of a handwritten digit classification task:</p><blockquote>“One version of a 2 may be given a probability of 10^-6 of being a 3 and 10^−9 of being a 7 whereas for another version it may be the other way around. This is valuable information that defines a rich similarity structure over the data (i. e. it says which 2’s look like 3’s and which look like 7’s)…”</blockquote><p>To capitalize upon this information, Hinton et al. raise the temperature <em>T</em> in the teacher network’s softmax function to soften the distribution of probabilities over the class labels in a process they call <em>distillation</em>, as demonstrated in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byuvd152TwODzr3CVLV6EQ.png" /><figcaption>An example of the effect of raising the temperature T in a network’s softmax function. The resulting probabilities align with what we know to be true, i.e. that a dog more closely resembles a cat than a cow and certainly more than a car. <a href="https://www.ttic.edu/dl/dark14.pdf">Source</a></figcaption></figure><p>The student network is then trained to minimize the sum of two different cross entropy functions: one involving the original hard targets obtained using a softmax with <em>T</em>=1 and one involving the softened targets. Hinton et al. demonstrate the effectiveness of this technique by training a teacher network with two hidden layers of 12,000 units and a student with two hidden layers of only 800 units. On a test set, the teacher achieves 67 test errors and the student achieves 74, as compared to the 146 test errors made by a network of the same size as the student but that was trained without distillation.</p><p>After this initial breakthrough by Hinton et al. of training the student to imitate the softmax outputs of a teacher, researchers <a href="https://arxiv.org/pdf/1412.6550.pdf">Romero et al.</a> found that the student can also use information from the teacher’s intermediate hidden layers to improve its final performance. Specifically, they propose what they call “FitNets,” which are student networks that are thinner but deeper than their teachers, with their increased depth allowing them to generalize well while their small widths still make them compact. Romero et al. introduce one “guided layer” in the middle of the student network that is tasked with learning from one “hint” layer in the middle of the teacher network. The table below demonstrates the speedup, reduced parameter count, and generally increased accuracy the FitNets of varying sizes achieve as compared to their teacher architecture on the CIFAR-10 image classification dataset. Further, their performance was on-par with state-of-the-art methods, of which the highest accuracy at the time was 91.78%:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rBCRfGcihTtnF4pMGW2vIg.png" /></figure><p>Impressive results like these have spurred research on a wide range of different methods for transferring knowledge from teacher to student networks. Indeed, the field of research on knowledge distillation has become so broad and specialized in some areas that it is difficult to evaluate the overall efficacy of general approaches against one another. A drawback of knowledge distillation as a compression technique, therefore, is that there are many decisions that must be made up-front by the user to implement it; for example, unlike the other compression techniques we’ve discussed, the compressed network doesn’t even need to have a similar structure to the original. But this also means that knowledge distillation is very flexible and can be adapted to a wide range of tasks. If you’re interested in learning more about different knowledge distillation techniques, <a href="https://arxiv.org/pdf/2004.05937.pdf">this 2020 paper</a> performs a comprehensive review of state-of-the-art approaches for vision-based tasks.</p><h3>Neural Architecture Search (NAS)</h3><p>The reality is that multiple of the compression techniques we’ve discussed so far could be applied in a given scenario, and when you take into account combinations of them, the number of possible architectures to explore expands dramatically. The hard part is, of course, choosing the optimal one. This is where Neural Architecture Search (NAS) comes in. NAS in the most general sense is a search over a set of decisions that define the different components of a neural network—it is a systematic, automized way of learning optimal model architectures. The idea is to remove human bias from the process to arrive at novel architectures that perform better than human-designed ones.</p><p>Obviously, for any given task there are infinite possible model architectures to explore and, with this, many different approaches to searching through them. A <a href="https://arxiv.org/pdf/1808.05377.pdf">2019 survey</a> categorizes different NAS techniques according to the following three dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y2gBOxUYM8NJEKCbY83kuw.png" /><figcaption>How the three fundamental components of NAS fit together in a training pipeline. <a href="https://arxiv.org/pdf/1808.05377.pdf">Source</a></figcaption></figure><ul><li><strong>Search space</strong>: The possible architectures that can be discovered in the search. We’re aware that networks can consist of a whole host of operations such as convolutions, pooling, concatenation and activation functions, and defining a search space involves imposing constraints on how and which of these components can be combined to generate the networks that are searched through. For example, defining a search space might involve restricting the number of possible convolutional layers the network can have or requiring it to repeat a general pattern of operations several times. Inevitably, imposing such restrictions introduces some human bias into the search process. And even with these restrictions, the search space will still be very large, as is the point of NAS — to discover and evaluate architectures outside of the realm of what we might normally construct.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoRf6QSlvGGLL8J9ByHNeA.png" /><figcaption>An example of a search space where skip connections between layers are permitted (left) and one constrained by a general architecture template (right) where a pattern of operations is repeated but connections between the dark blue layers are not fixed. <a href="https://arxiv.org/pdf/1905.01392.pdf">Source</a></figcaption></figure><ul><li><strong>Search strategy</strong>: The strategy followed to guide the exploration of the search space, i.e. what determines the next architectures to explore in the search. While this could be random, it’s unlikely given the huge scope of a given search space that an optimal architecture will be happened upon by random chance, so the search strategy typically takes into account the performance of previously explored architectures. For example, so-called “evolutionary” algorithms are based on maintaining an evolving population of candidate architectures throughout the training process. There are also <a href="https://arxiv.org/pdf/1611.01578.pdf">reinforcement-learning-based</a> strategies where an agent is trained to estimate the performance of architectures on unseen data.</li><li><strong>Performance estimation strategy</strong>: How the performance of candidate models on unseen data is estimated. Performance feedback is used to optimize the search strategy. This can be as simple as training each network from scratch and measuring their accuracy on a validation set, but this can be very costly; thus, strategies that involve parameter sharing between many models or that use low-fidelity approximations of data or the networks themselves, for example, have been developed.</li></ul><p>As you can imagine, NAS is a very broad field of research, so here we will just focus on its use for compressing pre-trained models, specifically. In 2018, for example, He et al. introduced <a href="https://arxiv.org/pdf/1802.03494.pdf">AutoML for Model Compression</a> (AMC), a technique that uses a reinforcement learning search strategy to compress pre-trained networks layer-by-layer. Specifically, AMC’s search space is parametrized by a user-defined, hardware-based constraint such as maximum latency, model size, or number of FLOPS. The agent proceeds through the network one layer at a time, outputting a compression ratio that is based on the composition of the layer and that also adheres to the hardware constraint. After all layers are pruned according to their ratios via a structured or unstructured approach, the validation accuracy of the compressed model is computed without fine-tuning and used as the agent’s reward. Forgoing fine-tuning after compressing the model is a tactic He et al. take in their performance estimation strategy that allows for faster policy exploration.</p><p>AMC’s learning-based pruning was tested against handcrafted, rule-based approaches on various models and was found to exhibit all-around superior performance. For example, the following table shows the results of AMC’s compression with a 50% FLOP or 50% latency constraint on MobileNet as compared to a rule-based strategy that prunes the network to 75% of its original parameters (second row):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BTC7rhEwf6DD1E1f710QA.png" /></figure><p>As we can see, the networks pruned with AMC achieve nearly the same accuracy as the original MobileNet (top row) with reduced latency and memory size, as opposed to the rule-based pruning technique.</p><p>More recently in 2019, <a href="https://arxiv.org/pdf/1902.00383.pdf">Cao et al.</a> use Bayesian Optimization to search for an optimal compressed architecture. In their implementation, they continuously add to a set models that are all based on an original network but have been compressed by randomly removing or shrinking layers and adding skip connections. These architectures are evaluated based on the reduced parameter count and accuracy they achieve as compared to the original. Over a number of epochs, the models are sampled from and used to learn to <em>predict</em> to what extent new, randomly generated compressed models will outperform the current best model of the set in terms of compression and accuracy—this way, the randomly generated architectures don’t have to go through the time-intensive process of actually be evaluated on data and more architectures can be explored instead. Based on these predictions, the most promising of the newly generated models are evaluated on data and added to the growing set of models, and the process continues. At the end, the best model of the set in terms of compression and accuracy is selected. The following table demonstrates the effectiveness of Cao et al.’s approach on compressing three architectures for image classification on the CIFAR-100 dataset as compared to a random NAS approach and to Ashok et. al’s state-of-the-art <a href="https://openreview.net/pdf?id=B1hcZZ-AW">“N2N”</a> technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abvAOXlemVvPu67CvpWjJg.png" /><figcaption>Note: “removal” indicates compression only by layer removal, as was all N2N reported results for for ResNet-34. f(x) is a metric that incorporates both accuracy and size of a compressed model as compared to the original.</figcaption></figure><p>We’ve seen two demonstrations of NAS’s effectiveness at achieving more compact models. The possibilities really are endless with NAS, but successful implementation relies on picking a search space, search strategy, and performance estimation strategy that are suited to the problem at hand, which can require a decent amount of domain knowledge and poses a barrier to entry to it as a compression technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zAd9ys0XTWLQlOnJ.png" /><figcaption>Google’s AutoML GUI. <a href="https://mljar.com/blog/mljar-vs-google-cloud-automl-tables/">Source</a></figcaption></figure><p>Luckily, software does exist that abstracts away some of the complexity to make NAS more accessible. For example, Google’s <a href="https://cloud.google.com/automl/">Cloud AutoML</a> makes the process as simple as inputting a training dataset and letting its algorithm search for an optimal set of building blocks for the network—a baseline architecture that the user can fine-tune to optimize further. All of this is done within its GUI to make the process accessible even to inexperienced programmers. <a href="https://github.com/keras-team/autokeras">Auto-Keras</a> is an open-source NAS package that takes a different approach in that the user specifies the high-level architecture of the model and its algorithm conducts a search through the details of the configuration.</p><h3>Conclusion</h3><p>We’ve now developed a basic understanding of the inner workings of a few popular compression techniques for deep learning models. The next step would be to actually try some of them out—a task we’ll tackle in an upcoming blog. Specifically, we’ll use some of the techniques discussed here to compress a few of the <a href="https://medium.com/the-downlinq/spacenet-6-winning-model-release-a8ce702d482a">winning models</a> from the SpaceNet 6 challenge to demonstrate how networks for building footprint segmentation might be made more resource-efficient for deployment in space.</p><h3>References</h3><p><em>A huge thanks to Eric Quist from </em><a href="https://www.capellaspace.com/"><em>Capella Space</em></a><em> for feedback and suggestions</em></p><ul><li><a href="https://arxiv.org/pdf/2007.11089.pdf">Accelerating Deep Learning Applications in Space</a></li><li><a href="https://www.tensorflow.org/lite/performance/model_optimization">https://www.tensorflow.org/lite/performance/model_optimization</a></li></ul><h4>Pruning</h4><ul><li><a href="https://towardsdatascience.com/pruning-deep-neural-network-56cae1ec5505">https://towardsdatascience.com/pruning-deep-neural-network-56cae1ec5505</a></li><li><a href="https://arxiv.org/pdf/2003.03033.pdf">What is the State of Neural Network Pruning?</a></li><li><a href="https://arxiv.org/pdf/1506.02626.pdf">Learning both Weights and Connections for Efficient Neural Networks</a></li><li><a href="https://arxiv.org/pdf/1710.01878.pdf">To prune, or not to prune: exploring the efficacy of pruning for model compression</a></li><li><a href="https://arxiv.org/pdf/1801.07365.pdf">Learning to Prune Filters in Convolutional Neural Networks</a></li></ul><h4>Quantization</h4><ul><li><a href="https://www.tutorialspoint.com/dip/concept_of_quantization.htm">https://www.tutorialspoint.com/dip/concept_of_quantization.htm</a></li><li><a href="https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/">https://petewarden.com/2016/05/03/how-to-quantize-neural-networks-with-tensorflow/</a></li><li><a href="https://nervanasystems.github.io/distiller/quantization.html">https://nervanasystems.github.io/distiller/quantization.html</a></li><li><a href="https://sahnimanas.github.io/post/quantization-in-tflite/">https://sahnimanas.github.io/post/quantization-in-tflite/</a></li><li><a href="https://arxiv.org/pdf/1510.00149.pdf">Deep Compression: Compressing Deep Neural Networks with Pruning, Trained Quantization and Huffman Coding</a></li></ul><h4>Low-Rank Approximation</h4><ul><li><a href="https://en.wikipedia.org/wiki/Rank_(linear_algebra)">https://en.wikipedia.org/wiki/Rank_(linear_algebra)</a></li><li><a href="https://www.groundai.com/project/learning-low-rank-approximation-for-cnns/1">Learning Low-Rank Approximation for CNNs</a></li><li><a href="https://www.cv-foundation.org/openaccess/content_cvpr_2013/papers/Rigamonti_Learning_Separable_Filters_2013_CVPR_paper.pdf">Learning Separable Filters</a></li><li><a href="http://www.bmva.org/bmvc/2014/files/paper073.pdf">Speeding up Convolutional Neural Networks with Low Rank Expansions</a></li></ul><h4>Knowledge Distillation</h4><ul><li><a href="https://arxiv.org/pdf/1503.02531.pdf">Distilling the Knowledge in a Neural Network</a></li><li><a href="https://nervanasystems.github.io/distiller/knowledge_distillation.html">https://nervanasystems.github.io/distiller/knowledge_distillation.html</a></li><li><a href="https://www.ttic.edu/dl/dark14.pdf">https://www.ttic.edu/dl/dark14.pdf</a></li></ul><h4>Neural Architecture Search</h4><ul><li><a href="https://arxiv.org/pdf/1905.01392.pdf">A Survey on Neural Architecture Search</a></li><li><a href="https://arxiv.org/pdf/1808.05377.pdf">Neural Architecture Search: A Survey</a></li><li><a href="https://www.pyimagesearch.com/2019/01/07/auto-keras-and-automl-a-getting-started-guide/">https://www.pyimagesearch.com/2019/01/07/auto-keras-and-automl-a-getting-started-guide/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd8d4ce84e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gsi-technology/an-overview-of-model-compression-techniques-for-deep-learning-in-space-3fd8d4ce84e5">An Overview of Model Compression Techniques for Deep Learning in Space</a> was originally published in <a href="https://medium.com/gsi-technology">GSI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Concepts in Reinforcement Learning By Example]]></title>
            <link>https://medium.com/gsi-technology/core-concepts-in-reinforcement-learning-by-example-dc8e839f6a2c?source=rss-d47c7e37bf13------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc8e839f6a2c</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[editors-pick]]></category>
            <dc:creator><![CDATA[Hannah Peterson]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 19:40:18 GMT</pubDate>
            <atom:updated>2020-08-12T18:29:08.352Z</atom:updated>
            <content:encoded><![CDATA[<h4>Taking a ride in OpenAI Gym’s MountainCar to explore RL theory</h4><p><em>By Hannah Peterson and </em><a href="https://medium.com/@georgewilliams"><em>George Williams</em></a><em> (gwilliams@gsitechnology.com)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DaVKyCgxiJ9GGeIjFKoGyg.jpeg" /><figcaption><a href="https://unsplash.com/photos/fzOITuS1DIQ">Source</a></figcaption></figure><p>You may recall from the <a href="https://medium.com/@hbpeters/demystifying-markov-decision-processes-cd8f119aa3d1?source=friends_link&amp;sk=fb3a4078c3af79f97b46ffc713a7f18a">previous post</a> in this series on Reinforcement Learning (RL) that a Markov Decision Process (MDP) is a mathematical framework for modeling RL problems. To ground the mathematical theory of an MDP in reality, we identified each of its elements in the context of OpenAI Gym’s <a href="https://gym.openai.com/envs/MountainCar-v0/">MountainCar</a> game. Now that we understand them individually, let’s explore how they combine to form equations, continuing to refer to MountainCar when applicable. The field of RL consists of using different algorithms to approximate optimal solutions to the equations we derive here.</p><p><em>Disclaimer: All of the math involved in MDPs can easily get overwhelming, so I don’t go through step-by-step derivations for every equation. Additionally, there’s not one correct way to write these equations—they have multiple representations invoking a variety of notions, from which I picked those that I found to be the most intuitive. If you’re interested in lower-level explanation, I suggest taking a look at the resources I link to in the References section</em></p><h3>OpenAI Gym Basics</h3><p>First, let’s explore some basic commands in Gym to help us see how an MDP is realized within the MountainCar game. These are the building blocks for the code we will be writing in the next post for getting the car agent to learn an intelligent decision-making process.</p><p>The command env = gym.make(&quot;MountainCar-v0&quot;) creates an instance of the MountainCar game environment. Recall that in this game, a state (i.e. a snapshot of the environment) is defined by the car’s horizontal position and velocity, of which there are theoretically infinite combinations. This is why when we access the environment’s observation_space (i.e. all its possible states) attribute, we find it is represented by a 2D box. In contrast, we see its action_space consists of 3 discrete values, corresponding to the 3 actions available to the car agent in a given state: accelerate to the left, don’t accelerate, or accelerate to the right, encoded as actions 0, 1 and 2, respectively. Actions are taken to transition between states, creating a series of states known in RL as an <em>episode</em> or <em>trajectory</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*sqVevCzc9LaaeMw3K58tNg.png" /><figcaption>A random starting state in the MountainCar game environment.</figcaption></figure><p>To begin an episode, we invoke the game&#39;s reset() function, which yields a vector with a randomly generated position and a velocity of 0, representing the episode’s starting state. Calling env.action_space.sample() generates a random action (0, 1, or 2) from the action space. We take an action by inputting it into the step() function, which returns a [state, reward, done, info] array. Here, state , reward , and done correspond to the new current state, the reward received, and a boolean of whether the agent has reached its goal as a result of taking the action (info is not relevant in this game—it’s just an empty dictionary). We can see that taking the random action leads to a new state with a slightly different position and non-zero velocity from the starting state.</p><p>Having familiarized ourselves with the basics of OpenAI Gym, we can now ask the all-important question of <em>How does our car determine which actions to take?</em> Above, we used the random env.action_space.sample() function, which samples from a uniform distribution across all actions—that is, each of our 3 actions has a 0.33 probability of being selected. With this naive decision-making approach, we can imagine the extremely high number of trials it would take for the car to reach the flag at the top of the hill. We’ll now go over the math involved in teaching our agent a more intelligent way of choosing between actions.</p><h3>Deciding Which Actions to Take</h3><h4>The Policy Function</h4><p>A natural approach to this problem is to think, well, the flag is to the right of the car, so the car should just accelerate to the right to reach it; however, the game is structured such that the car is unable to overcome the force of gravity by only accelerating to the right—rather, it has to build up its momentum by moving left and right between the two slopes, alternating its acceleration. To determine when to switch between these actions, the cart must take into account its current position and velocity, i.e. its<em> state</em>. In RL, the function that decides which action <em>a </em>should be taken in a particular state <em>s</em> is called a <strong>policy</strong>, π<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*iIOeyI7P1EdSTzQ_L76jDg.png" /></figure><p>This function represents a distribution, taking a state as input and outputting a probability for each possible action, which is sampled from during gameplay to determine which action to take. As we discussed above, the policy for env.action_space.sample() is a uniform distribution across all 3 actions, one that does not take into account an input state <em>s</em>. Let’s take a look at what an optimal policy for MountainCar that does take state into account might look like, bearing in mind that this is a vastly simplified example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pMtQk5h_w3ArWbA83ZX9rg.png" /><figcaption>The agent navigates between states to reach the flag by taking actions outputted by its policy. The flag is at position x = 0.5, and states have a reward of -1 if the agent is at x &lt; 0.5 and a reward of 0 otherwise. Note, this idealized example does not take into account stochasticity of the environment (which we’ll account for later).</figcaption></figure><p>Ideally, such a policy would know with 100% certainty the best action to take in any state, that is, it would output a probability of 1 for this action and 0 for the other two. Recall that the cart’s starting position is randomized for each episode, so there’s no one optimal route for the policy to learn. Additionally, we see that the agent refers to the policy <em>at each state</em> to determine which action to take; that is, it’s not as if the policy just takes in the episode’s starting state and outputs the optimal series of actions for the agent to follow through to the end—rather, it outputs one action per state. This is because, while a pre-planned approach could potentially work for a simple game like MountainCar, MDPs are also used to model <em>dynamic</em> environments, in which it’s imperative for the agent to make decisions based on real-time information about its state.</p><p>In reality, it’s not feasible to learn policies as decisive as the one above, rather, we use RL algorithms to arrive at decent approximations. In sum, <em>the fundamental goal of RL is to find a policy that maximizes the reward the agent can expect to receive over the course of an episode by acting on it.</em> There are two important things to note here:</p><ol><li>That reward is the metric of interest</li><li>That we must rely on expectation</li></ol><p>To address the first, you may notice that the policy equation we defined above doesn’t include a variable for reward. Indeed, the policy still needs some means of assigning rewards to actions so it can output high probabilities for “rewarding” actions and vice versa, which requires us to first find a way of mapping rewards to <em>states</em>, since actions are just transitions between states. Let’s discuss how to go about assigning rewards to states, for which we must take into account the second point—the notion of expectation.</p><h4>Determining Expected Reward</h4><p>The inclusion of the word <em>expect</em> in the fundamental goal of RL implies that:</p><ol><li>The agent has some awareness of the future</li><li>The future is associated with uncertainty</li></ol><p>Regarding the first point, our agent needs to map rewards to states in a way that isn’t based solely on how rewarding a given state is immediately upon visiting it but also on its potential for being a part of an overall rewarding trajectory of many states; that is, the agent’s calculation of reward needs to be structured such that it is still able to recognize states that may be penalizing in the short term but beneficial in the long term as rewarding. With this in mind, it makes sense to define the “rewardingness” of a particular state using a sum of rewards of future states.</p><p>But, as the second point addresses, the future is uncertain. Recall that MDPs are used to model environments that are <em>stochastic</em> in nature, meaning that instructing an agent to take a particular action doesn’t lead to it actually be carried out 100% of the time. Further, environments are often <em>dynamic </em>in ways that are extremely difficult to model directly, such as games played against a human opponent. Given these factors, it makes sense to weigh expected rewards less heavily the further in the future they occur because we are less certain we will actually receive them.</p><h4>The State-Value Function</h4><p>With these two points in mind, we can introduce the <strong>state-value function</strong>, which maps values to states in MDPs. The value of a state <em>s</em> is defined as the <em>total reward an agent can expect to receive</em> by starting in <em>s</em><strong><em> </em></strong>and following a trajectory of successive states from<em> s</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Myqm5MRbPPwvGykQIenO_Q.png" /></figure><p>Here, the first term in the expectation operator is the <em>immediate reward </em>the agent expects to receive by being in <em>s</em> and the remaining terms are the rewards for successive states, which we see are weighted by <em>γ.</em> <em>γ </em>is a constant between 0 and 1 called the <strong>discount factor</strong> because it gets exponentiated to weigh future expected rewards less heavily in the sum of total expected rewards attributed to <em>s</em>, accounting for uncertainty of the future in this way. The closer <em>γ </em>is to 1, the more future reward is considered when attributing value to the present state and vice versa. We can group the discounted terms together, arriving at the following representation of the state-value function<strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fRnEfiz0IQNv7R8Mqad6A.png" /></figure><p>Additionally, it is the policy function π that determines the trajectory of states the agent takes, so π can be viewed as another parameter of the function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Cfz2MnIPvA6-bymwIzOzXw.png" /></figure><p>This is what is known as the <strong>Bellman equation</strong> for the state-value function. A Bellman equation is a type of optimization equation that specifies that the “value” of a decision problem at a given point in time depends on the value generated from an initial choice and the value of resulting choices, and, hence, is recursive in nature.</p><h4>The Action-Value Function</h4><p>Given we now have a means of mapping a value to a given <em>state</em>, we can use the fact that an action is a transition between states to map values to <em>state-action pairs</em> as well. Using such a mapping, the agent in any state will have a way to estimate the value of taking each action available to it so it can choose the one with the highest chance of contributing to a maximum overall reward. This is achieved by the <strong>action-value function</strong>, which takes in a state <em>s</em> and action <em>a</em> and outputs the expected reward (a scalar value) for taking <em>a</em> from <em>s</em> and following policy π to take actions thereafter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hjPizu_SVlyhF6U4MnOiA.png" /></figure><p>You may notice it is also a Bellman equation, and that it looks very similar to the state-value function. How are these two equations related? The value of a state <em>s</em> can be determined by taking the sum of the action-values for all actions, where each action-value term is weighted by the probability of taking the respective action <em>a </em>from <em>s</em>, which, as we know, is determined by the policy. Thus, the state-value function can be re-written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*eLOTug3UDcHpZfuU.png" /></figure><p>In MountainCar, for example, say the car is following some policy π that outputs probabilities of 0.3, 0.1 and 0.6 and its action-value function outputs values of 1.2, 0.4 and 2.8 for the three actions given its current state <em>s. </em>Then the value of <em>s</em> is 0.3(1.2) + 0.1(0.4) + 0.6(2.8) = 2.08.</p><p>We can also define the action-value function in terms of the state-value function. Calculating the action-value of a state <em>s</em> and some action <em>a </em>must take into account the stochastic nature of the environment, that is, that even if the agent chooses to take <em>a</em>, random interaction with the environment may cause it to take a different action. You may recall from the first blog that this randomness is encoded in an MDP as a matrix <em>P</em> where an entry <em>P_ss’</em> is the probability of ending up in state <em>s’</em> by choosing to take <em>a</em> from <em>s</em>. We can visualize this using an example in MountainCar. In this case, let’s assume a policy that takes in state <em>s</em> and outputs probabilities of 0.8, 0.06 and 0.14 for actions 0, 1 and 2, respectively. The agent draws from this distribution and chooses action 0 (accelerate to the left), as expected given it has the largest probability. Despite this choice, the probability <em>P_ss’ </em>that the agent actually takes this action is less than certain, equaling 0.9 for example, with the remaining probability being distributed among the other two actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*AV90PxTo5xlaHp_FG8lg3Q.png" /></figure><p>This uncertainty in taking actions means that to calculate the expected reward (i.e. the action-value) for taking any action <em>a</em> in state <em>s</em>, the immediate expected reward for <em>a</em> and <em>s</em> must be added to the discounted sum of expected rewards (i.e. state-values) of all possible successor states, weighted by their probabilities of occurring:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/0*DHnlSMb4-1f0HUcR.png" /></figure><p>We can substitute the new form of the state-value function we derived above into this formula to arrive at the following definition of the action-value function, which we see is the same as the initial equation with the expectation operator applied:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*N9-7yyYfc-JAZeKh.png" /></figure><h4>The Optimization Problem</h4><p>The action-value function gives us a way of determining the value of any action <em>a</em> from any state <em>s</em> in a trajectory determined by policy π—the higher the output of the action-value function, the better that action is for accumulating a high reward over the course of the trajectory. Thus, the <em>optimal</em> policy will know which actions result in the highest action-values with 100% certainty and, as we discussed earlier with the first MountainCar example, will output a probability of 1 for those actions and 0 for the others:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*BUnCpFYFOglU86FG.png" /></figure><p>With this, we arrive at the <strong>Bellman optimality equation</strong> for the action-value function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*wC6fyZmFld_stNaK159esw.png" /></figure><p>This is what Reinforcement Learning aims to solve through a wide variety of approaches. In the next blog of this series, we’ll walk through the theory behind one popular approach called “Q-Learning” to arrive at an estimate of this optimal action-value function using MountainCar.</p><h3>References</h3><ul><li><a href="https://towardsdatascience.com/self-learning-ai-agents-part-i-markov-decision-processes-baf6b8fc4c5f">https://towardsdatascience.com/self-learning-ai-agents-part-i-markov-decision-processes-baf6b8fc4c5f</a></li><li><a href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html">https://spinningup.openai.com/en/latest/spinningup/rl_intro.html</a></li><li><a href="https://www.jeremyjordan.me/markov-decision-process/">https://www.jeremyjordan.me/markov-decision-process/</a></li><li><a href="https://en.wikipedia.org/wiki/Markov_decision_process">https://en.wikipedia.org/wiki/Markov_decision_process</a></li><li><a href="https://en.wikipedia.org/wiki/Bellman_equation">https://en.wikipedia.org/wiki/Bellman_equation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc8e839f6a2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gsi-technology/core-concepts-in-reinforcement-learning-by-example-dc8e839f6a2c">Core Concepts in Reinforcement Learning By Example</a> was originally published in <a href="https://medium.com/gsi-technology">GSI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Markov Decision Processes]]></title>
            <link>https://medium.com/gsi-technology/demystifying-markov-decision-processes-cd8f119aa3d1?source=rss-d47c7e37bf13------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd8f119aa3d1</guid>
            <category><![CDATA[mathematical-modeling]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai-gym]]></category>
            <dc:creator><![CDATA[Hannah Peterson]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 22:59:39 GMT</pubDate>
            <atom:updated>2020-08-12T18:53:51.820Z</atom:updated>
            <content:encoded><![CDATA[<h4>Defining a foundational RL concept with help from OpenAI Gym</h4><p><em>By Hannah Peterson and </em><a href="https://medium.com/@georgewilliams"><em>George Williams</em></a><em> (gwilliams@gsitechnology.com)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxPP7R6n7EntQGHljN5H-w.jpeg" /><figcaption><a href="https://capx.co/yes-theres-a-problem-with-rail-fares-theyre-too-low/">Source</a></figcaption></figure><p>If you’re just starting to dabble in Reinforcement Learning (RL), it’s very easy to get overwhelmed by the multitude of complex equations and technical jargon you come across in trying to piece together what all the ready-made code out there is doing. And this makes sense—after all, it’d be unreasonable to expect the technology that empowers computers to beat pro-gamers at complex games like Go to be simple. But having some understanding of the inner workings of these state-of-the-art algorithms is important if you want to be able to effectively implement them yourself, and that’s what I aim to develop in this series of blogs.</p><p>In this first blog, I’ll introduce Markov Decision Processes (MDPs) and define one in the context of a simple game from <a href="https://gym.openai.com/">OpenAI Gym</a>. In the next blog, I’ll walk-through the equations associated with MDPs to reach the central optimization problem that RL algorithms aim to solve. Then, in the last blog, we’ll actually implement a deep RL algorithm to learn to play a game.</p><h3>What is a Markov Decision Process?</h3><p>Reinforcement learning can be applied to environments in which actions are associated with rewards, as it consists of teaching a model, known as an <strong>agent</strong>, which actions to take in an environment to maximize the reward it receives over the course of some process through trial and error. An MDP is a mathematical framework for modeling such systems; in other words, RL is a means of solving problems that can be expressed as MDPs.</p><p>Specifically, an MDP is a method for planning in what is known as a <strong>stochastic environment</strong>, meaning one in which instructing an agent to take a particular action does not necessarily lead to that action being carried out (as opposed to a <em>deterministic </em>environment)—with a small probability, it is up to the environment to decide what happens to the agent. Assuming a degree of randomness in this way is useful for modeling real-world scenarios because the sensory information an agent collects about its environment may have noise associated with it, for example, and accounting for it allows us to build more robust systems.</p><p>RL is often applied to gaming because games present isolated environments with explicit sets of available actions and rewards based on those actions, whereas real-world scenarios are typically not so clearly parametrized. For this reason, we will continue to discuss reinforcement learning in the context of a game scenario, which is where OpenAI Gym comes in. If you’re unfamiliar with it, OpenAI Gym is a Python library containing various parametrized game environments that the user can easily interact with using code for the purpose of testing out RL algorithms. Let’s take a look at its simple <a href="https://gym.openai.com/envs/MountainCar-v0/">MountainCar</a> game, which we will be programming in a future post. In this game, the agent is represented by a car whose goal is to overcome gravity by moving left and right to reach a flag at the top of a hill:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-foHEKRUCQR-sOyjm9_Tvg.gif" /></figure><p>If we want to be able to solve this problem using RL, we need to be able to represent the MountainCar environment as an MDP. An MDP is expressed as a 4-element tuple &lt;S, A, P, R&gt;, where S is the finite set of states the agent can experience in the environment (known as the <em>state space</em>), P is a matrix of probabilities of transitioning between two successive states, A is the set of actions the agent can take to transition between states (known as the<em> action space</em>), and R is the set of rewards the agent can expect to receive in those the states. Let’s break down each element of an MDP in the context of the MountainCar game to better ground them in reality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*Y38AlpRvuMlsjXgOAmEmOw.png" /><figcaption>A visualization of how the different components of an MDP fit together. The agent takes an action which transitions it to a different state with an associated reward in its given environment. <a href="http://www.juyang.co/reinforcement-learning-ii-markov-decision-process-and-rl-agent/">Source</a></figcaption></figure><ul><li>A <strong>state </strong><em>s</em><strong><em> </em></strong>within S is a snapshot of the environment that the agent is currently in which the agent has partial or complete awareness of. In the case of MountainCar, the car has knowledge of the horizontal components of its position <em>x ∈ [-1.2, 0.6]</em> and velocity <em>v ∈ [-0.07, 0.07]</em> in any given state and this information gets collected 30 times per second. The game ends when the car passes the flag positioned at x=0.5 or when 200 states have occurred. The car’s starting state is initialized to a random position between -0.6 and -0.4 and a velocity of 0.</li><li>An <strong>action </strong><em>a </em>within A transitions the agent from its current state <em>s</em> to another state <em>s’. </em>A sequence of states and actions is called a <strong>trajectory </strong>or an <strong>episode</strong>. The set of actions available for the agent to take may or may not vary dependent on the state the agent is in, but for MountainCar, the agent always has the option of firing its engine to accelerate to the left, to the right, or not at all (whether the car <em>actually</em> accelerates in the desired direction also depends on its interaction with the acceleration of gravity, though).</li><li>An entry <em>P_a(s, s’)</em> in P is the probability that instructing the agent to take action <em>a</em> from <em>s</em> will lead to <em>s’ </em>(recall that MDPs model stochastic environments, in which actions have some randomness associated with them). Translated to our car environment, this is akin to saying that if the car is in state <em>s</em> with position x=0.1 and is instructed to accelerate to the left to <em>s’</em>, there is, say, a 0.98 probability it will actually accelerate to the left — there is a small probability it could behave differently due to some random interaction with the environment.</li><li>Lastly, <em>R_a(s, s’)</em> is the<strong> reward</strong> an agent can expect to receive by taking action <em>a</em> from <em>s </em>to <em>s’</em>. In an MDP, each state is associated with a reward, which in turn means that each action is also associated with a reward since an action is a transition between states. In the MountainCar game, a state’s reward is based on the car’s orientation to the flag positioned at x = 0.5: States in which the car is at x &lt; 0.5 have a reward of -1, while those with x ≥ 0.5 have a reward of 0; thus, the agent’s goal is to get to the flag as quickly as possible to minimize the negative rewards it accumulates.</li></ul><p>We’ve now framed the MountainCar game as a Markov Decision Process. Even within this very simple environment, we can get a sense of the sheer number of possible trajectories available for the agent to take; thus, it needs some means of comparing how rewarding different actions will be—not just immediately upon taking them, but over the course of an entire episode—so that it can choose the paths that will yield the highest rewards. Defining the MountainCar environment as an MDP allows us to use the equations associated with these processes to arrive at a concrete optimization problem for maximizing total reward. We’ll walk through these equations in the next blog.</p><h3>References</h3><ul><li><a href="https://en.wikipedia.org/wiki/Markov_decision_process">https://en.wikipedia.org/wiki/Markov_decision_process</a></li><li><a href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html">https://spinningup.openai.com/en/latest/spinningup/rl_intro.html</a></li><li><a href="https://www.jeremyjordan.me/markov-decision-process/">https://www.jeremyjordan.me/markov-decision-process/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd8f119aa3d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gsi-technology/demystifying-markov-decision-processes-cd8f119aa3d1">Demystifying Markov Decision Processes</a> was originally published in <a href="https://medium.com/gsi-technology">GSI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Segmentation in
Satellite Images]]></title>
            <link>https://medium.com/gsi-technology/a-beginners-guide-to-segmentation-in-satellite-images-9c00d2028d52?source=rss-d47c7e37bf13------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c00d2028d52</guid>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[satellite-imagery]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hannah Peterson]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 23:44:51 GMT</pubDate>
            <atom:updated>2020-07-24T18:30:58.651Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Beginner’s Guide to Segmentation in Satellite Images</h3><h4>Walking through machine learning techniques for image segmentation and applying them to satellite imagery</h4><p><em>By Hannah Peterson and </em><a href="https://medium.com/@georgewilliams"><em>George Williams</em></a><em> (gwilliams@gsitechnology.com)</em></p><p>In my <a href="https://medium.com/gsi-technology/getting-started-with-satellite-data-processing-7653dbd4fc1e">first blog</a>, I walked through the process of acquiring and doing basic change analysis on satellite data. In this post, I’ll be discussing image segmentation techniques for satellite data and using a pre-trained neural network from the SpaceNet 6 challenge to test an implementation out myself.</p><h3>What is image segmentation?</h3><p>As opposed to image classification, in which an entire image is classified according to a label, image segmentation involves detecting and classifying individual objects within the image. Additionally, segmentation differs from object detection in that it works at the pixel level to determine the contours of objects within an image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*aASOfFJyq6mNf7yWdYrTjQ.jpeg" /><figcaption><a href="https://research.fb.com/blog/2016/08/learning-to-segment/">Source</a></figcaption></figure><p>In the case of satellite imagery, these objects may be buildings, roads, cars, or trees, for example. Applications of this type of aerial imagery labeling are widespread, from analyzing traffic to monitoring environmental changes taking place due to global warming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cmzFoET7y9LX0CVNFHyyA.jpeg" /><figcaption><a href="https://deepsense.ai/deep-learning-for-satellite-imagery-via-image-segmentation/">Source</a></figcaption></figure><p>The SpaceNet project’s <a href="https://spacenet.ai/sn6-challenge/">SpaceNet 6 challenge</a>, which ran from March through May 2020, was centered on using machine learning techniques to extract building footprints from satellite images—a fairly straightforward problem statement for an image segmentation task. Given this, the challenge provides us with a good starting point from which we can begin to build understanding of what is an inherently advanced process.</p><p>I’ll be exploring approaches taken to the SpaceNet 6 challenge later in the post, but first, let’s explore a few of the fundamental building blocks of machine learning techniques for image segmentation to uncover how code can be used to detect objects in this way.</p><h3>Convolutional Neural Networks (CNNs)</h3><p>You’re likely familiar with CNNs and their association with computer vision tasks, particularly with image classification. Let’s take a look at how CNNs work for classification before getting into the more complex task of segmentation.</p><p>As you may know, CNNs work by sliding (i.e. <em>convolving</em>) rectangular “filters” over an image. Each filter has different weights and thus gets trained to recognize a particular feature of an image. The more filters a network has—or the <em>deeper</em> a network is—the more features it can extract from an image and thus the more complex patterns it can learn for the purpose of informing its final classification decision. However, given that each filter is represented by a set of weights to be learned, having lots of filters of the same size as the original input image makes training a model quite computationally expensive. It’s largely for this reason that filters typically decrease in size over the course of a network, while also increasing in number such that fine-grained features can be learned. Below is an example of what the architecture for an image classification task might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GcLCGzET18D9mwlwy5XTOA.png" /><figcaption><a href="https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/">Source</a></figcaption></figure><p>As we can see, the output of the network is a single prediction for a class label, but what would the output be for a <em>segmentation</em> task, in which an image may contain objects of multiple classes in different locations? Well, in such a case, we want our network to produce a <em>pixel-wise map</em> of classifications like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oTGzCBIH9nreQx59WiN93g.png" /><figcaption>An image and its corresponding simplified segmentation map of pixel class labels. <a href="https://www.jeremyjordan.me/semantic-segmentation/">Source</a></figcaption></figure><p>To generate this, our network has a one-hot-encoded output channel for each of the possible class labels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*AZiCAN-kbudhft4ZCiHCOg.png" /><figcaption><a href="https://www.jeremyjordan.me/semantic-segmentation/">Source</a></figcaption></figure><p>These maps are then collapsed into one by taking the argmax at each pixel position.</p><p>The tricky part of achieving this segmentation is that the output has to be aligned with the input image—we can’t follow the exact same downsampling architecture that we use in a classification task to promote computational efficiency because the size and locality of the class areas must be preserved. The network also needs to be sufficiently deep to learn detailed enough representations of each of the classes such that it can distinguish between them. One of the most popular kinds of architecture for meeting these demands is what is known as a Fully Convolutional Network.</p><h3>Fully Convolutional Networks (FCNs)</h3><p>FCN’s get their name from the fact that they contain no fully-connected layers, that is, they are fully convolutional. This structure was first proposed by Long et al. in a <a href="https://arxiv.org/abs/1411.4038">2014 paper</a>, which I aim to summarize key points of here.</p><p>With standard CNNs, such as those used in image classification, the first layer of the network is fully-connected, meaning it has the same dimensions as the input image; this means that the size of the first layer must be fixed to align with the input image. Not only does this render the network inflexible to inputs of different sizes, it also means that the network uses <em>global</em> information (i.e. information from the entire image) to make its classification decision, which does not make sense in the context of image segmentation in which our goal is to assign different class labels to different regions of the image. Convolutional layers, on the other hand, are smaller than the input image so that they can slide over it—they operate on <em>local</em> input regions.</p><p>In short, FCNs replace the fully-connected layers of standard CNNs with convolutional layers with large receptive fields. The following figure illustrates this process. We see how a standard CNN for classification of a cat-only image can be transformed to output a heatmap for localizing the cat in the context of a larger image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*OBSrgY3MrZsFyllxSuA3QQ.png" /><figcaption><a href="https://www.jeremyjordan.me/semantic-segmentation/">Source</a></figcaption></figure><p>Moving through the network, we can see that the size of the layers getting smaller and smaller for the sake of learning finer features in a computationally efficient manner—a process known as “downsampling.” Additionally, we notice that the cat heatmap is of coarser resolution than the input image. Given these factors, how does the coarse feature map get translated back to the size of the input image at a high enough resolution such that the pixel classifications are meaningful? Long et al. used what is known as <em>learned upsampling</em> to expand the feature map back to the same size as the input image and a process they refer to as “skip layer fusion” to increase its resolution. Let’s take a closer look at these techniques.</p><h4>Demystifying Learnable Upsampling</h4><p>Prior approaches to upsampling relied on hard-coded interpolation methods, but Long et al. proposed a technique that uses <em>transpose convolution</em> to upsample small feature maps in a learnable way. Recall the way that normal convolution works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*cFMF_uWgUFdVRMZAZ0Bfzg.gif" /><figcaption><a href="https://github.com/vdumoulin/conv_arithmetic">Source</a></figcaption></figure><p>The filter represented by the shaded area slides over the blue input feature map, computing dot products at each position to be recorded in the green output feature map. The weights of the filter are what is being learned by the network during training.</p><p>Transpose convolution works differently: the filter’s weights are all multiplied by the scalar value of the input pixel it is positioned over, and these values get projected to the output feature map. Where filter projections in the output map overlap, their values are added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*VecZjxpHfnwMIv54SdZGJw.png" /><figcaption><a href="http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture11.pdf">Source</a></figcaption></figure><p>Long et al. use this technique to upsample the feature map rendered by network’s downsampling layers in order to translate its coarse output back to pixels that align with those of the input image, such that the network’s architecture looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TES3tq3OE_TvRl0DVJ28wQ.png" /><figcaption>An example of a final upsampling layer appended to the downsampling path to render a full-sized segmentation map. Note that the final feature map has 21 channels, representing the number of classes for the particular segmentation challenge being explored in the paper. <a href="https://arxiv.org/pdf/1411.4038.pdf">Source</a></figcaption></figure><p>However, simply adding one of these transpose convolutional layers at the end of the downsampling layers yields spatially imprecise results, as the large stride required to make the output size match the input’s (32 pixels, in this case) limits the scale of detail the upsampling can achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*WItvWCdTKkI5O1qG9iLUbA.png" /><figcaption>The upsampled segmentation map (left) is appropriately scaled to the input image but lacks spatial precision. <a href="https://arxiv.org/pdf/1411.4038.pdf">Source</a></figcaption></figure><p>Luckily, this lack of spatial precision can be somewhat mitigated by “fusing” information from layers with different strides, as we’ll now discuss.</p><h4>Skip Layer Fusion</h4><p>As previously mentioned, a network must be deep enough to learn detailed features such that it can make faithful classification predictions; however, zeroing in closely on any one part of an image comes at the cost of losing spatial context of the image as a whole, making it harder to localize your classification decision in the process of zooming back out. This is the inherent tension at play in image segmentation tasks, and one that Long et al. work to resolve using <em>skip connections</em>.</p><p>In neural networks, a skip connection is a fusion between non-adjacent layers; in this case, skip connections are used to transfer local information by summing feature maps from the downsampling path with feature maps from the upsampling path. Intuitively, this makes sense: with each step we take through the downsampling path of the network, global information gets lost as we zoom into a particular area of the image and the feature maps get coarser, but once we have gone sufficiently deep to make an accurate prediction, we wish to zoom back and localize it, which we can do utilizing information stored in the higher resolution feature maps from the downsampling path of the network. Let’s take a more in depth look at this process by referencing the architecture Long et al. use in their paper:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GY2wbfZiCZHaAeNoj6OVQA.png" /><figcaption>Visualization of skip connections (left arrows) in a network and their effect on the granularity of resulting segmentation maps. <a href="http://deeplearning.net/tutorial/fcn_2D_segm.html">Source</a> (modified)</figcaption></figure><p>Across the top of the image is the network’s downsampling path, which we can see follows a pattern of two or three convolutions followed by a pooling layer. conv7 represents the coarse feature map generated at the end of the downsampling path, akin to the cat heatmap we saw earlier. The “32x upsampled prediction” is the result of the first architecture without any skip connections, accomplishing all of the necessary upsampling with a single transpose convolutional layer of a 32 pixel stride.</p><p>Let’s walk through the “FCN-16s” architecture, which involves one skip connection (see the second row of the diagram). Though it is not visualized, a 1x1 convolution layer is added on top of the “pool4” feature map to produce class predictions for all its pixels. But the network does not end there—it proceeds to downsample by a factor of 2 once more to produce the “conv7” class prediction map. Since the conv7 map is of half the dimensionality of the pool4 map, it is <em>up</em>sampled by a factor of 2 and its predictions are added to those of the pool4, producing a combined prediction map. This result is upsampled via a transpose convolution with a stride of 16 to yield the final “FCN-16s” segmentation map, which we can see achieves better spatial resolution than the FCN-32s map. Thus, although the conv7 predictions experience the same amount of upsampling in the end as in the FCN-32s architecture (given that 2x upsampling followed by 16x upsampling = 32x upsampling), factoring the predictions from the pool4 layer improves the result greatly. This is because pool4 reintroduces valuable spatial information from the input image into the equation—information that otherwise gets lost in the additional downsampling operation for producing conv7. Looking at the diagram, we can see that the “FCN-8s” architecture follows a similar process, but this time a skip connection is also added from the “pool3” layer, which we see yields an even higher fidelity segmentation map.</p><h4>FCNs—Where to go from here?</h4><p>FCNs were a big step in semantic segmentation for their ability to factor in both deep, semantic information and fine, appearance information to make accurate predictions via an “encoding and decoding” approach. But the original architecture proposed by Long et al. still falls short of ideal. For one, it results in somewhat poor resolution at segmentation boundaries due to loss of information in the downsampling process. Additionally, overlapping outputs of the transpose convolution operation discussed earlier can cause undesirable checkerboard-like patterns in the segmentation map, which we see an example of below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AIbEaVO1UPzQDKQtz3R7kg.png" /><figcaption>Criss-crossing patterns in a segmentation heatmap resulting from overlapping transpose convolution outputs. <a href="https://arxiv.org/pdf/1708.02031.pdf">Source</a></figcaption></figure><p>Many models have built upon the promising baseline FCN architecture, seeking to iron out its shortcomings, “U-net” being a particularly notable iteration.</p><h3>U-Net—An Optimized FCN</h3><p>U-net was first proposed in a <a href="https://arxiv.org/pdf/1505.04597.pdf">2015 paper</a> as an FCN model for use in biomedical image segmentation. As the paper’s abstract states, “The architecture consists of a contracting path to capture context and a symmetric expanding path that enables precise localization,” yielding a u-shaped architecture that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ox0y5jBz5_ebh_0WYbtCXg.png" /><figcaption>An implementation of the U-net architecture. Numbers at the top of the feature maps denote their number of channels, numbers at the bottom left denote their x-y-size. The white feature maps represent are copies from the downsampling path, which we can see get concatenated to feature maps in the upsampling path. <a href="https://arxiv.org/pdf/1505.04597.pdf">Source</a></figcaption></figure><p>We can see that the network involves 4 skip connections—after each transpose convolution (or “up-conv”) in the upsampling path, the resulting feature map gets concatenated with one from the downsampling path. Additionally, we see that the feature maps in the upsampling path have a larger number of channels than in the baseline FCN architecture for the purpose of passing more context information to higher resolution layers.</p><p>U-net also achieves better resolution at segmentation boundaries by pre-computing a pixel-wise weight map for each training instance. The function used to compute the map places higher weights on pixels along segmentation boundaries. These weights are then factored into the training loss function such that boundary pixels are given higher priority for being classified correctly.</p><p>We can see that the original U-net architecture yields quite fine-grained results in its cellular segmentation tasks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0o0aoujrc73IaO-WA_D9TA.png" /><figcaption>U-net segmentations results in images <strong>b </strong>and <strong>d</strong>, with ground truth boundaries outlined in yellow. <a href="https://arxiv.org/pdf/1505.04597.pdf">Source</a></figcaption></figure><p>The development of U-net yet was another milestone in the field of computer vision, and five years later, models continue to expound upon its u-shaped architecture to achieve better and better results. U-net lends itself well to satellite imagery segmentation, which we will circle back to soon in the context of the SpaceNet 6 challenge.</p><h3>Further Developments in Image Segmentation</h3><p>We’ve now walked through an evolution of a few basic image segmentation concepts—of course, only scratching the surface of a topic at the center of a vast, rapidly evolving field of research. Here is a list of a few other interesting image segmentation concepts and applications, with links should you wish to explore them further:</p><ul><li><a href="https://towardsdatascience.com/single-stage-instance-segmentation-a-review-1eeb66e0cc49">Instance segmentation</a> is a hybrid of object detection and image segmentation in which pixels are not only classified according to the class they belong to, but individual objects within these classes are also extracted, which is useful when it comes to counting objects, for example.</li><li>Techniques for image segmentation extend to video segmentation as well; for example, Google AI uses an “hourglass segmentation network architecture” inspired by U-net for <a href="https://ai.googleblog.com/2018/03/mobile-real-time-video-segmentation.html">real-time foreground-background separation</a> in YouTube stories.</li><li><a href="https://devblogs.microsoft.com/cse/2018/04/18/deep-learning-image-segmentation-for-ecommerce-catalogue-visual-search/">Clothing image segmentation</a> has been used to help retailers match catalogue items with physical items in warehouses for more efficient inventory management.</li><li>Segmentation can be applied to 3D volumetric imagery as well, which is particular useful in medical applications; for example, research has been done on using it to <a href="https://pdfs.semanticscholar.org/ad8d/730ee28dcb6198b1b0006297d3f77d4dd536.pdf#page=21">monitor the development of brain lesions</a> in stroke patients.</li><li>Many tools and packages have been developed to make image segmentation accessible to people of various skill levels. For instance, <a href="https://towardsdatascience.com/semantic-segmentation-of-150-classes-of-objects-with-5-lines-of-code-7f244fa96b6c">here</a> is an example that uses Python’s PixelLib library to achieve 150-class segmentation with just 5 lines of code.</li></ul><p>Now, let’s walk through actually implementing a segmentation network ourselves using satellite images and a pre-trained model from the SpaceNet 6 challenge.</p><h3>The SpaceNet 6 Challenge</h3><p>The task outlined by the SpaceNet challenge is to use computer vision to automatically extract building footprints from satellite images in the form of vector polygons (as opposed to pixel maps). In the challenge, predictions generated by a model are determined viable or not by calculating their intersection over union with ground truth footprints. The model’s f1 score over all the test images is calculated according to these determinations, serving as the metric for the competition.</p><p>The training dataset consists of a mix of mostly synthetic aperture radar (SAR) and a few electro-optical (EO) 0.5m resolution satellite images collected by <a href="https://www.capellaspace.com/">Capella Space</a> over Rotterdam, the Netherlands. The testing dataset contains only SAR images (for further explanation on SAR imagery, take a look at <a href="https://medium.com/gsi-technology/getting-started-with-satellite-data-processing-7653dbd4fc1e">my last blog</a>). The dataset being structured in this way makes the challenge particularly relevant to real-world applications, as SpaceNet explains, it is meant to “mimic real-world scenarios where historical optical data may be available, but concurrent optical collection with SAR is often not possible due to inconsistent orbits of the sensors, or cloud cover that will render the optical data unusable.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*3Y8XgMUw7LOgyY1VTu3krQ.png" /><figcaption>An example of a SAR image from the SpaceNet 6 dataset, with building footprint annotations shown in red. <a href="https://medium.com/the-downlinq/spacenet-6-dataset-release-66076c8fb79b">Source</a></figcaption></figure><p>More information on the dataset, including instructions for downloading it, can be found <a href="https://medium.com/the-downlinq/spacenet-6-dataset-release-66076c8fb79b">here</a>. Additionally, SpaceNet released a baseline model, for which they provide <a href="https://openaccess.thecvf.com/content_CVPRW_2020/papers/w11/Shermeyer_SpaceNet_6_Multi-Sensor_All_Weather_Mapping_Dataset_CVPRW_2020_paper.pdf">explanation</a> and <a href="https://github.com/CosmiQ/CosmiQ_SN6_Baseline">code</a>. Let’s explore the architecture of this model before implementing it to make predictions ourselves.</p><h4>The Baseline Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*N50bAyl7AseW-VwdWxNk6Q.png" /><figcaption>TernausNet architecture. <a href="https://arxiv.org/pdf/1801.05746.pdf">Source</a></figcaption></figure><p>The architecture SpaceNet uses as its baseline is called <a href="https://arxiv.org/abs/1801.05746">TernausNet</a>, a variant of U-Net with a VGG11 encoder. VGG is a family of CNNs, VGG11 being one with 11 layers. TernausNet uses a slightly modified version of VGG11 as its encoder (i.e. downsampling path). The network’s upsampling path mirrors its downsampling path, with 5 skip connections linking the two. TernausNet improves upon U-Net’s performance by initializing the network with weights that were pre-trained on Kaggle’s <a href="https://www.kaggle.com/c/carvana-image-masking-challenge">Carvana dataset</a>. Using a model pre-trained on other data can reduce training time and overfitting—an approach known as <em>transfer learning. </em>In fact, SpaceNet’s baseline takes advantage of transfer learning again by first training on only the optical portion of the training dataset, then using the weights it finds through this process as the initial weights in its final training pass on the SAR data.</p><p>Even with these applications of transfer learning, though, training the model on roughly 24,000 images is still a very time intensive process. Luckily, SpaceNet provides the weights for the model at its highest scoring epoch, which allow us to get the model up and running fairly easily.</p><h4>Making Predictions from the Baseline Model</h4><p>Step-by-step instructions for deploying the baseline model can be found in <a href="https://medium.com/the-downlinq/deploying-the-spacenet-6-baseline-on-aws-c811ad82da1">this blog</a>. In short, the process involves spinning up an AWS Elastic Cloud Compute (EC2) instance to gain access to GPUs for more timely computation and loading the challenge’s Amazon Machine Image (AMI), which is pre-loaded with the software, baseline model and dataset. Keep in mind that the dataset is very large, so downloads may take some time.</p><p>Once your downloads are complete, you can find the PyTorch code defining the baseline model in model.py. baseline.py takes care of image preprocessing and running training and testing operations. The weights of the pre-trained model with the best scoring epoch are found in the weights folder and are loaded when test.sh is run.</p><p>When we run an image through the model, it outputs a series of coordinates that define the boundaries of the building footprints we are looking to find as well as a mask on which these footprints are plotted. Let’s walk through the process of visualizing an image and its mask side-by-side to get a sense of how effective the baseline model is at extracting building footprints. Code for producing the following visualizations can be found <a href="https://github.com/fractalsproject/earth_observer">here</a>.</p><p>Getting a coherent visual representation of the SAR data is somewhat trickier than expected. This is because each pixel in a given image is assigned 4 values, corresponding to 4 polarizations of data in the X-band of the electromagnetic spectrum—HH, HV, VH and VV. In short, signals transmitted and received from a SAR sensor come in both horizontal and vertical polarization states, so each channel corresponds to a different combination of the transmitted and received signal types. These 4 channels don’t translate to the 3 RGB channels we expect for rendering a typical image. Here’s what it looks like when we select the channels one-by-one and visualize them in grayscale:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3doF1h1bbLAVVeMxFCEa0g.png" /><figcaption>Visual representations of the 4 polarizations of a single SAR image. <em>Image by author</em></figcaption></figure><p>Notice that each of the 4 polarizations captures a slightly different representation of the same area of land. We can combine these representations to produce a single-channel <em>span image</em> to plot alongside the building footprint mask the model generated, which we convert to binary to make the boundaries more clear. With this, we can see that the baseline model did recognize the general shapes of several buildings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58f6cYfh-u521IADFm6SeQ.png" /><figcaption>A visualization of the combined spectral bands of a SAR test image and the corresponding building footprint mask generated by the baseline model. Image by author</figcaption></figure><p>It is pretty cool to see the basic structures we’ve discussed in this post in action here, producing viable image segmentation results. But, it’s also clear that there is room for improvement upon this baseline architecture—indeed, it only achieves an f1 score of 0.21 on the test set.</p><h3>Conclusion</h3><p>The SpaceNet 6 challenge wrapped up in May, with the winning submission achieving an f1 score of 0.42—double that of the baseline model. More details on the outcomes of the challenge can be found <a href="https://medium.com/the-downlinq/spacenet-6-announcing-the-winners-df817712b515">here</a>. Notably, all of the top 5 submissions implemented some variant of U-Net, an architecture that we now have a decent understanding of. SpaceNet will be releasing these highest performing models on GitHub in the near future and I look forward to trying them out on time series data to do some exploration with change detection in a future post.</p><p>Lastly, I’m very thankful for the thorough and timely assistance I received from <a href="https://www.capellaspace.com/">Capella Space</a> for writing this—their insight into the intricacies of SAR data as well as recommendations and code for processing it were integral to this post.</p><h3>References</h3><ul><li><a href="https://missinglink.ai/guides/computer-vision/image-segmentation-deep-learning-methods-applications/">https://missinglink.ai/guides/computer-vision/image-segmentation-deep-learning-methods-applications/</a></li><li><a href="https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/">https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/</a></li><li><a href="https://engineering.matterport.com/splash-of-color-instance-segmentation-with-mask-r-cnn-and-tensorflow-7c761e238b46">https://engineering.matterport.com/splash-of-color-instance-segmentation-with-mask-r-cnn-and-tensorflow-7c761e238b46</a></li><li><a href="https://arxiv.org/abs/1411.4038">https://arxiv.org/abs/1411.4038</a></li><li><a href="https://www.youtube.com/watch?v=nDPWywWRIRo&amp;list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&amp;index=11">https://www.youtube.com/watch?v=nDPWywWRIRo&amp;list=PLC1qU-LWwrF64f4QKQT-Vg5Wr4qEE1Zxk&amp;index=11</a></li><li><a href="http://deeplearning.net/tutorial/fcn_2D_segm.html">http://deeplearning.net/tutorial/fcn_2D_segm.html</a></li><li><a href="https://www.topbots.com/semantic-segmentation-guide/">https://www.topbots.com/semantic-segmentation-guide/</a></li><li><a href="https://arxiv.org/pdf/1505.04597.pdf">https://arxiv.org/pdf/1505.04597.pdf</a></li><li><a href="https://medium.com/the-downlinq/spacenet-6-announcing-the-winners-df817712b515">https://medium.com/the-downlinq/spacenet-6-announcing-the-winners-df817712b515</a></li><li><a href="https://simularity.com/using-aisaroptical-to-find-the-invisible/">https://simularity.com/using-aisaroptical-to-find-the-invisible/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c00d2028d52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gsi-technology/a-beginners-guide-to-segmentation-in-satellite-images-9c00d2028d52">A Beginner’s Guide to Segmentation in
Satellite Images</a> was originally published in <a href="https://medium.com/gsi-technology">GSI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Satellite Data Processing]]></title>
            <link>https://medium.com/gsi-technology/getting-started-with-satellite-data-processing-7653dbd4fc1e?source=rss-d47c7e37bf13------2</link>
            <guid isPermaLink="false">https://medium.com/p/7653dbd4fc1e</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[earth-observation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[satellite-imagery]]></category>
            <dc:creator><![CDATA[Hannah Peterson]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 21:35:46 GMT</pubDate>
            <atom:updated>2020-08-12T18:02:20.342Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s easier than you think!</h4><p><em>By Hannah Peterson and </em><a href="https://medium.com/@georgewilliams"><em>George Williams</em></a><em> (gwilliams@gsitechnology.com)</em></p><h3>Introduction</h3><p>I’m currently a Data Science major at UC San Diego and was lucky enough to get an internship at GSI Technology for the summer. This is my first blog, and in it I’ll be giving some background on satellite imagery and walking through the process I went through of acquiring image data from Capella Space — an information services company providing Earth observation data on demand — and doing some basic exploration of it. I was excited to receive this assignment from my mentor because I’ve been curious about satellite data from reading about its current and potential applications in environmental conservation. This is a very easy way to get started with exploring it if you, too, are interested.</p><h3>Earth Observational (EO) Data</h3><p>You may be surprised by the great extent to which EO data can impact our day-to-day lives. Here are a few interesting examples:</p><ul><li>Satellite data is used to <a href="https://www.theatlantic.com/magazine/archive/2019/05/stock-value-satellite-images-investing/586009/">count cars</a> in the parking lots of major retailers such as Walmart, providing investment funds with predictors of corporate profits to help investors choose stocks.</li><li>In precision agriculture, <a href="https://www.satimagingcorp.com/applications/natural-resources/agriculture/">satellite imagery is used</a> to detect moisture and vegetation levels of crops, among other metrics, informing farmers of adjustments they can make to increase yields.</li><li><a href="https://abcnews.go.com/International/satellite-data-suggests-coronavirus-hit-china-earlier-researchers/story?id=71123270">Analysis</a> of satellite imagery of hospitals from before and during the coronavirus outbreak suggests hospital traffic monitoring could be useful in predicting future outbreaks of infectious disease sooner.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*AytNJTdJEgrD2RgWsOtItQ.jpeg" /><figcaption>An aerial view of a hospital in China showing the difference in the number of cars present on the same day both the year prior to the COVID-19 outbreak and in its midst.</figcaption></figure><p>These specific examples harness what is known as optical satellite data, but there is another widely used type called Synthetic Aperture Radar, or SAR, satellite data, which is the kind <a href="https://www.capellaspace.com/">Capella Space</a> specializes in and what we will be exploring.</p><h3>Capella Satellites and SAR Data</h3><p>Capella Space’s mission is to make timely, reliable and persistent Earth observation data the norm using SAR satellites. Capella’s technology can deliver sub-0.5 meter very high resolution geospatial imagery and data. The fine granularity — both spatially and temporally — of Capella’s geospatial data makes it possible to detect tiny, near real-time changes on the Earth’s surface. From analyzing traffic patterns to predicting wildfire occurrences, potential applications of such data span across countless industries.</p><p>But what exactly is so special about SAR satellites — how do they compare to optical satellites, the other most widely deployed type?</p><p>Optical sensors measure solar light reflected from the Earth’s surface in the visible spectrum to produce images similar to what the human eye sees, making them easily interpretable. However, this also means that optical images are limited by darkness and clouds or strong weather patterns. These factors make optical imagery less than desirable for use in short-term change detection, for which high-fidelity images need to be captured at regular time intervals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQ3MzueBTUwh-9sIAv-tPA.jpeg" /><figcaption>An example of high-resolution optical satellite imagery. <a href="https://www.defence24.com/optics-or-radars-what-is-better-for-the-earth-observation-purposes">Source</a></figcaption></figure><p>Radar sensors, on the other hand, work by emitting microwaves from an antenna towards a surface and recording the intensity and delay of reflected waves, making them sensitive to slight positional differences. The lengths of these waves are much longer than those of visible or infrared light, making the sensors functional in all lighting conditions and able to penetrate through clouds and dust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8J4RFmd80eiMSC8T9iOJ1g.jpeg" /><figcaption>An example of SAR satellite imagery. <a href="https://www.defence24.com/optics-or-radars-what-is-better-for-the-earth-observation-purposes">Source</a></figcaption></figure><p>The longer the radar sensor’s antenna (a.k.a. its <em>aperture</em>), the more reflected waves it can collect, leading to a higher resolution image. Synthetic Aperture Radar (SAR) satellites capture high resolution images by mimicking the effects of having longer apertures than they actually do. To illustrate, take a look at the following diagram of SAR operating from a plane:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*Fw-jLNakmHFbSJM36QtOmg.png" /><figcaption><a href="https://www.radartutorial.eu/20.airborne/ab07.en.html">Source</a></figcaption></figure><p>As the plane moves at velocity <strong><em>v</em></strong> from point <strong><em>A</em></strong> to <strong><em>D</em> </strong>over a time <strong><em>t</em></strong>, the SAR’s antenna emits continuous pulses. For the sake of simplicity, let’s say it only emits four pulses, one at each point; thus, any one point on the ship will reflect four frequencies, which are Doppler-shifted when received by the SAR antenna. By comparing these four shifted frequencies to a reference frequency, they can be traced back to the single point they reflected off of. In this way, the antenna is able to reconstruct the signal it would have obtained from a much longer antenna of length <strong><em>vT</em></strong><em>, </em>resulting in a higher resolution image.</p><p>Capella has maximized the smaller size benefit of SAR satellites to create their “micro-satellites,” which have “a payload bus the size of a backpack” and thus are much cheaper to manufacture and deploy than traditional satellites. Luckily, Capella makes the data generated by these nimble satellites freely accessible via its API. To request access to it, fill out the form found <a href="https://www.capellaspace.com/community/">here</a>.</p><h3>Interacting with Capella’s SAR satellite data</h3><p>Now, we will get into the coding portion of this post. Capella has provided some examples of how to fetch and render their satellite data via their <a href="https://github.com/capellaspace/jupyter-notebooks">public repository</a> of Jupyter Notebooks. I’ll be walking through their examples for generating a time series gif and a change heat map. Starting off, you may find you need to install some of the packages used in the Notebooks. Additionally, to be able to fetch the data with Capella’s API, you’ll need to have your login credentials saved to a “credentials.json” file formatted exactly like:</p><pre>{<br>  &quot;username&quot;: &quot;my_email@example.com&quot;,<br>  &quot;password&quot;: &quot;my_password&quot;<br>}</pre><h4>Making a time series gif</h4><p>First, let’s make the gif. The code is found in the “Capella-Time-Series-GIF-Example” in the GitHub repo. Make sure it’s downloaded to the same directory as the credentials.json file you made. Once you’ve done this and installed all the necessary packages, the code should run as is. But let’s walk through it to see how it works.</p><p>It starts off with some important parameters for fetching the desired satellite data:</p><pre><em># Data, BBOX, and time definition</em><br>bbox = [4.362831, 51.885881 ,4.376993, 51.894436]<br>timerange = &quot;2019-08-22T00:00:00Z/2019-08-24T23:59:00Z&quot;<br>collections = [&quot;rotterdam-aerial-mosaic&quot;]</pre><pre><em># Windows sizes for filtering</em><br>FILTSIZE = 3 <em># window size for speckle filter</em></pre><p>Once you have your API credentials, I suggest going to the Capella Console — Capella’s web-based portal for interacting with their existing archival images — to see what data is currently available. Capella has conducted and published aerial collection campaigns of The San Francisco Bay area and Rotterdam, the Netherlands and will soon publish data from their most recent aerial collect in the San Diego area. This is where the collections variable is relevant — it specifies the region you want to receive data from. In the notebook, collections is set to “rotterdam-aerial-mosaic,” so this means we’ll be fetching images of Rotterdam. You can check out what other collections are available through the Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjyifnF1gyJ23M1lTCF35g.png" /><figcaption>Imagery collections currently available in the Capella Console</figcaption></figure><p>timerange, as expected, specifies the window of time you want data from. Check the Console to make sure that there is in fact data available in the collection you chose within the timerange you specify; you can verify this by checking the “Start” parameter of the images in the collection. Additionally, bbox specifies the latitude and longitude coordinates of the bottom left and top right corners of the area that is rendered in the gif (formatted as [lon_lower_left, lat_lower_left, lon_upper_right, lat_upper_right]). You can change these around to render different areas, just make sure they fall within the area of the collection you choose.</p><p>A little farther down, we come across the concept of “speckle filtering”:</p><pre><strong>def</strong> lee_filter(img, size):<br>    img_mean = uniform_filter(img, (size, size))<br>    img_sqr_mean = uniform_filter(img**2, (size, size))<br>    img_variance = img_sqr_mean - img_mean**2</pre><pre>    overall_variance = variance(img)</pre><pre>    img_weights = img_variance / (img_variance + overall_variance)<br>    img_output = img_mean + img_weights * (img - img_mean)<br>    <strong>return</strong> img_output</pre><p>SAR images are inherently grainy due to the interference of scattered waveforms — this interference may be constructive (resulting in a bright spot) or destructive (resulting in a dark spot) dependent upon the relative phases of the waveforms. To get a clearer image, a filtering function is applied — in this case, the Lee filter, which is particularly good at edge preservation. Below is an example of what one of our SAR images looks like before and after filtering. Removing this random variation will be particularly important when doing change analysis in the next example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7UBhvQjGfiP5bSbgEz0OcA.png" /><figcaption>The same image over Rotterdam before and after speckle filtering.</figcaption></figure><p>Next, the reproject_bbox function is defined:</p><pre><strong>def</strong> reproject_bbox(bb, epsg):<br>    transformer = Transformer.from_crs(&quot;EPSG:4326&quot;, epsg, \    <br>          always_xy=<strong>True</strong>)<br>    obb = [0] * 4<br>    obb[0], obb[1] = transformer.transform(bb[0], bb[1])<br>    obb[2], obb[3] = transformer.transform(bb[2], bb[3])<br>    <strong>return</strong> obb</pre><p>When we provided the latitude and longitude coordinates of the bounding box for the images, we gave them values according to the ESPG 4326 — the Earth’s standard coordinate reference system (CRS). But when capturing the images, the satellite was in its own CRS. This function basically maps the coordinates of our bounding box to the CRS that the satellite was in, which is an essential step in making sure our images look the way we expect them to (I quickly found there is <em>lots</em> of math involved in transforming the SAR data into an interpretable image, but luckily, the author of notebook knew the right packages to use to finish the job).</p><p>Our login credentials and the variables we specified above are used to fetch the relevant image data from Capella’s catalog, and we ensure that they are sorted by time so that our time-series gif is meaningful.</p><p>Finally, the images are processed one-by-one and added to the gif. We can see that the projection transformation is applied by calling reproject_bbox(). In the following lines, the speckle filtering is applied to reduce random noise, the exposure is adjusted, and the colors are scaled so that we achieve a nice contrast in our final images:</p><pre>img1 = lee_filter(img1, FILTSIZE)<br>img1 = exposure.adjust_log(img1, gain=10)<br>            <br>img1_min = img1.min()<br>img1_max = img1.max()<br>img1_scaled = (img1 - img1_min) / (img1_max - img1_min) * 255</pre><p>With this, we achieve our final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*iWWNzfd-s1fc_8dO5lPxng.gif" /></figure><p>Capella had 11 images within the specified two day time period of 8/22/19 to 8/24/19, and we can see from the timestamps that the time intervals are not evenly spaced. We can see all the changes taking place in this busy port area, including the movement of the individual ships in the waterway. SAR technology makes it possible to visualize such small-scale changes.</p><p>Now that we’re familiar with the process of simply acquiring and rendering SAR satellite data, it’d be interesting to do some analysis on it. Capella’s repo has a Notebook to walk us through that process as well.</p><h4>Change heat map</h4><p>The code for this example can be found in Capella’s GitHub repo in the Notebook titled “Capella-Log-Ratio-Change-Detection-Example-Using-API-and-COGs.” The initial steps of specifying our time range, collection and bounding box and fetching the data are exactly the same as with making the gif.</p><p>When it comes to making the heat map, the overall change in the images over time is found by recording the change between pairs of adjacent images in matrices and then adding them together to build one cumulative change matrix. To accomplish this, adjacent images in the time series of images are looped through in pairs, speckle filtering is applied to both, and then the log-ratio of the pair is calculated:</p><pre># Calculate the log ratio of image pairs<br>dIx = np.log(lee_filt_img2/lee_filt_img1)</pre><p>The ratio of the two images is taken as opposed to their difference because noise in SAR images is multiplicative, meaning that the intensity of the noise in a particular region of an image varies with that region’s intensity, so taking the ratio ensures that changes between the images will be detected in the same manner in regions of both high and low intensity. Further, the logarithm of the ratio is taken to compress the range of variation of the ratio image such that its values are less extreme and to better balance the distribution of “changed” vs. “unchanged” pixels, which will be determined via comparison to a threshold value next. The following image demonstrates the effect of taking the ratio vs. the log-ratio of two images prior to thresholding, the “Context Image” being the first of the series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBS6CDbGZqU5yEsVWmggBw.png" /><figcaption>Ratio (center) and log-ratio (right) change heat maps between the Context Image (left) and the next image in the time series.</figcaption></figure><p>We can see that the pixel values in the log-ratio heat map are less extreme than in the pure ratio and that it picks up on variations that the pure ratio heat map does not — it is more sensitive to change.</p><p>Based on this matrix of log-ratios between pixel values, a threshold is calculated, and the ratios are mapped to either 0 or 1 depending on how they compare to it:</p><pre>thr = np.nanmean(dIx) + THRSET*np.nanstd(dIx)<br>dIx[dIx &lt; thr] = 0.0<br>dIx[dIx &gt; thr] = 1.0</pre><p>The value for the threshold is calculated according to the mean and standard deviation of the values in the log ratio matrix and thus is dependent upon the distribution of pixel values of the two images. It also involves the constant THRSET which can be lowered or increased if you want the map to be more or less sensitive to change, respectively. Additionally, because we will be layering multiple maps on top of each other in the end, mapping each individual one to binary values results in a more coherent representation of change than were we to stack maps with highly variable values within themselves.</p><p>Next, the following code uses a SciPy image processing function for “erasing small objects”:</p><pre># Morphological opening to reduce false alarms    <br>w = (MORPHWINSIZE, MORPHWINSIZE)<br>dIx = morphology.grey_opening(dIx, size=w)</pre><p>In the case of our SAR images, small objects are taken to be points of random noise not eliminated during the speckle filtering, which we don’t want to be recognized as meaningful change.</p><p>Having gone through all these steps, here is an example of what a change heat map between just two images looks like, with the “Context Image” being the first image of the time series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaLz3v3iFBY1X6HDfqllow.png" /></figure><p>As adjacent pairs of images are looped through, their heat maps are stacked on top of each another, resulting in the cumulative change heat map for the 11 images in the two-day series:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDlPNmpbEefMaH7ZZ-88Tg.png" /></figure><p>We can see that the most activity over these couple of days took place in the docking area in the bottom right, as we can see the ships that came and went and the moving equipment rendered in lighter shades of blue/green.</p><h3>Conclusion</h3><p>Thanks to the simple examples and accessible data Capella has provided, working with satellite data wasn’t as intimidating as I thought it would be. I have also gained a better understanding of the different types of satellite data and their respective use-cases. SAR satellite data isn’t the kind we’re used to seeing, but the simple heat map we have created demonstrates its usefulness in change detection.</p><p>Now that I’ve had some experience working with satellite data, in future posts I look forward to exploring more advanced approaches to change detection involving, for example, image segmentation with machine learning.</p><h3>References</h3><ul><li><a href="https://ecologyforthemasses.com/2020/05/27/radar-vs-optical-optimising-satellite-use-in-land-cover-classification/">https://ecologyforthemasses.com/2020/05/27/radar-vs-optical-optimising-satellite-use-in-land-cover-classification/</a></li><li><a href="https://earthi.space/blog/radar-vs-optical-earth-observation-why-both/">https://earthi.space/blog/radar-vs-optical-earth-observation-why-both/</a></li><li><a href="https://airsar.jpl.nasa.gov/documents/genairsar/radar.html">https://airsar.jpl.nasa.gov/documents/genairsar/radar.html</a></li><li><a href="https://www.defence24.com/optics-or-radars-what-is-better-for-the-earth-observation-purposes">https://www.defence24.com/optics-or-radars-what-is-better-for-the-earth-observation-purposes</a></li><li><a href="https://www.radartutorial.eu/20.airborne/ab07.en.html">https://www.radartutorial.eu/20.airborne/ab07.en.html</a></li><li><a href="https://en.wikipedia.org/wiki/Speckle_(interference)">https://en.wikipedia.org/wiki/Speckle_(interference)</a></li><li><a href="https://www.cs.uaf.edu/~olawlor/ref/asf/sar_equations_2006_08_17.pdf">https://www.cs.uaf.edu/~olawlor/ref/asf/sar_equations_2006_08_17.pdf</a></li><li><a href="https://ieeexplore.ieee.org/abstract/document/1542367">https://ieeexplore.ieee.org/abstract/document/1542367</a></li><li><a href="https://www.researchgate.net/publication/3203744_An_unsupervised_approach_based_on_the_generalized_Gaussian_model_to_automatic_change_detection_in_multitemporal_SAR_images#pfd">https://www.researchgate.net/publication/3203744_An_unsupervised_approach_based_on_the_generalized_Gaussian_model_to_automatic_change_detection_in_multitemporal_SAR_images#pfd</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7653dbd4fc1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gsi-technology/getting-started-with-satellite-data-processing-7653dbd4fc1e">Getting Started with Satellite Data Processing</a> was originally published in <a href="https://medium.com/gsi-technology">GSI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>