<?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 Romain Guion on Medium]]></title>
        <description><![CDATA[Stories by Romain Guion on Medium]]></description>
        <link>https://medium.com/@romain.guion?source=rss-5bce7397ff69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*StL6vaqzMDjrSEzXXfV_tA.png</url>
            <title>Stories by Romain Guion on Medium</title>
            <link>https://medium.com/@romain.guion?source=rss-5bce7397ff69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:07:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romain.guion/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[Building a culture of business owners and incremental innovations]]></title>
            <link>https://medium.com/vortechsa/building-a-culture-of-business-owners-and-incremental-innovations-53c14fb893bf?source=rss-5bce7397ff69------2</link>
            <guid isPermaLink="false">https://medium.com/p/53c14fb893bf</guid>
            <category><![CDATA[tech-culture]]></category>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[iteration]]></category>
            <category><![CDATA[responsibility]]></category>
            <category><![CDATA[management-and-leadership]]></category>
            <dc:creator><![CDATA[Romain Guion]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 17:11:02 GMT</pubDate>
            <atom:updated>2021-02-17T22:42:05.213Z</atom:updated>
            <content:encoded><![CDATA[<h4>Don’t ask for permission — ask for advice</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*1-6ifEM_dIhLnzCYsSPF-w.png" /></figure><p>In a high growth environment, osmosis and direct mentoring is not always enough to shape culture. To be deliberate about culture, I find it useful to write down a strawman, as an anchor to provoke debates with my team. Here is a short piece.</p><p>Context: in my teams, to enable individuals to be autonomous while fostering collaboration, I delegate quarterly objectives to squads of 2–4 people.</p><h3>Transferring ownership without losing the momentum in the delegation process</h3><blockquote><strong><em>Act as a business owner, which all of us are, and more specifically as owning the team quarterly objectives.</em></strong></blockquote><p>Teams owning objectives, or individuals owning tasks, are often handed not only with a goal, but also a vision of how that goal could be reached, along with perhaps prototypes that were made to derisk or scope the task.</p><p>Those visions or prototypes are valuable, and should be discussed in depth with their originators so they are well understood. But they are not gospel, and it is essential we challenge them in a constructive way, envision the future, and derisk what’s not clear in either the implementation or the requirements, at any step of the process.</p><p>For the best outcome, this needs to be balanced with focus and coordination. If we only explore without delivering, we’re exploring around a single point, like a Brownian motion without drift. So we need cycles of exploration and execution to maximise our learning.</p><p>When we decide which option to explore next, even if your option hasn’t been selected, and even if the decision isn’t the best one, we all need to stand behind the decision and push it to the next iteration cycle so we gather new information.</p><p>In optimisation theory, this is similar to the gradient descent algorithm, trying to point towards a global optimum while having only local knowledge at hand: the best algorithms aren’t the ones that maximise the search time from local knowledge (e.g. computing lots of derivatives and heuristics from lots of records), but those that balance this with more iterations — stochastic gradient descent being an example on an opposite extreme.</p><p>In a nutshell: keeping your eyes on the end goal, challenging each other, balancing exploration with execution and iterating often.</p><h3>How does that translate into rules or processes?</h3><blockquote><em>It doesn’t make sense to hire smart people and tell them what to do; we hire smart people so they can tell us what to do.</em></blockquote><p>Instead of rules and processes, many of which become stale pretty much immediately, we work towards shared <strong>goals</strong> and with a shared <strong>culture</strong>, allowing the bright minds in Vortexa to create value, coherently.</p><blockquote><em>Don’t ask for permission: you are the owner — ask for advice.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53c14fb893bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/building-a-culture-of-business-owners-and-incremental-innovations-53c14fb893bf">Building a culture of business owners and incremental innovations</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Satellite images object detection — part 2: the beauty & the beast]]></title>
            <link>https://medium.com/vortechsa/satellite-images-object-detection-part-2-the-beauty-the-beast-f92ff27b696a?source=rss-5bce7397ff69------2</link>
            <guid isPermaLink="false">https://medium.com/p/f92ff27b696a</guid>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[interpretability]]></category>
            <dc:creator><![CDATA[Romain Guion]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 09:10:49 GMT</pubDate>
            <atom:updated>2020-06-16T15:05:01.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Satellite images object detection — part 2: the beauty &amp; the beast</h3><p>Ship surveillance &amp; tracking — part 2: towards fully convolutional network, for more interpretability (example of CAM attention), early localisation properties, and capability to evolve into an image segmentation model. In the process, we’ll delve into the technique of transfer learning</p><p><strong>Motivation: </strong>although the simple ConvNet we built in Part 1 did pretty well at the classification task we gave it, the usage of dense layers makes it hard to interpret, both by human, and for further models to be built on top of it. In this post, we explore a different ConvNet structure that uses convolutional layers and pooling layers instead of dense layers, keeping connections localised. It is not only more interpretable when used for classification, but can also evolve into an object localisation / segmentation model, which we will present in part 3, with a U-Net.</p><p>While we’d like to start with the beauty, we often need to face the beast first:</p><ul><li><strong>The beast:</strong> insights into some of the unspoken practical challenges with transfer learning</li><li><strong>The beauty:</strong> decision interpretability through GAP/GMP’s pooling implicit localisation properties</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*TVHjbA9Zj9hVmOm6wcxhug.png" /><figcaption>Visualisation of the model’s attention, and with it emerging localisation properties. More details at the end of this post.</figcaption></figure><p><strong>This is the 2nd part of a 3 blog posts series:</strong></p><ul><li><a href="https://medium.com/@romain.guion/satellite-images-object-detection-part-1-95-accuracy-in-a-few-lines-of-code-8ee4acd72809"><strong>Ship detection — Part 1</strong></a>: binary prediction of whether there is at least 1 ship, or not. Part 1 is a simple solution showing great results in a few lines of code</li><li><a href="https://medium.com/@romain.guion/satellite-images-object-detection-part-2-the-beauty-the-beast-f92ff27b696a"><strong>Ship detection &amp; early localisation— Part 2</strong></a><strong>:</strong> towards object segmentation with (a) training fully convolutional NN through transfer learning, to build an encoder for a U-Net, and (b) first emerging localisation properties with CAM attention interpretability</li><li><a href="https://medium.com/@romain.guion/satellite-image-segmentation-part-3-eeb134fe3dd5"><strong>Ship localisation — Part 3</strong></a>: identify where ships are within the image, building a U-Net from the encoder developed in Part 2</li></ul><p><strong>What you will learn in this post (Ship detection — Part 2):</strong></p><ul><li><strong>Encoder for a U-Net:</strong> training a fully convolutional network on a classification task</li><li><strong>Transfer learning: </strong>a brief review of the image recognition architectures</li><li><strong>Practical transfer learning </strong>from MobileNetV2 and Xception, reaching 93% accuracy after having seen only 0.5 times the data set, along with the practical challenges involved in using and<strong> fine-tuning</strong> those complex pre-trained networks.</li><li><strong>Learning rate tuning techniques</strong>, such as landscaping and cycling to get out of local optima</li><li><strong>Visualise model attention and implicit localisation</strong> through the interpretation of hidden layers when Global Average / Max Pooling is used (GAP / GMP). In contrast to classic localisation algorithms that use localisation labels for training, this network remarkably learns basic localisation implicitely, with only ship / no ship labels</li></ul><p><a href="https://github.com/rugg2/ship_detection">Code available on github</a></p><h3>Transfer learning from pre-trained deep ConvNets</h3><p><strong>Transfer learning</strong> is the idea that strong neural networks trained for one application have generalisable features that can be leveraged for other applications. This means a large network fine-tuned for weeks on problems such as ImageNet, with 1000 classes and 1.2 million images, would have learned something fundamental about processing features, e.g. detecting edges, managing contrasts, etc.</p><p>To take advantage of such models, the first step is to use the pre-trained model as a feature extractor and add a simple classifier on top, and if performance and the data set warrants it, fine tune some layers of the pre-trained model.</p><p>Training those networks is expensive though: for example with ResNet50V2 the iteration time on my machine (CPU only) was 12h per pseudo-epoch vs 35min for the simple ConvNet presented in Part 1 (side note: with GPU you get a 15x increase in speed so that changes the game).</p><p>To choose what network to transfer from, I took a look at <a href="https://keras.io/applications/#build-inceptionv3-over-a-custom-input-tensor">the performance on the ImageNet competition</a>. A word on popular networks you may want to use for transfer learning:</p><ul><li><strong>Residual Nets</strong>: although deeper neural networks tend to make better use of neurons than wide shallow networks, they suffer from vanishing gradients, as the back propagation feedback from the loss function gets passed from layer to layer. ResNets tackled this problem by creating shortcuts that facilitate this backwards information transfer, and effectively make it very easy for each module to learn the identity function instead of bad performance that’d harm other layers. Note those shortcuts are “short skips” on a ResNet, and we’ll explore “long skips” with U-nets in the next blog post on localisation (Part 3).</li><li><strong>Inception Nets:</strong> core idea is to enable filters of multiple sizes to operate at the same level in the network, and let the network chose which is best placed to pick the right feature, depending e.g. on the size of the object on the image. To keep computational cost under control, a 1x1 depth filter is introduced to reduce the number of channel (effectively creating a bottleneck). More than InceptionV3, one of the most successful network with this architecture seems to be <strong>Xception</strong>.</li><li><strong>MobileNet</strong>: ResNet trying to be more light weight by performing depth-wise convolutions (to reduce the number of channels), and use bottleneck layers (a bit like InceptionNet is seems). The goal here is to keep high performance in environments with limited compute, such as mobile phones.</li></ul><h3>First go at transfer learning on TensorFlow 2.0 with MobileNetV2</h3><p>Given my computer’s performance limitations, I had a go at MobileNetV2, and got a pseudo-epoch iteration time of 2.5h (CPU).</p><p>Using the pretrained model as a feature extractor, a classifier can be built by adding 2 layers:</p><ul><li>a global pooling layer to aggregate the features over the spatial dimensions: (batch size, height, width, channels) -&gt; (batch size, 1, 1, channels), irrespective of image size. I chose global max pooling instead of global average pooling as I have the intuition average pooling would favour larger ship on the image.</li><li>adding a simple neuron to interpret those features as a sign of a vessel vs not. Basically, this is equivalent to building logistic regression on top of 1280 features.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*QzwIY3LVdczsKeRbnwTTOQ.png" /><figcaption>First attempt: add global pooling and 1 neuron on top of a frozen &amp; headless MobileNetV2</figcaption></figure><p>The model quickly converged to 77.5% accuracy, which may sound ok, but actually corresponds to the class imbalance. Looking more closely, the model only learned to always predict “no ship”, and the loss stayed flat for 5 pseudo-epochs (i.e. over 200k images). I explored a range of learning rates, but this didn’t change much:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*QUokrIXUSMoCE4cfKMLWIw.png" /><figcaption>Not as sexy as the graph shown in the previous post!</figcaption></figure><p>Although the model may not have enough capacity, and acknowledging the ImageNet dataset is pretty different from our satellite images of ship, I felt such a bad performance was suspicious.</p><p>I tried feeding the network repeatedly the same single batch of 40 images to see if the model is able to fully overfit, but it didn’t seem to… The model clearly has enough capacity to learn by heart 40 results.</p><p><strong>Turns out there was an error in the TF documentation</strong>, as raised in <a href="https://github.com/tensorflow/tensorflow/issues/28718">this Github issue</a>: <em>binary_crossentropy </em>expects by default a probability, not a <em>logit </em>(raw value, without activation). Fix in flight</p><p><strong>Lessons learned:</strong> trying to overfit a single batch to check the feedback mechanism works can be a pretty handy sanity check tool</p><h3>Second go at transfer learning on TensorFlow 2.0 with MobileNetV2</h3><p>Training single neuron dense layer (only 1k parameters).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoIRG_UfpyDUAL0FKV17ng.png" /><figcaption>Training only last Dense layer. Pretrained MobileNet’s weights frozen. Starting to overfit.</figcaption></figure><p>With transfer learning we observe quickly very high performance while only training 1k parameters. However, strangely the model starts to overfit despite so few parameters.</p><p>I tried adding dropouts, and even 50% didn’t curb the model’s overfit. I tried GAP instead of GMP to spatially regularise, and performance went down closer to 80% than 90%. The ImageNet images are pretty different from ours, so I decided to fine tune the last layers of the network with a small learning rate (3E-5), and got a boost in performance initially, and very quickly more overfitting. I didn’t try increasing the training set size as the model starts overfitting before having seen the entire data set!</p><p>At this point I thought the model may be stuck on a local optima, may benefit from larger images, fine tuning of deeper layers, or counter intuitively need more capacity / a new architecture. Let’s try some of those!</p><h3>Transfer learning from Xception network, and learning rate cycling to get out of local optima</h3><p>We first get a baseline with Xception of training the base classifier + fine tuning, without learning rate cycling:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Jhu4WeUecYpxvN0SkDOUsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*5_Cy04Q72BNzq5A1kjpdIw.png" /><figcaption>(Left) Xception weights frozen, with GAP, dropouts and a classifier. (Right) Exploring learning rate stability.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sH7tqFh4CIOSrahgQmFzkw.png" /><figcaption>LR: 3E-4 when frozen, 3E-5 when fine tuning</figcaption></figure><p>You can observe that fine tuning initially gives a boost in CV accuracy, but leads to aggressive overfitting.</p><p>Now we explore learning rate cycling to speed up learning and hopefully escape local optimum (<a href="https://github.com/rugg2/ship_detection/blob/master/learning_rate_utils.py">code</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*tNf7a3Gd8jK7vu75xeUe8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*4mbm3z7Y-vajqm1GMbqmfg.png" /><figcaption>LR cycling: varies between 3E-4 and 1E-3 when frozen, and 3E-5 and 5E-4 while fine tuning.</figcaption></figure><p>Learning rate cycling speeds up training, and gives a CV accuracy boost, but does not solve the underlying overfitting problem.</p><p>Best result is achieved with early stopping at about 12 epochs. We decided to stop fine tuning for this post: further improvements could explore:</p><ul><li>using progressively larger images: this can be changed in the argument of our pipeline ImageBatchGenerator, since we left the input size of our Xception model as None, and the GAP/GMP layer makes the classifier size-invariant.</li><li>train for longer, with an augmented data set (distortions, more images etc)</li><li>further regularisation</li></ul><p>Conclusion with transfer learning: although this can give great results fast on problems similar to the pretraining dataset, miracles shouldn’t be expected and quite a bit of work is needed in practice to extract the last percentages of accuracy. As we saw in this post, simpler solutions should not be overlooked!</p><p>That being said, we’ve got a pretty decent classifier with 94% accuracy, and that will be enough as a basis for our U-Net in Part 3.</p><p>Now we will look into a cool feature of networks using GAP / GMP layers: interpretability of hidden layers and localisation as an emerging behaviour.</p><h3>The concept of network’s attention, and with it implicitly learned object localisation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WsiZ3rBp-n0TPyZOQCK-g.png" /><figcaption>In red the parts of the image where the model focuses its attention. What is remarkable is how much those heat maps overlap with the ship, despite the model having never been told where the ships were in the image. This technique called Class Activation Mapping (CAM) is a spatial attribution of the ship / no ship classification decision (first described in this MIT paper <a href="https://arxiv.org/pdf/1512.04150.pdf">https://arxiv.org/pdf/1512.04150.pdf</a>)</figcaption></figure><p>Neural networks have a reputation for being hard to interpret, and are often described as black boxes. With CNNs using global pooling layers, an activation map indicating the discriminative image regions used by the network can easily be calculated.</p><p>Just before the final output layer, we have performed global pooling on the convolutional feature maps, and then used those features in a fully-connected layer producing the desired classification. Given this simple connectivity structure, we can identify the importance of the image regions by projecting back the weights of the output layer on to the convolutional feature maps, a technique known as Class Activation Mapping (CAM).</p><p>Another way to understand this is to look at our simplified architecture:</p><ul><li>Image inputs: (batch size=40, height=299, width=299, channels=3)</li><li><strong>Xception output</strong>:<strong> </strong>(batch size=40, height at this layer=10, width at this layer=10, channels at this layer=2048)</li><li>Global Max Pooling output: (batch size=40, 1, 1, channels at this layer=2048)</li><li><strong>Classifier </strong>(dense) output: (batch size=40, classification dim=1)</li></ul><p>The quantity we show on the heatmap is the Xception output, summed over the channels axis, with the sum weighted by the Classifier’s weights for each channel.</p><p>This simple quantity can be directly visualised. In practice though the resolution is quite low (10x10), as we are deep into the network , so in the visualisation above we have upsampled it (back to 299x299 to overlay with original image).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65c45ea99ce1097ea57650a9e27c05f2/href">https://medium.com/media/65c45ea99ce1097ea57650a9e27c05f2/href</a></iframe><p>I hope you enjoyed the ride and got some good take-away. I’d love to hear of your own experience with transfer learning, and whether there are steps in the analysis you interpret differently!</p><p>In the next post, we will reuse the Xception classifier we trained in this post to 94% accuracy, and will reuse it as the encoder of our U-Net for image segmentation / ship localisation. <a href="https://medium.com/@romain.guion/satellite-image-segmentation-part-3-eeb134fe3dd5">Click here to read part 3!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f92ff27b696a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/satellite-images-object-detection-part-2-the-beauty-the-beast-f92ff27b696a">Satellite images object detection — part 2: the beauty &amp; the beast</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Satellite image segmentation— part 3]]></title>
            <link>https://medium.com/vortechsa/satellite-image-segmentation-part-3-eeb134fe3dd5?source=rss-5bce7397ff69------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeb134fe3dd5</guid>
            <category><![CDATA[shipping]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <dc:creator><![CDATA[Romain Guion]]></dc:creator>
            <pubDate>Fri, 12 Jun 2020 23:04:02 GMT</pubDate>
            <atom:updated>2020-06-16T19:16:28.780Z</atom:updated>
            <content:encoded><![CDATA[<p>Ship surveillance &amp; tracking — part 3: identifying where ships are on an image, using a U-net built on top of the encoder trained in part 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*oRQRIAnOBphaJkZ5QZ0X5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*Dtg3gfKKoZb5-1nyT67KgA.png" /><figcaption>Inputs and outputs of the U-Net model we build in this blog post</figcaption></figure><p><strong>This is the 3rd part of a 3 blog posts series:</strong></p><ul><li><a href="https://medium.com/vortechsa/satellite-images-object-detection-part-1-95-accuracy-in-a-few-lines-of-code-8ee4acd72809"><strong>Ship detection — Part 1</strong></a>: binary prediction of whether there is at least 1 ship, or not. Part 1 is a simple solution showing great results in a few lines of code</li><li><a href="https://medium.com/vortechsa/satellite-images-object-detection-part-2-the-beauty-the-beast-f92ff27b696a"><strong>Ship detection &amp; early localisation — Part 2</strong></a><strong>:</strong> towards object segmentation with (a) training fully convolutional NN through transfer learning, to build an encoder for our U-Net, and (b) first emerging localisation properties with CAM attention interpretability</li><li><a href="https://medium.com/@romain.guion/satellite-image-segmentation-part-3-eeb134fe3dd5"><strong>Ship localisation — Part 3</strong></a>: identify where ship are within the image, building a U-Net from the encoder developed in Part 2</li></ul><p><a href="https://github.com/rugg2/ship_detection">Code available on github</a></p><h3>Introduction to image segmentation, and U-net</h3><p>Image segmentation has a long history of traditional algorithms, from thresholding to clustering and Markov random fields. With the progress in deep learning, a number of algorithms to draw bounding boxes then became state of the art, like Single Shot multibox Detector (SSD) or You Only Look Once (YOLO), popular with autonomous vehicles. In this article, we will build on the <em>implicit localisation properties</em> of fully convolutional networks we demonstrated with CAM in Part 2 of this blog post series. We will build a U-Net, an architecture created in 2015 in the paper <a href="https://arxiv.org/abs/1505.04597">“U-Net: Convolutional Networks for Biomedical Image Segmentation”</a> , itself an improvement of <a href="https://arxiv.org/abs/1411.4038">“Fully convolutional networks for semantic segmentation”</a> . Both of these networks take a different strategy to YOLO and the like, and perform pixel by pixel segmentation instead of bounding boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*8C-1pvkX9p1w6iRly7aoTg.png" /><figcaption>U-Net architecture <a href="https://arxiv.org/pdf/1505.04597.pdf">from the original U-Net paper</a>, with encoder / downsampling part on the left of the U, and decoder / upsampling part on the right of the U. In this post, we trained the encoder on a classification task in part 2.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iNmOsDOQN8yqTD_VWTf7nw.png" /><figcaption>Illustration of downsampling in encoder until pool5, and then upsampling in decoder, <a href="https://arxiv.org/pdf/1411.4038.pdf">from the original FCN paper</a></figcaption></figure><p>A segmentation task is different from a classification task because it requires predicting a class for each pixel of the input image, instead of only 1 class for the whole input. Classification needs to understand <em>what</em> is in the input (namely, the context).</p><p>To do this, in this post we expand on the Fully Convolutional Networks (FCNs) we developed in part 2, built only from locally connected layers, such as convolution, pooling and upsampling. In part 2, we discovered that the classifier had implicit localisation properties, stemming from this local topology, and we visualised the results through a very rough static upsampling step. The idea in this post is to train a network at this upsampling step, this time with labeled masks of how we want to image to be reconstituted.</p><ul><li><strong>Downsampling path</strong> : capture semantic/contextual information (<em>what</em>). In this post, we will reuse the encoder Xception trained in part 2 on a classification task (ship / no ship), and keep its weights frozen</li><li><strong>Upsampling path</strong> : recover spatial information (<em>where</em>). In this part 3, this is the part of the network we will train.</li></ul><h3>Labeled data: images and masks with ships</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSXhO3ru2wSL--1RdPyaSQ.png" /><figcaption>Data input: images and masks highlighting which pixels correspond to a ship</figcaption></figure><h3>U-Net implementation in TensorFlow, for this ship localisation task</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/707f2dcf3a34ce134d14878dcd2afb6a/href">https://medium.com/media/707f2dcf3a34ce134d14878dcd2afb6a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*PsxrlpqaRCPCH6QxG01tCQ.png" /><figcaption>U-Net implementation in tensorflow. The variable “model” is the encoder (here Xception pretrained in part 2)</figcaption></figure><h3>Managing class imbalance</h3><p>In the dataset we’re using, 78% of images have no ship. For images with ≥ 1 ship, the ratio of pixels with a ship to pixels with no ship is about 1/1000. Together, this makes about 1/5000 class imbalance, which is tough to handle. To manage this class imbalance, we’re taking 2 actions:</p><ul><li>separate the ship detection task from the image segmentation task</li><li>for the segmentation task, pixel accuracy probably won’t cut it (network would likely learn to always say “no ship”, so we’ll mix the loss function with a different metric called the DICE similarity coefficient (2 * |X| inter |Y|) / (|X| + |Y|). We’ll also track a similar metric called intersection over union (|X| inter |Y|) / (|X| U |Y|), and the true positives rate of pixels</li></ul><h3>Managing overfitting</h3><p>In this first implementation, I have managed overfitting as upstream as I could, by:</p><ol><li>performing a lot of data augmentation on our already pretty large training set (given the short training I gave for this blog post, training set isn’t even seen once by the neural network, let alone with data augmentation, but this means we could train for much longer and see benefits)</li><li>freezing encoder weights, so the capacity of the model is reduced: out of 28 million weights, “only” 7 millions are trainable. Fine tuning at a later stage may be valuable, but to start it reduces the number of weights.</li></ol><p>What could be done next is more traditional regularisation, dropouts and early stopping.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de7a36d7c9d2522e090074459c91e816/href">https://medium.com/media/de7a36d7c9d2522e090074459c91e816/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wyxyas6PdbD8VW81TUYcfA.png" /><figcaption>Training data for U-Net: data augmentation multiplies the effective training set, helping the model to generalise / reduce overfitting</figcaption></figure><h3>Training process</h3><p>After only 10 min of training (iterating through 8000 images), our U-Net already already made pretty decent predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egnsSqy-qyfUtE2Ejn4JWg.png" /><figcaption>Prediction after 2 pseudo-epochs (2 x 200 steps x 20 images). The U-net localises vessels after very little training, and that’s probably the reflection of the implicit localisation properties of our fully convolutional encoder, as highlighted by the CAM model in part 2. That may also contribute to the model being robust to mislabeling: on this image there are clearly 3 vessels, but the label highlights only 2.</figcaption></figure><p>Although the performance started relatively high, presumably stemming from our pretrained fully convolutional encoder, the initial training attempts staled at a validation Dice coefficient of about 0.35, stagnating for about 20 pseudo-epochs (of 200 steps of 20 images). Using Adam, and changing learning rates didn’t seem to help. Under the assumption of a premature convergence to a local optimum, a strategy of learning rate cycling was adopted (discussed in Part 2; <a href="https://github.com/rugg2/ship_detection/blob/master/learning_rate_utils.py">code</a>). This brought the val Dice to 0.75, highlighting once more the importance of tuning convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*CRahAUC_D2LdOMC0s-Y4WQ.png" /><figcaption>Learning rate cycling schedule used to escape local optima, ranging from 5e-6 and 1e-3.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1iByTY0H0DaNidvl9_ZDvQ.png" /><figcaption>Performance during training of U-Net for a couple of hours.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*pIqfUB2tViS1bBtduWoWPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*7u_fHQCeAarGgdsO6D7Plw.png" /><figcaption>Picks up all shapes, although some vessels moored alongside are merged into one.</figcaption></figure><p>Through a pretty basic training we reached a decent performance for the model: val dice 0.75, val IoU 0.37, val true positive pixel rate of 0.67 (and val binary pixel accuracy of 0.997). For some applications, this performance may already be enough. And notice that what we did was overall pretty simple, and the results presented here should really be seen as a starting point from which many simple improvements can be made:</p><ul><li>train for longer: the model has not actually seen all the training data yet, let alone the augmented data!</li><li>model seems to overfit the training data: this is odd given the model hasn’t seen all the training set yet, and could be due to a bug (opportunity to improve!). Beyond the bug, regularisation, batch normalisation and dropouts are classic next steps.</li><li>refine loss function to better represent the learning objective. For example recent Kaggle competitions seem to use “Focal Loss”, defined by a recent Facebook paper <a href="https://arxiv.org/pdf/1708.02002.pdf">(FAIR, 2018)</a>. It adds a factor (1 − pt)^γ to the standard cross entropy criterion. Setting γ &gt; 0 reduces the relative loss for well-classified examples (pt &gt; .5), putting more focus on hard, misclassified examples</li><li>hyperparameter optimisation: U-Net structure was pretty random, and where the skips are placed probably matters</li><li>better train the encoder (in part 2 we also stopped as soon as we got decent performance)</li></ul><p>I hope you enjoyed the ride, and that you now feel that building an image detection and segmentation algorithm isn’t that big a deal!</p><p>To conclude, we will show more predictions where the model sometimes does well, and other times not so well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*QWWCGluRrivu9tYzIFWVlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*i_-g_DynouquTApKXuRzAQ.png" /><figcaption>Model can learn complex shapes despite labels being rectangular</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*dsPEvHhpDkWJrwKTIcp_Og.png" /><figcaption>Model handles various contrasts quite well</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*6T2rByVR40doDIOoMzYWQw.png" /><figcaption>Some ships are tiny</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*dez7jiS3hgwvasqtdSh3_A.png" /><figcaption>partial view of a vessel is handled ok</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*8Yu1vSnCI7I91RGp42Mu_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*oI0I3FHh1tjHmf3-bG3QQQ.png" /><figcaption>Model may have learned to ignore wash, which makes is ignore some vessels in the wash of others here?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*2-miHAm0PIN4St9MFvTGcA.png" /><figcaption>Struggling with the shadow, or just too small?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*eA6hpNqD7I_3RWF-lfjCGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*U-1_Rxm7jSbJEXUcA3gEhA.png" /><figcaption>Robust to partial / corrupted images</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeb134fe3dd5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/satellite-image-segmentation-part-3-eeb134fe3dd5">Satellite image segmentation— part 3</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Satellite images object detection — part 1: 95% accuracy in a few lines of code]]></title>
            <link>https://medium.com/vortechsa/satellite-images-object-detection-part-1-95-accuracy-in-a-few-lines-of-code-8ee4acd72809?source=rss-5bce7397ff69------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ee4acd72809</guid>
            <category><![CDATA[convolutional-neural-net]]></category>
            <category><![CDATA[ship-tracking]]></category>
            <category><![CDATA[satellite-imagery]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Romain Guion]]></dc:creator>
            <pubDate>Tue, 04 Feb 2020 17:51:56 GMT</pubDate>
            <atom:updated>2020-06-16T15:30:53.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>Satellite images object detection —part 1: 95% accuracy in a few lines of code</h3><p>Ship surveillance &amp; tracking with TensorFlow 2.0 — part 1: the basic solution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*O3OOv9lENclVpDEat8W6-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*SVg0BYIZTNpC_ubgsFKZhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*yzcAlqLwc98lgTg2q0QVVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*J53vgb1Y5O1JOdujoUm0LQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*rW_LIAhgcWzhTmKdgEQcKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*hz9GeW5Po339pgGrbzKqdQ.png" /><figcaption>Diversity of satellite images conditions and scales makes object detection one step harder.</figcaption></figure><h3><em>The question is not “if”, but “how” image-based insights should be consumed</em></h3><p>Given the exponential growth of images, and in particular optical, infrared and SAR satellite images, business opportunities are growing faster than the number of data scientists that know how to handle them.</p><p>For companies used to consume structured data, this means:</p><ul><li>Dedicating a number of their data scientists to develop image processing skills in-house, or</li><li>Consuming already processed feeds, for example <a href="https://www.vortexa.com/">Vortexa </a>and its <a href="https://medium.com/vortechsa/arming-commodity-experts-with-vortexas-python-sdk-fed68fdb01b4">SDK</a> or its <a href="https://medium.com/vortechsa/scaling-vortexa-data-sets-with-aws-data-exchange-ccfcb5e591da">datasets on AWS data exchange</a> in the case of ship analytics.</li></ul><p><strong>Target audience for this post</strong>:</p><ul><li>The data scientist tasked with developing image processing skills will be interested in the simple implementation of Part 1, as well as the thinking process in dealing with the often unspoken architecture and optimisation choices made in Part 2 &amp; 3.</li><li>The reader interested in consuming already processed feeds might want to look at images and their captions in both posts, and get a feel for what’s involved in object detection, and their interpretability.</li></ul><p><strong>This is the 1st part of a 3 blog posts series:</strong></p><ul><li><a href="https://medium.com/vortechsa/satellite-images-object-detection-part-1-95-accuracy-in-a-few-lines-of-code-8ee4acd72809"><strong>Ship detection — Part 1</strong></a>: ship detection, i.e. binary prediction of whether there is at least 1 ship, or not. Part 1 is a simple solution showing great results in a few lines of code</li><li><a href="https://medium.com/vortechsa/satellite-images-object-detection-part-2-the-beauty-the-beast-f92ff27b696a"><strong>Ship detection &amp; early localisation —</strong> <strong>Part 2</strong></a><strong>:</strong> towards object segmentation with (a) training fully convolutional NN through transfer learning, to build an encoder for a U-Net, and (b) first emerging localisation properties with CAM attention interpretability</li><li><a href="https://medium.com/@romain.guion/satellite-image-segmentation-part-3-eeb134fe3dd5"><strong>Ship localisation — Part 3</strong></a>: identify where ships are within the image, building a U-Net from the encoder developed in Part 2</li></ul><p><strong>What you will learn in this post (Ship detection — Part 1):</strong></p><ul><li><strong>Context: </strong>satellite imaging context &amp; opportunities</li><li><strong>On the fly preprocessing</strong> generators with Tensorflow</li><li><strong>Learning rate selection technique</strong></li><li><strong>Simple ConvDenseNet</strong> (LeCun style) implementation, reaching 95% accuracy while having seen the data set only 2.5 times</li></ul><p><a href="https://github.com/rugg2/ship_detection">Code available on github</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*UeVtmucVygO8ODl0Nyrs7w.png" /><figcaption>Source: Kanjir et al, 2018, Remote Sensing of Environment, <a href="https://www.sciencedirect.com/science/article/pii/S0034425717306193">https://www.sciencedirect.com/science/article/pii/S0034425717306193</a></figcaption></figure><h3><strong>Context, motivation and opportunities.</strong></h3><p>With the increase of satellites in orbit, daily pictures of most of the world are now widely available. Data sources include both free (USGS, Landviewer, ESA’s Copernicus etc) and commercial (Planet, Orbital insight, Descartes labs, URSA etc) entities. The competition is fierce, and seems to yield very fast innovation, with companies such as Capella Space now pitching hourly updates by launching constellations of small satellites of only a few kg. Those satellites increasingly cover beyond the optical visible spectrum, notably Synthetic Aperture Radar (SAR), which offers the benefit to work independently of clouds or daylight. Along with the growth of other image sources, the ability to interpret image data is a key to untapped commercial opportunities.</p><p>The monitoring of human activity is increasing for the purpose of fishing, drilling, exploration, cargo and passenger transport, tourism, for both governmental and commercial purposes, particularly at sea. For ship tracking in particular, satellite images offer a rich complement to baseline cooperative tracking systems such as AIS, LRIT and VMS.</p><h3><strong>Feeding the beast: preprocessing steps</strong></h3><ul><li><strong>Label </strong>each image as ship / no-ship.</li><li><strong>Mini-batch </strong>data into 40 images chunks. Using batches &gt; 1 leverages vectorisation and makes computation faster compared to stochastic gradient descent (i.e. batch size = 1). Using smaller batches (~20–500) than the entire dataset (200k images here) first allows the data to fit in memory, and the extra noise tends to prevent premature convergence on local minima.</li><li><strong>Reduce the image size </strong>from 768 x 768 x 3 to e.g. 256 x 256 x 3, to make training faster, and reduce overfitting. Using modern ConvNet (fully convolutional or with GAP/GMP), it is good practice to start training with small images and fine tune with larger images later.</li><li><strong>Data augmentation</strong>: flip horizontally and vertically initially. Extra distortions could be added later on, when the model starts overfitting to squeeze extra performance.</li><li><strong>Renormalise </strong>magnitude from [0, 255] to [0, 1].</li></ul><p>Here is how we conduct this preprocessing on the fly with Keras’ <em>ImageDataGenerator </em>class, with the labeling done with <em>flow_from_dataframe, </em>all feeding later on into the <em>fit / fit_generator API:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/184f5d55145b426c32d9a181bdc12a08/href">https://medium.com/media/184f5d55145b426c32d9a181bdc12a08/href</a></iframe><h3>1st architecture — a simple ConvDense network</h3><p>Starting simple and iterating:</p><ul><li><strong>Images are represented as 4 dimensional tensors</strong>: batch size, height, width and channels (RGB at the input, layers of features deeper in the network)</li><li>3 <strong>blocks of convolutional + max pooling</strong> to extract features from the image (with 3x3 sliding windows). As we go deeper into the network and work with increasingly abstract features, the image dimension is reduced (256 -&gt; 128 -&gt; 64 -&gt; 32) while the number of channels is increased (3 -&gt; 16 -&gt; 32 -&gt; 64)</li><li>1<strong> dropout layer </strong>for regularisation (i.e. prevent over-fitting)</li><li>2 <strong>dense layers </strong>to make sense of all these extracted features, and combine the presence or absence of those to decide whether there is a ship on the image or not</li></ul><p>To optimise this model we need:</p><ul><li><strong>loss</strong>: <em>sparse_categorical_crossentropy </em>if using softmax as the last activation, or as there are only two categories <em>binary_crossentropy </em>with <em>sigmoid </em>as the last activation (can also work with raw <em>logit</em>, with a twist, see Part 2)</li><li><strong>optimiser</strong>: one choice is using Adam, and tune (image below) or cycle the learning rate (to get out of local minima, more on this in Part 2). For this first run I ended up choosing a learning rate of 3E-4. The other parameters controlling the exponentially weighted averaged moments of gradient use the default values (first order is called momentum and parameter beta1, second order is called RMS prop and parameter beta2)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*xafJJQ6hzAGH6mTdWu3BJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*s888mLXMwVD4YPsSjxs5Dg.png" /><figcaption>[Left] Illustration of a neural network optimisation problem: the goal here is to find the minimum while being blindfolded. [Right] Exploring the learning rate landscape — we want to pick the learning rates with the largest loss gradient, and stay away from divergence. Method: start at a very low LR, say 1E–7, and at each batch increase the LR slowly, until a high LR, say 1E-2 or even 10. This is a very approximate method, as both weights and data are changing as the learning rate increase. However, this is computationally cheaper than running multiple simulations in parallel, so hopefully a reasonable stop-gap solution to pick a safe learning rate.</figcaption></figure><p>Here is the Tensorflow 2.0 implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c0e09d9a9345400a2d372a1985e0732/href">https://medium.com/media/5c0e09d9a9345400a2d372a1985e0732/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*r_XXjh-BimcPT6-jHYe7cw.png" /><figcaption>Keras’ architecture summary of the network described earlier, following a classic LeNet design (LeCun) of a series of convolutional and max pooling layers, followed by dense layers. Note that most of the weights are in the dense layer, despite limiting the image size to 256 x 256 pixels. More recent architectures have moved away from this design, and are now fully convolutional, avoiding this concentration of weights on a single layer, which, all things being equal, tends to overfit and yield lower performance. See Part 2.</figcaption></figure><p>Here is the basic Tensorflow / Keras code to train the model, with the parameters used.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0a92d5d49e6239a2268ed4e0296ba24/href">https://medium.com/media/a0a92d5d49e6239a2268ed4e0296ba24/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHg1op8zXIxXkyejHuHM_g.png" /><figcaption>X-axis is the number of pseudo-epoch, i.e. 1000 batches of 40 pictures. Given 200k training samples, and data augmentation x 4 (flipping horizontally and vertically), this makes ~ (200k x 4) / (1k x 40) = 20 pseudo-epochs for the model to see all the images, i.e. 1 true epoch is ~ 20 pseudo-epoch.</figcaption></figure><p>By showing this simple neural network our training set about 2.5 times, we reached 94.8% cross-validation accuracy. A naive approach given the class imbalance would be 77.5%.</p><p>Note that the model is still learning, and that we aren’t yet observing signs of overfitting. This is by design, due to the relatively small size of the model compared to the dataset size (200k + 600k augmentation), and the dropout layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYZYNjwdfZVTx6dv3PR9Jw.png" /><figcaption>Sample predictions from this simple ConvDense model.</figcaption></figure><p>Examples of misclassification below. We can see that some cases are hard to resolve to the human eye while there still seems to be a minority of easy wins. Also interesting that a fraction of labels seem wrong: another reason to avoid overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*LZelOHYarrt6tUAD5flOuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*E_-cru3BzRJ9Y6GRW3RNwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*BmZdrF9mnbSgUbvTthz6YA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*mjd1o3a4olpWtdVl2nDycg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*i1-B8WSINgqxj61onlnfWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*aIT4yyKpBrhiKd4Y2GS7Ww.png" /><figcaption>Misclassifications tend to involve small vessels at the edge of the image, as well as potential mislabeling (image on row 1 column 3)?</figcaption></figure><h3>Improving this model</h3><p>A tested improvement to this model is to add batch normalisation between weights and activation: it allows the model to reach 93% accuracy in only 10 pseudo-epochs, compared to 25 pseudo-epochs without. The plateau seems the same, close to 95% (only trained 40 pseudo-epochs).</p><p>Further improvements could involve more capacity for our model as it may underfit slightly currently, as well as exploit higher resolution images.</p><p>An issue with this architecture is that input image size is fixed. That can be solved through</p><ul><li><strong>Global Averaging / Max Pooling layers (GAP / GMP) </strong>at the end, just before a or multiple dense layers, for a global aggregation over the spatial dimensions (batch size, height, width, channels) -&gt; (batch size, 1, 1, channels), irrespective of image size.</li><li><strong>Fully Convolutional Network (FCN)</strong>, using a similar idea but generalising it with a learned spatial operation through a 1x1 depth filter.</li></ul><p>In the second part of this post, we explore the former architecture, along with a deeper network. <a href="https://medium.com/vortechsa/satellite-images-object-detection-part-2-the-beauty-the-beast-f92ff27b696a">Click here to read part 2!</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*TVHjbA9Zj9hVmOm6wcxhug.png" /><figcaption>Visualisation of the model’s attention, and with it emerging localisation properties, while having never labeled ship location! Explanation in part 2 of this post.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ee4acd72809" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/satellite-images-object-detection-part-1-95-accuracy-in-a-few-lines-of-code-8ee4acd72809">Satellite images object detection — part 1: 95% accuracy in a few lines of code</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning a repetitive business task into a self-improving process]]></title>
            <link>https://medium.com/vortechsa/turning-a-repetitive-business-task-into-a-self-improving-process-929c6b9a52dc?source=rss-5bce7397ff69------2</link>
            <guid isPermaLink="false">https://medium.com/p/929c6b9a52dc</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[learning-curve]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Romain Guion]]></dc:creator>
            <pubDate>Fri, 02 Aug 2019 13:02:40 GMT</pubDate>
            <atom:updated>2019-09-09T10:07:18.589Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Simple and practical end-to-end case study of managing the bias vs variance trade-off on a small text data set</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m3fy0bvMcoc882bpjSc43g.jpeg" /><figcaption>Credit: <a href="https://www.fotolibra.com/gallery/collection/90826/world-history-archive/">World History Archive</a></figcaption></figure><p>It comes with little surprise that spam detection at Google or tracking 200,000 vessels at Vortexa involves machine learning and data engineering. Humans cannot process billions of data points, and aren’t as reactive and consistent as computers.</p><p><strong>For many analysts, this can feel quite far from their day to day though</strong>. In many cases creating a new ad hoc Excel spreadsheet or SQL query can yield good results pretty fast. However, companies that are also applying this kind of technology in non-core areas are gaining a competitive advantage, both for scalability and data-driven decision making. Failing that, routine processes will fill up your weeks, and give you little headroom to spot exceptional opportunities.</p><p>In this blog post, we share an example of how a repetitive business task can be transformed into a self-improving process in only a couple of hours. This first prototype is less than 10 lines of code, and achieves 90% accuracy with only a training sample of 1000.</p><p><strong>Who should read this? </strong>This article is for those that already know a few data analytics concepts, and want to learn how to bring those together to solve a concrete business problem.</p><p><strong>After reading this post, you will</strong></p><ul><li>be able to improve and automate your manual text processing tasks</li><li>know in practical terms how to measure and control under/overfitting</li><li>understand how machine learning can yield benefits in your day to day, in only a few hours, without having to beg your engineering or IT teams for resources</li><li>expand your intuition on what machine learning actually looks like, beyond the buzzwords</li></ul><h3>Business context</h3><p>As part of their benchmarking activities, our energy market analysts need to identify what piece of reference data from customs data or national statistics (e.g. JODI or EIA) corresponds to the data produced by Vortexa for its clients. Each data source has its own definition of what the product is, and this blog post will focus on interpreting a description string. Below are examples of product descriptions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*-S7eGFsycgsGNAe-Ku5w-w.png" /><figcaption>This is the type of data we are trying to classify into a Vortexa product category</figcaption></figure><p>From these descriptions, our market analysts match each reference data type to the relevant product in Vortexa’s taxonomy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZMZPQFE063GOD--mfdGCg.png" /><figcaption>DESCRIPTION is our text feature we want to classify (X), and PRODUCT is the classification / supervision made by our market analysts (y)</figcaption></figure><h3>Problem formulation: text classification</h3><p>Our market analysts noticed a repetitive pattern, and asked the R&amp;D team how they could demultiply their efforts with some automated processing.</p><p>As formulated, the problem looks like an instance of <em>classification </em>based on text features, also known as <em>natural language processing</em> (NLP).</p><h3>Reality check: manually generated supervision sets tend to be quite small</h3><p>Although they have tens of thousands of data types to classify for benchmarking, our market analysts had manually labelled only 1400 samples at the time of writing. In contrast, in our data set there are 650 different words — that’s only 2 samples per words on average.</p><p>What’s worse is the words cannot be straightforwardly associated with a result: e.g. in our example #2 above, the description includes “excl. blends of biodiesel”. This means words will have to be interpreted in their context: we cannot simply infer that the presence of the word “biodiesel” means it is biodiesel (quite the opposite!).</p><p>A first simple proxy to capture the context of words is to track neighbouring words — a concept called <em>n-gram</em>.</p><figure><img alt="Example of 1-gram, 2-gram, 3-gram and 4-gram in the context of our data set" src="https://cdn-images-1.medium.com/max/336/0*WOjrb8sMd6PVOvAt" /><figcaption>Example of 1-gram, 2-gram, 3-gram and 4-gram in the context of our data set</figcaption></figure><p>If we consider all combinations of 1, 2, 3 and 4 neighbouring words (1, 2, 3, 4-grams), this leads to 6600 features.</p><p>This is 6 times more parameters than data points. If we are not careful, a model could be built that learns by heart all the examples, but is not able to learn generalisable lessons from them. This means that it will make zero mistakes on the training set, but will not be able to predict new cases effectively. In statistics jargon this is called <em>overfitting </em>or <em>variance</em>. Example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JPBCOVYqNhmGbCUO" /><figcaption>Illustration of overfitting and underfitting, in a simple example with ‘Time’ as a feature X, and ‘Values’ as the variables to predict y. On the left a 1 degree polynomial underfits the data set (too simplistic), which would display poor performance on the training data. In the middle this looks like a balanced model. On the right, the very high degree polynomial overfits the data set, which would show high performance on the training data, but wouldn’t generalise well on the test data (<a href="https://medium.com/greyatom/what-is-underfitting-and-overfitting-in-machine-learning-and-how-to-deal-with-it-6803a989c76">source for the illustration</a>)</figcaption></figure><h3>Choosing a robust &amp; easy to use algorithm for a first prototype</h3><p>State of the art NLP typically uses complex <a href="https://en.wikipedia.org/wiki/Long_short-term_memory">neural networks</a>, and it can be tempting as a data scientist to jump on those tools at any opportunity. The context in which those tools are used typically involves both very large data sets and highly complex inference tasks (e.g. chatbots or some of Vortexa’s core models). However, they tend to have many parameters to tune and can make the overfitting problem worse.</p><p>Instead, we chose another class of algorithm: <a href="https://en.wikipedia.org/wiki/Random_forest">Random Forest classifiers</a>. Why we chose those is beyond the scope of this post. In a word, this class of model works well without much optimisation — it is particularly robust to overfitting.</p><h3>Extracting a tiny bit more information than a bag-of-words</h3><p>Previously we saw that text patterns can be of different kinds (incl. word and n-gram). Those patterns of language, also called <em>tokens</em>, are linked together with grammar, and the absolute and relative sequence of tokens can be quite complex in human language. This section is about the amount of complexity we want to encode to resolve the task at hand and how.</p><p>Simply identifying the presence of a specific patterns / word in the description can actually go a long way — it is often called a Bag-of-Words (BoW) and is basically encoding words as dummy variables (each pattern / word will be represented as a new column that is equal to 1 when the word is present in the row, 0 otherwise).</p><p>A simple method to extract a bit more information from a group of documents is to remove or penalise words used non-specifically in many descriptions (documents), and highlight words that appear only in some specific cases and are perhaps used with insistence in that specific context.</p><p>Scikit-learn implements into a single method a number of strategies that go in that direction: removing stop words (and / then etc), setting bounds to term frequency, and scoring terms by <em>Term Frequency and Inverse Document Frequency</em> (<a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf"><em>TF-IDF</em></a>), and storing them in a memory-efficient ‘sparse’ matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/0*7vnNsnSVuMiDoUbp" /><figcaption>Implementation of Term Frequency Inverse Document Frequency (TF-IDF), in Python with scikit-learn</figcaption></figure><h3>Further step to control overfitting: dimensionality reduction</h3><p>Applying dimensionality reduction algorithms to our product descriptions’ will identify what groups of words best separate our samples. The idea here is to remove groups of words that are redundant or overlapping (collinearity) and identify what combination seems the most complementary. Here is an illustration of the concept of <a href="https://en.wikipedia.org/wiki/Dimensionality_reduction">dimensionality reduction</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I042NuQUKahO6awY" /><figcaption>Illustration of the concept of dimensionality reduction, using the example of an algorithm called PCA — Principal Component Analysis <a href="https://ourcodingclub.github.io/img/PCAexample.png">(illustration source)</a>. This describes a data cloud in a 2D space. PCA will identify in which directions the data gets best split, and will return the data on this new base. The axis are ordered by decreasing discriminatory power: as you can see PCA1 axis separates the data cloud more than PCA2. From there, dimensionality reduction consists in keeping only the top N dimensions. In this example, we could choose to keep only PCA1, and we would have reduced the dimensionality from 2D to 1D.</figcaption></figure><p>Reducing the number of features this way can improve the effectiveness of our classifier downstream for a fixed computational time. If we were to tune the downstream model perfectly, and didn’t care about processing time, chances are this wouldn’t improve the model’s performance, and would even decrease it given the information lost in the dimensionality reduction.</p><p>However, for a quick job I’d argue this can help performance by reducing the risk of overfitting (fewer features) and make the feature choice more optimal (orthogonal features, i.e. that aren’t collinear, are chosen more effectively). Given the high number of features here and the small number of samples, I judged likely that dimensionality reduction would help get good results fast. Training our classifier for longer or selecting features in different ways may lead to better results in the long term though.</p><p>There are a range of dimensionality reduction strategies and algorithms. I semi-arbitrarily chose <em>truncated </em><a href="https://en.wikipedia.org/wiki/Singular_value_decomposition"><em>Singular Value Decomposition (SVD)</em></a><em> </em>to preserve the sparse matrix structure of our pipeline. This is for memory optimization, but the benefits are limited while the data set is small.</p><h3>Let’s try it!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*tJTmVgCjIX0Erzsb" /><figcaption>Python implementation of text processing (TF-IDF vectoriser), dimensionality reduction (SVD) and classification (Random Forest) using a scikit-learn Pipeline object</figcaption></figure><p>Our simple prototype fits in only a few lines of code. We wrap it up in a pipeline so it is easier to tune (see later).</p><p><strong>How should we assess what good is?</strong> The choice of the metric depends on the business problem. Here we want a high fraction of correct results vs incorrect results, because that’s what market analysts will have to correct: this is called <em>accuracy</em>. With this quick prototype we get 90% accuracy — not bad for such a small data set and simple model!</p><p>In your specific case you need to choose your metric carefully — accuracy may not be the best metric for you. In particular, it is important to monitor imbalanced classes (e.g. much more gasoline than naphtha here). To do so, looking at predictions separately within each class is a good idea, and other aggregate metrics will come in handy. For example, we noticed that some classes have bad scores where reviews are few (e.g. naphtha). This means we should not use results for this category yet, until our analysts reviews more of that category. For the simplicity of communication we’ll keep to <em>accuracy</em> henceforth.</p><h3>A word on fine-tuning — hyperparameter optimisation</h3><p>Even after a careful design process, there are still case-dependent optimisations that are hard to anticipate from a theoretical standpoint. One way to further improve an algorithm is pretty basic: try lots of combinations of different parameters — this is called <em>Gridsearch</em>.</p><p>To optimise the parameters of both the preprocessing steps and the classifier step, we wrapped them into a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html">Pipeline object</a>. Below is an illustration of how simple Gridsearch looks like, with a first set of parameters to explore, based on my experience:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDwG8wsLNC-lfavz0mRTZQ.png" /><figcaption>Illustration of how Gridsearch works in Python with scikit-learn</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rtsioqw9LQYPc3xxhX9TPQ.png" /><figcaption>Gridsearch results for param_grid chosen above</figcaption></figure><p>A note of caution: if you use only a <em>train </em>set and a <em>test </em>set, after a large hyperparameter optimisation you may have indirectly fitted the hyperparameters to the specificity of your test set. Instead, you probably want a <em>training </em>set, a <em>cross-validation (CV)</em> set, and a <em>test </em>set. More sophisticated methods allow you optimise training and CV, e.g. k-folds, beyond the scope of this post.</p><h3>What actually had an impact?</h3><p>So far I gave you my perspective on how this problem should be approached. Let’s try our base model with all parameters constants, apart from the number of n-grams and with or without dimensionality reduction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*zmTVkZHfA-fM6Bi9Jur6Pw.png" /><figcaption>Impact of 2 parameters on model accuracy: number of n-gram, and using dimensionality reduction or not (SVD is the dimensionality reduction algorithm we picked here)</figcaption></figure><p>Here SVD seems to have helped the model learn faster (given more trees and therefore more computational time no-SVD may have reached a similar level). Adding more n-grams seems to have only a marginal impact.</p><p>Let’s also take a step back on what we have achieved: by using 6-gram with SVD we can predict 9 times out of 10 the right product. At this stage you may decide that (i) this is good enough, (ii) this can be corrected manually with way less effort and (iii) this needs improving. Case (i) doesn’t need more comments, and for case (ii) you would want to review in priority low probabilities. For the rest of this post we assume you are in situation (iii).</p><h3>Would more data help?</h3><p>A key question an organisation needs answering is whether more of the same data would help improve the results, or if more effort needs to be spent in creating new features, or better data / deeper / more precise.</p><p>The learning curves below show the models having been trained on a fixed-size evaluation set.</p><p><strong>→ The x-axis</strong>: training set size increasing from left to right.</p><p><strong>→ The y-axis</strong> shows accuracy:</p><ul><li><em>The red curve</em> represents the accuracy on the training set: the model is trained and evaluated on the same data. This represents how closely the model manages to fit the data.</li><li><em>The blue curve</em> represents the cross-validation accuracy, i.e. on data the model has never seen yet. This represents how well the model can generalise.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*Pnc5XC41wlkL4bMeV8jDfA.png" /><figcaption><em>Top-left: no SVD, 1-gram ; top-right: with SVD, 1-gram ; bottom-left: no SVD, 6-gram ; bottom-right: with SVD, 6-gram</em></figcaption></figure><h4>Interpreting training performance (red curve)</h4><p>It is expected that the training accuracy will decrease as the dataset size increases, as the number of degrees of freedom of the model remain the same while a broader dataset displays more variability, and therefore is harder to fit.</p><p>More interestingly, on the graph above the training accuracy is pretty low when there is no SVD (on the left side): this could be that the model cannot capture or encode the variability shown in the data. However, with SVD the training accuracy is pretty good with the same underlying features. So probably what is happening is that without SVD, our classifier does not manage to identify what features matter and fails to fit the data! While with SVD we did an unsupervised pre-selection.</p><h4>Interpreting cross-validation performance (blue curve)</h4><p>It is expected that the CV accuracy will increase with more data, as the model learns to distinguish noise (that would be overfitted) from genuine generalisable signal.</p><p>In the case with no SVD (left column), adding more data seems to slow improvements to the model. That’s probably because more data also brings more new words, and so more features. For the classifier as defined, the increase of signal and noise seems to be growing at a similar speed, and the signal to noise ratio only barely improves.</p><p>In contrast, for the model with dimensionality reduction (right column), adding more data clearly helps the model make better predictions.</p><h4>Interpreting the difference between training and CV performance</h4><p>The gap between training and CV performance is an indication of how much gain more data would make.</p><p>If both are really close, more data of the same kind won’t help, and more features, a better model or perhaps deeper / more precise data needs to be explored. Or perhaps we reached the maximum information that can be extracted from the data, and perhaps the remaining error is true noise that nobody or no algorithm could reduce — e.g. there could be mistakes in the data being analysed.</p><p>If the gap between training and validation is large, the model is managing to fit the data, but doesn’t generalise well. Often the difference reduces with more data, as is the case here, and this is an indication that more data is needed to improve the model performance, and reduce the overfit.</p><h3>Conclusion</h3><p>With this benchmarking example, half a day of work allowed the team at Vortexa to reduce the workload on market analysts by 90%.</p><p>Through this article you have learned how to approach a practical machine learning problem, and how to measure its performance and interpret how to improve it.</p><p>In this journey we used a few specific tools:</p><ul><li>N-grams and TF-IDF to extract simple information from text,</li><li>SVD for dimensionality reduction,</li><li>Random Forest as a classifier,</li><li>Gridsearch and pipelines to tune our model,</li><li>Learning curves to understand whether to improve the model or get more data</li></ul><p>For Vortexa, the next step here is to increase the supervised set through labelling more of our raw data. This will be prioritised to focus where the business needs higher performance, and where the classifier makes the most meaningful mistakes. In parallel, we have also improved our results with other features, outside the scope of this post.</p><p>If that solution proves valuable, it may need to be wrapped into a bit more engineering to be automated, and deployed in a scalable way throughout the organisation. This is the topic of an upcoming blog post. However, this should by no means prevent you from improving and automating your work and that of your close colleagues:both for proof of concept and immediate impact.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=929c6b9a52dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vortechsa/turning-a-repetitive-business-task-into-a-self-improving-process-929c6b9a52dc">Turning a repetitive business task into a self-improving process</a> was originally published in <a href="https://medium.com/vortechsa">VorTECHsa</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>