<?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 Chen Yanhui on Medium]]></title>
        <description><![CDATA[Stories by Chen Yanhui on Medium]]></description>
        <link>https://medium.com/@sgmle?source=rss-a77da8047f57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*m7xZRQPnGjP0A3YE.</url>
            <title>Stories by Chen Yanhui on Medium</title>
            <link>https://medium.com/@sgmle?source=rss-a77da8047f57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:51:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sgmle/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[A Battle Against Amnesia: A Brief History and Introduction of Recurrent Neural Networks]]></title>
            <link>https://medium.com/data-science/a-battle-against-amnesia-a-brief-history-and-introduction-of-recurrent-neural-networks-50496aae6740?source=rss-a77da8047f57------2</link>
            <guid isPermaLink="false">https://medium.com/p/50496aae6740</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Chen Yanhui]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 12:08:53 GMT</pubDate>
            <atom:updated>2021-03-08T15:06:00.761Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Life can only be understood looking backward. It must be lived forward.</blockquote><blockquote>— The Curious Case of Benjamin Button</blockquote><p>This is my second article (<a href="https://towardsdatascience.com/from-alexnet-to-nasnet-a-brief-history-and-introduction-of-convolutional-neural-networks-cf63bf3320e1">first on Convolution Neural Network</a>) of the series on Deep Learning and Reinforcement Learning.</p><p>There are many sequential modelling problems in day-to-day life: machine translation, voice recognition, text classification, DNA sequencing analysis, etc. Most of these problems belong to supervised learning. Either the input or output of the models is sequential with variable size. Normal neural networks have difficulties dealing with input and output of varied sizes.</p><p>In the following sections, I am going to explain why Recurrent Neural Network or RNN works for sequential modelling problems. Then I will talk about the representative architectures of <strong>Vanilla RNN, Long Short Term Memory (LSTM)</strong>, as well as <strong>Encoder-Decoder with Attention</strong> that has been famously applied in machine translation and many other use cases. And finally I will demonstrate LSTM with a simple implementation in Pytorch.</p><h3>1 Why RNN</h3><h4>1.1 The History</h4><p>The concept of RNN was brought up in <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">1986</a>. And the famous LSTM architecture was invented in <a href="https://en.wikipedia.org/wiki/Long_short-term_memory">1997</a>. The number of well-known architectures of RNN is much less than that from CNN. As the famous saying “<strong><em>A picture is worth a thousand words</em></strong>” implies, images have much more information and space to maneuver, so it is no surprise that the evolution history of RNN is not as colorful. I have tried to categorize the history into 3 phases, which are <strong>Overloaded Single Memory </strong>for Vanilla RNN,<strong> Multiple Gate Memories </strong>for LSTM and <strong>Pay Attention </strong>for Encoder-Decoder architecture with RNN respectively.</p><p>As I walk you through, you will realize that the main theme of the evolution of RNN is to <strong>battle Amnesia</strong>. In other words, each generation of RNN was trying to <strong>remember as much important information as possible from the past</strong>, so that the future can be more accurately forecasted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*QSlp4VzdD-DZEn5K3rZuOA.png" /><figcaption>Evolution of RNN</figcaption></figure><h4>1.2 Why RNN Works for Variable Inputs/Outputs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RsRIEyJyfgvisdW363CbDw.jpeg" /><figcaption>Image Source: <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">Andrej Karpathy</a></figcaption></figure><p><strong>It is difficult for normal neural networks to deal with input and output of varied sizes.</strong> Below are some of the use cases that they are unable to handle. Note that <strong>Many </strong>is not a fixed number for each input or output to the models.</p><ul><li><strong>One to Many: </strong>image captioning, text generation</li><li><strong>Many to One: </strong>sentiment analysis, text classification</li><li><strong>Many to Many: </strong>machine translation, voice recognition</li></ul><p>RNN is able to handle these use cases by having a<strong> recursive processing unit</strong> (single or multiple layers of cells) with a <strong>hidden state derived from the past</strong>.</p><p>The recursive nature of the architecture is both a blessing and a curse. The blessing is that it can handle <strong>inputs/outputs of varied size.</strong> But it comes at the cost of, in addition to the <strong>difficulties of remembering the past</strong>, the problem of <strong>vanishing/exploding gradients</strong>. Anyone who has some programming experience will recall vividly how easy it is for recursive programs to get <a href="https://en.wikipedia.org/wiki/Stack_Overflow">Stack Overflow</a> or <a href="https://en.wikipedia.org/wiki/Out_of_memory">OutOfMemory </a>exceptions.</p><h3>2 The RNNs</h3><h4>2.1 Vanilla RNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0JSn8gH7bCKLA7WI-pUqw.png" /><figcaption>Basic RNN Architecture. From <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">Wikipedia</a></figcaption></figure><p>Above is the basic RNN architecture with self-looping or recursive pointer to itself. <strong>x, o </strong>and <strong>h </strong>are the input, output and hidden state, with <strong>U, W </strong>and <strong>V</strong> are the parameters applied on them respectively. Inside the green color RNN cell, there could be one or more layers of normal neurons or other types of RNN cells.</p><p><strong>The recursive pointing structure is the the central concept of RNN.</strong> It means a few things:</p><ul><li>the size of inputs and outputs is varied</li><li>there is a <strong>hidden state to represent past knowledge</strong>, which is also served as an input to the next step. The hidden state from the<strong> </strong>previous<strong> </strong>step, together with the input of the current step, is used to derive the current hidden state. It is then used to derive the output of the current step.</li><li>Every step of RNN shares the same activation function and the same sets of parameters. In the above example, U<strong>, V </strong>and <strong>W are shared among all the RNN cells, no matter how big the RNN network grows.</strong></li><li><strong>hidden state becomes the key component of RNN</strong>, because it not only bridges input and output, but more importantly past and present.</li></ul><p>By now you should have noticed that the bottleneck of RNN is the shared parameters among all the RNN cells, especially for the hidden state parameters V when the network grows too big. A brain with a single set of memory is <strong>easily overloaded</strong> and cannot remember the past with some distance.</p><p>Vanilla RNN cells with multi layers could improve the performance to some degree, but logically doesn’t make much difference, because it is still consider one processing unit for one dimension of data. But there are many dimensions of information to process.</p><h4><strong>2.2 Simple Example of How RNN Works</strong></h4><p>I will explain with an example of simplified <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">Character-Level Language Model to predict the next character of the word “hello”</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*z9EcsU96fNQD88zVulBG6w.png" /><figcaption>Simplified Character-Level Language Model. Image Source: <a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">Andrej Karpathy</a></figcaption></figure><ul><li>Step 1: Character Embedding. The dictionary is [h, e, l, o]. “h” becomes [1, 0, 0, 0], “e” becomes [0, 1, 0, 0], “l” becomes [0, 0, 1, 0] and “o” becomes [0, 0, 0, 1]</li><li>Step 2: Calculate Errors. Randomly instantiate the network and input the character “h”, “e”, “l”, “l”, “o” to the network sequentially. At the 1st time step for the input “h”, we get output “o” (because 4.1 is the biggest confidence score and it is at 4th position) instead the expected “e” (green color). And vice versa for the other time steps. We want to increase the confidence scores of Green Colors’ positions and decrease the other values.</li><li>Step 3: Back-Propagation. Aggregate the errors and do Back-Propagation to update the parameters of <strong>W(hh), W(xh) </strong>and <strong>W(hy) </strong>respectively.</li><li>Step 4: Repeat step 2 and 3 until the network predicts the correct sequence of characters with high confidences.</li></ul><h4>2.3 LSTM</h4><p><a href="https://en.wikipedia.org/wiki/Long_short-term_memory">LSTM </a>is the most popular RNN architecture, even after more than 20 years of its birth. But why LSTM? The biggest reason is that Vanilla RNN cannot remember the past very well. The only few set of parameters in Vanilla RNN has to process and remember too much information and it is easily overloaded.</p><p>For sequential information like conversations and texts, there are a few dimensions to process like what to emphasize, what to output and what to forget. LSTM introduces three types of selected memories (gates) which are <strong>Input, Output </strong>and <strong>Forget Gates</strong> respectively, as well as <strong>Sigmoid </strong>function to represent the percentage of information for processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*cU0pLdq-KvhebSNYiF-hYw.png" /><figcaption>LSTM Overview. Image Source: <a href="https://www.researchgate.net/figure/The-structure-of-the-Long-Short-Term-Memory-LSTM-neural-network-Reproduced-from-Yan_fig8_334268507">ResearchGate</a></figcaption></figure><ul><li><strong>Input Gate: what to remember</strong>. ie. words like “a”, “the” that are not useful will not be in the input.</li><li><strong>Output Gate: what to output.</strong> ie. some information will be stored in the hidden state but not in the output.</li><li><strong>Forget Gate: what to forget.</strong> ie. context has changed. Some of the previous information will be forgotten</li><li><strong>Sigmoid Function: percentage of information.</strong> The value of sigmoid function is between 0 to 1, which is perfectly suitable to represent the percentage of information to input, output and forget.</li></ul><p>Having three logical units of memories to process different dimensions greatly improves the capability of LSTM to remember both the long and short term information. I will illustrate LSTM in more details with a concrete coding example in the latter section.</p><h4>2.4 Encoder and Decoder with Attention</h4><p><strong>2.4.1 Encoder-Decoder</strong></p><p>Strictly speaking Encoder-Decoder is a generic architecture that does not belong to RNN. It is widely applied in <a href="https://en.wikipedia.org/wiki/Seq2seq">Sequence to Sequence</a> deep-learning use cases. <a href="https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)">Transformer </a>is another Encoder-Decoder architecture that is not based on RNN. The state-of-the-art pretrained NLP models <a href="https://en.wikipedia.org/wiki/GPT-2">GPT-2</a> and <a href="https://en.wikipedia.org/wiki/GPT-3">GPT-3</a> from OpenAI are based on the Transformer architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*NlACkT12MtRVGwyPBt4HAg.png" /><figcaption>Encoder-Decoder Architecture. Image Source: <a href="https://www.quora.com/What-is-an-Encoder-Decoder-in-Deep-Learning">Quora</a></figcaption></figure><p>Encoder-Decoder is trying to imitate the cognition process of human brain. For example, when we see something and we “encode” it as some format (Encoder Vector) into our “neural network” (brain). When we want to describe what we have seen, we bring out the Encoder Vector from our brain and “decode” it into our own language through our mouth.</p><p>The Vector that comes out at the end of the Encoder has another name called <a href="https://towardsdatascience.com/understanding-latent-space-in-machine-learning-de5a7c687d8d">Latent Space</a>. <strong>Latent Space a very important and useful concept in machine learning. It means that for information of any types (ie. voice, text, image or video), as long as they could be represented in the same Latent Space, they could communicate and understand one another, </strong>such as image-to-text (image captioning) and voice-to-text (voice recognition).</p><p><strong>2.4.2 Attention</strong></p><p>What is the problem with vanilla Encoder Decoder? The fixed-length Vector from the end of Encoder is the only medium of exchange between Encoder and Decoder. Decoder is exposed to the Encoder outcome only after the last step of Encoder. The Encoder Vector has become an information bottleneck. The further step away, the more difficult it is for the information to be kept in the Encoder Vector.</p><p>Does it sound familiar to the problem of Vanilla RNN? Yes. The same solution with more memories applies. Instead of one fixed-length Encoded Vector, <strong>we have one vector for each target word</strong>, which is called Attention Vector. Attention Vector, together with hidden state and input, is then used to predict the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*hvJVFz66WTRZCBdqJcMOBQ.png" /><figcaption>Encoder-Decoder with Attention. Image Source: <a href="https://www.researchgate.net/figure/RNN-Encoder-Decoder-Network-with-Attention-layer-Encoder-is-a-bidirectional-LSTM-whose_fig2_326570264">ResearchGate</a></figcaption></figure><p>Intuitively each Attention Vector allows each target word to focus on just a few words from the input. Below is the heatmap of the Attention Matrix of <a href="https://www.tensorflow.org/tutorials/text/nmt_with_attention">one machine translation example</a>. You can see that each target word focuses more of its attention on just a few input words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*PsvKVf0jzziNmTyz7lPBMA.png" /><figcaption>Attention Heatmap from <a href="https://www.tensorflow.org/tutorials/text/nmt_with_attention">Google Tensorflow Machine Translation Example</a></figcaption></figure><h4>2.5 RNN Tuning Techniques</h4><p>Most of the Neural Networks tuning techniques could be used to improve the performance of RNN as well, such as <strong>Dropout, Batch Normalization, Residual Learning, Activation Function, </strong>etc. You have to try various techniques based on your use cases to achieve the best performance.<strong> </strong>Neural network tuning is an art rather than science a lot of the time.</p><h3>3 The Example: Implementation of LSTM in Pytorch</h3><h4>3.1 The Use Case</h4><p>I have used the <a href="https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html">AG News Dataset from torchtext for text classification</a>. The inputs are news texts, which are classified into the labels of 10 categories.</p><p>Pytorch’s <a href="https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html">Embedding</a> is used to encode the inputs. In order for efficient batch processing, the length of each input is capped at 50. The words beyond will be truncated, while the shortage will be filled “DUMMY” words. Please refer to <a href="https://github.com/ahhuisg/deep-learning-practice/blob/main/notebooks/lstm-pytorch.ipynb"><strong>this notebook</strong></a> for reference.</p><h4>3.2 The LSTM Implementation</h4><p>Please also refer the implementation to <strong>the architecture image in the above LSTM section</strong>.</p><h4><strong>3.2.1 Forget Gate</strong></h4><pre><em># Forget Gate Calculation</em><br>forget_gate = torch.sigmoid(torch.matmul(embedded_input, self.f_x) + torch.matmul(h, self.f_h) + self.f_b)</pre><p><strong>3.2.2 Output Gate</strong></p><pre># Output Gate Calculation<br>output_gate = torch.sigmoid(torch.matmul(embedded_input, self.o_x) + torch.matmul(h, self.o_h) + self.o_b)</pre><p><strong>3.2.3 Input Gate</strong></p><pre># Input Gate Calculation<br>input_gate = torch.sigmoid(torch.matmul(embedded_input, self.i_x) + torch.matmul(h, self.i_h) + self.i_b) </pre><p><strong>3.2.4 New State &amp; Output</strong></p><pre># mid state for new state calculation<br>input2_state = torch.tanh(torch.matmul(embedded_input, self.i2_x) + torch.matmul(h, self.i2_h) + self.i2_b)</pre><pre># New State after the LSTM Cell<br>state = input2_state * input_gate + state * forget_gate</pre><pre># New Output from the LSTM Cell<br>h = output_gate * torch.tanh(state)</pre><p><strong>3.2.5 Test Result</strong></p><p>I have trained and tested the model for only 10 epochs. The accuracy went up from 0.29 to 0.78.</p><pre>Done Training with Epoch 9 - Loss: 0.30023258924484253. Test Accuracy: 0.7806578947368421</pre><h3>4 Conclusion</h3><p>In this article, I have briefly talked about a few RNN architectures and I have also illustrated LSTM with a simple implementation in Pytorch. RNN is uniquely capable to handle sequential modelling problems and the evolution of RNN are all about <strong>remembering as much important information as possible from the past</strong>, so that the future can be more accurately forecasted.</p><p>“<a href="https://www.goodreads.com/quotes/117526-no-man-ever-steps-in-the-same-river-twice-for"><strong><em>No man ever steps in the same river twice</em></strong></a>”. Many real-life use cases are sequentially dependent. I am quite confident that other than LSTM, newer and better types of RNN will come up and RNN will continue to play a key part in the AI industry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50496aae6740" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-battle-against-amnesia-a-brief-history-and-introduction-of-recurrent-neural-networks-50496aae6740">A Battle Against Amnesia: A Brief History and Introduction of Recurrent Neural Networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From AlexNet to NASNet: A Brief History and Introduction of Convolutional Neural Networks]]></title>
            <link>https://medium.com/data-science/from-alexnet-to-nasnet-a-brief-history-and-introduction-of-convolutional-neural-networks-cf63bf3320e1?source=rss-a77da8047f57------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf63bf3320e1</guid>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Chen Yanhui]]></dc:creator>
            <pubDate>Fri, 26 Feb 2021 11:39:52 GMT</pubDate>
            <atom:updated>2021-02-26T13:46:42.707Z</atom:updated>
            <content:encoded><![CDATA[<h4>With a Simple Implementation of ResNet in Keras</h4><blockquote>Learn from yesterday, live for today.</blockquote><blockquote>— Albert Einstein</blockquote><p>Historically Machine Learning on images had been a big challenge until 2012, when <a href="https://en.wikipedia.org/wiki/AlexNet">AlexNet </a>won the first prize of the ImageNet competition and got the attention of the general public. Ever since then, Convolution Neural Network or CNN has evolved so fast that AlexNet has soon become a thing of the past. CNN has surpassed human performance significantly in terms of image processing.</p><p>However, the concept of CNN was already brought out and put into practice <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network#Receptive_fields_in_the_visual_cortex">more than 30 years ago</a>. The main reason why CNN or deep-learning has become so effective and popular is due to the abundance and democratization of both data and computation power in the past decade.</p><p>In the following sections, I will firstly talk about why CNN works on images. Then I will briefly introduce to you various CNN types, along the evolution axis of both time and architecture. I will also talk about the representative architectures of AlexNet, VGGNet, InceptionNet, MobileNet, ResNet and NASNet. And finally I will demonstrate with a simple implementation of ResNet that I have come up with in Keras.</p><h3>1. Why CNN on Images</h3><h4><strong>1.1 The Problem of Normal Neural Networks on Images</strong></h4><p>Each image has thousands of pixels, each of which is considered a feature, which means that for an 1000 * 1000 image, there are 1,000,000 features. And for normal feed-forward neural networks, each layer is full-connected with the previous input layer.</p><p>Let’s say for example we use a normal feed-forward neural network of one single-layer with 1 million neurons to process the image, the number of parameters required is 1000 * 1000 * 10⁶ = 10¹². There are simply <strong>too many parameters</strong> required for normal neural network for image learning.</p><p>But what is the problem with too many parameters in the network? Firstly it is very easy to get overfitted and it needs large amount of data for proper training. Secondly it requires much more memory and computation for training and prediction.</p><h4><strong>1.2 Why CNN Works</strong></h4><p>Let’s get back to the major characteristics of images. There are 2 main characteristics of images that make CNN works on images, which are <strong>feature localization </strong>and <strong>feature independence of location </strong>respectively.</p><p><strong>Feature Localization:</strong> Each pixel or feature is closely correlated to the other pixels around it. For example, the neighboring pixels of a pixel on the nose is mostly probably also the pixels of the nose.</p><p><strong>Feature Independence of Location: </strong>Each feature is the same regardless of where it is in the image. For example, a nose is still a nose regardless of its location on the image.</p><p>CNN solves the too-many-parameters problem with <strong>Shared Parameters</strong> (<strong>Feature Independence of Location</strong>) of <strong>Locally Connected Networks</strong> (<strong>Feature Localization</strong>), which is also called Convolution Net. In the preceding example, the number of parameters can be reduced from 10¹² to 10³ parameters using Convolution Net.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*0PljyKt6DNGspGqK8ZUPyQ.png" /><figcaption><a href="https://arxiv.org/pdf/1706.09077.pdf">CNN Seen from Neural Network Perspective</a></figcaption></figure><h4><strong>1.3 Main Components of CNN</strong></h4><p>There are 3 main components of CNN, which are the <strong>Convolution</strong>, <strong>Pooling </strong>and <strong>Fully-Connected Layer</strong> respectively.</p><p>The Convolution Layer consist of <strong>Filters </strong>and <strong>Stride</strong>. <strong>The Filters are the locally connected networks, each of which learns some particular features of the images</strong>. Each Filter moves around the images with configured step size called Stride. For example, for a Filter of size 10 * 10 with Stride 1, each time the filter window will overlay an image with an area of 10 * 10 pixels to calculate the inner product between the pixel values and the parameters. And it will move horizontally and vertically by 1 pixel (Stride) on an image, until it covers the whole image.</p><p>There are typically <a href="https://machinelearningmastery.com/pooling-layers-for-convolutional-neural-networks/">2 type of Pooling Layers</a>, which are Max-Pooling and Average-Pooling Layers respectively. Max-Pooling Layer picks the maximum value from each window and Average-Pooling Layer calculate the average value from each window.<strong> </strong>The intuition of the Pooling layer is to increase the resilience of the Filters. It also reduces the number of parameters even further and imposes some degree of regularization to reduce overfitting.</p><p>The Fully-Connected Layer flattens out the last convolution layer and fully connect the neurons to the output layer. You could have more than one fully-connected layers. However, the number of the parameters of the fully-connected layers is much more than that from Convolution layers. In a typical CNN, the number of the parameters from the fully-connected layer is 60% to 80% of the total network.</p><h3>2. The CNNs</h3><p>Ever since AlexNet caught the eyes of the public, the evolution of the CNN has gone through 3 phases, the theme of which are what I call <strong>Deeper is Better</strong>, <strong>Architecture Engineering</strong> and <strong>AutoML </strong>respectively. Each of the phases have its representative network architectures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*BXrjezB7xbEFB3LsFz-06g.jpeg" /><figcaption>Evolution of CNN</figcaption></figure><h4>2.1 Deeper is Better</h4><p><strong>2.1.1 AlexNet</strong></p><p>In 2012, AlexNet competed in the ImageNet competition and <a href="https://en.wikipedia.org/wiki/AlexNet">achieved an error rate of 15.3% beating the 2nd place by 10.8%</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*AP79GF9TocvqnnrS9aYntw.png" /><figcaption>AlexNet’s architecture. From the <a href="https://kr.nvidia.com/content/tesla/pdf/machine-learning/imagenet-classification-with-deep-convolutional-nn.pdf">AlexNet Paper</a></figcaption></figure><p>AlexNet consists of 5 convolution layers, 3 max-pooling layers and 2 fully-connected layers. The structure of the AlextNet was split with 2 GPUs, partly because at that time the GPU memory was not big enough.</p><p><em>Activation Function</em></p><p>AlexNet was the first CNN to use <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)"><strong>ReLU </strong></a>as activation function, instead of <a href="https://en.wikipedia.org/wiki/Sigmoid_function"><strong>Sigmoid</strong></a><strong> </strong>function. The introduction of ReLU as activation function greatly improved the training speed of deep-learning networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*fw5CZWxzgpTzDmpS0zfMjg.png" /><figcaption>ReLU vs Sigmoid (dotted line). From the <a href="https://kr.nvidia.com/content/tesla/pdf/machine-learning/imagenet-classification-with-deep-convolutional-nn.pdf">AlexNet Paper</a></figcaption></figure><p><em>Dropout</em></p><p>AlexNet also used <a href="https://medium.com/@amarbudhiraja/https-medium-com-amarbudhiraja-learning-less-to-learn-better-dropout-in-deep-machine-learning-74334da4bfc5"><strong>Dropout </strong></a>in the fully-connected layers. AlexNet ’s Dropout nullifies 50% of the neurons for each training epoch. Intuitively there are 2 benefits that Dropout brings. Firstly it causes each neuron to be more independent. Secondly it is like training a sub-network each time and the final result is the ensembling of the sub-networks, which is better than a single big network.</p><p>The reason why AlexNet applied Dropout on the fully-connected layers is that, as mentioned previously, the number of parameters from the fully-connected layers is much more than that from the convolution layers. Applying Dropout on the fully-connected layers brought some regularization effect and reduced overfitting.</p><p><em>Data Augmentation</em></p><p>AlexNet input images are of size 224 x 224, which are randomly sampled from ImageNet’s 256 x 256 images. By doing such sampling in the competition, AlexNet increased their training data size by <a href="https://kr.nvidia.com/content/tesla/pdf/machine-learning/imagenet-classification-with-deep-convolutional-nn.pdf">2048 times.</a></p><p><strong>2.1.2 VGGNet</strong></p><p>VGGNet also came to fame in the ImageNet competition in 2014. It has much more convolution layers than AlexNet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*HzxRI1qHXjiVXla-_NiMBA.png" /><figcaption><a href="https://neurohive.io/en/popular-networks/vgg16/">VGG16 Architecture</a></figcaption></figure><p>In addition to a deeper architecture, some of the <a href="https://arxiv.org/pdf/1409.1556.pdf">noticeable new concepts</a> from VGGNet are: heavily used 3 x 3 filters for convolution layers (replacing 5 x 5 or 7 x 7 filters to have wider scanning areas and reduce numbers of parameters), 1 x 1 filters for nonlinear transformations, doubling number of channels after each pooling layer to recover lost information from the pooling layers.</p><h4>2.2 Architecture Engineering</h4><p><strong>2.2.1 ResNet</strong></p><p>When the number of network layers of CNN increased to a certain number, the performance of the CNN decreased instead. The reason is that deeper networks are much harder to optimize <a href="https://arxiv.org/pdf/1512.03385.pdf">due to the notorious problem of vanishing/exploding gradients</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*fMkrYeOhVkz0Z8PEEIHmwA.jpeg" /><figcaption>CNN performance decreases with more layers. From the <a href="https://arxiv.org/pdf/1512.03385.pdf">ResNet Paper</a></figcaption></figure><p>Is there a way to increase the number of convolution layers while avoiding the gradient exploding/vanishing problem? In 2015, ResNet was invented to solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*CFqMNz0W-jtHrAqOrvQWjw.png" /><figcaption><a href="https://arxiv.org/pdf/1512.03385.pdf">Residual Learning</a></figcaption></figure><p>ResNet introduced a concept called <a href="https://arxiv.org/pdf/1512.03385.pdf">Residual Learning</a>. Intuitively the output of the each residual convolution layer is at least as good as the input. ie. F(x) + x ≥ x. This architecture was proven to address the gradient problem nicely. The biggest number of the convolution layers of ResNet could be more than 1000.</p><p><strong>2.2.2 InceptionNet</strong></p><p>Before <a href="https://arxiv.org/pdf/1409.4842v1.pdf">InceptionNet</a>, most of the approaches to improve CNN was by adding more convolution layers. Benefit from the superior engineering strength from Google, <a href="https://arxiv.org/pdf/1409.4842v1.pdf">InceptionNet </a>twisted the structure of the convolution layers by using filters of various sizes in the convolution layers.</p><p>It is very difficult to have one best filter size for all images because the same object might have very different sizes in different images. The main idea of InceptionNet is to have filters of different sizes for the same object. Intuitively the network becomes “Wider” instead of “Deeper”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a51TucCF-9AvWa5a1Qvy_g.png" /><figcaption>InceptionNet Architecture. From the <a href="https://arxiv.org/pdf/1409.4842v1.pdf">InceptionNet Paper</a></figcaption></figure><p>InceptionNet has gone through from <a href="https://towardsdatascience.com/a-simple-guide-to-the-versions-of-the-inception-network-7fc52b863202">v1 to v4</a>. In addition to v1, its v2 to v4 versions reduced the computation complexity and increased the performance with <a href="https://towardsdatascience.com/a-simple-guide-to-the-versions-of-the-inception-network-7fc52b863202">various clever techniques</a>. And it has also combined with ResNet to create <a href="https://towardsdatascience.com/a-simple-guide-to-the-versions-of-the-inception-network-7fc52b863202">InceptionResNet</a> to make the network <strong>both “Wider” and “Deeper”</strong>.</p><p><strong>2.2.3 MobileNet</strong></p><p><a href="https://arxiv.org/pdf/1704.04861.pdf">MobileNet </a>was another CNN architecture by Google of trying to adapt InceptonNet to mobile devices. The purpose was to reduce the number of parameters and computations, while at the same time preserving the performance as much as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*kA48bqKVINi2OaGOJCL5JQ.png" /><figcaption>Depthwise Separable Convolution in MobileNet. From the <a href="https://arxiv.org/pdf/1704.04861.pdf">MobileNet Paper</a></figcaption></figure><p>MobileNet introduced a filter architecture called Depthwise Separable Convolution, of which the main idea is to have different filters for different input channels. MobileNet significantly reduced the numbers of the parameters and as a result <a href="https://towardsdatascience.com/review-mobilenetv1-depthwise-separable-convolution-light-weight-model-a382df364b69">the computation required is typically just 1/9 of the original network, with small reduction in accuracy</a>.</p><h4>2.3 AutoML</h4><p><strong>2.3.1 NASNet</strong></p><p>Equipped with abundance of computing power and engineering genius, Google introduced <a href="https://arxiv.org/pdf/1707.07012.pdf">NASNet</a>, which framed the problem of finding the best CNN architecture as a <a href="https://en.wikipedia.org/wiki/Reinforcement_learning">Reinforcement Learning</a> problem.</p><p>Basically the idea was to search the best combination of parameters of the given <strong>search space of filter sizes</strong>, <strong>output channels</strong>, <strong>strides</strong>, <strong>number of layers</strong>, etc. In this Reinforcement Learning setting, the reward after each search action was the accuracy for the searched architecture on the given dataset.</p><p><a href="https://sh-tsang.medium.com/review-nasnet-neural-architecture-search-network-image-classification-23139ea0425d">NASNet achieved state-of-the-art result</a> in the ImageNet competition. However, the computation power required for NASNet was so big that only a handful of companies were able to make use of the same methodology.</p><h3>The Example: ResNet Implementation in Keras</h3><p>I have implemented ResNet 34 in Keras from scratch and used it to train and test it in <a href="https://www.cs.toronto.edu/~kriz/cifar.html">CIFAR10 dataset</a>. Please refer to the <a href="https://github.com/ahhuisg/deep-learning-practice/blob/main/notebooks/resnet-keras.ipynb">notebook for reference</a>.</p><p>Despite there are similar implementation out there, I still go ahead to implemented it manually because I’d like to get some coding practices on it. And I also wanted to show and explain to you the inner working of ResNet.</p><h4><strong>The Residual Block</strong></h4><p>At the heart of the ResNet is the residual block. There are 2 types of basic residual blocks in ResNet, one with the number of output channels remained the same, the other’s number of output channel doubled.</p><p>For the case of number of channels remained the same, the input image will go through 2 Conv2D layers with the size intact, then the output (residual) will be added to the original input image as the final result from the block.</p><p>For the case of number of channels doubled, the input image will go through Conv2D with output image width and length halved. And in order to do the residual learning, the original input image’s width and length needs to be halved with its number of the channels doubled through padding. The intuition is that the doubling of the channels and halving the image size at the same time enables the residual blocks to capture the features with more granularities.</p><pre>def _residual_block(self, x, num_output_channel):<br>    num_input_channel = K.int_shape(x)[-1]</pre><pre>    if num_output_channel == num_input_channel * 2:<br>        # number of output channel doubled. 3 things will happen:<br>        # 1. The output image&#39; width and length will be halved<br>        # 2. The input image will go through a pooling layer with its width and length will be halved too<br>        # 3. pad the number of channels of the input images for residual learning<br>        output_channels_doubled = True<br>        strides = (2, 2)<br>    elif num_input_channel == num_output_channel:<br>        # number of output channel remain the same<br>        # go through 2 convolution layers without changing image&#39; size<br>        output_channels_doubled = False<br>        strides = (1, 1)<br><br>        <br>    conv1 = Conv2D(num_output_channel, <br>                       kernel_size=(3, 3), <br>                       strides=strides, <br>                       padding=&#39;same&#39;, <br>                       activation=&#39;relu&#39;)(x)</pre><pre>    conv2 = Conv2D(num_output_channel, <br>                       kernel_size=(3, 3), <br>                       strides=(1, 1), <br>                       padding=&#39;same&#39;, <br>                       activation=&#39;relu&#39;)(conv1)</pre><pre>    if output_channels_doubled:<br>        pooled_x = AveragePooling2D(pool_size=(2, 2),<br>                                        strides=(2, 2),<br>                                        padding = &#39;same&#39;)(x)</pre><pre>        padded_x = tf.pad(pooled_x,<br>                              [[0,0],<br>                               [0,0],<br>                               [0,0],<br>                               [num_input_channel // 2, num_input_channel // 2]])</pre><pre>    else:<br>        padded_x = x</pre><pre>    #residual learning<br>    output_x = conv2 + padded_x</pre><pre>    return output_x</pre><h4>The ResNet Configuration</h4><p>ResNet 34 has 4 layers of residual blocks, each of which has 3, 4, 6 and 3 residual blocks respectively. The number of output channels (num_filters) doubled for each layer, but within the layer each residual block has the same number.</p><pre>num_residual_blocks_arr=[3, 4, 6, 3],</pre><pre>for num_residual_blocks in num_residual_blocks_arr:<br>    num_filters = num_filters * 2<br>    for _ in range(num_residual_blocks):    <br>        conv = self._residual_block(last_layer, num_filters)<br>        last_layer = conv</pre><p>At the end of the network, the last block was flattened and connect to a fully-connected layer for label outputs.</p><h4>The Result on CIFAR10</h4><p>I have trained the ResNet on the CIFAR10 dataset with 5 epochs in my laptop. The accuracy is around 75% on the test set.</p><pre>Epoch 1/5<br>391/391 [==============================] - 2343s 6s/step - loss: 2.0021 - accuracy: 0.2924 - val_loss: 1.3157 - val_accuracy: 0.5139<br>Epoch 2/5<br>391/391 [==============================] - 2123s 5s/step - loss: 1.2212 - accuracy: 0.5572 - val_loss: 1.0442 - val_accuracy: 0.6267<br>Epoch 3/5<br>391/391 [==============================] - 2220s 6s/step - loss: 0.9501 - accuracy: 0.6587 - val_loss: 0.9108 - val_accuracy: 0.6772<br>Epoch 4/5<br>391/391 [==============================] - 2196s 6s/step - loss: 0.7628 - accuracy: 0.7299 - val_loss: 0.8016 - val_accuracy: 0.7155<br>Epoch 5/5<br>391/391 [==============================] - 2109s 5s/step - loss: 0.6145 - accuracy: 0.7821 - val_loss: 0.7327 - val_accuracy: 0.7482</pre><h3>Conclusion</h3><p>In this article, I have briefly talked about various CNN types, along the evolution axis of both time and architecture. And I have also demonstrated with a simple implementation of ResNet that I have come up with in Keras.</p><p>CNN is the cornerstone for many AI technologies today such as self-driving car and all the other image or visual related industrial AI applications. The history of CNN is a history of combating overfitting with machine learning and engineering ingenuities. And although AutoML types of CNN are still at an early stage, it will play a more and more important role in the evolution of CNN.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf63bf3320e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-alexnet-to-nasnet-a-brief-history-and-introduction-of-convolutional-neural-networks-cf63bf3320e1">From AlexNet to NASNet: A Brief History and Introduction of Convolutional Neural Networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microkernel Architecture for Machine Learning Library]]></title>
            <link>https://medium.com/data-science/microkernel-architecture-for-machine-learning-library-c04b797e0d5f?source=rss-a77da8047f57------2</link>
            <guid isPermaLink="false">https://medium.com/p/c04b797e0d5f</guid>
            <category><![CDATA[hands-on-tutorials]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning-engineer]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Chen Yanhui]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 04:15:19 GMT</pubDate>
            <atom:updated>2021-02-15T16:48:56.526Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/hands-on-tutorials">Hands-on Tutorials</a></h4><h4>An Example of Microkernel Architecture with Python Metaclass</h4><h3><strong>What is Microkernel Architecture</strong></h3><p><a href="https://learning.oreilly.com/library/view/software-architecture-patterns/9781491971437/ch03.html">The Microkernel Architecture is sometimes referred as Plug-in Architecture. It consists of a Core System and Plug-in components</a>.</p><p>Th Core System contains the minimal functionality required to make the system operational. The Plug-in components are standalone and independent from one another, each of which enhances or extends the Core System with additional capabilities.</p><p>The Core System also maintains a plug-in registry, which defines information and contracts between the Core System and each Plug-in component, such as input/output signature and format, communication protocol, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QFzdkU2zDEJ4gkLeiJKK9w.png" /><figcaption>Image from O’Reilly: <a href="https://www.oreilly.com/library/view/software-architecture-patterns/9781491971437/">Software Architecture Pattern</a></figcaption></figure><p>The pros and cons of the Microkernel Architecture is quite obvious. On one hand, the separation of concerns makes it very flexible and extensible as well as easy to maintain, test and evolve. It is especially suitable for product-based applications, in which you could provide a MVP to customers and adding more releases and features along the way with little changes.</p><p>On the other hand, this architecture is not suitable for system in which it requires frequent communications and dependencies among different components. You could certainly add dependencies among the Plug-in modules, but the maintenance cost will be exponentially high with the number of dependencies, which outweighs the benefits it brings.</p><h3>Why Microkernel Architecture for Machine Learning Libraries</h3><p>Besides training and prediction, there are many concerns that a typical machine learning library has, such as configurable source/sink of the data sources, and cross-cutting concerns like standardization, monitoring, security, etc. These aspects and concerns are isolated and independent from the modelling techniques and algorithms of the data scientists. And they are best addressed by other engineers.</p><p>Microkernel Architecture is a natural fit for such a purpose. It enables paralleled developments of both data science and the Plug-in engineering components, while at the same time maintains a high degree of flexibility and maintainability.</p><h3>An Example of Microkernel Architecture with Python Metaclass</h3><h4><strong>What is Python Metaclass</strong></h4><p>In Python, a metaclass is the class of class. It defines how a class behaves and how the instances of that class are instantiated. You can view metaclass as a class-factory, which allows you to do something extra when creating a class. In our case, we create a metaclass for registering Plug-in components with the main model class. And thus separating the modelling instances from engineering modules. Data scientists could just focus all their attention on the modelling stuff, while the engineers could work on the engineering components in parallel.</p><h4>The Example</h4><p>I have created a PyPi package <a href="https://pypi.org/project/mkml/0.0.2/"><strong>mkml </strong></a>for this Microkernel architecture. Please refer to the <a href="https://github.com/ahhuisg/mkml"><strong>github </strong></a>repository for how to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*fudI_ghy2iSM2xkn51YfdA.png" /><figcaption>ML Library with Microkernel Architecture</figcaption></figure><p>For demonstration purpose, I created 3 plugin components, which are <strong>Standardization</strong>, <strong>Monitoring </strong>and <strong>Data Source</strong> plug-in respectively:</p><ul><li><strong>StandardizationPlugin </strong>enforces the method signatures of the model class. In our case, the model class must have <strong>fit, predict</strong> and <strong>score</strong> methods</li><li><strong>MonitoringPlugin </strong>monitors all the functions of the model class. In our case, it logs the input parameters, exception as well as the duration of each function in the model class</li><li><strong>LocalDataSourcePlugin </strong>helps loading the data locally. It dynamically ingest data-loading functions into the model class to help data scientist retrieve the data without them worrying how to retrieve it</li></ul><p><strong>Install from PyPi</strong></p><pre>pip install mkml</pre><p><strong>Create your own model by extending from BaseModel that is linked to the custom metaclass</strong></p><pre>from sklearn.linear_model import LinearRegression<br>from mkml import BaseModel<br><br>class UserModel(BaseModel):<br>    def __init__(self):<br>        self._model = LinearRegression()<br>        <br>    def fit(self, features, labels):<br>        self._model.fit(X_train, y_train)<br><br>    def predict(self, features):<br>        self._model.predict(features)<br><br>    def score(self, features, labels):<br>        return self._model.score(features, labels)</pre><p><strong>Instantiate the model class instance and load features and labels for training and prediction</strong></p><pre>um = UserModel()<br><br>features = um.get_local_data(feature_mart_location=&#39;data&#39;, group_id=&#39;train_features&#39;)<br>labels = um.get_local_data(feature_mart_location=&#39;data&#39;, group_id=&#39;train_labels&#39;)<br><br>um.fit(features, labels)<br><br>test_features = um.get_local_data(feature_mart_location=&#39;data&#39;, group_id=&#39;test_features&#39;)<br>test_labels = um.predict(test_features)</pre><p><strong>Create your own custom Plug-in module (ie. Plug-in for Remote DataSource)</strong></p><pre>from mkml import BasePlugin<br><br>class RemoteDataSourcePlugin(BasePlugin):<br>	<br>    def __init__(self, name):<br>        self._name = name<br>    <br>    def apply(self, attrs, **kwargs):<br>        logger.debug(&#39;Entering data source plugin&#39;)<br>        attrs[&#39;get_remote_data&#39;] = self._get_remote_data<br>    <br>    def _get_remote_data(self, feature_mart_location, group_id):<br>        # To be implemented<br>        pass</pre><p><strong>Register the custom plug-in module with the metaclass</strong></p><pre>## You can add additional instantiation parameters to the Plug-in class as well	<br>MKMLMetaclass.register(&#39;remote_datasource&#39;, RemoteDataSourcePlugin, &#39;remote_ds_plugin&#39;)</pre><p>The metaclass <strong>MKMLMetaclass </strong>controls the instantiation behavior of the <strong>UserModel </strong>class. Therefore once <strong>RemoteDataSourcePlugin </strong>is registered with the metaclass, the UserModel class will be equipped with the capability that the plugin brings.</p><p><strong>Use the new Remote DataSource Plug-in to retrieve features and labels</strong></p><pre>um = UserModel()<br><br>features = um.get_remote_data(feature_mart_location=&#39;http://fm&#39;, group_id=&#39;train_features&#39;)<br>labels = um.get_remote_data(feature_mart_location=&#39;http://fm&#39;, group_id=&#39;train_labels&#39;)</pre><p>Please refer to this <a href="https://github.com/ahhuisg/mkml/blob/main/notebooks/mkml.ipynb">notebook </a>for sample usage.</p><h3>Conclusion</h3><p>In this article, I have introduced what Microkernel Architecture is and I have also created an PyPi package <a href="https://pypi.org/project/mkml/0.0.2/"><strong>mkml </strong></a>to demonstrate how such architecture could bring benefits to the ML Library designs.</p><p>In my opinion, the biggest advantage of the Microkernel Architecture is the decoupling between Data Science and Engineering workloads, while at the same time maintaining a very high-degree of extensibility and maintainability of the system. <strong>A good architectural design always strikes for a clear separation of Control, Logic and Data.</strong> This architecture clearly demonstrates such a characteristic.</p><p>One final note is that although Python’s metaclass is used for the implementation and it is a very powerful tool, be extremely careful when trying to use it as it will cause many problems when used inappropriately.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c04b797e0d5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/microkernel-architecture-for-machine-learning-library-c04b797e0d5f">Microkernel Architecture for Machine Learning Library</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Large Scale Distributed RandomForest with Kubernetes Operator]]></title>
            <link>https://medium.com/data-science/large-scale-distributed-randomforest-with-kubernetes-operator-797c68c065c?source=rss-a77da8047f57------2</link>
            <guid isPermaLink="false">https://medium.com/p/797c68c065c</guid>
            <category><![CDATA[machine-learning-engineer]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Chen Yanhui]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 08:47:23 GMT</pubDate>
            <atom:updated>2021-01-02T17:31:27.894Z</atom:updated>
            <content:encoded><![CDATA[<h4>Distributed Training in Kubernetes Cluster with a Simple YAML File</h4><p>A few days ago I was exploring the RandomForest model with a huge dataset. To my disappointment, the training data couldn’t fit into the memory of the single working node. I had to manually split the training data to train a few RandomForest models, before combining the models into a single one.</p><p>This prompted me to an idea: <strong>can I come up with a framework to automate and distribute the trainings for ensemble-able models with huge datasets? </strong>I could just prepare and <strong>submit a simple configuration file </strong>and the framework will <strong>orchestrate, monitor and distribute </strong>the trainings<strong> </strong>and produce the model artifact <strong>automatically</strong>.</p><p>After a few days of research and implementation, I have come up with the first version of such a framework, which is a Kubernetes Operator. I have made use of <a href="https://sdk.operatorframework.io/">operator-sdk</a> (0.19.4) and the Kubernetes cluster (1.16.15) from GCP. The operator fulfills the basic requirements for the automation of the distributed training, although there is still much room for improvement. The github repository is <a href="https://github.com/ahhuisg/distributed-training">here</a>.</p><p>In the following sections, I will explain what Kubernetes Operator is, followed by what the <strong>DistributedTraining Operator</strong> looks like. And finally, I will also show you how to set up the Operator in your own cluster.</p><h3>1. What is Kubernetes Operator</h3><p>In a nutshell, a Kubernetes operator is an application-specific controller that extends the functionality of the Kubernetes API to create, configure, and manage instances of complex applications on behalf of a Kubernetes user.</p><p>You might be familiar with the basic Kubernetes concepts like Pod, Deploy, Service etc. These are the built-in Kubernetes API Resources. However, automating and managing complex stateful applications have become and hassle in the early days of Kubernetes.</p><p>Since version 1.7, Kubernetes introduced an API plugin mechanism: Custom Resource Definition or CRD. CRD allows user to specify their own API Resource (Customer Resource). Kubernetes Operator makes use of custom Kubernetes controller and <strong>Custom Resource</strong> (CR) to manage applications and their components.</p><p>In my example, the Custom Resource is called <strong>DistributedTraining</strong>, which consist of 1 master Deployment &amp; Service with 1 Pod, and 1 worker Deployment with user-specified number of Pods. The Operator automatically orchestrate, monitor and manage all the components and the working relationships among them.</p><h3>2. The DistributedTraining Operator</h3><p>Below is the working flow of whole process. What user needs to do is just to specify and submit the configuration file. The Operator will take care of the rest of the steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*e_r14I9m6OcBeoad1HykVA.jpeg" /></figure><h4>The YAML configuration file</h4><pre>apiVersion: ahhuisg.com/v1<br>kind: DistributedTraining<br>metadata:<br>  name: dt-test1<br>spec:<br>  name: dt-test1<br>  baseGcsBucket: distributed-randomforest<br>  <br>  model:<br>    module: sklearn.ensemble<br>    class: RandomForestClassifier<br>    parameters: &quot;n_estimators=500, max_leaf_nodes=16, random_state=666, n_jobs=-1&quot;<br>    merger:<br>      module: merge_list_rfs<br>      function: combine_rfs<br>    <br>  image:<br>    master:<br>      repository: ahhuisg/dt-master<br>      tag: 0.0.2<br>    worker:<br>      number: 3<br>      repository: ahhuisg/dt-worker<br>      tag: 0.0.2</pre><ul><li><strong>Prerequisite</strong>: the model must be ensemble-able (bagging, boosting or stacking). In my example, a RandomForest model could be ensembled from multiple RandomForest models</li><li><strong>baseGcsBucket</strong>: the bucket name from Google Cloud Storage, inside which contains the training datasets, the final combined model as well as the python script for merging the models</li><li><strong>model.module</strong> &amp; <strong>model.class</strong> &amp; <strong>model.parameters</strong>: the model module, class and instantiation parameters</li><li><strong>model.merger</strong>: this contains the python script for how to merge the models from the workers. You can specify how you want to ensemble the models. In the example below, the python script is named merge_list_rfs.py (model.merger.module) and the ensembling function is called combine_rfs (model.merger.function)</li></ul><pre>merge_list_rfs.py:</pre><pre>def combine_rfs(rfs):<br>    rf_a = rfs[0]<br>    for rf in rfs[1:]:<br>        rf_a.estimators_ += rf.estimators_<br>        rf_a.n_estimators = len(rf_a.estimators_)<br>    return rf_a</pre><ul><li><strong>image.master</strong>: contains the container image for the master pod. There is only one master pod in the Operator.</li><li><strong>image.worker</strong>: contains the container images for the worker pods. There could be N number of worker pods in the operator</li></ul><p>As you can see that the YAML configuration file is fairly straight -forward. After preparing the training data in the GCS bucket, you just need to specify the <strong>model-related values, the bucket name as well as the number of workers</strong>, depending on the Kubernetes capacity and your requirements. Then <strong>you could just submit the file to the cluster (kubectl apply -f &lt;file_name&gt;) and wait for the model artifact to be available.</strong></p><h3><strong>3. Set up the Operator in Your Cluster</strong></h3><h4>Clone My Github Repository</h4><pre>git clone <a href="https://github.com/ahhuisg/distributed-training">https://github.com/ahhuisg/distributed-training</a></pre><h4>Set up ServiceAccount, Role and RoleBinding (only done once)</h4><pre>kubectl create -f deploy/service_account.yaml<br>kubectl create -f deploy/role.yaml<br>kubectl create -f deploy/role_binding.yaml</pre><h4>Set up Operator and Custom Resource Definition (only done once)</h4><pre>kubectl create -f deploy/operator.yaml<br>kubectl apply -f deploy/crds/dt_crd.yaml</pre><h4>Create and Run Your Distributed Training</h4><ul><li>Prepare your data at the GCS bucket (as specified in baseGcsBucket). Currently there must be a <strong>data </strong>sub-directory inside the bucket. Inside the data directory, each partition of the training data should be in pickle file format and named as training_&lt;n&gt;.pkl/label_&lt;n&gt;.pkl</li><li>The number of partitions should be the same as that of <strong>image.worker.number </strong>in the configuration file</li><li>Modify the yaml file <strong>deploy/crds/dt_cr.yaml</strong>. You could specify the model-related properties in the model section of the config file. For example, if you want to use XGBoost for distributed training, you can set the model module, class and parameters. You should also define how you want to combine the sub-models by changing the merger section</li></ul><pre>kubectl apply -f deploy/crds/dt_cr.yaml</pre><h3>4. My Example Demo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7bqGv5ENaD2Mf-2LKHpwOQ.jpeg" /><figcaption>GCS Bucket</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBFzJQHZr31lG52F1CUyMA.jpeg" /><figcaption>Data Directory in GCS Bucket</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*4zVpjdv2cADExQWEgnnYFw.jpeg" /><figcaption>Create ServiceAccount, Role &amp; RoleBinding</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*NDa1X2CVaWuePcSIG_dIFA.jpeg" /><figcaption>Create CRD &amp; Operator</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*S_Qle_8ldirvMrhiTYHmrw.jpeg" /><figcaption>Apply Custom Resource and Trigger Training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2K0x4QWQeLEJPbjVzGU0RA.jpeg" /><figcaption>Run Successful and Combined Model Saved to GCS</figcaption></figure><h4>Validation</h4><p>Using a simulated dataset of 40,000 data points, I have validated the models from the 3 sources:</p><ul><li>Single RandomForest model (accuracy: 0.909)</li><li>Combined RandomForest model locally (accuracy: 0.908)</li><li>Combined RandomForest model from the Operator (accuracy: 0.908)</li></ul><p>Please refer to this <a href="https://github.com/ahhuisg/distributed-training/blob/main/notebook/distributed_randomforest.ipynb">notebook</a> for further reference</p><h4>Things to Improve</h4><ul><li>Automatically split and save the training data according to the number of workers, instead of manual splitting and saving data to GCS bucket currently</li><li>Allow each worker training instance to have its own model parameters, to take advantage of more variety and randomness in ensemble-learning</li></ul><h3>5. Conclusion</h3><p>In this article, I have introduced the Kubernetes Operator that I developed for Distributed Training of ML models. Kubernetes is a very popular and powerful platform for automatically orchestrating and managing distributed workloads. The declarative nature of workloads in Kubernetes, plus its exceptional capability for defining and managing complex relationship within applications, make Kubernetes one of the most suitable tools for handling complicated ML workloads. I hope this small little tool could make your life easier if you have similar use cases!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=797c68c065c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/large-scale-distributed-randomforest-with-kubernetes-operator-797c68c065c">Large Scale Distributed RandomForest with Kubernetes Operator</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technical Debts of Machine Learning Systems]]></title>
            <link>https://medium.com/swlh/technical-debts-of-machine-learning-systems-9738e39a1ba6?source=rss-a77da8047f57------2</link>
            <guid isPermaLink="false">https://medium.com/p/9738e39a1ba6</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-systems]]></category>
            <dc:creator><![CDATA[Chen Yanhui]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 14:35:13 GMT</pubDate>
            <atom:updated>2020-09-29T12:48:28.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>Common problems of machine learning system and sharing of personal experience</h4><p>With the democratization of Machine Learning (ML) technologies and the advancement of ML tooling and frameworks, developing and deploying ML systems has become fast and cheap. However, maintaining such systems over time proves to be difficult and expensive, due to the peculiarity and unique characteristics of ML systems.</p><p>I am going to briefly summarize some of the <a href="https://papers.nips.cc/paper/5656-hidden-technical-debt-in-machine-learning-systems.pdf">technical debts of ML systems</a> from 3 perspectives, which are <strong>Data Dependency</strong>, <strong>ML System Peculiarity</strong> and <strong>System Architecture and Design</strong> respectively. After that, I will try to relate some of them to a ML project that I have done previously.</p><h3>ML System Technical Debts</h3><h4><strong>Due to Data Dependency</strong></h4><p>ML System’s Data Dependency is the root of all evils why ML systems are so much more difficult to maintain. In addition to the normal problems of software systems, there are more complicated problems caused by data dependency.</p><p>The best practices of software engineering use encapsulation and modular design to create maintainable code. The strict boundaries among the software components express logical, consistent and deterministic relationship between inputs and outputs.</p><p>However in ML system, any change in the input data would cause changes in code logic and parameter values in ML system. It is a <strong>Change Anything Change Everything (CACE)</strong> system. In other words, the software and the data dependencies are in <strong>Entanglement</strong>. And even worse, the data dependencies are much more <strong>Unstable </strong>than code dependencies.</p><p>The solution to the data dependency problem requires a mindset change: we need to <strong>treat data as a first-class citizen in ML system</strong>, on par with source codes and infrastructure. In other words, we need to have corresponding tooling to continuously monitor and validate data throughout the whole lifecycle of ML system.</p><p>The most important thing is to have an effective and flexible <strong>Monitoring and Testing </strong>mechanism that could help check for all kinds of data problems such as <strong>Training-Serving Skew</strong>, <strong>Data Drifting</strong>, etc. This mechanism should also allow users to plug in their own monitoring metrics, which are then visualized on the dashboard.</p><p>Another specific approach is <strong>Static Analysis of Data Dependencies, </strong>which builds data dependency graphs and enables data sources and features to be annotated. Automated checks can then be run to ensure that all dependencies have the appropriate annotations, and dependency trees can be fully resolved.</p><p>One more approach is called <a href="https://mlsys.org/Conferences/2019/doc/2019/167.pdf"><strong>Model Unit Testing</strong></a>, which checks for errors in the training code using synthetic data generated through data schema. The data schema is not fixed and it has a lifecycle empowered by <a href="https://mlsys.org/Conferences/2019/doc/2019/167.pdf"><strong>Data Analyzer and Data Validator</strong></a> with certain degree of human intervention and domain knowledge.</p><h4><strong>Due to ML System Peculiarity</strong></h4><p>ML system is different from normal software system in that it is experimental in nature. The ML model need to be re-trained continuously given the new training data and labels. However, the new data might be the result of the old system, which means that any error in the old model will be amplified in the new system (<strong>Feedback Loop</strong>).</p><p>Classification model needs to set a fix threshold for decision boundary. Most of the time this threshold is manually set and becomes a problem in a dynamic environment (<strong>Fix Threshold</strong>).</p><p>The solution to the Feedback Loop problem has to come back to <strong>Monitoring and Testing</strong> again. It can detect the change in data as well as the deterioration of the model performance. Also the <strong>Model Unit Testing</strong> framework together with <strong>Data Analyzer </strong>and <strong>Data Validator</strong> mentioned above could give you an early warning.</p><p>The other approach is to have an <strong>Experimentation Platform</strong>. After all, all the work that you have done before deploying is hypothetical. Having an Experimentation Platform for A/B Testing not only helps you release your model with high-degree of confidence and gathering effective feedbacks, but also minimizing damage for erroneous models. Specific for the problem of Fix Threshold, you could dynamically adjust your threshold by running experiments through the platform.</p><h4><strong>Due to System Architecture and Design</strong></h4><p>ML System make use of data from many sources to construct features for the model, sometimes incrementally as new sources and features are identified. Without careful consideration and design, the ETL and pre-processing create a jungle or a spider web of intermediate steps with files and outputs. Managing, testing and maintaining these pipelines becomes a nightmare and costly (<strong>Pipeline Jungle</strong>).</p><p>Data needs to be pre-processed before passing to ML model. In some ML packages or the models developed in-house, a large chunk of supporting code is bundled together with the ML model source codes (<strong>Glue Code</strong>). This makes it much harder to maintain and also reduce its extensibility. We should be consciously be aware of the difference between the supporting and model source codes during model development and separate them into different packages.</p><p>The solution to Pipeline Jungle is to think holistically about data collection and feature extraction. Firstly you need to organize pipelines into logical groups and standardize the flow of steps for each group. Secondly you need to constantly examine the pipelines to extract the common logics and build them into reusable components across the pipelines. Thirdly as new sources and features are added, you might want to re-organize the pipelines from time to time into more manageable logical groups.</p><h3><strong>Personal Experience</strong></h3><p>Previously I was leading a team consists of both data scientists and data engineers in a utility company. My team’s responsibility was to apply machine learning to solve energy and operation problems. We take care of the whole lifecycle of machine learning, all the way from the design and develop of the ML models and pipelines to the deployment and maintenance of them.</p><p>In the following I will share one of the ML solutions for the False Alarm Reduction of metering alarms.</p><h4><strong>The Problem</strong></h4><p>The company’s meter technical support unit sends personnel to inspect electricity meter of every household bi-monthly. And the metering system will generate an alarm ticket if it suspects there is something wrong with the meter reading. The unit has to send personnel to inspect the meter device again for every alarm ticket.</p><p>It turns out that more than 90% of the tickets were false alarms out of the 3000 monthly tickets. It not only incurs unnecessary financial costs but also casts a big stress on human resources.</p><h4><strong>The Challenges</strong></h4><p>We have to come up with a ML solution to reduce the false alarms while at the same time try not to miss any true alarms.</p><p>All of the data are in SAP transactional systems. It is very difficult to build ML pipelines and models that are directly interfacing with SAP.</p><p>Our newly set-up team was the only ML team in the company. There was no machine learning infrastructure at all. We had to build the ML infrastructure from scratch for effective training, testing and deployment of the models.</p><h4><strong>The Solution</strong></h4><p><strong>Prerequisite</strong></p><p>Before investing lots of efforts into a ML project, you have to ask yourself many questions from business and technical &amp; operational perspectives.</p><p>Some business questions are like: Is there any more straight-forward and heuristic approach? Is there enough room for improvement? Does the P&amp;L make sense? Will the estimated benefits outweighs the costs of development, maintenance, and operation?</p><p>Some technical &amp; operational questions are like: Does enough labelled data exist? Where does the data come from? How easily is it to get the data? How do you evaluate the model? What are the success and fail metrics? How long does it take to know the model fails?</p><p><strong>Develop</strong></p><p>Then we started to gather training data from various stakeholders for exploratory data analysis and model development. Once the model proved working on the testing data, we started discussions and cooperation with various SAP operation teams to build the ML pipeline for data ETL as well as model scoring and output.</p><p>In anticipating that the data would be needed by many other use cases, we built from scratch a data warehouse and feature marts for the model to consume from. We also packaged the model as a restful service as a step in the pipeline.</p><p>As the model was developed and improved iteratively, new sources and features came into picture incrementally. The data pipelines became increasingly complex and hard to manage. We encountered the problem of <strong>Pipeline Jungle</strong>.</p><p>However with <a href="https://nifi.apache.org/">Apache Nifi</a>, we managed to separate the the pipelines into logical groups and standardize the flow of steps in each group. At the same time we extracted the commonalities of the processing logics into <a href="https://nifi.apache.org/developer-guide.html">Custom Nifi Processors</a> as reusable components in the pipelines. In the meanwhile, we scrutinized and refactored the model to separate away the pre-processing and supporting logic to avoid the problem of <strong>Glue Code</strong>.</p><p><strong>Deploy</strong></p><p>The deployment of the model impacted new training data and labels, which means we couldn’t get any new untainted training data any more once the model is deployed. This is the typical problem of <strong>Feedback Loop</strong>.</p><p>We have put some consideration into it at that time. But because there were other mechanisms for users to report the status of their metering devices, and there was no proper Experimentation Platform, we went ahead with the model deployment.</p><p>However, I think we should have done A/B testing to validate the model in production despite all the difficulties. This was a lesson learnt. Luckily the overall result was very good. We managed to reduce a significant amount of false alarms every month while keeping almost all of the true alarms. And our effort was recognized by both the stakeholders and the company.</p><h3>Conclusion</h3><p>In this article I have discussed briefly some common problems of ML systems and relate a few of them to one of my previous projects. Maintainability is one of the most important aspects of any software system, and it is even more so for ML system due to its data dependency and experimental nature.</p><p>Fast and cheap development and deployment of ML projects is a worrying trend with accumulated technical debts. A good and comprehensive ML infrastructure plus careful considerations on the entire lifecycle before starting a ML project will improve the maintainability of a ML system tremendously.</p><h3>References</h3><ol><li><a href="https://papers.nips.cc/paper/5656-hidden-technical-debt-in-machine-learning-systems.pdf">Hidden Technical Debt in Machine Learning Systems</a></li><li><a href="https://mlsys.org/Conferences/2019/doc/2019/167.pdf">Data Validation for Machine Learning</a></li></ol><h3>Related</h3><ol><li><a href="https://medium.com/@yanhui79/enable-model-driven-business-with-machine-learning-platform-bb5605818126">Enable Model-Driven Business with Machine Learning Platform</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9738e39a1ba6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/technical-debts-of-machine-learning-systems-9738e39a1ba6">Technical Debts of Machine Learning Systems</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>