<?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 Pavlos Mitsoulis on Medium]]></title>
        <description><![CDATA[Stories by Pavlos Mitsoulis on Medium]]></description>
        <link>https://medium.com/@pavlosmitsoulis?source=rss-1ec579663bf0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4HG2U7sU3Gk_89sC.jpg</url>
            <title>Stories by Pavlos Mitsoulis on Medium</title>
            <link>https://medium.com/@pavlosmitsoulis?source=rss-1ec579663bf0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 11:02:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pavlosmitsoulis/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[How to Deploy a Machine Learning Model as a Streaming Application]]></title>
            <link>https://pavlosmitsoulis.medium.com/how-to-deploy-a-machine-learning-model-as-a-streaming-application-a16e4c2d3959?source=rss-1ec579663bf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a16e4c2d3959</guid>
            <category><![CDATA[ml-model-deployment]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[aws-sagemaker]]></category>
            <dc:creator><![CDATA[Pavlos Mitsoulis]]></dc:creator>
            <pubDate>Tue, 23 Feb 2021 21:10:55 GMT</pubDate>
            <atom:updated>2021-02-23T21:10:55.939Z</atom:updated>
            <content:encoded><![CDATA[<p>Streaming based machine learning predictions are very useful when it comes to high traffic and democratizing predictions of models in organizations.</p><p>Let’s examine a use case where a streaming based machine learning system is more efficient compared to real-time (synchronous) predictions (RESTful in most cases) and batch predictions.</p><p>You’re leading the recommenders system team at a e-commerce company and your goal is to develop a model that will power product recommendation carousels in many parts of the website using the same model. After some data analysis, you concluded that recent user behaviour is crucial signal for delivering high quality product recommendations. Therefore, a batch based recommender system is not the best option.</p><p>How about deploying the recommender model as a REST API? One naive way to architect this solution is to call the recommender model every time a user lands on a page of the website where a product recommendation carousel is served. The problem here is that this piece of client code will need potentially to calculate the required features and call the model through a REST API. Another option is to build a REST service that would get as input the user id and get back the recommended products. This REST service will need to query some database that keeps a state of the user in order to calculate the required features and call the model.</p><p>The problem is that you need to add the same client code on many parts of the website and that makes it very hard to maintain it. Also, it would be challenging to deal with high traffic.</p><p>If you have already set up a clickstream infrastructure (usually <a href="https://kafka.apache.org/">Kafka</a> or <a href="https://aws.amazon.com/kinesis/">AWS Kinesis</a>) that captures all user actions on your website, you can create a streaming application that subscribes to specific events, generates the appropriate features, calls the REST API with these features and forwards the predictions to some other topic. Then, your application engineers can subscribe to this topic and use the output on any part of the website. You could even set up a pipeline that pushes predictions from the latter topic to a NoSQL database (such as <a href="https://cassandra.apache.org/">Cassandra</a> or <a href="https://aws.amazon.com/dynamodb/">DynamoDB</a>) and build an API in front of this database in order to provide multiple patterns of access to these predictions.</p><p>Let’s talk about democratizing predictions of models in organizations now! The latter mentioned approach of having model predictions in some <a href="https://kafka.apache.org/">Kafka</a> topic and in a NoSQL database will enable any product/engineering team to access them without having to call your REST API services that comes at the cost of integration and putting unnecessary traffic burden on it.</p><p>So, how about having a MLOps tool where data scientists and ML scientists/engineers only have to specify the prediction logic of their trained model in a predict(input_json) Python function, and then this tool will automatically deploy this model as a REST API and set up a streaming pipeline around it.</p><p>Yes, you can do it now with <a href="https://github.com/Kenza-AI/sagify">Sagify</a> (from version 0.21.0)! I’m excited to announce the new experimental <a href="https://github.com/Kenza-AI/sagify">Sagify</a> feature for setting up streaming based prediction pipelines!</p><p>As you see in the diagram below, you can create with 2 CLI commands:</p><ul><li>The model REST API, i.e. deploy the trained model as a REST API</li><li>The streaming based prediction pipeline: a) Features topic, b) Model Prediction Streaming App and c) Model Predictions topic</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2pRsWHTkj3W2ya2-iEE0Kw.png" /></figure><p>But how? Let’s assume that your trained model is stored at s3://my-bucket/recommender-model-outputs/output-1/model.tar.gz . The first step is to deploy this model as a REST API:</p><p>sagify cloud deploy -m s3://my-bucket/recommender-model-outputs/output-1/model.tar.gz -n 1 -e ml.m4.xlarge</p><p>This command will deploy your trained model in 1 EC2 instance of type m4.xlarge and will return the endpoint name (let’s assume it’s my-recommender-endpoint-1 )</p><p>The second step is to set up the streaming based prediction pipeline:</p><p>sagify cloud create-streaming-inference --name recommender-worker --endpoint-name my-recommender-endpoint-1 --input-topic-name features --output-topic-name model-predictions --type SQS</p><p>This command will create a <a href="https://aws.amazon.com/lambda/">Lambda</a> function with name recommender-worker that will consume features from the <a href="https://aws.amazon.com/sqs/">SQS</a> queue features , then, it will call the endpoint my-recommender-endpoint-1 for each features message and, finally, forward the predictions to the <a href="https://aws.amazon.com/sqs/">SQS</a> queue model-predictions .</p><p>It’s so easy! Please, check out the <a href="https://kenza-ai.github.io/sagify/#cloud-create-streaming-inference">docs</a> for more info!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a16e4c2d3959" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Multi-Armed-Bandits can help us in the fight for Covid-19 — Part 1]]></title>
            <link>https://medium.com/analytics-vidhya/how-multi-armed-bandits-can-help-us-in-the-fight-for-covid-19-part-1-6dac796851b4?source=rss-1ec579663bf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dac796851b4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[multi-armed-bandit]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Pavlos Mitsoulis]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 14:08:45 GMT</pubDate>
            <atom:updated>2020-03-31T04:52:13.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Multi-Armed-Bandits can help us in the fight for Covid-19 — Part 1</h3><p>I’m an AWS ML Hero and I was thinking how Reinforcement Learning and AWS can help to make the distribution of Covid-19 test kits in a more effective and efficient manner. Why? Identifying as many people who are infected as possible looks to be one of the key things to minimize or stop the spread of Covid-19. This looks to be one of the reasons why South Korea managed to flatten the curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OfZhQS02MxMgyWxB3dxKTA.png" /><figcaption>Source: <a href="http://91-divoc.com/pages/covid-visualization/">http://91-divoc.com/pages/covid-visualization/</a></figcaption></figure><p>So, let’s define first what Multi-Armed-Bandits (MABs) are. First of all it’s a Reinforcement Learning methodology. <strong>You’re faced repeatedly with the problem of choosing among <em>k </em>different options or actions or arms. After each choice/decision you receive a numerical reward. Each arm’s reward is associated with a stationary probability distribution which is unknown. Your objective is to maximize the expected total reward over some time period or discrete time steps.</strong></p><p>Some Multi-Armed-Bandit Examples:</p><ul><li>A doctor choosing between experimental treatment for a series of seriously ill patients (from <em>Reinforcement Learning: An Introduction by Richard Sutton and Andrew Barto)</em></li><li>An ad system choosing which ad to show on which website</li><li>A recommender system choosing which articles to show on the home page</li></ul><p>Given all this information, I’m pretty sure you have already started shaping in your heads a Covid-19 MAB problem definition. Here’s the problem definition:</p><ul><li>There are <em>M</em> areas. It’s similar to the boroughs (Camden, Islington, Westminster, etc) in London, for example.</li><li>We assume that given the current lockdowns, people don’t move between areas/boroughs or there is a very small percentage of them that have to.</li><li>There is a central factory between these areas that manufactures Coviv-19 test kits in an ongoing basis.</li><li>Whenever a new test kit is produced, a choice has to be made which area/borough it should be delivered to.</li><li><strong>So, areas are the arms of this MAB problem and the objective is to maximize the number of true positives.</strong></li></ul><p>I know that this problem doesn’t align with all the theoretical assumptions of MABs but the main purpose of this blog post is to spark new ideas!</p><p>The main assumption of this problem definition is that it assumes that each area/borough has stationary probability distributions for true positives. Probably, they’re not but later on in another part, we’ll address this issue!</p><p>Let’s try out a simple MAB solution, <em>Epsilon-Greedy or E-Greedy. </em>Here’s the pseudocode (source: <em>Reinforcement Learning: An Introduction by Richard Sutton and Andrew Barto)</em>:</p><pre>ε &lt;- user_input()  // In range (0.0, 1.0). User defines this.<br>Initialize, for a = 1 to k:  // k is number of arms<br>   Q(a) &lt;- 0  // estimated rewards per arm a<br>   N(a) &lt;- 0  // number of times arm a is chosen</pre><pre>Loop forever:<br>   random_number &lt;- random()  // random number in [0.0, 1)<br>   if (random_number &lt; ε):  // exploration part<br>      A &lt;- choose a random arm a<br>   else:  // exploitation part<br>      A &lt;- argmax Q(a)  // choose arm with highest Q(a) so far<br>   <br>   R &lt;- bandit(A)  // receive reward for chosen arm<br>   N(A) &lt;- N(A) + 1<br>   Q(A) &lt;- Q(A) + 1/N(A)[R - Q(A)]</pre><p>First of all, let’s implement the <em>EGreedy</em> algorithm.</p><pre>import numpy as np</pre><pre>class EGreedy:<br>    &quot;&quot;&quot;<br>    Implementation of EGreedy algorithm as described in Section 2 of book:<br>    Reinforcement Learning: An Introduction (Version 2)<br>    Richard S. Sutton and Andrew G. Barto<br>    &quot;&quot;&quot;<br>    def __init__(self, k, epsilon=0.1):<br>        &quot;&quot;&quot;<br>        Constructor of EGreedy<br>        :param k: [int], number of arms. 0-based indexing.<br>        :param epsilon: [float, default=0.1], epsilon value in range (0.0, 1.0) for exploration<br>        &quot;&quot;&quot;<br>        self.k = k<br>        self.epsilon = epsilon<br>        self.rewards = np.asarray([0.0 for _ in range(k)])<br>        self.steps = np.asarray([0 for _ in range(k)])</pre><pre>def reset(self):<br>        self.rewards = np.asarray([0.0 for _ in range(self.k)])<br>        self.steps = np.asarray([0 for _ in range(self.k)])</pre><pre>def choose(self):<br>        random_number = np.random.uniform(0.0, 1, 1)[0]</pre><pre>if random_number &lt; self.epsilon:<br>            return np.random.choice(self.k, 1, replace=False)[0].item()<br>        else:<br>            return np.argmax(self.rewards, axis=0)</pre><pre>def feedback(self, arm_id, reward):<br>        self.steps[arm_id] += 1<br>        self.rewards[arm_id] += (1 / self.steps[arm_id]) * (reward - self.rewards[arm_id])</pre><p>Then, we have to define the stationary probability distributions of infected people per area/borough. I’ll use Beta Distribution for this kind of distributions, and parameters <em>a/b</em> define the ratio <em>infected/non_infected</em> people. Let’s assume that there are <em>M=5</em> areas.</p><ul><li>Area 1 has a <em>Beta(a=10, b=2)</em></li><li>Area 2 has a <em>Beta(a=4, b=2)</em></li><li>Area 3 has a <em>Beta(a=2, b=2)</em></li><li>Area 4 has a <em>Beta(a=2, b=4)</em></li><li>Area 5 has a <em>Beta(a=2, b=6)</em></li></ul><p>As you can see from the distributions plotted below, area 1 has the highest probability of finding infected people. The next one is area 2 and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*eex0mfKfCjOkvmUn0QMbzg.png" /><figcaption>Infection Probability Distribution for Area 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*-6fekQAxXcZqDErcDp_NAw.png" /><figcaption>Infection Probability Distribution for Area 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*kq9U9HfmiptGthVhowFSnw.png" /><figcaption>Infection Probability Distribution for Area 3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*6ZJKy2LmfsxeImwvsFxRag.png" /><figcaption>Infection Probability Distribution for Area 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*zgQlvFltp0qrwSriix8_xw.png" /><figcaption>Infection Probability Distribution for Area 5</figcaption></figure><p>The next thing we need to implement is the simulation part. Here’s the pseudocode:</p><pre>egreedy = initialize_egreedy()<br>for i=1 to num_test_kits:<br>    area &lt;- egreedy.choose()  // choose an area to send this kit<br>    beta_distro &lt;- find_distro(area)  // find distro of area<br>    random &lt;- random()  // random number in [0.0, 1) uniform distro<br>    if random &lt; beta_distro.draw():<br>       reward = 1  // found an infected person using this kit<br>    else:<br>       reward = 0  // this kit was used on a non infected person</pre><pre>    egreedy.feedback(area, reward)</pre><p>As you can see, every newly created test kit is sent to an area and used on a person of this area. Then, a number is sampled from the Beta Distribution of this area to determine if the test kit was used on an infected person or not. We assume that the test kit is perfect (no false positives and no false negatives).</p><p>The expected reward rate chart after running the simulation for 5,000 test kits is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*_IWxIIiYIJFlDxsoYseV0w.png" /></figure><p>and the distribution of test kits between the areas is:</p><ul><li>Area 1: 4594</li><li>Area 2: 92</li><li>Area 3: 114</li><li>Area 4: 102</li><li>Area 5: 98</li></ul><p>This simple online MAB algorithm distributed most of the test kits to the area with the most infected people but didn’t distribute them “fairly” in the rest areas. But, we still have a big improvement from nothing!</p><p>Stay tuned! In the next part, I’ll show you how to deploy this algorithm on AWS and how to improve the distribution of test kits in an ordered manner.</p><p>PS: Github repo: <a href="https://github.com/pm3310/mab-covid19">https://github.com/pm3310/mab-covid19</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dac796851b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-multi-armed-bandits-can-help-us-in-the-fight-for-covid-19-part-1-6dac796851b4">How Multi-Armed-Bandits can help us in the fight for Covid-19 — Part 1</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SageMaker Reinforcement Learning: From Zero to Hero]]></title>
            <link>https://pavlosmitsoulis.medium.com/sagemaker-reinforcement-learning-from-zero-to-hero-b6897d13f7c7?source=rss-1ec579663bf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6897d13f7c7</guid>
            <category><![CDATA[cartpole]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Pavlos Mitsoulis]]></dc:creator>
            <pubDate>Sat, 15 Jun 2019 10:24:25 GMT</pubDate>
            <atom:updated>2019-06-15T10:24:25.867Z</atom:updated>
            <content:encoded><![CDATA[<p>Do you remember the days at university studying AI and Reinforcement Learning theories before the last decade’s AI boom? <strong>YES! :-)</strong></p><p>I’m pretty sure that you were also exposed to some toy examples, such as finding your way in a Maze or the Atari Pong game. Then, you asked yourself “Amazing! I can solve real problems now!” So, you turned on your laptop but you realized that you were missing some important parts:</p><ol><li>Are there simulators/environments (such as open AI Gym) to mimic a real-world scenario?</li><li>Are there mature RL libraries out there to develop RL algorithms and test them on environment?</li><li>Do these RL libraries (if they exist) make it easy to apply RL theory in practice?</li><li>Can I easily train my own RL algorithms somewhere apart from my laptop ?</li></ol><p>Machine Learning and Deep Learning have made so much impact these days because there are easy and quick answers for similar questions with the above ones! In case of Deep Learning:</p><ol><li><strong>Where can I find a realistic dataset?</strong> That can be the equivalent of environments. Plenty of open realistic datasets in Kaggle and other sources. For example, <a href="https://www.kaggle.com/c/quora-insincere-questions-classification">https://www.kaggle.com/c/quora-insincere-questions-classification</a></li><li><strong>Are there mature libraries out there to train DL algorithms?</strong> YES! Tensorflow, Keras, Pytorch, <a href="https://mxnet.apache.org/">MXNet</a>, Chainer, etc</li><li><strong>Do these DL libraries (if they exist) make it easy to apply DL theory in practice?</strong> Of course, you need a few lines of code for Convolution Neural Network in Keras as depicted in Figure 1.</li><li><strong>Can I easily train my own DL algorithms somewhere apart from my laptop?</strong> <a href="https://aws.amazon.com/sagemaker/features/">AWS SageMaker</a> is here to the rescue! It’s a mature and easy to use ML infrastructure!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*jox8cVJtF1JF6zEE9xvmEw.png" /><figcaption>Figure 1</figcaption></figure><p>You heard that DeepMind published in 2013 a famous paper, <a href="https://arxiv.org/abs/1312.5602">Playing Atari with Deep Reinforcement Learning</a>, in which they introduced a new algorithm called Deep Q Network (DQN). You even watched a <a href="https://www.youtube.com/watch?v=V1eYniJ0Rnk">clip</a> that shows the DQN in action! Then, you asked yourself “Is there any similarity between DQN and Q-Learning that I was taught at university?”. You read the paper and discovered that there is. And, more specifically, DQN uses a neural network to approximate the reward function based on the state <em>Q(s, a)</em> where <em>s</em> is and <em>a</em> is action.</p><p>Here is an implementation of <a href="https://github.com/keon/deep-q-learning">DQN</a> in Keras:</p><pre>import random<br>import numpy as np<br>from collections import deque<br>from keras.models import Sequential<br>from keras.layers import Dense<br>from keras.optimizers import Adam</pre><pre>class DQNAgent:<br>    def __init__(self, state_size, action_size):<br>      self.state_size = state_size<br>      self.action_size = action_size<br>      self.memory = deque(maxlen=2000)<br>      self.gamma = 0.95 # discount rate<br>      self.epsilon = 1.0 # exploration rate<br>      self.epsilon_min = 0.01<br>      self.epsilon_decay = 0.995<br>      self.learning_rate = 0.001<br>      self.model = self._build_model()</pre><pre>    def _build_model(self):<br>        # Neural Net for Deep-Q learning Model<br>        model = Sequential()<br>        model.add(Dense(24, input_dim=self.state_size, activation=’relu’))<br>        model.add(Dense(24, activation=’relu’))<br>        model.add(Dense(self.action_size, activation=’linear’))<br>        model.compile(loss=’mse’,<br>            optimizer=Adam(lr=self.learning_rate))<br>        return model</pre><pre>    def remember(self, state, action, reward, next_state, done):<br>        self.memory.append((state, action, reward, next_state, done))</pre><pre>    def act(self, state):<br>        if np.random.rand() &lt;= self.epsilon:<br>            return random.randrange(self.action_size)<br>        act_values = self.model.predict(state)<br>        return np.argmax(act_values[0]) # returns action</pre><pre>    def replay(self, batch_size):<br>        minibatch = random.sample(self.memory, batch_size)<br>        states, targets_f = [], []<br>        for state, action, reward, next_state, done in minibatch:<br>            target = reward<br>            if not done:<br>                target = (reward + self.gamma *<br>                      np.amax(self.model.predict(next_state)[0]))<br>            target_f = self.model.predict(state)<br>            target_f[0][action] = target <br>            # Filtering out states and targets for training<br>            states.append(state[0])<br>            targets_f.append(target_f[0])<br>        history = self.model.fit(np.array(states),         np.array(targets_f), epochs=1, verbose=0)<br>        # Keeping track of loss<br>        loss = history.history[‘loss’][0]<br>        if self.epsilon &gt; self.epsilon_min:<br>            self.epsilon *= self.epsilon_decay<br>        return loss</pre><p>Now, you’re familiar with theory and implementation behind DQN, and you want to try it out on a different problem, the CartPole game. The goal of CartPole is to balance a pole connected with one joint on top of a moving cart. Instead of pixel information, there are 4 kinds of information given by the state, such as angle of the pole and position of the cart. An agent can move the cart by performing a series of actions of 0 or 1 to the cart, pushing it left or right.</p><p><strong>You just realized that you need to find an environment that simulates the CartPole problem! </strong><a href="https://gym.openai.com/"><strong>OpenAI Gym</strong></a><em> </em>offers you a collection of various already implement environments (such as CartPole) and the ability to create your own custom one.</p><p>Then, you need a framework that trains RL algorithms in various environments. <a href="https://github.com/NervanaSystems/coach">Coach</a> is a Python framework that enables you choose an environment (for example, OpenAI Gym) and a state-of-the-art RL algorithm implementation in order to compare the performance of various algorithms in a reliable and reproducible way. It uses Deep Learning libraries (such as <a href="https://www.tensorflow.org/">Tensorflow</a> and <a href="https://mxnet.apache.org/">MXNet</a>) to define RL algorithms. Additionally, it gives you the ability to implement your own RL algorithm without worrying about low-level details.</p><p>Finally, you need a RL cloud infrastructure to run all the above without worrying about computational resources.</p><p><strong>You’re lucky! There is an example of solving the CartPole problem on SageMaker!</strong></p><p>For the sake of brevity, I will only highlight the most important code snippets. You’ll find the complete example on <a href="https://github.com/Kenza-AI/sagemaker_rl_template">Github</a> that uses <a href="https://github.com/NervanaSystems/coach">Coach</a> and <a href="https://mxnet.apache.org/">MXNet</a>.</p><p><a href="https://aws.amazon.com/sagemaker/features/">SageMaker RL</a>, which is one great feature of <a href="https://aws.amazon.com/sagemaker/features/">AWS SageMaker</a>, puts everything together. <strong>Hence, it bridges theory and practice</strong>!</p><p>You need to define the RL algorithm (<em>DQNAgentParameters()</em>) and the preset of the algorithm in the Coach graph (Python script <em>src/preset-cartpole-dqn.py</em>). Easy, right? You don’t have to implement the DQN. It’s already implemented for you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*fc4L0qJiB6HW-xHx4Z6rAg.png" /><figcaption>Figure 2</figcaption></figure><p>The Python script <em>src/train-coach.py</em> contains the code that kicks off and manages the training. It also overrides some of the parameters.</p><p>Then, you use the <a href="https://sagemaker.readthedocs.io/en/stable/">SageMaker Python SDK</a> to define a <em>RLEstimator</em> that handles the training where we define the following</p><ol><li>The entry point script</li><li>Any dependency python files</li><li>The toolkit (i.e. environment)</li><li>The Deep Learning framework (i.e. Tensorflow or MXNet)</li><li>EC2 instance type</li><li>…</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*N62vEY9I1KX_xkHptnEebQ.png" /><figcaption>Figure 3</figcaption></figure><p>Figure 4 depicts the increase of training reward as more and more episodes are created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*3BrycX0vFKRpYODV35nz6A.png" /><figcaption>Figure 4</figcaption></figure><p>Finally, it’s really cool that you can deploy the trained RL model as a REST Endpoint!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbCbjYV_ER7mVp54Aq696A.png" /><figcaption>Figure 5</figcaption></figure><p>And don’t forget to delete the endpoint and save some money :-)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t8XYjWXCs32EOtY9C4Ar2g.png" /></figure><p><strong>Next time, I’ll show you how to create a custom environment for Atari Pong game!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6897d13f7c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sagify: Training and Deploying ML/DL models on AWS SageMaker made simple]]></title>
            <link>https://medium.com/kenza-ai/training-and-deploying-ml-dl-models-on-aws-sagemaker-made-simple-e1132719838d?source=rss-1ec579663bf0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1132719838d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Pavlos Mitsoulis]]></dc:creator>
            <pubDate>Mon, 21 May 2018 19:14:28 GMT</pubDate>
            <atom:updated>2018-05-21T20:15:39.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHiIWLOoCTvxUB1yu4OS_A.png" /></figure><p>As a Data Scientist or Machine Learning engineer, I’m sure you have faced the following situation: you are working on a Machine Learning or Deep Learning project, and you need to train and deploy your models in production. But you had enough creating your own recipe scripts to train the models on the cloud (AWS, Google Cloud, etc) or waiting for ages to train the models locally on your workstation.</p><p><strong>This is why you started using </strong><a href="https://aws.amazon.com/sagemaker/"><strong>AWS SageMaker</strong></a><strong>!</strong> However, it is still not straightforward to deploy your own training/prediction code on SageMaker. You know, AWS is like IKEA! They provide you with all the required processed parts, screws, screwdrivers but at the end of the day it is still your responsibility to follow the instructions correctly and connect all the bits and pieces in the right way. What if you don’t want to go through all this hassle?</p><p>For those of you not looking to assemble your next IKEA library, but deploy your next Machine Learning or Deep Learning project on SageMaker, <a href="https://github.com/Kenza-AI/sagify"><strong>Sagify</strong></a><strong> comes to the rescue!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UHxP3ahrWPFlOePpuiMzg.gif" /></figure><p>So, wouldn’t it be AWESOME to code your own training logic, as you usually do, and then call a simple command from the terminal to execute it on AWS like this:</p><pre>sagify cloud train -d local-src-dir/ -i s3://my-bucket/training-data/ -o s3://my-bucket/model-output/ -e ml.m4.xlarge</pre><p>There are clear benefits in using the above command:</p><ol><li>No need to move data to your code, but code goes to data (-i s3://my-bucket/training-data/).</li><li>Trained models are saved in timestamped subfolders under s3://my-bucket/model-output/, for example: s3://my-bucket/model-output/my-code-2018–04–29–15–04–14–483/model.tar.gz</li><li>Easy way to specify EC2 instance.</li><li>Code is deployed to AWS in a Docker image and pushed to <a href="https://aws.amazon.com/ecs/">AWS ECS</a>.</li><li>Training data from S3 are available to EC2 instance’s EBS storage seamlessly.</li></ol><p>Let’s dive into an example on how to use <strong>Sagify</strong>. Please, follow the <strong>Getting Started</strong> section in <a href="https://kenza-ai.github.io/sagify/">docs</a> for a complete walkthrough. Here is the gist of it:</p><h4>Step 1:</h4><p>Clone a Deep Learning codebase that will evaluate arithmetic additions on up to 3 digit integers git clone <a href="https://github.com/Kenza-AI/deep-learning-addition.git">https:</a><a href="https://github.com/Kenza-AI/deep-learning-addition.git"><em>//github.com/Kenza-AI/deep-learning-addition.git</em></a></p><h4>Step 2:</h4><p>Initialize <strong>Sagify</strong> by executing the following command on your terminal:sagify init -d src</p><h4>Step 3:</h4><p>Call your training logic in train(…) function in sagify/training/train file like:</p><pre>try:<br>    my_train_logic(<br>         input_path=input_data_path,<br>         output_path=model_save_path<br>    )<br>    print(&#39;Training complete.&#39;)<br>except Exception as e:</pre><h4>Step 4:</h4><p>Build the Docker image that will contain your code: sagify build -d src -r requirements.txt</p><h4>Step 5:</h4><p>Push the code to AWS ECS: sagify push -d src</p><h4>Step 6 (Optional):</h4><p>Upload the data to S3, if they are not already available there:</p><p>sagify cloud upload-data -d src -i data/processed/ -s s3://my-dl-addition/training-data</p><h4>Step 7:</h4><p>Finally, train your model on AWS SageMaker:</p><p>sagify cloud train -d src/ -i s3://my-dl-addition/training-data/ -o s3://my-dl-addition/output/ -e ml.m4.xlarge</p><p>I’m pretty sure that some of you have spotted something important here. The above commands can be orchestrated by tools such as <a href="https://github.com/apache/incubator-airflow">Airflow</a> to automate your training pipeline! <strong>Why is this important</strong>?</p><ol><li>No more manual execution of training.</li><li>Keep track of training code, hyperparameters, trained models, etc on a storage like S3.</li><li>Avoid situations like “it works on my laptop”.</li><li>Catch issues early rather than later.</li><li>Increase visibility enabling greater communication.</li><li>Spend less time debugging and more time adding features.</li></ol><p>Do these points remind you of anything?</p><p>Well, these are some of the benefits of <a href="https://www.thoughtworks.com/continuous-integration">Continuous Integration/Continuous Delivery</a>! At the end of the day, you want your Machine Learning and Deep Learning models to be part of a software system, so you still have to follow Software Engineering Best Practices alongside Machine Learning Best Practices!</p><h3>About Kenza</h3><p><a href="https://github.com/Kenza-AI/sagify"><strong>Sagify</strong></a> is open sourced by the team behind <a href="https://www.producthunt.com/upcoming/kenza-ai"><strong>Kenza</strong></a><strong>, </strong>one of the winners of Product Hunt Global Hackathon. We are currently working on a Continuous Integration solution for Machine Learning on top of open source projects! <a href="https://github.com/Kenza-AI/sagify"><strong>Sagify</strong></a> is one them as we believe in <strong>openness, sharing</strong> and <strong>passion for Machine Learning!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMwmUE6uDHfm5HN8RtxsiQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1132719838d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kenza-ai/training-and-deploying-ml-dl-models-on-aws-sagemaker-made-simple-e1132719838d">Sagify: Training and Deploying ML/DL models on AWS SageMaker made simple</a> was originally published in <a href="https://medium.com/kenza-ai">Kenza Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>