<?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 Natarajan C on Medium]]></title>
        <description><![CDATA[Stories by Natarajan C on Medium]]></description>
        <link>https://medium.com/@natarajan8993?source=rss-3df072833a91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LySEr7WlNDVa5AoZQM2eIg.jpeg</url>
            <title>Stories by Natarajan C on Medium</title>
            <link>https://medium.com/@natarajan8993?source=rss-3df072833a91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:38:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@natarajan8993/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[What, Why and How to Build a Custom Environment Using OpenAI Gym for Reinforcement Learning (RL)]]></title>
            <link>https://medium.com/data-science-from-signify-research-eindhoven/what-why-and-how-to-build-a-custom-environment-using-openai-gym-for-reinforcement-learning-rl-76c951d75af3?source=rss-3df072833a91------2</link>
            <guid isPermaLink="false">https://medium.com/p/76c951d75af3</guid>
            <category><![CDATA[openai-gym]]></category>
            <category><![CDATA[rl-training-and-testing]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[custom-environment]]></category>
            <dc:creator><![CDATA[Natarajan C]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 11:11:07 GMT</pubDate>
            <atom:updated>2020-11-13T11:11:07.305Z</atom:updated>
            <content:encoded><![CDATA[<h4>Quick Introduction to Reinforcement Learning and Building Custom Environment With OpenAI Gym</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ETuq0UiZZcrED_z9" /><figcaption>Photo by <a href="https://unsplash.com/@feelfarbig?utm_source=medium&amp;utm_medium=referral">Feelfarbig Magazine</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Reinforcement Learning (RL) is an area of machine learning in which an agent continuously interacts with the environment where it operates to establish a policy — a mapping between environment states and action- that maximizes an expected reward. RL is particularly suited for decision-making problems that need to trade-off between long term and short term rewards and where the environment is complex and uncertain.</p><p>Reinforcement Learning usage in a real-life application has become more widespread due to both the advancements in the algorithms as well as the available toolkits. In this article, I will give a basic introduction to RL and how to use an open-source toolkit, OpenAI Gym, to define your very own RL problem in a custom environment.</p><h3><strong>Let’s Start With An Example</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g7P-can6U_Xra-4e" /><figcaption>Photo by <a href="https://unsplash.com/@rodrigospabreu?utm_source=medium&amp;utm_medium=referral">Rodrigo Abreu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For the sake of simplicity, let’s take a factious example to make the concept of RL more concrete.</p><p>Imagine we need to ship goods from a port to a location present inland. There are 3 classes of trucks present to do this job. The goal is to decide which class of truck takes which goods to the designated location to reach on time and get maximum profit.</p><p><strong>For delivering the goods we have three available classes of trucks.</strong></p><p>a. Short trip — trucks that are suitable for delivering the goods within 50km</p><p>b. Medium trip — trucks that can be used for transporting goods to a location within 200km</p><p>c. Long trip — trucks that can be used for delivering the goods to the locations beyond 200km</p><p>One of the <strong>constraint </strong>here is that short trip trucks cannot be used for a long distance delivery; but, long trip trucks can be used for a short distance delivery. Our main <strong>goal </strong>is to deliver the goods on time while achieving maximum efficiency or profit. We have many factors to consider such as fuel consumed, driver’s salary, and charges for time spent in loading and unloading the truck. This is a kind of problem RL can be very useful for. So, let me first give a short intro to the basics of RL below.</p><h3>Basics of RL</h3><p>RL model is a decision-making model that learns what to do next under the current scenario to perform efficiently or to reach the goal. Any RL problem is formulated as a Markov decision process (MDP) to capture the behavior of the environment through observation, action and reward. The common terminologies and their interaction is explained further below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*xQQacEzDeiwHsGKZe1GPjw.jpeg" /><figcaption>RL — agent and environment interaction</figcaption></figure><p>An<strong> environment </strong>is a finite-state machine that has all the states that an agent can observe. This receives an action from the agent, takes a step from the current state and gives the obtained reward and the next state that is reached for this action from the current state. In the considered example, the world for RL is the trucks and the goods that are available for it to choose from.</p><p><strong>State</strong> is a position in an environment. For instance, 10 out of 15 trucks are booked for transporting goods to 4 out of 6 destinations.</p><p><strong>Agent </strong>is the algorithm that gives the next action that needs to be performed by the environment. This receives the current state in the environment, a reward for the previous action from the previous state. PPO, TRPO, A2C, DQN, DDPG are a few of the many agents present for RL task.</p><p><strong>Action </strong>is a possible move that can be made in the environment to shift from the current state to the next state (observed state). Below I tried to draw a diagram to explain an <em>Action </em>a little bit more visually for our example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*vyh8nFwZUcIN6wh7RBEpjA.jpeg" /><figcaption>Model state diagram for the given example</figcaption></figure><p>Reward — Performance measure of action from the current state. For instance, in the above figure, if 2 long trip trucks are assigned for 1 short trip destination, then the long trip destination will not have trucks for transportation. Eventually, this particular sequence of actions will receive an overall lesser reward compared to sequences in which all the destinations are covered.</p><p>Observation — A state in the environment that is reached after performing the given action. The block corresponding to <em>Observed state </em>in the above diagram.</p><p>Reset — Restart the game or delete all modifications made and bring everything back to the initial state, i.e. before starting reinforcement learning task (learning will not be lost). Delete all the job assignments to different trucks and start assigning the jobs from the beginning.</p><p>Step — The environment performs the action given by the agent and this is called taking a step.</p><p>Trajectory steps — Sequence of steps taken between any two resets of the environment. One trajectory step is the step taken after receiving an action suggestion.</p><p>Training step — A set of trajectory steps. In other words, 1 training step is completed if the end or the maximum number of trajectory steps to be taken is reached. One training step is completed if either all the destinations are covered or all the trucks are booked.</p><p>Policy — A strategy learned by the agent to choose the next action.</p><p>Exploring — Choosing a new action (the action that was not taken in previous training steps) from the current state. Choose different actions from previous states so that 3 long trip trucks and 3 short trip trucks are remaining before performing the last action. This way, more fuel can be saved and more profit can be achieved.</p><p>Exploiting — Choosing a known action from the current state that would give the best possible reward. For instance, first book trucks for long trip destinations, then medium trip destinations and finally for short trip destinations.</p><p>Model — A representation of the environment for the agent to plan the steps before starting the task.</p><h3>What and Why a custom environment</h3><p>OpenAI Gym and Tensorflow have various environments from playing Cartpole to Atari games. We can learn how to train and test the RL agent on these existing environments. However, for most businesses, this is not the use case for which they need an agent. There are many situations where we want to use RL for our specific tasks and obviously, the environment for such tasks will neither be present in OpenAI Gym nor Tensorflow. This brings the need to have an environment that is specific to our task, i.e. acustom environment. We can decide on the actions the agent can take, what to do when reset environment is invoked, how to take a step, the maximum number of trajectory steps that will be considered as a training step, the starting and the ending point. Through this, we will develop a world for the RL agent to learn from.</p><h3>How to Build a Custom Environment</h3><p>Before building the custom environment, we need to decide on how to invoke the custom environment into our training script. There are two ways to do this</p><p>a. Import the environment class as a module</p><p>We can directly import a custom environment as a python module and start working with its functions. The path to the environment class should be given in the import and the functions inside the environment can be accessed as it is done for other python packages.</p><p>b. Locally register the environment with Gym (installed in the local system) and invoke this environment from the Gym library with an ‘id’ given to it.</p><p>This requires to have a folder structure as given below with the following files present in it.</p><blockquote>gymEnv/</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*pg4wiaATCTVpDVhO4-r5YQ.jpeg" /><figcaption>Folder structure</figcaption></figure><p>A folder structure similar to the folder structure given in the figure has to be created. <em>gymEnv/</em> will contain all the dependencies for our use. <em>README.md </em>is an empty file, setup.py has the installs that are required for the execution of our environment.</p><blockquote>gymEnv/setup.py</blockquote><pre>from setuptools import setup</pre><pre>setup(name=&#39;customEnv&#39;,<br>  version=&#39;1.0&#39;,<br>  install_requires=[&#39;gym&#39;]  # And any other dependencies Env needs<br>  )</pre><blockquote>gymEnv/customEnv/__init__.py</blockquote><p><em>customEnv/ </em>contains the <em>__init__.py</em> file which has the environment ‘id’ and the corresponding class that has to be invoked when a particular environment ‘id’ is given in the training/testing script.</p><pre>from gym.envs.registration import register</pre><pre>register(<br>     id=&#39;truckOpt-v1&#39;,<br>     entry_point=&#39;customEnv.envs:truckEnv&#39;,<br> )<br> register(<br>     id=&#39;truckOpt-v2&#39;,<br>     entry_point=&#39;customEnv.envs:truckEnv&#39;,<br> )</pre><blockquote>gymEnv/customEnv/envs</blockquote><p><em>envs/</em> contains <em>__init__.py </em>that<em> </em>imports the custom environment and its corresponding class and has the script for our custom environment</p><blockquote>gymEnv/customEnv/envs/__init__.py</blockquote><pre>from customEnv.envs.truckEnv import efficientTransport1<br>from customEnv.envs.truckEnv import efficientTransport2</pre><blockquote>gymEnv/customEnv/envs/truckEnv.py</blockquote><p>An example code snippet on how to write the custom environment is given below</p><pre>import gym<br>from gym import spaces</pre><pre>class efficientTransport1(gym.Env):<br>   &quot;&quot;&quot;Custom Environment that follows gym interface&quot;&quot;&quot;<br>   metadata = {&#39;render.modes&#39;: [&#39;human&#39;]}</pre><pre>def __init__(self, arg1, arg2, ...):<br>     super(CustomEnv, self).__init__()<br>     # Define action and observation space<br>     # They must be <em>gym.spaces</em> objects<br>     # Example when using discrete and continuous actions:<br>     <br>     self.truckType = [&#39;short&#39;,&#39;mid&#39;,&#39;long&#39;]<br>     self.routeID = [id for different routes present to reach the <br>                     destination]<br>     self.action_space = spaces.Tuple(<br>                (spaces.Discrete(len(self.truckType)), # to select <br>                                                      the truck type<br>                (spaces.Discrete(len(self.routeID)), # to select a <br>                                                     route to reach <br>                                                     the destination<br>                (spaces.Box(low = 0, high = 23))) # to select the <br>                                            optimal start time in  <br>                                            hrs of the day to reach<br>                                            the destination<br>     <br>     # Example for using discrete and continuous observation:<br>     <br>     self.observation_space = spaces.Tuple( <br>                             (spaces.Discrete(len(self.truckType)),<br>                              spaces.Discrete(len(self.routeID)),<br>                              spaces.Box(low = 0, high = 23)))</pre><pre># Initialize all the variables that will be used</pre><pre>def reset(self):<br>        # Reset all the required variables to start optimization <br>          again<br>        # Reset the state of the environment to the initial state or<br>          the starting point from which optimization has to be done<br>        self.reward = 0<br>        self.done = False</pre><pre>&#39;&#39;&#39; After resetting the environment, the current state has to be<br>    determined (observed state) and given to the agent&#39;&#39;&#39;</pre><pre>return(observedState)</pre><pre># The agent will get this current observed state and suggests the action that has to be taken from the current observed satate</pre><pre>def step(self, action):<br>     # Receive the action action given by the agent<br>     # action[0] corresponds to truckID<br>     # action[1] corresponds to routeID<br>     # action[2] corresponds to starting timestamp of the truck</pre><pre>     &#39;&#39;&#39; Calculate the performance of the action suggested by the <br>     agent using a reward function and the observed state due to <br>     this action&#39;&#39;&#39;<br>     &#39;&#39;&#39; Cumulative reward is used here as all the jobs should be <br>     distributed optimally between the trucks. While testing, the <br>     best sequence of actions that resuted in the highest reward <br>     will be considered as the optimal distribution&#39;&#39;&#39;</pre><pre>     if (max number of trucks of the suggested truck type is reached<br>         or wrong truck type is selected):<br>         self.reward = self.reward + 0</pre><pre>     else:<br>         self.reward = self.reward + (A function of time taken to <br>         reach the destination and fuel consumed by the selected <br>         truck)</pre><pre>         &#39;&#39;&#39; RL agent will update its policy while training and  <br>         finds the optimal truck type, optimal route and optimal <br>         starting time to reach the destination in shortest time <br>         within deadline to get more profit&#39;&#39;&#39;</pre><pre>     if(no more truck is available to take the pending jobs or all<br>          jobs are allocated)<br>         <br>         self.done = True<br>     <br>     return(observedState, self.reward, self.done, {})<br>   <br>def render(self, mode=&#39;human&#39;, close=False):<br>     # Render the happenings within the environemnt to the screen if<br>       required</pre><p>After the setup is ready, open command prompt/terminal, navigate to <em>gymEnv/</em> folder and type the following. <em>Note: do not forget the “.” at the end.</em></p><pre>pip3 install -e .</pre><p>This would install the created folder structure as a package in the local system. Training and testing the RL agent can be done after writing the script for the environment and installing the same.</p><h3>Training and Testing</h3><p>In the training phase, the environment will be explored/exploited to find the optimal policy. Whereas, in the testing phase, the optimal policy obtained via training would be exploited to achieve the best possible reward</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyJ8hiH_h4651EdvE-6eBA.png" /><figcaption>Left: Training phase, Right: Testing Phase</figcaption></figure><p>In the figure above, the block diagram on the left side will be followed while training. A better policy would be obtained by exploring the environment and the maximum performance of the adapted policy would be evaluated by exploitation. The trade-off between exploration and exploitation would be based on the obtained <em>policy_loss</em> values in <em>stable-baselines</em>.</p><p>The block diagram on the right side will be followed while testing. The obtained optimal policy would be exploited to get a sequence of actions that would result in the best possible reward.</p><p>The training and testing can be done as follows</p><pre># Training</pre><pre>import gym # gym package<br>import customEnv # package that has custom environment</pre><pre>from stable_baselines.common.policies import MlpPolicy<br>from stable_baselines.common.vec_env import DummyVecEnv<br>from stable_baselines import PPO2</pre><pre>env = gym.make(r&#39;truckOpt-v1&#39;) # the registered custom environment <br>                                 with gym<br>env = DummyVecEnv([lambda: env]) # vectorization of the environment<br>                                   for running parallely on multiple<br>                                   cores, by default it is 1<br>model = PPO2(MlpPolicy, env, verbose = 1) # create the model<br>model.learn(total_timesteps = 32000) # train the model for 32000 <br>                                       trajectory steps<br>model.save(r&#39;/model/TruckOptimization&#39;) # save the trained model</pre><pre>del model # to delete the local copy of the model</pre><pre># Testing</pre><pre>model = PPO2.load(r&#39;/model/TruckOptimization&#39;) # load the trained <br>                                                 model<br>obs = env.reset() # manually reset the model</pre><pre>numTrucks = t # number of trucks that are present<br>numJobs = j # number of jobs to be done for the given time period<br>numRuns = n # number of times the sequence should be executed</pre><pre># among n different sequences, the sequence that gave the highest final cumulative reward is the optimal sequence</pre><pre>if t&gt;j:<br>   for i in range(t*n):<br>      action, _states = model.predict(obs) # predict the next action<br>      # get the next observed state, reward received for the <br>      # suggested action, if a particular sequence is done or not, <br>      # other user information<br>      obs, reward, done, info = env.step(action) <br>      env.render() # display what id happening in the environment<br>else:<br>   for i in range(j*n):<br>      action, _states = model.predict(obs)<br>      obs, reward, done, info = env.step(action)<br>      env.render()</pre><p>After training the RL agent, the optimal policy that is found is stored in the model. This model can be used for testing/deployment. If # of training/testing/deployment step is &gt;1, then the best sequence that gave the highest reward could be treated as the optimal action combination (optimal job assignment to the available trucks).</p><h3>Conclusion</h3><p>For any application, the challenge is to derive a good reward function, write a full flow for the custom environment, register the custom environment with gym and import them similar to OpenAI Gym’s in-built environment. Once the custom environment that is specific for our use case and the required packages are installed, the existing state-of-the-art algorithm present in stable-baselines can be used as the agent. This article covers why, when and how to build the custom environment and also how to train and test it.</p><h3>References:</h3><ol><li>A. King, “Creating a Custom OpenAI Gym Environment for Stock Trading,” <em>Medium</em>, Oct. 17, 2019. <a href="https://towardsdatascience.com/creating-a-custom-openai-gym-environment-for-stock-trading-be532be3910e">https://towardsdatascience.com/creating-a-custom-openai-gym-environment-for-stock-trading-be532be3910e</a></li><li>K. Fraser, “🏋️ Custom OpenAI Gym Environment,” <em>Medium</em>, Oct. 08, 2019. <a href="https://medium.com/@kfraser_63104/%EF%B8%8F-custom-openai-gym-environment-bfce3103fd54">https://medium.com/@kfraser_63104/%EF%B8%8F-custom-openai-gym-environment-bfce3103fd54</a></li><li>“PPO2 — Stable Baselines 2.10.2a0 documentation.” <a href="https://stable-baselines.readthedocs.io/en/master/modules/ppo2.html">https://stable-baselines.readthedocs.io/en/master/modules/ppo2.html</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76c951d75af3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science-from-signify-research-eindhoven/what-why-and-how-to-build-a-custom-environment-using-openai-gym-for-reinforcement-learning-rl-76c951d75af3">What, Why and How to Build a Custom Environment Using OpenAI Gym for Reinforcement Learning (RL)</a> was originally published in <a href="https://medium.com/data-science-from-signify-research-eindhoven">Data Science Stories From Signify Research Eindhoven</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>