<?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 Guillaume Androz on Medium]]></title>
        <description><![CDATA[Stories by Guillaume Androz on Medium]]></description>
        <link>https://medium.com/@guandroz?source=rss-e9c80b7a94f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fV035Nx1XqjmfBwM.jpeg</url>
            <title>Stories by Guillaume Androz on Medium</title>
            <link>https://medium.com/@guandroz?source=rss-e9c80b7a94f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:15:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guandroz/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[Improve python performances with ctypes]]></title>
            <link>https://medium.com/data-science/improve-python-performances-with-ctypes-ef51cee2eb59?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef51cee2eb59</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Wed, 05 May 2021 14:50:46 GMT</pubDate>
            <atom:updated>2021-05-05T21:33:57.564Z</atom:updated>
            <content:encoded><![CDATA[<h3>Improve Python Performances with ctypes</h3><h4>An application example of ctypes usage: the Levenshtein distance computation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1vuFJg5UotXqRKVlUtWrA.jpeg" /><figcaption>Tachometer from <a href="https://unsplash.com/@chrisliverani">@chrislivernani</a> on unsplash</figcaption></figure><h3>Context</h3><p>When it’s time to look at python performances, it is commonly proven that python is a slow, really slow if you compare to compiled and lower level languages like C or C++. One way to drastically increase speed of your code is to vectorize it with the help of numpy. To further increase speed, you can then look at numba which is often a good choice to simply turn a slow algorithm into a really fast one with just a decorator.</p><p>That said, I like to come back to low level languages like C. Python kernel is written in C, so why don’t we try to build our own library for the computation intensive parts? That’s the goal of the following article.</p><h3>Python-C interfacing</h3><p>When it’s time to interface your python code with some C library, you mainly have two choices:</p><ul><li>use a third party tool/library which transcripts your code into the corresponding C code with a transpiler</li><li>manually load the C library and marshall the data to the corresponding C part</li></ul><h4>Transpiler</h4><p>The first approach and not my favorite is the use of an intermediate transpiler that converts your python code into a C code. I only know Cython, but maybe others exist. Cython is very close to python (and supports native python as well as numpy) which is a great advantage. However, I find it too close to python and tuning the code to really improve performances can be hard. Sometimes you have to declare the type of your variables, sometimes not. You have kind of a profiler to help you find the bottlenecks in your code which is of great help, but really, I find it hard to learn and hard to achieve the maximum performances.</p><p>So instead of trying to tweak some not-so-python-surely-not-c code, why don’t we directly use C code ? That’s where ctypes come into action.</p><h4>Marshalling with ctypes</h4><p>ctypes is a native library in python which, according to its <a href="https://docs.python.org/3/library/ctypes.html">documentation</a></p><blockquote>ctypes provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.</blockquote><p>So what’s really interesting with ctypes is that you can develop your library in pure C language, compile and debug it like you would do with any C library, and just use it directly in python ! kind of magic.</p><p>Loading a C library is really straight-forward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3004aa1c48105c71b4adf0b925b7dff4/href">https://medium.com/media/3004aa1c48105c71b4adf0b925b7dff4/href</a></iframe><p>We are now able to call any function of the library just as you would do with a python module. The only hard thing is to realize that you call a C function, so it expects typed parameters so you have to give it the right <a href="https://docs.python.org/3/library/ctypes.html#fundamental-data-types">argument type</a>.</p><p>To illustrate all of that, let’s take a simple example aka. the computation of the Levenshtein distance between two strings</p><h3>The Levenshtein distance</h3><p>The Levenshtein distance is a distance (mathematically speaking) that measures the edition distance between two strings. It measures the number of characters to insert, delete or replace to match both strings. The more the two strings differ the higher the distance.</p><p>To compute the distance, we allow three edition operations: delete, insert or replace a character. Sometimes the cost associated to each operation is the same and equal to 1, sometime we set the replace operation cost to 2 as it can be decomposed as a delete followed by an insert operation. The algorithm is quite simple and consists in building a matrix of rank MxN where M is the number of characters of the source string plus one, and N the number of character in the target string plus one. The Levenshtein distance is then the element D[M,N] of the matrix.</p><h4>Matrix initialization</h4><p>The first step to compute the matrix D is to initialize it. We construct an empty matrix of rank MxN where M is the number of characters of the source string plus one, and N the number of character in the target string plus one to allow the use of an null character #.</p><p>The first row of the matrix then computes the distance from the null string to each sub-string of the target string. For example, let’s take the word levenshtein as our source string, and levenstein as our target (where the letter h has been omitted). Then for each sub-string of the target, we had a cost of ins_cost in each column. Indeed, to reach the string &#39;l&#39; from the null string &#39;#&#39;, we have to insert a letter, so the distance &#39;#&#39; → &#39;l&#39; is equal to ins_cost. We do the same to compute the distance &#39;#&#39; → &#39;le&#39; which equals to 2 x ins_cost and so on for the first row. The reasoning is the same for the first column but using the del_cost instead of the ins_cost as the distance from &#39;l&#39; to &#39;#&#39; is measured by the delete cost. With a delete and insert cost of 1, the resulting initial matrix is then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*xwvgTMCOJW-dD9uTt0nKlA.png" /><figcaption>Distance matrix initialization</figcaption></figure><h4>Matrix elements computation</h4><p>Once the matrix has been initialized, it’s time to fill it according to Levenshtein algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*_nZpj5EZn1_7fIYqn3uL9Q.png" /><figcaption>Levenshtein distance computation algorithm</figcaption></figure><p>So, we start from the first letter of the two strings, in out case letters &#39;l&#39;i.e. we are interested in cell D[1, 1].</p><ul><li>The first line of the algorithm tells us to take the content of the previous row of the current column (the cost of &#39;#&#39; → ‘l&#39;) and add it the delete cost</li><li>The second line starts adds the insert cost of the previous column of the current row (the cost of &#39;l&#39; → &#39;#&#39;) so that its the total cost &#39;l&#39; → &#39;#&#39; → &#39;l&#39; and it equals to 2</li><li>For the last line, we notice that the letters of the source and the target are the same for this cell, so we simply take the cost of the previous row and previous column i.e. we don’t need any edition to perform this step.</li><li>Finally, we keep the minimum of the three costs which would be 0 in this case</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*8kDbPclbB--lzRcS_yDmzg.png" /><figcaption>Matrix computation</figcaption></figure><p>With this algorithm, we then iterate over each cell of the matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*RwShptPXnvGqFh4FM6n2ag.png" /><figcaption>Matrix computation result</figcaption></figure><p>The minimum edition distance between the two strings &#39;levenshtein&#39; and &#39;levenstein&#39; is then equal to 1, which perfectly makes sense as we only need to delete one letter to reach the target from the source string.</p><h3>Algorithm implementation</h3><p>The Levenshtein algorithm is quite simple to implement (and you can find numerous versions of it) and using C language would normally be no challenge. Perfect time to try ctypes ! So here my naive C implementation of the algorithm:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31d331b1603013e663d34dcd2adb34f0/href">https://medium.com/media/31d331b1603013e663d34dcd2adb34f0/href</a></iframe><p>We’ve followed all the steps of the algorithm from initialization to iteration over each cell. I’ve chosen to return the whole matrix, but we could have chosen to output only the distance.</p><p>The previous implementation could be improved if we notice that we only need to access the contents of the previous row (or column) when computing. Hence, we can use only one row and update its content as we perform the computation. An improved version of the implementation is as follow (notice that we now return the distance and not the whole matrix as we do not keep it in memory)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6058c059e55be7446b5f1c9fbb3d26/href">https://medium.com/media/fa6058c059e55be7446b5f1c9fbb3d26/href</a></iframe><h3>Call C function from python</h3><p>Now that we built our C library, we can load it directly into python code and call any function in it thanks to ctypes.</p><p>Loading a library with ctypes is straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f29f63abed75d195d75d7380ab682df/href">https://medium.com/media/1f29f63abed75d195d75d7380ab682df/href</a></iframe><p>The only tricky part relates to the fact that C is a typed language and not python, so that ctypes needs to marshall python variable into the corresponding C type. That what is done in lines 5 and 11 where we explicitly tells the C function what type of variable it expects and what type of result we get. In our case, we pass two strings (pointer to char in binary format) plus three integers and we expect an integer as a result.</p><p>All we need now is to call the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/645f3dbaf98a8c57fbdf375dfecacc7f/href">https://medium.com/media/645f3dbaf98a8c57fbdf375dfecacc7f/href</a></iframe><h3>Conclusion</h3><p>We presented here a gentle introduction to ctypes to show how easily we can increase (substancially) python code performances with C libraries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*cRIPvdVZaZC2ziR4o0ngng.png" /><figcaption>Performance of the C version of the Levenshtein distance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*LcjoVvYpFXXQ43adtlWhgQ.png" /><figcaption>Performance of the python version of the Levenshtein distance</figcaption></figure><p>As we already mentionned, numba or cython are alternative goods choices but I personnly find them harder to use and optimize. Using raw C code makes perfect sense to me and I really like to use ctypes with such easy piece of code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef51cee2eb59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/improve-python-performances-with-ctypes-ef51cee2eb59">Improve python performances with ctypes</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[Deep Q-Learning with Pytorch and OpenAI-gym: The Taxi-cab puzzle]]></title>
            <link>https://guandroz.medium.com/deep-q-learning-with-pytorch-and-openai-gym-the-taxi-cab-puzzle-e7a3028f732?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7a3028f732</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Tue, 16 Mar 2021 17:40:26 GMT</pubDate>
            <atom:updated>2021-03-16T17:40:26.176Z</atom:updated>
            <content:encoded><![CDATA[<h4>REINFORCEMENT LEARNING FOR BEGINNERS</h4><p>Reinforcement Learning with a deep learning model to choose proper action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6UaE2FQ4_l5AziWMOgRRw.jpeg" /><figcaption><a href="https://unsplash.com/photos/NZOgPLpL4Lk">Unsplash from petekasprzyk</a></figcaption></figure><p>In a <a href="https://towardsdatascience.com/reinforcement-learning-teach-a-taxi-cab-to-drive-around-with-q-learning-9913e611028f">previous post</a>, I tried to explain how we can play a simple game Taxi-v3 from OpenAI automatically by applying reinforcement learning basics with the Q-learning algorithm. This approach paved the way to the deep-Q-learning algorithm.</p><p>Deep-Q-Learning or more generally deep reinforcement learning has been emphasized by Deepmind and its AlphaGo program. In this article, we’ll go through this new approach step-by-step and I’ll try to give you a quick view on the challenges it brings, even for very simple environments such as the Taxi-v3 game.</p><h3>Q-table reminder</h3><p>Let’s remind what a Q-table is about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*VgP5BuhrGSpOInpH53pOHA.png" /><figcaption>Use of a Q-table</figcaption></figure><p>A Q-table is just a table learnt by exploring then exploiting an environment and experiences, mapping couples (state, action) to Q-values. The Q-values are learnt by playing with the environment and incrementally updated thanks to the Bellman equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*8E-Kce9HGTvTLOSI.png" /><figcaption>Bellman equation. How to update Q-values in the Q-table</figcaption></figure><p>Another way to look at a Q-table is to consider it as a general function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*SCQZNpYRQ4FOnyL3rJvLsA.png" /><figcaption>General function</figcaption></figure><p>where A is the action space and S the state space.</p><p>This function can be anything, and it is especially true with more complicated environments where the states or the actions are continuous values or composed vectors.</p><p>Thanskfully for us, such general or complicated functions can be approximated with neural networks (NN) or even deep neural networks (DNN).</p><h3>Deep-Q-learning</h3><p>So the principle of deep-Q-learning is simple, just replace the Q-table by a deep neural network and it’s done !… well not so fast. You are right if you think the principle is the same, but evil is in the details.</p><p>Just as the Q-learning algorithm, DQL uses the epsilon-greedy exploration/exploitation algorithm to first explore, construct kind of a memory then exploit the collected informations. A DQL approach has in fact three main components:</p><ul><li>A training network</li><li>A target network (same as the training network)</li><li>A large enough memory</li></ul><h4>Network training</h4><p>You may be familiar with deep-learning model training. You got some data, well labelled data, and you got your model. What you do is feeding the model with your data, compute the loss between the expected values and the model prediction, then propagate the loss inside the network to update its weights. You iterate like that several times until “convergence” and your’re done.</p><p>The problem with reinforcement learning is that you do not have such data. All you have is an environment you can explore and play with, but you have no idea of what the rewards look like, you have to discover it by yourself (or your model has to).</p><p>So let’s have a look at the different steps to train our agent network.</p><h4>First Exploration</h4><p>Just as in the case of Q-learning, we first need to intialize our networks, generally with random values (the same weights are assigned to both networks!). Then come the exploration phase where we let the agent randomly naviguate in the environment, taking actions and gettings rewards accordingly.</p><p>All the experiences are logged into a memory, a big experience replay memory. This step or warmup step is just here to initialize the training of our network, to gather some useful data.</p><h4>Exploration vs. exploitation: ε-greedy action selection</h4><p>Once the memory has been fed with some random exploration, we can begin to exploit our training model. Just like with a Q-table approach, we select an action to take for the current state with ε-greedy action selection. It means that for a given state, we choose the action to take randomly with a probability ε, or we take the action predicted by the training model. As the training model predicts Q-values for every possible action for a given state, we choose the most rewarding action i.e. the action with the highest Q-value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ocl8z8ky5gtau8BUs_vrA.png" /></figure><p>The new tuple (state, action, reward, next state) is then pushed into the replay memory to enrich data diversity. Note that the training model is not trained during this phase, just used to computed predicated Q-values so the action predicated might not be accurate at the beginning of the process.</p><h4>Network training</h4><p>After having explored a little and gathered some data, we can start the training process of the network. That’s where the memory comes into action.</p><p>First, we randomly sample a batch from the memory experience replay. This batch will be fed into the networks to predict the Q-values. Each experience of the batch represents a state of the environment, the reward the agent got when he took the action stored in memory and the resulting state. So an experience is a tuple (state, action, reward, next state).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*SPaQsrcmeCP8BPthMn-v0g.png" /><figcaption>Forward pass</figcaption></figure><p>The states in the batch are sent to the training network to predict the Q-values, but we only retain the Q-values corresponding to the action written in the memory for each experience. These Q-values are our predicted Q-values and will be used to compute the model loss.</p><p>To train a deep learning model the supervised way, we need labelled data but we’ve already said tha twe do not have any from our environment. We then need to construct labelled data and that’s the aim of the target network. The target network takes the next states and predicts the best Q value out of all actions because that’s what we want our model to predict, the most rewarding action to take for each state. Said another way, the next state is the state we would have like the training model had predicted. To reach this state, the model had to choose the proper action, and regarding the target model, it is the action corresponding to its highest Q-value.</p><h4>Loss</h4><p>What we just said is : for memory sample (state S, action A, reward R, next state S&#39;) we wanted our training model to predict the same highest Q-value Qt(S&#39;) as the target network, corresponding to action A’, but it predicted Q(S, A) instead. The observed loss is then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*Iaua2kY8ngTYJfnbrcGEYA.png" /><figcaption>Naive loss</figcaption></figure><p>However, if we work with this simple naive loss, we miss a crutial information which is the expected reward, and our model will not tend to maximize the final reward. That’s where the Bellman equation comes into action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*X947422fJKMCOrqHgB-5fw.png" /><figcaption>Bellman equation</figcaption></figure><p>Now, the expected Q-value is not only given by the maximum predicted Q-values, but it is also modulated by the expected reward R. The γ factor is a discount factor, an hyperparameter to adjust to give more or less weight to the target Q-value.</p><h4>Back-propagation</h4><p>So we now have Q-values predicted by the training model, and target (or labelled) Q-values predicted by the target network. The rest is the same we find when training deep learning model, i.e. loss back-propagation. And generally in reinforcement learning, we use the Huber loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*2CZDFSx4EXyzySu4c9O7Tg.png" /><figcaption>Huber loss</figcaption></figure><h4>Recap</h4><p>The recapitulate all the steps to train our model:</p><ol><li>Initialize memory with a few warmup random steps</li><li>Reset environment so that we are in a known state</li><li>Choose an action with ε-greedy action selection policy</li><li>Perform a step with this action and store the results into memory</li><li>Sample a batch from memory</li><li>Predict Q-values with both training and target networks</li><li>Compute Huber loss and back-propagate in the training network</li><li>Update target network periodically</li></ol><h3>Look at the target network</h3><p>You may wonder why we bother with a second network, the target network, and why we just don’t use the same network ? I’m glad you ask ! And the answer is, well you can use the same network but…. you may encounter some issues.</p><p>I say it again, but we do not have any labelled data here to train the model. We compute the labelled data at each batch, so if we use the training model to label the data and we sample the same entry from the memory, we may not have the same target ! The target data is a moving target and if we update it too often, we won’t be able to track it when training our model. It is just as simple as that !</p><p>Using a second target network that is not trained, we ensure that the target Q-values are stable during a given period (a few episodes). However, we know that the targets are not the best ones, at least at the beginning of the training. That’s why the target network has to be update periodically. How often ? well, it depends and the period is another hyperparameters you have to play with.</p><p>I could not say it better than the Google Deepmind scientists who actually proposed this approach to play Atari games :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSRSGgUybGtCYMrLG3pLVA.png" /><figcaption><a href="https://www.nature.com/articles/nature14236">Human-level control through deep reinforcement learning, V. Mnih &amp; al., <em>Nature</em> <strong>volume 518</strong>, pages529–533(2015)</a></figcaption></figure><h3>Pytorch Implementation</h3><p>I don’t want to bother you with tones of lines of code here, so I refer you to my github repo :</p><p><a href="https://github.com/gandroz/rl-taxi">gandroz/rl-taxi</a></p><h4>Note on the model</h4><p>The model used for this toy example is very simple. It consists of an embedding layer (a state is a simple integer from 0 to 500), two hidden dense layers with ReLU activation without any regularization of any kind, and a final dense linear layer i.e. without activation function. because the Q-values are not limited in their values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*85nYGKfjxo8oQlyJXnCL3w.png" /><figcaption>model architecture</figcaption></figure><p>The embedding layer embeds the input integer to a 4-coordinates vector. I use hidden layers with 50 nodes and the last dense layer maps the nodes to a 6-coordinates vector as Taxi-v3 game has 6 possible actions.</p><h3>Hyperparameters tuning</h3><p>Throughout this article, we’ve often spoken of hyperparameters, discount-factor, ε-greedy policy, target network update period, but we can also mention the learning rate and batch size. Tuning these batch size can be tricky as I already said, the target in deep-Q-learning is a moving target so the process may not be very stable. So let’s dig a little in each of these hyperparameters to try to see their influence on the training process.</p><p>First, here the training result I ended up</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*YQart9sw9BCjeNPlELMGZQ.png" /><figcaption>Training curves for a set of hyperparameters that made the training converging</figcaption></figure><p>We see on this figure the rewards curve, the steps curve and the ε curve. The reward plot is the sum of all the rewards for each episode. An episode is play round starting with a fresh new environment and ending with either the end of the game (passenger dropped-off at the right place) or a maximum number of steps because we don’t want the exploration of the environment to take too much time. The steps curve is the number of steps performed in each episode. What we want is to maximize the reward and minimize the number of steps for each episode.</p><p>We also find the ε curve on the figure. It is the evolution of the hyperparameter ε of the ε-greedy policy. This parameter has been chosen to vary along the episodes because we want the training process to let our agent explore the environment at the beginning, but we also want it to exploit the learnt model. The ε parameter make this choice : it is near 1 at the beginning so that the probability to choose a random action for a step is close to 1 i.e. the agent explores the environment. This probability exponentially decreases along the road to a low value (0.1 in the present case) to let the agent exploit the model.</p><h4>Batch size</h4><p>A simple hyperparameter is the batch size. Too few samples in the batch and the model won’t see lots of data to perform an epoch, and too much data and it will see too much “wrong” data. Indeed, at least at the beginning of the training, data gathered are almost randomly chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*ZWgJho9EYW3urD620iIvuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*4ffHT-fFQ9PoQSs-9bc77g.png" /><figcaption>Large batch size (left) vs. small batch size (right)</figcaption></figure><p>As we can see here, using a large batch size speeds the training to….a random model. The model is unable to converge as the data is of too low quality. On the contrary, with a too smal batch size, the model learns slowly and does not converge either (at least not after 10,000 episodes) as it has too few data to exploit.</p><h4>Learning rate</h4><p>I won’t detail a lot about the learning rate as I assume you are familiar with it, but here are the comparison between a high and a low LR</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*u-KoFtfkhJnqJYjySoIAzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*MVCYiplHL4jpQ_6dSPL5TQ.png" /><figcaption>High learning rate (left) vs. low learning rate (right)</figcaption></figure><p>Note that to achieve the training curve of the converged model, I did not use a constant learning rate. Instead I let it exponentially decrease over the episodes to speed up the learning at the beginning and help convergence at the end.</p><h4>ε-greedy policy</h4><p>We can already see on the figures that the ε hyperparameter is not constant over the episodes. I already explained why, but we can still vary the ending point and choose if we want the agent to explore more or less at the end of the training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*pHv_ws6ibqwrEETdBlXsUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*GNyJ3HZER5tPmCeck1GJxw.png" /><figcaption>High steady state ε (left) vs. low ε (right)</figcaption></figure><p>If we let the agent explore too much the environment, it could be hard for us to say that the model converges. To be sure, we need to evaluate the model over several episodes and see if it plays well the game. The left curve tell us that the variance decreases over the episodes, so we can suspect the model has converged, but the remaining high variance is probably due to the high probability of exploration. Even if the model takes the right decision, the ε-greedy policy forces the agent to choose another way. On the opposite, if the probability of exploration is too low too quickly and the model has note converge, we will end up with data in the memory that are progressively replaced by non-accurate ones so that the model can start to diverge. That’s what we see in this example.</p><h4>Discount factor</h4><p>It was our choice to use a high discount factor, ~0.99. It means that we give the same weight to the reward as to the target Q-values. If the discount factor is too low, we do not allow the model to learn from its mistakes and it won’t converge, at least not fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*x_pCN9iONyO461JR33l9jg.png" /><figcaption>Low discount factor</figcaption></figure><h4>Update period</h4><p>As state by the authors of the Google Deepmind paper, using a second network and updating it periodically stabilize the learning process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Bd03qsJDOwzDpEDrGh60Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*iTHAHrQMmIIbB7fQCQGxmQ.png" /><figcaption>Update the target model very often (left) vs. rarely (right)</figcaption></figure><p>We can see that updating the model too often destabilizes the learning process as it is seen from the high variance. The predictions might be quite good as the rewards are high, but as the target changes too often, it is not stable. However, if the updating frequency is too low, the model converges rapidly to the target, but to a wrong target. The model eventually converges, but it could converge faster.</p><h3>Conclusion</h3><p>In this article, we’ve seen how to use reinforcement learning and deep learning together to learn some policy to play a simple game. Whereas it is possible to use a table to map each state to the right action to take for this simple game, it could be tricky even impossible for more complex games. That’s why we’ve replaced the Q-table by a deep-learning model in an approach that could generalize for more environments. However, we’ve also seen that training such a model can be harder that traditionnal deep-learning models. Not that the model itself is more complicated, but because the data is a moving target so that the process is hardly stable.</p><p>I hope you enjoyed the journay as much as I did !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a3028f732" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Always Know Your IP for Remote Connection]]></title>
            <link>https://medium.com/geekculture/how-to-always-know-your-ip-for-remote-connection-223c01912573?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/223c01912573</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[remote-working]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Mon, 15 Mar 2021 13:14:43 GMT</pubDate>
            <atom:updated>2021-03-16T21:26:30.913Z</atom:updated>
            <content:encoded><![CDATA[<h4>Keep track of your IP address to easily connect to your desktop at home.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvvpUqR8HpVYWV0qRjhQDw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin">casparrubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">unsplash</a></figcaption></figure><p>In the current pandemic days, I’m not the only person on Earth to work remotely. I used to work from home some days, but not on a regular basis, but I can say that I like it. The most enjoyable part is that working remotely allows you to work from home, from your chalet, from your parent’s … well wherever you want ! The only condition though, is that you own a laptop and a good connection.</p><p>However, as a datascientist, my two GPU rig does not travel as well as my laptop, but it is far more powerful. Sure I could have setup the equivalent cloud based VM, but hey, how could I game ?!</p><p>So, the simple solution is to travel with my laptop and let my desktop at home. The coding part is done on my laptop when I am away from home and let the heavy process happens on my desktop. All I need is to connect to my desktop with a secured SSH connection. Even VSCode allows you to open a SSH connection directly in the IDE which is even more easy. Thanks MSFT !</p><p>The only problem for this to happen is to always know your public IP. Unless you pay for a fixed IP, it might change over time, but not too often as your internet provider tries hard to give you the same IP. So you have to track your public IP and have a place to log it.</p><p>The solution I found is simply to make a service that checks periodically my public IP and detects any change in it. If my IP changes, an email is then sent to my inbox (I use gmail). I used my favorite language python and the <a href="https://developers.google.com/gmail/api/quickstart/python">Google API</a> for that (the documentation is very well written):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f349b658577ef69d9e85699d505d753a/href">https://medium.com/media/f349b658577ef69d9e85699d505d753a/href</a></iframe><p>Not bad ! Just a few lines of code and you’re done. Now all you have to do it to automate the process with a systemd service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/688cc0c429500637b2fb190cb3bd516d/href">https://medium.com/media/688cc0c429500637b2fb190cb3bd516d/href</a></iframe><p>and run this service hourly by defining a timer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ab644ba380b125315a93904be9c5d22/href">https://medium.com/media/7ab644ba380b125315a93904be9c5d22/href</a></iframe><p>And voila ! You now track your public IP with a linux service that sends you an email when your IP changes so you can let your desktop at home and enjoy working wherever you want !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223c01912573" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-always-know-your-ip-for-remote-connection-223c01912573">How to Always Know Your IP for Remote Connection</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning — Teach a Taxi Cab to drive around with Q-Learning]]></title>
            <link>https://medium.com/data-science/reinforcement-learning-teach-a-taxi-cab-to-drive-around-with-q-learning-9913e611028f?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9913e611028f</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Sun, 14 Mar 2021 02:52:29 GMT</pubDate>
            <atom:updated>2021-03-16T18:17:56.575Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reinforcement Learning for Beginners</h4><h3>Reinforcement Learning — Teach a Taxi Cab to drive around with Q-Learning</h3><h4>A gentle introduction to RL with OpenAI-gym and Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6UaE2FQ4_l5AziWMOgRRw.jpeg" /><figcaption><a href="https://unsplash.com/photos/NZOgPLpL4Lk">Unsplash from petekasprzyk</a></figcaption></figure><p>I played a lot with machine learning for fun and for work. I’ve built deep-learning models with PyTorch and TensorFlow for NLP, vision and healthcare. However, reinforcement learning was still a mystery for me and reading a lot about Deepmind, AlphaGo and so on was very intriguing. Having a little more time now and I decided to deep dive into RL to try to understand the basics.</p><p>My choice was to use a simple basic example, python friendly, and OpenAI-gym is such a very good framework to start with. The toy example I chose was the taxi-cab environment. This <a href="https://gym.openai.com/envs/Taxi-v3/">environment</a> is very simple :</p><blockquote>There are 4 locations (labeled by different letters) and your job is to pick up the passenger at one location and drop him off in another. You receive +20 points for a successful dropoff, and lose 1 point for every timestep it takes. There is also a 10 point penalty for illegal pick-up and drop-off actions.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*wLUSa716Be2cS3E3t3AjvA.png" /><figcaption>OpenAI taxi-V3 environment. Image by Author</figcaption></figure><p>As stated in the documentation, you drive a taxi-cab. There are four locations at the four corners of the table. A passenger is waiting for the taxi at one location and you have to drive him to the designated location. You are rewarded for each move, with a low penalty when you are on travel, with a large penalty if you pick-up or drop-off the passenger at the wrong location, but you earn a big reward if you succeed. Simple as hell.</p><h4>States</h4><p>In RL, a state is… well the state your agent (your taxi-cab) stands in. In the taxi problem, a state is described by the location on the grid (a row and a column number between 0 and 4), a location to drop-off the passenger from four choices, and the passenger which can be in one of the four locations or inside the taxi.</p><p>If you count well, we then have 5x5x5x4=500 possible states.</p><h4>Actions</h4><p>The actions now. There exactly six possible actions. With your taxi, you can try to move to the four cardinal directions : South, North, East or West. It does not mean that the move is allowed neither possible. There are also two other possible actions which are the pick-up or the drop-off for a great total of six actions.</p><ul><li>0 = South</li><li>1 = North</li><li>2 = East</li><li>3 = West</li><li>4 = Pickup</li><li>5 = Dropoff</li></ul><p>Note here that you are not penalized more if you try to move to an unauthorized location. For example, in the figure above, you cannot move to the west, but you still get the -1 penalty, no more no less. The same goes when you try to move farther than the 5x5 grid. However, you are severely penalized if you try to pick-up or drop-off the passenger at the wrong location.</p><h3>Play with OpenAI-gym and python</h3><p>Now that we described the environment, it is time to play with it with python. OpenAI provides us with a gym environment already fully coded so the task is quite easy.</p><h4>Rendering</h4><p>The first step is to render a random environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e283177482c029bdac23812fca108f98/href">https://medium.com/media/e283177482c029bdac23812fca108f98/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*dtU96s2xQyQQzHF2sglJzQ.png" /><figcaption>Random environment sample state</figcaption></figure><p>A new environment is also easily generated by calling the reset method state = env.reset().</p><h4>Moving around</h4><p>When you try to play within an environment, you have to tell it what you want to do, which action you take. For example in the example above, you may want to go in the north direction. The north action has the code 1 so to perform a step in this direction we call</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd26f5365081eb4e4e41b31f48a15982/href">https://medium.com/media/cd26f5365081eb4e4e41b31f48a15982/href</a></iframe><p>This call returns a tuple (204, -1, False, {&#39;prob&#39;: 1.0}) which components are</p><ul><li><strong>state</strong>: new state of the environment, coded from 1 to 500</li><li><strong>reward</strong>: the reward you got with your action. -1 meaning you’ve simply moved</li><li><strong>done</strong>: a boolean to indicate if we’ve successfully dropped off a passenger previously picked up</li><li><strong>info</strong>: information not relevant for our usage</li></ul><p>Note that we could have chosen to randomly pick an action. gym framework provides us with a useful method for that env.action_space.sample().</p><h3>A gentle introduction to Q-learning</h3><p>Ok, so what is Q-learning about? I knew that for training a deep-learning model, I needed lots of data, possibly annotated data, and I needed a method to let a model learn a function to minimize the error between the training data and its prediction. However, reinforcement learning has not the same approach. Here, we need our agent to explore its environment and let it decide which action to take to maximize its expected reward. So right now, we see a fundamental concept of RL which is the trade-off between exploring (the environment) and exploiting (what he learnt).</p><p>Now, how do you explore a new environment and exploit what you learnt of your experiences? Imagine you are in a labyrinth. You know there is an exit and you have to find it out. Imagine then you have a great memory, a memory large enough to remember a big number of your last moves. With that in mind, you could imagine that you can reconstruct a mental image of the labyrinth to be able to step back and explore a new way to the exit. Of course, you are rewarded if you manage to find the exit with sweeties :) What you’ve just constructed is a kind of a table where you know exactly what to do, where to go from anywhere within the labyrinth to find the exit. In RL, this table is known as the Q table.</p><p>The Q-table is a table where you find a Q-value for each couple (state, action). For each state, we can have several possibleactions, so several Q-values. The goal is to learn to choose the higher Q-value for each state which means choose the action with the best chance to get the maximum reward.</p><p>To start learning, the Q-table is generally randomly initialized (or initialized to 0). The agent then explores its environment by randomly choosing an action and get a reward for its action. The idea is to let the agent exploring the environment and getting some rewards. But after a while, we need to exploit the information gathered. From a given state, the agent must compute the expected reward for each action it can take and choose the one with the maximum expected reward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*9-oSoiaqKjisWz5l270w9g.png" /><figcaption>Expected rewards</figcaption></figure><p>The core of RL is then given by the Bellman equation which tells us how to update the Q-values of the Q-table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*xp-Fp_igVf6D364_oxxNTQ.png" /><figcaption>Q-value update</figcaption></figure><p>where</p><ul><li><strong><em>α</em></strong><em> </em>is the learning rate</li><li><strong><em>γ </em></strong>is a discount factor to give more or less importance to the next reward</li></ul><p>What the agent is learning is the proper action to take in the state by looking at the reward for an action, and the max rewards for the next state. The intuition tells us that a lower discount factor designs a greedy agent which wants immediate rewards without looking forward.</p><h4>Explore vs. Exploit</h4><p>We already mentioned it several times, but we now see more clearly what the trade-off between exploring and exploiting is all about. If we let the agent always randomly choose an action, it could eventually learn the Q-table, but the process will never be efficient. On the contrary, if we only choose an action based on the maximization of the Q-value, the agent will tend to always take the same route, overfitting the current environment setup. Furthermore it will suffer from great variance as it will not be able to find the proper route in another environment setup.</p><p>To prevent those two scenarios to occur and to try to find a trade-off, we add another hyperparameter epsilon ϵ, which is the probability with which we choose a random action instead of the one computed from the Q-table. Playing with this parameter allows us to find an equilibrium.</p><h3>Implementation in python</h3><p>I know what you looking for, so first here is the code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd07d1679785a020407cb28b9fdec2e2/href">https://medium.com/media/cd07d1679785a020407cb28b9fdec2e2/href</a></iframe><p>Simple right? But as surprising as it looks, this piece of code learns a Q-table from exploring an environment, with no historical well-labelled data, just as a basic intelligence would do. Awesome!</p><p>But to convince you, why not play with our new toy?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/222fe9382fc52bc51642b78381279025/href">https://medium.com/media/222fe9382fc52bc51642b78381279025/href</a></iframe><h3>Conclusion</h3><p>Oh yeah! We’ve just completed our first RL-toy agent. It does not take complicated mathematics neither hard algorithms to understand the basics of RL. And with only several lines of code, we were able to train an agent to play the taxi game.</p><p>The journey only starts. Now we can play with the various hyperparameters and see their influence on the training and on the performances of the agent. And to evaluate the performances, all you need to do is play several times with the agent (code a simple for-loop, do not do it by hand !) and see how the hyperparameters influence the mean expected rewards and the mean number of steps to complete an episode.</p><p>Also, stay tuned to conjugate both worlds of RL and DL by replacing the Q-table with a DL model in a <a href="https://medium.com/mlearning-ai/deep-q-learning-with-pytorch-and-openai-gym-the-taxi-cab-puzzle-e7a3028f732#5aec-da0488a82349">coming post</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9913e611028f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reinforcement-learning-teach-a-taxi-cab-to-drive-around-with-q-learning-9913e611028f">Reinforcement Learning — Teach a Taxi Cab to drive around with Q-Learning</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[Deploy autoscaling machine learning model inference stack to AWS with CDK]]></title>
            <link>https://medium.com/data-science/deploy-autoscaling-machine-learning-model-inference-stack-to-aws-with-cdk-84d26acf8a99?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/84d26acf8a99</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Mon, 17 Aug 2020 21:38:31 GMT</pubDate>
            <atom:updated>2020-08-17T22:06:16.305Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use the power of AWS/CDK to deploy ML models in a stack that scales automatically for inference on CPU or GPU</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_EZxXczHOxaSYl2PzHnSQ.jpeg" /><figcaption>source: <a href="https://unsplash.com/photos/jkuR9QteDGY">unsplash</a></figcaption></figure><p>For several years now, data science and machine learning were sexy and lots of companies embraced “artificial intelligence” as a new powerful tool to automate complex tasks as a black box. In this area, deep learning appears to be the Holy Grail to build models to detect and classify images or texts among other cool things. Once models are trained, it is common to deploy them on a small web server and expose a simple REST API to perform inference on a given sample. It is very convenient as usually, whereas training a model needs lots of computation power and lots of GPU, inference only needs a relatively low power CPU to make a prediction on a single sample. You could find numerous articles and blog posts on this approach; event open source projects and companies could be found to make the whole thing painless.</p><p>There exist cases, however, where you need to perform inference on not just a sample, but on a batch of samples. In this case, inference can take a lot of time when performed on CPU and you need to use a GPU to parallelize the job. Using a small web server is now no more relevant as you don’t want to pay for an ever running machine with an attached GPU. For example, imagine you have to perform some prediction on large files that are uploaded to your S3 bucket. Your file is first split into small chunks on which the model makes a prediction. What you want is your stack to automatically launch when a file is ready to process, use a machine with a GPU, and shut down the whole thing when there is nothing to process anymore. As there is no serverless stack available (will there be one, one day?), we need to build a stack to scale automatically to our need.</p><h3>Architecture</h3><p>The proposed architecture is the following: we get a SQS message with the task to perform. For example, it could be the name of a file on S3 to process. Depending on a configuration parameter found in the parameter store of AWS, this message is forwarded to another SQS queue, one for a CPU-based stack, and one for a GPU-based stack. An ECR cluster then uses Cloudwatch alarms to trigger the scaling of two autoscaling groups, one with CPU-only instances and one with GPU-enabled instances. The result is then returned into a S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otgGVA0g90s78fmvlfx1nw.png" /><figcaption>Proposed architecture</figcaption></figure><h3>Automation</h3><p>To automate a little more the whole thing, we can use a CDK application. Just like Terraform or Kubernetes offer to build a stack by code, CDK tends to be the reference to deploy stacks on AWS. You can of course use Cloudformation, but just the idea to use very large YAML files to manage a stack makes me run away. However, using a modern programming language like Typescript, C# or Python is way more interesting. In the <a href="https://github.com/gandroz/deploy_model_ecs_medium">repository source code</a>, you could find two classes to build the stack : DeployModelEcsMediumStackCore and DeployModelEcsMediumStack. The first one as its name suggests builds the core of the stack i.e. the main SQS queue, attach a lambda function to it, an ECS cluster and the definition of some IAM policies. Then the DeployModelEcsMediumStack class builds a stack for the CPU or for the GPU architecture. A SQS queue and associated metrics, an autoscaling group with the right AMI, instance type and the scaling policies, and the ECS task with the right ECR image to retrieve.</p><h4>Cluster</h4><p>First, a cluster shall be created with ecs.Cluster construct. From there, we create an autoscaling group adding a capacity provider to the cluster with cluster.addCapacity static method. We then need to create a task with the construct ecs.Ec2TaskDefinition providing the proper ECR image retrieved with the static method ecs.ContainerImage.fromEcrRepository. The image has to be an ECS optimized AMI based image to work properly. There is no official AWS AMI that support GPU for ECS, but you can find custom ones. We also need to pay attention to the gpuCount property and set it to 1 when we want to use a GPU. Finally, the service is created with the construct ecs.Ec2Service and attached to the cluster.</p><h4>Work with the stack</h4><p>Once everything has been deployed, all you need is to send a message in the main SQS queue with the command to execute i.e. the name of the file to retrieve on S3 in my example. To decide whether to use a GPU based instance or a CPU only instance, we only need to change the configuration found in the parameter store in the system manager. An example of such a message could be</p><pre>aws sqs send-message --queue-url <a href="https://sqs.ca-central-1.amazonaws.com/1234567890/MediumArticleQueue">https://sqs.ca-central-1.amazonaws.com/1234567890/MediumArticleQueue</a> --message-body &#39;{&quot;filename&quot;: &quot;file_to_process.bin&quot;}&#39;</pre><h4>Queues</h4><p>There are three SQS queues in the proposed architecture, but the user only needs to send a message in the main queue <a href="https://sqs.ca-central-1.amazonaws.com/1234567890/MediumArticleQueue">MediumArticleQueue</a>. Once a message is received, a lambda function is triggered and regarding to the configuration (a parameter in the SSM/Parameter Store), the message is forwarded to the proper queue, GPUQueue for an autoscaling group managing GPU based instances and CPUQueue for CPU only based instances.</p><h4>Code</h4><p>The typescript/python code for this CDK stack is a bit large to publish here, but you could find the sources in this <a href="https://github.com/gandroz/deploy_model_ecs_medium">repo</a>. Feel free to copy or fork code, just a thumb up or a little comment would be appreciated.</p><h3>Final note</h3><p>In the source code, I defined my alarms to scale the autoscaling group but not the tasks count. The reason is that when adding an ECS service, we also set its autoscaling behaviour with ecsService.autoScaleTaskCount method. However, AWS/CDK does not properly link task scaling and instance scaling, which is the role of the capacity provider. This behaviour can be achieved when you work directly in the console, but not programatically. There is a <a href="https://github.com/aws/aws-cdk/pull/9192">PR</a> to correct it, but it was not available at the time this article was published. To later support this feature, I added a commented code section to illustrate what the code could look like when the feature is released.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84d26acf8a99" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploy-autoscaling-machine-learning-model-inference-stack-to-aws-with-cdk-84d26acf8a99">Deploy autoscaling machine learning model inference stack to AWS with CDK</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[GLR with Python and scikit-learn library]]></title>
            <link>https://medium.com/data-science/glr-with-python-and-scikit-learn-library-67b5b0d418ea?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b5b0d418ea</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Sun, 24 May 2020 02:35:30 GMT</pubDate>
            <atom:updated>2020-05-25T15:40:50.592Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine Learning</h4><h3>Linear Regression with Python and scikit-learn library</h3><h4>An Introduction to Generalized Linear Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZXc4vX6Ra_sXZH21LYibg.png" /><figcaption>from <a href="https://unsplash.com/@fabioha">@fabioha</a> on <a href="https://unsplash.com/">https://unsplash.com/</a></figcaption></figure><p>One of the most used tools in machine learning, statistics and applied mathematics, in general, is the regression tool. I say the regression, but there are lots of regression models and the one I will try to cover here is the well known generalized linear regression. The idea underneath this complex word is quite simple: the observation we try to fit is supposed to be a linear combination of input explanatory variables. Mathematically, the observation vector be formulated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*TB9w0X_IDbVylkzwKeqO4g.png" /></figure><p>where the <em>x</em>ₖ stands for the explanatory vector <em>k</em>, and the <em>w</em>ₖ are the weight of each explanatory variable. Furthermore, as we usually need for an intercept, by convention we set <em>x</em>₀<em>=1</em> so that the weight <em>w</em>₀ represents the intercept.</p><h3>Linear Regression</h3><p>As a first example, let’s begin by a simple linear regression which consists of minimizing the sum of error squares. The error is defined as the difference between the expected true value and the predicted value obtained by our model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*46IQv7W09DJEPNkNxC-15g.png" /><figcaption>Cost function of linear model</figcaption></figure><p>for all M points <em>(xᵢ, yᵢ)</em></p><p>To illustrate this simple example, let’s use the awesome library scikit-learn and especially the package sklearn.linear_model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9523d931ff7e16948fb839217c50f534/href">https://medium.com/media/9523d931ff7e16948fb839217c50f534/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*il_Z_bhZ-OKJOS6L.png" /><figcaption>Simple linear regression</figcaption></figure><p>The model we use here is quite simple, it is just a line. The model seems quite good with fitted coefficients of <em>w₀ =-0.87998</em> and <em>w₁=4.54914</em>, but the error is not null (mean squared error = 15.57 in the example). Sometimes a way to reduce the residual error is to change the model by a slightly more complex one. In our case, we simply fitted a polynom of degree 1. What if we increase the polynom degree? For example, let’s say we increase the degree up to 12:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab4f182ea8ed1fcd23b35a8a46eeb418/href">https://medium.com/media/ab4f182ea8ed1fcd23b35a8a46eeb418/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*4SmgRTt40afDDZ_q.jpg" /><figcaption>Influence of the polynomial degree</figcaption></figure><p>As we can see, the more we increase the polynomial degree of the model, the more we reduce the residual error. However, and it is particularly evident in this example, the reductions of the error is not necessarily a sign of a better model. Indeed, imagine we use a high degree polynom as our model, the error tends to be null (and it is actually here as we have a polynom degree equal to the number of observations). But if we add an extra observation, our model surely experiences a high residual error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5507bb7f775422840a9474155b3f13a2/href">https://medium.com/media/5507bb7f775422840a9474155b3f13a2/href</a></iframe><p>and the result is</p><p>The residual error <strong>for</strong> X=15 <strong>is</strong> [ 57.50465854]<br>The residual error <strong>for</strong> X=15 <strong>is</strong> [ 540.59208041]<br>The residual error <strong>for</strong> X=15 <strong>is</strong> [ 23711.11027247]<br>The residual error <strong>for</strong> X=15 <strong>is</strong> [ 192880.65211092]<br>The residual error <strong>for</strong> X=15 <strong>is</strong> [ 3.55927302e+09]<br>The residual error <strong>for</strong> X=15 <strong>is</strong> [ 4.83622098e+12]</p><p>As we can see in this example, adding an observation at x=15 leads to increasing error with the polynom degree. This behavior is known as overfitting, i.e. the model fit very well the data but tends to poorly perform on new data. We say that it suffers from great variance.</p><p>To overcome this problem, we need to choose the right polynom degree. We could, for example, split our dataset into two parts, a train set and a test set. Then, the best model would be the one with the least residual error on the test set. However, there a clever method to limit the overfitting phenomenon: regularization.</p><h3>Regularization</h3><p>Regularization consists of adding a penalty to a model, with the goal of preventing overfitting. It comes from the constatation that when the degree of the polynom increases (to take our first example), the weights of each monom also increases. Therefore, to overcome overfitting, we penalize monoms with high weight. The minimization function now becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcSFHTV7Ha6lyA_5NF761Q.png" /><figcaption>Cost function with regularization</figcaption></figure><p>where |.| is typically L1 or L2 norm, and lambda is an hyper-parameter that can be tunable to adjust the penality sensibility (0 means no penalty, i.e. unregularized model). The two widely used regularization methods are L1 and L2 regularization, also called <a href="http://en.wikipedia.org/wiki/Least_squares#Lasso_method">LASSO</a> and <a href="http://en.wikipedia.org/wiki/Tikhonov_regularization">RIDGE </a>regression.</p><h3>LASSO</h3><p>To cite content of the scikit-learn library</p><blockquote>LASSO is useful in some contexts due to its tendency to prefer solutions with fewer parameter values, effectively reducing the number of variables upon which the given solution is dependent. For this reason, the LASSO and its variants are fundamental to the field of compressed sensing. Under certain conditions, it can recover the exact set of non-zero weights.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9093dee38a72fd4206febf7fbb5e2601/href">https://medium.com/media/9093dee38a72fd4206febf7fbb5e2601/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*4QHAMtIFGyzPoYf8.png" /><figcaption>Influence of the LASSO regularization</figcaption></figure><p>We clearly see the effect of regularization. When we increase the penalty, we strongly limit the weights of each coefficient, up to only keep the intercept. But how to choose the right parameter? Well, here again, we need to look at the residual error computed on a set which is not the training set. Such a method is known as validation. The principle is to split the data set into three parts, say 80% for the training set, 10% for validation and 10% for test. The model is trained on the training set, then the validation set is used to choose the hyper-parameter. Finally, the test set is used to estimate the true error of the model. However, on small data sets, this approach is not efficient enough as it limits the amount of data available for training. For such small data sets, we can apply the method of cross-validation. For that, we split the data set into two parts, one for the training and the other for the test. The training is then performed on all the training set but some k samples. So let’s imagine that the training set is composed of N samples. We perform N/k regressions on the N-k samples and we compute the validation error on the k remaining samples. After all those regressions, the validation error is the mean error of all the validation errors.</p><p>In the scikit-learn library, there is a class that implement this approach and finds the optimal hyper-parameter: LassoCV. We then re-use the preceeding code sample omitting the alpha parameter to force the use of the LassoCV model :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*GLgWE1a9fke1ucSL.png" /><figcaption>Optimal solution with LASSO regularization</figcaption></figure><p>According to the LassoCV model, the optimal hyper-parameter alpha=4.16e⁻⁴.</p><h3>RIDGE Regression</h3><p>The RIDGE regression is quite similar to LASSO, and differs only by the order of the norm used in the regularization term. In LASSO, we used a norm of order 1 (L1) and in the RIDGE regression we use a norm of order 2 (L2). The behavior of this regularization technique is that all resulting weights of the models are still non null, but eventually with very small value so that their influence on the predicted value is quite low. On the opposite, LASSO imposes sparsity of the model by eventually setting weights to null which make the model interpretation easier. The main advantage of the RIDGE regression is that it is indifferent to multiplicative factor, and tends to equals weights of highly-correlated variables whereas LASSO will choose or the other.</p><p>The implementation of our example is really similar to the previous LASSO case. All we have to do is replacing Lasso and LassoCV by Ridge and RidgeCV !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08959e9b32dac57639ba566be840cafd/href">https://medium.com/media/08959e9b32dac57639ba566be840cafd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*G1-7XArZ2BMX3lQi.png" /><figcaption>Influence of the RIDGE regularization</figcaption></figure><p>And with the use of cross-validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*xABSUVlCdV9bDmtC.png" /><figcaption>Optimal solution wit RIDGE regularization</figcaption></figure><p>As we can see, the resulting model is a little different as with the LASSO regularization. And if we now look at the weight coefficients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*eIYb2UNMFtHHubkUeuqd-w.png" /><figcaption>Regression coefficient comparison for both regularizations</figcaption></figure><h3>Conclusion</h3><p>In this article, we saw two regularization techniques and the importance to use regularization when we try to fit a model. We also saw that both techniques, although quite similar, give very different results. Indeed, whereas the RIDGE technique includes all the explanatory variables, LASSO results in a sparse model which is often easier to understand. However, LASSO performs less well in the case of highly correlated variables as it tends to produce high sparsity in the result. And that’s exactly what we saw in our example when we tried to fit a cosinus with a polynom. Each variable are highly correlated so that the resulting model has a lot of zero values as weight coefficients. Along with RIDGE and LASSO, Elastic Net is another useful techniques which combines both L1 and L2 regularization. It allows for learning a sparse model while it also keep RIDGE properties.</p><h3>End note</h3><p>We briefly went through the subject, but as always in machine learning, we need several datasets to train the model, validate it and test it. We discussed that a little and we quickly saw how to deal with small datasets with cross-validation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b5b0d418ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/glr-with-python-and-scikit-learn-library-67b5b0d418ea">GLR with Python and scikit-learn 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[Deploy your Auto-Scaling Stack with AWS-CDK]]></title>
            <link>https://medium.com/swlh/deploy-your-auto-scaling-stack-with-aws-cdk-abae64f8e6b6?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/abae64f8e6b6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cdk]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Wed, 06 May 2020 01:08:21 GMT</pubDate>
            <atom:updated>2020-05-06T12:57:10.693Z</atom:updated>
            <content:encoded><![CDATA[<h4>AWS</h4><h4>How to deploy an auto-scaling group stack that scales according to the size of a SQS queue with the help of AWS-CDK</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*LHt1OdlaWH2zM1jknkeYlg.png" /><figcaption>AWS Cloud Development Kit</figcaption></figure><h3>Context</h3><p>Amazon Web Services are a collection of dozens of services, from simple storage to machine learning pipelines. There are so many services that even a senior representative does not know all of them. I must admit that the first time I had a look at AWS, I was completely lost, not knowing from where to start.</p><h4>Step 1</h4><p>Of course, you need a project, something to build. It can be a web application, a serverless data pipeline automation, a machine learning inference API, a <a href="https://medium.com/swlh/how-to-use-aws-codebuild-as-a-ci-for-your-python-project-82dd7dab7afb">CI/CD integration</a> so you can use large machines to execute your tests and so on. In the case here, we will build a scalable fleet of workers that have to process orders issued by a third party service and stacked in a queue.</p><h4>Step 2</h4><p>This is perhaps the most difficult task, you need to design your project, propose an architecture, explore all the Amazon services to find which corresponds to your needs the best. Sometime it is straightforward, but sometime you could end with several architectures more or less complex until you find that there is a service that does almost all what you’re trying to manually build. Of course, there is a cost to those services with a high degree of abstraction, but it can be more efficient than building your own.</p><h4>Step 3</h4><p>Finally, you have to experiment, build some prototypes, explore more services and iterate with step 2. But once you manage to build your super hyper stack, what’s next ?</p><h3>The need for automation</h3><p>I’m a big fan of automation. As an engineer, I don’t like to perform the same action twice especially if it is a non valuable task, and even more if it is done manually. So manually deploying a stack is not something I’m keen on.</p><p>But as I said in the step 3, you need to experiment, and when it’s time to play with AWS, experiments are usually done with the console. AWS console is a really great tool. You can build everything you want, you can monitor your application, launch EC2 instances, store your data in a S3 bucket etc. all with a few clicks. The tricky part however, is that there are tons of parameters to set, tons of names to repeat, links to draw between your services. If your stack has few services, it can be manageable, but as soon as you want to plug say four, five, twenty services, it turns out to be a nightmare.</p><blockquote>The solution is found in automation</blockquote><p>Fortunately, AWS has already anticipated that people like me are lazy and don’t find any pleasure to repeat all the same parameters to build a new stack, when the only thing we want it just to change one. For that purpose, we have access to the <a href="https://aws.amazon.com/cli/">CLI</a>. With just one tool, you can write commands to build each of your service. The fun part is that you can now gather all the commands in a script (typically a bash script) and parameterize them so it is easier to perform multiple experiments.</p><p>However it is a really nice first approach, there are some limitations. What if something fails during the deployment of your stack ? How can we retry and being sure that we started a clean stack ? What is several people are trying to deploy the same stack, how to manage the race conditions ? How to update your stack without having tons of if-conditions to control the flow ?</p><p>That’s why Amazon developed AWS CloudFormation. So what is AWS CloudFormation</p><blockquote>AWS CloudFormation provides a common language for you to model and provision AWS and third party application resources in your cloud environment.<br> — <a href="https://aws.amazon.com/cloudformation/">https://aws.amazon.com/cloudformation/</a></blockquote><p>What does it mean ? Well, instead of using a scripting and non managed approach to deploy a stack, you now use a declarative one. All you need is to build a YAML file like you build a code script, defining all your needs and CloudFormation provisions the stack in a secure and repeatable manner. It is a managed service that knows how to update a stack, manage errors and rollback when something goes wrong. You can now define your infrastructure as code.</p><p>But there is actually an even better approach, an applicative one. You can now use your favorite programming language (or the most popular these days i.e. Javascript, Typescript, Java, Python and C#) in a unified framework : <a href="https://aws.amazon.com/cdk/">Amazon Cloud Development Kit or CDK</a>. It is now much easier to design your stack and use code to build it. It is much more readable and easier to maintain. Of course, CDK is sill quite young and not everything is supported yet, but it is enough for most needs. CDK is not a new language, it is “just” a framework, an abstraction layer to transcode into a YAML file that can be used with CloudFormation. Of course, you don’t have to manually deploy your YAML file, there is a command for that.</p><h3>The Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*a_od0MijGXNTVO-1c2DvOA.png" /><figcaption>AWS Stack</figcaption></figure><p>The stack we’ll explore here is quite common. Imagine a todo list, a list of task a worker has to perform, a list which size varies in time so as the work load. In AWS, this todo list has a name, it is a Simple Queue or SQS.</p><p>AWS has also EC2 instances we can use as our worker. It can be a general purpose instance, or a specific one with lots of RAM, high computing power, or even a GPU attached on it. The problem is that we don’t know how many workers or instances we need. Too few and the work can be long to do, too many and we pay for instances not to run at max capacity.</p><p>We need to automatically scale in and out regarding to the work load i.e. to the size of the queue. Here again, AWS has already thought about it and proposes Auto Scaling Groups. The group can instanciate new EC2 instances, the exact copy of the preceding ones. Custom images or AMI are especially useful for that. The scaling reacts to alarms that trigger when to scale in and out.</p><p>Alarms are raised by another service, CloudWatch, that monitors a metric for us (the SQS size in our case). When this metric crosses a given threshold, the alarm is set.</p><p>So to summarize. A third party fills a SQS queue. CloudWatch service monitors the length of the queue and set alarms according to our pre-defined thresholds. An Auto Scaling Group automatically adjust its size in reaction to the alarms. Each instance created is the exact copy of previous ones in the same scaling group thanks to a custom AMI.</p><h3>AWS CDK</h3><p>Amazon Cloud Development Kit articulates around three concepts : an Application, a Stack and Constructs.</p><p>And application is the executive part, that’s where your stack(s) is actually built. The stack is the list of units, each piece of the puzzle. And finally there are the constructs which are the actual units, the building blocks.</p><p>As the stacks in CDK are implemented through the CloudFormation stacks, everything you find in CloudFormation can be implemented with the CDK. However, we also suffer of the same limitations.</p><h4>The Application</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac44ac03f922ed9afa68024a8122841c/href">https://medium.com/media/ac44ac03f922ed9afa68024a8122841c/href</a></iframe><p>The application code is straightforward. All you need is to import your stack(s) and instantiate it. We further specified an environment through the env_dev variable as recommended by AWS. Indeed, imagine you have two or more accounts, one for development purpose and one for production. Of course, you want your stacks to be identical across all your accounts, that’s where the env property is interesting as you can reuse the same stack code.</p><h4>The Stack</h4><p>An AWS CDK Stack is a container where you declare every unit you want to use. It is the place where you organize the puzzle. A Stack object is a base class that adhere to only a basic interface (ok, python has not the concept of interface, but as CDK is implemented in TypeScript, some classes need to adhere to some interface rather than inheriting from another class). As so, a Stack only needs you to implement its constructor</p><pre>from aws_cdk.core import Stack, Construct<br></pre><pre>class MyStack(Stack):<br>    def __init__(self, scope: Construct, id: str, **kwargs) -&gt; None:<br>        super().__init__(scope, id, **kwargs)<br>    <br>        # The declaration of Constructs goes here</pre><h4>The Constructs</h4><p>Now the fun part, the building blocks i.e. the Constructs. A Construct is the code implementation of a cloud component like a S3 bucket, an EC2 instance and so on. Before going into details, here is the whole code of our Stack example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e152aeb025b80001d11f2489247aa0aa/href">https://medium.com/media/e152aeb025b80001d11f2489247aa0aa/href</a></iframe><p><strong>i-</strong> The first block is an IAM role. We need this role to allow our EC2 instances to read messages from the SQS queue and delete the once processed. We need to specify which service will assume the role with assumed_by property, the role_name and the policy, here a managed_policy we want to give to the role.</p><p><strong>ii-</strong> Then, we declare the SQS queue, and all we need it to give it a name.</p><p><strong>iii-</strong> The third part is one of the most important part in our stack because that’s where we declare the metric we want to track to scale the fleet of EC2 instances. The metric is easy to declare as we don’t need a custom metric, just use one provided by AWS for a SQS queue : the approximate_number_of_messages_visible. Once we have the metric, we construct an alarm that we can further use to scale the fleet. Here, we want to raise the alarm when the number of visible messages in the queue is greater than 1. The auto-scaling group we’ll use will have a minimum size of 0, i.e. we want the group to stay idle when there is nothing to do. We want then to wake up the group and create an instance when there are messages in the queue, at least one message. To do that, the alarm will be raised when there is at least one message in the queue for one minute. We could not decrease the time resolution under one minute by default as it is not allowed by AWS, but it would possible to do if we build a custom metric. However, it is out of the scope of this demonstration. One detail though. CloudWatch set the alarm in an insufficient_data state when the queue length is zero. The trick is to tell the alarm to consider the insufficient_data state as an ok state so that no alarm is raised.</p><p><strong>iv-</strong> Networking. Our scaling group is part of an existing VPC, so we need to fetch it with the from_lookup function that take the VPC ID as an argument. We then specify that we’ll use the private subnets from our VPC, and we look for the security group we also already have in a previous stack. To fetch the security group, the method is the same as to fetch the VPC, we use the tool from_security_group and simply provide the SG ID.</p><p><strong>v-</strong> Now the fun part, the autoscaling group (ASG). But before creating it, we need to retrieve the AMI we will use to create the EC2 instances. For this, we will use a custom AMI previously built so we fetch it as a generic_linux image giving the AMI ID to the CDK function. And we are good to create the ASG. We need to provide the role we want our EC2 instances to heritate, the VPC where to host the ASG, the type of instance (here we simply use a t2.micro), the AMI, the key-pair name if we want to be able to SSH into the EC2 instances, the subnets and finally the ASG scaling parameters. We choose to scale our ASG from 0 to 2 instances as we want the ASG to be idle when there is no message in the SQS queue. The desired capacity is then set to 0 either.</p><p>The creation of an ASG also creates a default security group (by the time this article has been published). However, it appears to be kind of a bug as we are not allowed to change it, we can only add another SG. This issue has been <a href="https://github.com/aws/aws-cdk/issues/3433">reported</a> to the AWS CDK team. Another issue also <a href="https://github.com/aws/aws-cdk/issues/6734">reported</a>, is the use of ASG launch configurations. AWS pushes to now use templates instead of launch configurations to create an ASG. However, CloudFormation and so CDK does not support this feature yet.</p><p><strong>vi-</strong> And finally, the glue between our services, i.e. we need to tell the ASG to react to the alarm. For this purpose, we define a scaling_action (here a simple Step Action) that will adjust the number of EC2 instances to 1 when the difference between the metric and the alarm threshold is more than 1. Once the action is built, all that remains is to tell the scaling policy to add the action. The trick here is to cast the aws_autoscaling.StepScalingAction into a aws_cloudwatch_actions.AutoScalingAction (the python API does not manage it under the hood yet).</p><h3>Deployment</h3><p>The deployment is the exciting part. It is when we see that our stack actually builds up…. or fail. Thanks to CloudFormation, if something goes wrong during deployment, everything is rolled back, that’s the power of CloudFormation. AWS CDK provides three function to play with our stack: synth, deploy and destroy.</p><h4>Synth</h4><p>The synth function is a kind of compiler where our python script is translated into a YAML file that is understood by CloudFormation. It is also here that the SG ARN for example is retrieve from the existing stack.</p><blockquote>Note: You must specify your credentials and an AWS Region to use the AWS CDK CLI. The CDK looks for credentials and region in the following order:</blockquote><blockquote>* Using the <strong>— profile</strong> option to <strong>cdk</strong> commands.<br>* Using environment variables.<br>* Using the default profile as set by the AWS Command Line Interface (AWS CLI).</blockquote><blockquote>Each Stack instance in your AWS CDK app is explicitly or implicitly associated with an environment (env). An environment is the target AWS account and AWS Region into which the stack is intended to be deployed.</blockquote><blockquote>If you don’t specify an environment when you define a stack, the stack is said to be <em>environment-agnostic</em>. AWS CloudFormation templates synthesized from such a stack will try to use deploy-time resolution on environment-related attributes</blockquote><blockquote>For production stacks, it is recommended to explicitly specify the environment for each stack in the app using the env property.</blockquote><p>Furthermore, as we want to retrive an existing VPC :</p><blockquote>The AWS CDK distinguishes between not specifying the env property at all and specifying it using CDK_DEFAULT_ACCOUNT and CDK_DEFAULT_REGION. The former implies that the stack should synthesize an environment-agnostic template. Constructs that are defined in such a stack cannot use any information about their environment. For example, you can&#39;t write code like if (stack.region === &#39;us-east-1&#39;) or use framework facilities like <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#static-from-wbr-lookupscope-id-options">Vpc.fromLookup</a> (Python: from_lookup), which need to query your AWS account. These features do not work at all without an explicit environment specified; to use them, you must specify env.</blockquote><h4>Deploy</h4><p>The function deploy is obvious, we actually deploy our stack to our AWS account. A YAML file is also built just as with the synth method, but it is now sent to CloudFormation that processes it. You can of course follow the deployment directly onto the console and see your stack building. If anything goes wrong (for example the AMI does not exist), the build-up is rolled back and your stack is not updated/built.</p><h4>Destroy</h4><p>Here again, the function name says all, we can destroy an existing stack. However, the python script must reflect the actual state of the stack. It is obvious because you can not destroy something that has not been deployed yet, but it can have been updated.</p><h3>Conclusion</h3><p>I hope this post will help you architect a simple queue worker stack. The example here uses Amazon SQS and Auto-Scaling Group to better manage the costs. You could reduce even more the costs by using spot instances instead of on-demand instances. For other resources, I suggest you read the great article on <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-using-sqs-queue.html">AWS blog</a> this post is based on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abae64f8e6b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/deploy-your-auto-scaling-stack-with-aws-cdk-abae64f8e6b6">Deploy your Auto-Scaling Stack with AWS-CDK</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>
        <item>
            <title><![CDATA[How to use AWS CodeBuild as a CI for your Python project]]></title>
            <link>https://medium.com/swlh/how-to-use-aws-codebuild-as-a-ci-for-your-python-project-82dd7dab7afb?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/82dd7dab7afb</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 17:02:37 GMT</pubDate>
            <atom:updated>2020-04-21T21:43:19.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LIUb52skB7s2NnjG_iLeA.png" /><figcaption>The Phoenix Project by Gene Kim</figcaption></figure><p>In a <a href="https://medium.com/@GuAndroz/ci-python-project-with-gitlab-157774bed129">previous</a> post, I was presented the trend started somewhere around 2017 aka DevOps. One of the things in this new mantra is the continuous integration and deployment CI/CD that allows devs to continuously test their code to ensure that everything is always up and running. The goal is to maintain a branch or maybe we can call it the trunk of your code repository that is always in a state ready to be deployed.</p><p>How can we ensure that our code is always deployable ? Well, we must continuously test it ! That’s exactly where tools like GitLab are very useful…. but there are very annoying limitations.</p><p>First, if you work on a huge project that runs hundreds of tests, it can be very slow. And secondly, if like me you need some reference files to process in your application, very big files, you need lots of computing power. Often, you are kicked out by the GitLab (or CircleCi or whatever tool you use) even before the tests finish, which is very frustrating. The only thing you can do is running tests on a local machine to ensure that those long lasting unit tests or the high demanding resource integration tests succeeded. That’s ok if there aren’t many devs, but it is not scalable. So what could be a solution ?</p><h3>AWS CodeBuild</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*CZ2dW2UkQUtL8UPSAtwlKw.png" /></figure><p>I like AWS, and whereas I am not an expert, I always find new services that fit my needs. Maybe Amazon devs already had the same issues ? Maybe I’m not alone ?</p><p>Whereas I could not find an exact solution for my usecase, I was able to build one and it works so well ! The idea was to use <em>AWS CodeBuild</em>, because</p><blockquote>AWS CodeBuild is a fully managed continuous integration service that compiles source code, runs tests, and produces software packages that are ready to deploy.</blockquote><p>That’s exactly what I need ! But how is it different from GitLab, CircleCi or Jenkins ? It seems that <em>AWS CodeBuild</em> also runs your code in a Docker container, so why does it suit better my needs ?</p><p>The answer can be found in the AWS “ecosystem”. <em>AWS CodeBuild</em> is indeed the test engine, but it can interact with all other AWS services, and that’s its power.</p><h3>Reference files management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*EV4n9s63SWMQs8aRzVJ4YQ.png" /><figcaption>AWS S3 service</figcaption></figure><p>As I mentioned, I have long lasting tests and some integration tests that process huge data files. The solution with GitLab or similar services is to create our own Docker image and push it on Docker Hub. Fortunately, we can build our image based on the one provided by our test engine. Our custom image contains all the pre-built packages and our reference files. However, it is very annoying and time consuming to rebuild and push an image each time we update or add a reference file. And at the end, we still cannot perform all our tests because of resource limitations.</p><p>With AWS CodeBuild, we can also use your own Docker image. But whereas wcan use a powerful <em>AWS EC2</em> instance to run the tests, we still do not fix the reference files management issue.</p><p>But here is the hack. With <em>AWS CodeBuild</em>, you can specify two code sources.</p><blockquote>With AWS CodeBuild, you can specify two code sources.</blockquote><p>All we have to do is using our source code repository as the main source, and a <em>AWS S3</em> bucket as the second source.That way, all we have to do is updating the files directly in the bucket instead of building a new Docker image. Awesome !</p><h3>Reporting with AWS CodeBuild</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*3OUevq-C4JmpllXgzt8_4Q.png" /><figcaption>AWS CloudBuild service</figcaption></figure><p>In a DevOps context, and especially in a regulated environment, reporting is crucial. We need to prove to auditors or the QA team that everything is running well and we have sane code ready to be deployed.</p><p>The <em>AWS CodeBuild </em>console provides us a rapid overview of the status of our tests, helping us to quickly spot and fix any bug before deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AJ5I5dTQOoN9f34UgS6BUw.png" /><figcaption>AWS CodeBuild console</figcaption></figure><p>AWS <a href="https://aws.amazon.com/fr/blogs/devops/test-reports-with-aws-codebuild/">announced on late 2019</a> a new reporting feature in <em>AWS CodeBuild</em>. This feature allows to view the reports generated by our tests. The reports can be in the JUnit XML or Cucumber JSON format. The same way we can generate an HTML report with <em>pytest-html</em>, we can view metrics such as Pass Rate %, Test Run Duration, and number of Passed versus Failed/Error test cases in one location.</p><p>Test reports created by <em>AWS CodeBuild</em> are stored in Report Group, where they are stored for 30 days. We can also you can store the reports in an <a href="http://aws.amazon.com/s3">Amazon S3</a> bucket as archives. Each test report is further broken down by individual test cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSbQtjccUwcqlHMy5iOMbw.png" /><figcaption>AWS CodeBuild Reports Groups console</figcaption></figure><p>In the <em>Reports</em> tab of the current test, we can find the reports generated by our tests. In the example above, two reports are generated, one for the test coverage and one for the unit and functional tests.</p><p>Each report in each reports group can be further expanded to spot if and which test failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D0gj67B-H4BfgVTLRgnLiQ.png" /><figcaption>AWS CodeBuild Report console</figcaption></figure><p>In the example above, we see that our test run succeeded with 86 pass tests and 6 skipped, no fail test. Furthermore, we can expand each test case and look at the associated log if any.</p><p>Finally, we can view the artifacts that have been saved into <em>AWS S3</em> in a bucket we specified during configuration time. Artifacts are stored there as long as we do not delete them from the bucket and ensure traceability for QA or regulatory audits.</p><h3>AWS CLI to orchestrate the whole thing</h3><h4>Core of the project: the buildspec file</h4><p>As I am somehow a <a href="https://levelup.gitconnected.com/a-good-programmer-is-a-lazy-programmer-8982b2d971bb"><em>lazy</em></a> person, I don’t like to do the same thing twice especially when it can be automated or at least scripted. So first of all, here is a toy-project in python that we can use to test <em>AWS CodeBuild</em>.</p><pre>dummy_project/<br>│<br>├── .buildspec.yml<br>├── setup.py<br>├── README.md<br>├── .gitignore<br>│<br>├── src/<br>│   └── __init__.py<br>│   └── app.py<br>│<br>└── tests/<br>    └── __init__.py<br>    └── test_app.py<br>    └── requirements.txt</pre><p>Nothing exceptional here, just a tiny python project with a bunch of tests. The most important part of this toy project is the <em>buildspec.yml</em> file which details the commands to run a build.</p><blockquote>A <em>buildspec</em> is a collection of build commands and related settings, in YAML format, that CodeBuild uses to run a build. Without a build spec, CodeBuild cannot successfully convert your build input into build output or locate the build output artifact in the build environment to upload to your output bucket.</blockquote><p>Our toy project <em>buildspec</em> details as follow:</p><p><a href="https://gist.github.com/gandroz/7e0414a7b557270d8480298e3775873b">https://gist.github.com/gandroz/7e0414a7b557270d8480298e3775873b</a></p><p>Note that we did not specify here where to find the source code, that will be seen soon after.</p><p>The first part of the <em>buildspec</em> is the pre-build commands. These commands basically install all the needed packages to run tests. In the presented case, it consists in building a virtual environment and installing all the needed python packages and of course the package under test.</p><p>Next, we find the build commands. For our python toy project, the build command is just the call to the <em>pytest</em> command with the options</p><ul><li>— html to generate a HTML report we can store as artifact</li><li>— self-contained-html to incude all the needed CSS and JS directly into the HTML report for offline reading</li><li>-s and -v to increase verbosity and segregate outputs during test</li><li>— cov to generate a coverage report</li><li>— cov-report to indicate where to store the coverage report</li><li>— junitxml to generate a JUnit report used by AWS CodeBuild to populate Reports in a Reports Group</li></ul><p>Finally, we find the report section where we indicate the two CodeBuild Reports we want to generate, one for the test coverage and one for the test results. We’ll see how to tell <em>AWS CodeBuild</em> how to also store the artifacts into <em>AWS S3</em>.</p><h4>Create AWS CodeBuild project with CLI</h4><p>As I said, I like to use scripts to build things for repeatability purpose, and that’s where the AWS CLI comes into play. The CLI command is really simple</p><blockquote>aws codebuild create-project [options]</blockquote><p>I let you find out all the possible options in the <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/getting-started-cli-create-build-project.html">documentation</a>, but here is the JSON file I used to create the project</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62a32d45cd9738cdc69751e008ba3979/href">https://medium.com/media/62a32d45cd9738cdc69751e008ba3979/href</a></iframe><p>I won’t detail all the sections but I refer you to the <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/create-project.html#create-project-cli">documentation</a>.</p><p>The important parts are the source sections. As said, there is a source for the source code (a bitbucket repositorty in my case) and a <em>AWS S3</em> bucket as a second source where I put my reference files. Note that to allow <em>AWS CodeBuild</em> to connect to our repository, we first need to create a token as stated <a href="https://docs.aws.amazon.com/codebuild/latest/userguide/sample-access-tokens.html">here</a>.</p><p>As our tests are computing intensive, we need a large <em>AWS EC2</em> instance defined in the environment section.</p><p>Finally, we specify the <em>AWS S3</em> bucket where to store test artifacts and the group where to log in <em>AWS CloudWatch</em>. This is particularly useful to further trigger alerts or email notifications when tests fail.</p><h4>Create the Report Groups</h4><p>The same procedure is used to create Report Groups where we will store the test results and test coverage.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cad35bae63cc1a6f32c3036ddd3957c/href">https://medium.com/media/8cad35bae63cc1a6f32c3036ddd3957c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ca7f1fcd0dad9e06c1c4ffb496726eb/href">https://medium.com/media/2ca7f1fcd0dad9e06c1c4ffb496726eb/href</a></iframe><h4>Gather CLI commands</h4><p>Finally, all we need is gathering the AWS CLI commands in a bash script so that we can create our <em>AWS CodeBuild</em> project in one simple command. In the following script, I add commands to create the project, run a test and clean/delete the project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50594874ef2788587d2628d704402a9b/href">https://medium.com/media/50594874ef2788587d2628d704402a9b/href</a></iframe><h3>Conclusion</h3><p>In this post, we’ve seen how <em>AWS CodeBuild</em> could help us to run computing intensive tests using a large <em>AWS EC2</em> instance, and use <em>AWS S3</em> as a source of reference files we want to process.</p><p>We gave an example of a python toy project to support the demonstration. We also provided the needed steps to create such a project with the AWS CLI that allows us to script the creation for better reproducibility.</p><p>Finally, we propose how we can orchestrate and gather all these concepts in a simple bash script to create a project, run tests and clean the project in one command.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82dd7dab7afb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-use-aws-codebuild-as-a-ci-for-your-python-project-82dd7dab7afb">How to use AWS CodeBuild as a CI for your Python project</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>
        <item>
            <title><![CDATA[CI Python project with Gitlab]]></title>
            <link>https://guandroz.medium.com/ci-python-project-with-gitlab-157774bed129?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/157774bed129</guid>
            <category><![CDATA[ci]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Fri, 21 Feb 2020 21:30:56 GMT</pubDate>
            <atom:updated>2020-04-09T02:18:20.837Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>DevOps is the new trend, and developers must embrace or …. well you know.</blockquote><p>This is the kind of article I just read this morning, and I must admit that it is indeed clearly a trend. As a Python developer, I try to do my best to be TDD as much as possible. However one thing was still missing until I switched to Gitlab : Continuous Integration and Automated Testing. Gitlab offers a very convenient pipeline for your projects and quite easy to setup. I then created a <a href="https://gitlab.com/gandroz/gitlab_test">dummy project</a>. All you need to do, is adding a YML file to your project and you’re done !</p><h3>Setup</h3><p>Imagine you have a running project with tests associated and you want to run tests automatically after each commit on the master branch. The project structure looks like this</p><pre>gitlab-demo/<br>│<br>├── .gitlab-ci.yml<br>├── README.md<br>├── .gitignore<br>│<br>├── src/<br>│   └── __init__.py<br>│   └── app.py<br>│<br>└── tests/<br>    └── __init__.py<br>    └── test_app.py</pre><h3>Code</h3><p>For this dummy project, we’ll use very useless code just to illustrate our point. Source code can be found <a href="https://gitlab.com/gandroz/gitlab_test">here</a>. The app.py and test_app.py code file can look as follow:</p><h4>src/app.py</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acd5ddb5d4a2d47192788d6f20956fb8/href">https://medium.com/media/acd5ddb5d4a2d47192788d6f20956fb8/href</a></iframe><h4>tests/test.py</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/560157b255fda2e8f44a432073dc9f9d/href">https://medium.com/media/560157b255fda2e8f44a432073dc9f9d/href</a></iframe><h3>Gitlab config file</h3><p>Now, let the magic begins. All you need, is adding a .gitlab-ci.yml file to the project root. For more informations on how to write the YML configuration file, please refer to the <a href="https://docs.gitlab.com/ce/ci/yaml/README.html">documentation</a>.<br>For our simple case, this file is quite short:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f306766a368222038b3bc2465c6dac02/href">https://medium.com/media/f306766a368222038b3bc2465c6dac02/href</a></iframe><p>Let’s now describe the sections of the file</p><h4>image</h4><p>Pipelines are built on a Docker image. You can then specify any image you want, from public ones to private custom ones. And that’s really cool as Gitlab offers a Docker registry for your projects ! For our dummy example, we simply use a light Python 3.6 image.</p><h4>before_script</h4><p>This defines a script (bash) that must be executed before all jobs. In our case, we just print the Python version for debugging purpose.</p><h4>stages</h4><p>That’s where we define the order the different jobs have to be executed. All jobs associated to a stage are run in parallel, and each stage is executed sequentially. If a job fails, subsequent stages/jobs are not executed. In our case, we just defined a single stage <strong>test</strong> , but in real life you might probably want multiple stages, for example <strong>test</strong>, staging , deploy etc.</p><h4>test_job</h4><p>Here you can provide any name for your job. I choose test_job . The rest of the file is then the list of every jobs your CI can run. A job must have at least a script clause. You can refer to the <a href="http://]%20%7Bhttps//docs.gitlab.com/ce/ci/yaml/README.html%7D">documentation</a> for more details on the clauses you can use. In our case, we first specify the stage. As we only have one stage, it is straightforward. Then the core of the file is the script clause. It is a shell script and can contain multiple lines. Then script of our project prints Running tests on screen (useless, but just for the demo), then runs the unittests we defined in the tests folder. We allow here Python to discover the tests to run.</p><h3>Final word</h3><p>And that’s all ! After that, every commit will trigger the pipeline. Of course, you can customize to run only certain jobs on commit of a given branch of your project. You can find details on the documentation page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=157774bed129" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy MLflow with docker compose]]></title>
            <link>https://medium.com/data-science/deploy-mlflow-with-docker-compose-8059f16b6039?source=rss-e9c80b7a94f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8059f16b6039</guid>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Guillaume Androz]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 19:49:30 GMT</pubDate>
            <atom:updated>2021-03-18T13:49:27.387Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine Learning</h4><h4>Track your machine learning experiences with MLflow easily deployed thanks to docker-compose</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOGJFh0tcyMSvbHhI7UO-g.jpeg" /><figcaption><a href="https://unsplash.com/">https://unsplash.com/</a></figcaption></figure><p>When in the process of building and training machine learning models, its very important to keep track of the results of each experiment. For deep learning models, TensorBoard is a very power tool to log training performances, track gradient, debug a model and so on. We also need to track the associated source code, and whereas Jupyter Notebooks are hard to version, we can definitely use a VCS such as git to help us. However, we also need a tool to help us keep track of the experiment context, the choice of hyperparameters, the dataset used for an experiment, the resulting model etc. MLflow has been explicitly developped for that purpose as stated on their website</p><blockquote>MLflow is an open source platform to manage the ML lifecycle, including experimentation, reproducibility and deployment.</blockquote><blockquote><a href="https://mlflow.org/">— https://mlflow.org/</a></blockquote><p>For that purpose, MLflow offers the component MLflow Tracking which is a web server that allows the tracking of our experiments/runs.</p><p>In this post, I will show the steps to setup such a tracking server and I will progressively add components that could eventually be gathered into a docker-compose file. The docker approach is particularly convenient if MLflow has to be deployed on a remote server, for example on EC2, without having to configure the server by hand every time we need a new one.</p><h3><strong>Basic local server</strong></h3><p>The first step to install a MLflow server is straightforward, we only need to install the python package. I will assume that python is installed on your machine and your are confortable with creating a virtual environment. For that purpose, I find conda more convenient than pipenv</p><pre>$ conda create -n mlflow-env python=3.7<br>$ conda activate mlflow-env<br>(mlflow-env)$ pip install mlflow</pre><p>From this very basic first step, our MLflow tracking server is ready to use, all that remains is launching it with the command:</p><pre>(mlflow-env)$ mlflow server</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzC5d6HN9-Tc8oQxTbSg7g.png" /><figcaption><em>Tracking server UI found at </em><a href="http://localhost:5000*"><em>http://localhost:5000</em></a></figcaption></figure><p>We can also specify the host address that tells the server to listen on all public IPs. Although it is a very unsecure approach (the server is unauthenticated and unencrypted), we will further need to run the server behing a reverse proxy such as NGINX or in a virtual private network to control the accesses.</p><pre>(mlflow-env)$ mlflow server — host 0.0.0.0</pre><p>Here the 0.0.0.0 IP tells the server to listen to all incoming IPs.</p><h3><strong>Using AWS S3 as artifact store</strong></h3><p>We now have a running server to track our experiments and runs, but to go further we need to specify the server where to store the artifacts. For that, MLflow offers several possibilities:</p><ul><li>Amazon S3</li><li>Azure Blob Storage</li><li>Google Cloud Storage</li><li>FTP server</li><li>SFTP Server</li><li>NFS</li><li>HDFS</li></ul><p>As my goal is to host a MLflow server on a cloud instance, I’ve chosen to use Amazon S3 as an artifacts store. All we need is to slightly modify the command to run the server as</p><pre>(mlflow-env)$ mlflow server — default-artifact-root      s3://mlflow_bucket/mlflow/ — host 0.0.0.0</pre><p>where mlflow_bucket is a S3 bucket that have been priorly created. Here you would ask “how the hell does MLflow access to my S3 bucket ?”. Well, simply read the <a href="https://www.mlflow.org/docs/latest/tracking.html#artifact-stores">documention</a> hehe</p><blockquote>MLflow obtains credentials to access S3 from your machine’s IAM role, a profile in ~/.aws/credentials, or the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY depending on which of these are available.</blockquote><blockquote>— h<a href="https://www.mlflow.org/docs/latest/tracking.html#artifact-stores">ttps://www.mlflow.org/docs/latest/tracking.html</a></blockquote><p>So the more pratical is to use an IAM role, especially if we want to run the server on an AWS EC2 instance. The use of a profile is quite the same as the use of environment variables but for the illustration, I’ll use environment variables as further explained with the use of docker-compose.</p><h3><strong>Using backend store</strong></h3><h4><strong>SQLite server</strong></h4><p>So our tracking server stores artifacts on S3, fine. However, the hyperparameters, comments and so on are still stores in files on the hosting machine. Files are arguably not a good backend store, and we prefer a database backend. MLflow supports various database dialects (essentially the same as SQLAlchemy): mysql, mssql, sqlite, and postgresql.</p><p>First I like to use SQLite as it is a compromise between files and databases as the whole database is stored in one file that can easily be moved. The syntax is the same of SQLAlchemy:</p><pre>(mlflow-env)$ mlflow server — backend-store-uri sqlite:////location/to/store/database/mlruns.db — default-artifact-root s3://mlflow_bucket/mlflow/ — host 0.0.0.0</pre><h4><strong>MySQL server</strong></h4><p>Keeping in mind that we want to use docker containers, it is not a good idea to store those files locally because we’ll loose the database after each restart of the containers. Of course, we can still mount a volume and an EBS volume on our EC2 instance, but it is cleaner to use a dedicated database server. For that purpose, I like to use MySQL. As we’ll use docker for deployment, let’s postpone the MySQL server installation (as it will be a simple docker container from an official docker image) and focus on MLflow usage. First, we need to install the python driver we want to use to interact with the MySQL. I like pymysql because it is very simple to install, very stable and well documented. So on the MLflow server host, run the command</p><pre>(mlflow-env)$ pip install pymysql</pre><p>and now we can update the command to run the server according to the syntax of SQLAlchemy</p><pre>(mlflow-env)$ mlflow server — backend-store-uri mysql+pymysql://mlflow:strongpassword@db:3306/db — default-artifact-root s3://mlflow_bucket/mlflow/ — host 0.0.0.0</pre><p>where we assume that our server name is db and it listens on port 3306. We also use the user mlflow with the very strong password strongpassword. Here again, it is not very secure in a production context, but when deploying with docker-compose, we can use environment variables.</p><h3><strong>NGINX</strong></h3><p>As mentionned earlier, we’ll use the MLflow tracking server behind a reverse proxy, NGINX. For that, here again we’ll use an official docker image and simply replace the default configuration /etc/nginx/nginx.conf by the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c1fe88cf570d9bbc0803ecd80a8acab/href">https://medium.com/media/2c1fe88cf570d9bbc0803ecd80a8acab/href</a></iframe><p>You can play with this basic configuration file if you need further customization. And finally, we’ll make a configuration for the MLflow server we’ll store in /etc/nginx/sites-enabled/mlflow.conf</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91da7b4ed1e5f30db20195bd9807fd46/href">https://medium.com/media/91da7b4ed1e5f30db20195bd9807fd46/href</a></iframe><p>Notice the URL used to refer to the MLflow application <a href="http://web:5000.">http://web:5000.</a> The MLflow server uses the port 5000, and the app will run in a docker-compose service which name will be web.</p><h3><strong>Containerization</strong></h3><p>As stated before, we want to run all of these in docker containers. The architecture is simple and is composed of three containers:</p><ul><li>A MySQL database server,</li><li>A MLflow server,</li><li>A reverse proxy NGINX</li></ul><p>For the database server, we’ll use the official MySQL image without any modification.</p><p>For the MLflow server, we can build a container on a debian slim image. The Dockerfile is very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a7daa059b00bc0fede208b5a8a704f2/href">https://medium.com/media/2a7daa059b00bc0fede208b5a8a704f2/href</a></iframe><p>And finally the NGINX reverse proxy is also based on the official image plus the configuration presented before</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a769f1fe9c42c3005dc3e9d4a830dbad/href">https://medium.com/media/a769f1fe9c42c3005dc3e9d4a830dbad/href</a></iframe><h3><strong>Gather with docker-compose</strong></h3><p>Now we have all set, it’s time to gather it all in a docker-compose file. It will then be possible to launch our MLflow tracking server with only command, which is very convenient. Our docker-compose file is composed of three services, one for the backend i.e. a MySQL database, one for the reverse proxy and one for the MLflow server itself. It looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eac2bdf5c2a2a979d6457f9cb52140d/href">https://medium.com/media/1eac2bdf5c2a2a979d6457f9cb52140d/href</a></iframe><p>First thing to notice, we have built two custom networks to isolate frontend (MLflow UI) with backend (MySQL database). Only the web service i.e. the MLflow server can talk to both. Secondly, as we don’t want to loose all the data as the containers go down, the content of the MySQL database is a mounted volume named dbdata. Lastly, this docker-compose file will be launched on an EC2 instance, but as we do not want to hard-code AWS keys or database connection string, we use environment variables. Those environment variables can be located directly on the host machine or inside an .env file in the same directory as the docker-compose file. All that remains is building and running the containers</p><pre>$ docker-compose up -d --build </pre><p>The -d option tells that we want to execute the containers in daemon mode, and the --build option indicates that we want to build the docker images if needed before running them.</p><p>And that’s all ! We now have a perfectly running remote MLflow tracking server we can share between our team. This server can easily be deployed anywhere with only one command thanks to docker-compose.</p><p>Happy machine learning !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8059f16b6039" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deploy-mlflow-with-docker-compose-8059f16b6039">Deploy MLflow with docker compose</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>