<?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 Athanasios Kapoutsis on Medium]]></title>
        <description><![CDATA[Stories by Athanasios Kapoutsis on Medium]]></description>
        <link>https://medium.com/@athanasios.kapoutsis?source=rss-7283e71e9e82------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Kh98xRzDA72QsqsisxbgsA.jpeg</url>
            <title>Stories by Athanasios Kapoutsis on Medium</title>
            <link>https://medium.com/@athanasios.kapoutsis?source=rss-7283e71e9e82------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:18:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@athanasios.kapoutsis/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[Engage and Learn: Practical Insights into the Basics of Reinforcement Learning]]></title>
            <link>https://medium.com/@athanasios.kapoutsis/engage-and-learn-practical-insights-into-the-basics-of-reinforcement-learning-8254944a7ed3?source=rss-7283e71e9e82------2</link>
            <guid isPermaLink="false">https://medium.com/p/8254944a7ed3</guid>
            <category><![CDATA[hands-on]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[workshop]]></category>
            <dc:creator><![CDATA[Athanasios Kapoutsis]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 12:21:13 GMT</pubDate>
            <atom:updated>2024-04-23T13:38:47.844Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to our <em>hands-on workshop</em> on the fundamental concepts of <em>Reinforcement Learning (RL)</em>, designed to enhance your understanding through an <strong>engaging, interactive</strong> approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iOkCuWhqqQ8El0Y3_u7k6g.png" /></figure><p>While there are extremely good and comprehensive articles that explain the theory behind RL (e.g., [<a href="https://towardsdatascience.com/reinforcement-learning-an-introduction-to-the-concepts-applications-and-code-ced6fbfd882d">1</a>], [<a href="https://medium.com/@cedric.vandelaer/reinforcement-learning-an-introduction-part-1-4-866695deb4d1">2</a>], [<a href="https://medium.com/ai%C2%B3-theory-practice-business/reinforcement-learning-part-1-a-brief-introduction-a53a849771cf">3</a>], etc.), this article envisions offering a different learning experience that allows you to see these concepts in action. Using a notebook environment, we guide you through each term and principle not just theoretically but practically, with real-time examples, exercises and demonstrations that can easily be replicated and reveal the fascinating nature of RL. A first-principles, complete book about the basic concepts of RL is “<a href="https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf"><em>Reinforcement Learning: An Introduction</em></a><em>”</em> by Sutton, Richard S., and Andrew G. Barto (must read!).</p><p>Whether you’re a budding enthusiast or a seasoned professional, our workshop provides a powerful way to strengthen your grasp of RL by actively participating in the learning process. Join us as we explore this cutting-edge technology in a format that’s both educational and uniquely effective.</p><h4>Live execution:</h4><p>All materials have been deployed to this <a href="https://colab.research.google.com/drive/1TTwg4LvcZ2tiARKuxl7kvPyASH_IF-Wg?usp=sharing">Collab notebook</a> also!</p><h4>Introduction</h4><p>In Reinforcement Learning (RL), the interaction between the <strong>agent</strong> and the <strong>environment</strong> is central to the learning process. The <em>agent</em>, an entity that makes decisions, continuously interacts with the <em>environment</em>, which represents the system or context within which the agent operates. During these interactions, the agent performs actions, and the environment responds by presenting new <strong>states</strong> and providing feedback in the form of <strong>rewards</strong>.</p><p>Interplay between two characters <strong>Agent</strong> and <strong>environment</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9PA2cGJzK_7TaWlOYAL2QA.png" /></figure><p>But enough with the chit-chat, let’s roll up our sleeves and start really understanding these things by doing!</p><p>First things, first! Let’s install the required packages:</p><pre>pip install --upgrade pip setuptools wheel<br>pip install gym==0.25.0<br>pip install matplotlib==3.5.3<br>pip install scikit-learn==1.0.2<br>pip install torch==1.13.1<br>pip install torchsummary==1.5.1<br>pip install pygame==2.1.0<br>pip install opencv-python<br>pip install ale-py<br>pip install gym[atari,accept-rom-license]</pre><pre>rm -rf banana-gym<br>git clone https://github.com/MartinThoma/banana-gym.git<br>cd banana-gym<br>pip install -e .</pre><h4>Environment</h4><p>To represent the environment we are going to use <a href="https://github.com/openai/gym">openAI gym library</a> (which is a tool for developing and comparing reinforcement learning algorithms) and more specifically the <a href="https://www.gymlibrary.dev/environments/classic_control/mountain_car/">MountainCar </a>setup.</p><pre>import gym<br>env = gym.make(&#39;MountainCar-v0&#39;)</pre><figure><img alt="mountain_car.gif" src="https://cdn-images-1.medium.com/proxy/1*T019tdSPvig5n24eisugIg.gif" /></figure><h4>States and Observations</h4><p>A <strong>state</strong> <em>s</em> is a complete description of the state of the world. There is no information about the world that is hidden from the state. An <strong>observation</strong> <em>o</em> is a partial description of a state, which may omit information.</p><p>When the agent can observe the complete state of the environment, we say that the environment is <strong>fully observed</strong>. When the agent can only see a partial observation, we say that the environment is <strong>partially observed</strong>.</p><p>Practically speaking, <strong>almost always</strong> the agent has access to a <strong>subset</strong> of the whole state variables, rendering the knowledge distillation more challenging.</p><pre>observation, info = env.reset()<br>print(f&#39;MountainCar Observation: (1) position of the car along the x-axis (2) velocity of the car&#39;)<br>print(f&#39;Instance from p_0: {observation}&#39;)</pre><pre>MountainCar Observation: (1) position of the car along the x-axis (2) velocity of the car<br>Instance from p_0: -0.14796312153339386</pre><p>Observation can be:</p><ol><li>Real value vector</li></ol><pre>observation<br>print(&quot;MountainCar Observation Space: &quot;, env.observation_space)</pre><pre>MountainCar Observation Space:  Box([-1.2  -0.07], [0.6  0.07], (2,), float32)</pre><p>2. Matrix</p><pre>env_Breakout = gym.make(&#39;Breakout-v4&#39;)<br>print(&quot;Breakout Observation Space: &quot;, env_Breakout.observation_space)</pre><pre>Breakout Observation Space:  Box(0, 255, (210, 160, 3), uint8)</pre><h4>Action Spaces</h4><p>Action spaces define how the agent can <strong>intervene/affect</strong> the environment.</p><p><strong><em>Usual assumption:</em></strong> All elements of the action space are reachable (can be selected) in any given state <em>s</em>.</p><p>Action can be:</p><ol><li>Discrete</li></ol><pre>env = gym.make(&#39;MountainCar-v0&#39;)<br>env.action_space</pre><pre>Discrete(3)</pre><p>2. Continuous</p><pre>env_continuous = gym.make(&#39;MountainCarContinuous-v0&#39;)<br>env_continuous.action_space</pre><pre>Box(-1.0, 1.0, (1,), float32)</pre><p><strong><em>Tip:</em></strong> OpenAI Gym framework supports the generation of random samples over the valid action space by using .sample() function, e.g.,</p><pre>env_continuous.action_space.sample()</pre><pre>array([-0.67912346], dtype=float32)</pre><p>Such a feature can be particularly useful when wanting to generate a random, <strong>exploration-driven</strong> action.</p><h4>Transitions</h4><p>A single transition describes the change of the environment <strong><em>from</em></strong> state <em>sᵢ</em> <strong><em>to</em></strong> <em>sᵢ ₊ ₁</em> after applying an action aᵢ and it encapsulates the environmental dynamics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/136/0*RRRieLvNgs0C5Am-" /></figure><p>In other words, the above <strong>transition function </strong>expresses the <strong>probability of arriving </strong>as state <em>sᵢ ₊ ₁,</em> given that we are at state <em>s</em> and we apply action <em>aᵢ</em></p><p>A transition can be</p><ol><li>Deterministic: from a given <em>sᵢ</em> and after applying <em>aᵢ</em> we will always find ourselves in <em>sᵢ ₊ ₁</em>, i.e.,</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/0*hQSFKv85mYFGuEGY" /></figure><pre>a1 = env_continuous.action_space.sample()<br><br>for _ in range(15):<br>    env_continuous.reset(seed=42) # Fix randomness to always start from the same state s1<br>    s1 = env_continuous.reset()<br>    s2, r, done, _ = env_continuous.step(a1) # Apply pre-generated action a1<br>    print(f&#39;Transition: (s1:{s1[0]}, a1:{a1}, s2:{s2[0]}, r:{r})&#39;) #  # Always arrive at the same s2</pre><pre>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)<br>Transition: (s1:-0.16112156212329865, a1:[0.49403438], s2:-0.16259409487247467, r:-0.024406996834600483)</pre><p>2. Stochastic: There is a (usually unknown) distribution that describes the probabilities of arriving at all possible states from sᵢ and after applying <em>aᵢ</em></p><h4>Finite vs Infinite Horizon Episode</h4><p>In the <strong><em>finite episode</em></strong> case, the RL agent has a <strong>time cap</strong>, namely <em>T</em>, in the <strong>number of interactions</strong> with the environment before the end of an episode cycle. On the contrary, in the <strong><em>infinite horizon</em></strong> case, the agent <strong>may interact indefinitely</strong> (continuous) with the environment without any foreseeable end.</p><p><em>Notice</em>: The majority of state-of-the-art RL algorithms can be applied in a finite episode format. Most RL environments do not directly implement a time cap inside the dynamics propagation. Such operation is usually performed by the RL algorithm itself (triggering the reset function from the openai gym framework).</p><p><em>— Code-based conceptualization purposes only! DO NOT RUN ME —</em></p><pre>#Example of step function from MountainCar    <br>def step(self, action: np.ndarray):</pre><pre>position = self.state[0]<br>    velocity = self.state[1]<br>    force = min(max(action[0], self.min_action), self.max_action)</pre><pre>velocity += force * self.power - 0.0025 * math.cos(3 * position)<br>    if velocity &gt; self.max_speed:<br>        velocity = self.max_speed<br>    if velocity &lt; -self.max_speed:<br>        velocity = -self.max_speed<br>    position += velocity<br>    if position &gt; self.max_position:<br>        position = self.max_position<br>    if position &lt; self.min_position:<br>        position = self.min_position<br>    if position == self.min_position and velocity &lt; 0:<br>        velocity = 0</pre><pre># The termination condition has to do only whether or not the car reached a specific location<br>    terminated = bool(<br>        position &gt;= self.goal_position and velocity &gt;= self.goal_velocity<br>    )</pre><pre>reward = 0<br>    if terminated:<br>        reward = 100.0<br>    reward -= math.pow(action[0], 2) * 0.1</pre><pre>self.state = np.array([position, velocity], dtype=np.float32)</pre><pre>if self.render_mode == &quot;human&quot;:<br>        self.render()<br>    return self.state, reward, terminated, False, {}</pre><h4>Reward and Return</h4><p>The reward function attributes a specific credit to each one of these transitions <em>(sᵢ, aᵢ) → sᵢ ₊ ₁</em>. Such a reward function is considered unknown and usually depends on both the previous, next state and also the executed action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/0*9eavAH5AAj8JEEfl" /></figure><p>although (depending on the specifics of the environment) it may depend just on the previous state and the selected action <em>rᵢ =ℛ(sᵢ, aᵢ)</em> or even only the previous state <em>rᵢ =ℛ(sᵢ)</em></p><pre>s0 = env_continuous.reset()<br>a0 = env_continuous.action_space.sample()<br>s1, r0, _, _ = env_continuous.step(a0)<br>print(f&#39;The reward after applying action {a0[0]} from state {s0[0]} and resulting in state {s1[0]} is {r0}&#39;)</pre><pre>The reward after applying action 0.3316483795642853 from state 0.2585979104042053 and resulting in state 0.2573107182979584 is -0.01099906476676162</pre><p><em>Notice: The usual RL formulation assumes a </em><strong><em>deterministic function</em></strong><em> </em>ℛ<em>. If such a case does not hold, then the whole Markov decision Process is time-varying and </em><strong><em>the majority of state-of-the-art RL algorithms cannot be directly applied</em></strong><em>.</em></p><p>Although, there are instances where a (time-invariant) stochasticity in the reward function can be tackled. An example of a stochastic reward function can be found in the third-party openai gym_banana environment:</p><pre>import gym_banana<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br><br>env_stochastic = gym.make(&#39;Banana-v0&#39;)<br>a1 = env_stochastic.action_space.sample()<br>for _ in range(15):<br>    s1 = env_stochastic.reset()<br>    s2, r, done, _ = env_stochastic.step(a1) # Apply pre-generated action a1<br>    print(f&#39;Transition: (s1:{s1[0]}, a1:{a1}, s2:{s2[0]}, r1:{r})&#39;) #</pre><pre>2024-04-21 22:16:31,364 - root - INFO - BananaEnv - Version 0.1.0<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.8)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.0)<br>Transition: (s1:3, a1:18, s2:2, r1:0.8)</pre><p>The objective of the agent is to maximize the cumulative reward that will receive. Therefore, for an episodic environment (finite horizon), the agent should find a “way” to always maximize the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/0*YIGbWZTjLFOi9Pex" /></figure><p>For the infinite-horizon case, the return is defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/0*D49syJfxIDafdo-n" /></figure><p>In both cases, <em>0&lt;γ≤1</em> is a discount factor that is used to give more priority to early rather than delayed rewards. In cases where <em>γ=1</em> we have an undiscounted return, where all the rewards contribute equally to the formation of the overall assessment.</p><pre>done = False<br>env_continuous.reset()<br>ep_return, ep_return_g = 0, 0<br>step=0<br>gamma = .99<br>while not done:<br>    action = env_continuous.action_space.sample()<br>    _, reward, done, _ = env_continuous.step(action)<br>    ep_return += reward<br>    ep_return_g += gamma**step * reward<br>    step += 1<br>print(f&#39;For the same MountainCarContinuous episode with random movements:&#39;)<br>print(f&#39;The undiscounted (gamma=1) return was: {ep_return}&#39;)<br>print(f&#39;The discounted (gamma={gamma}) return was: {ep_return_g}&#39;)</pre><pre>For the same MountainCarContinuous episode with random movements:<br>The undiscounted (gamma=1) return was: -33.689509363494146<br>The discounted (gamma=0.99) return was: -3.3208218966150795</pre><p><strong>Question</strong>: Why would we ever want a discount factor, though? Don’t we just want to get all the rewards?</p><p><strong>Answer</strong>: We do, but the discount factor is both intuitively appealing and mathematically convenient. On an intuitive level: cash now is better than cash later. Mathematically: an infinite-horizon sum of rewards may not converge to a finite value and is hard to deal with in equations. But with a discount factor and under reasonable conditions, the infinite sum converges.</p><p><em>Notice: While the line between these two formulations of return is quite stark in RL formalism, deep RL practice tends to blur the line a fair bit — for instance, we frequently set up algorithms to optimize the undiscounted return, but use discount factors in estimating value functions.</em></p><h4>Trajectories</h4><p>A trajectory <em>τ</em> is a valid sequence of states and actions pairs in the environment,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*4eUt9cwmIMm91YII" /></figure><p>Therefore, after applying <em>aᵢ</em>, a new state <em>sᵢ ₊ ₁</em> is derived from the (either deterministic or probabilistic) dynamics of the environment.</p><h4>Question: But where does the s₀ come from?</h4><p>Usually, we assume that the first state <em>s₀</em> is sampled from the <strong>start-state distribution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/0*6fVPQDIUb2qPMJ6-" /></figure><p>and represents the distribution of initial states we might find the agent and environment at the beginning of the agent’s interaction with the environment.</p><p>Randomly generate observations from the initial distribution</p><pre>init_obs = [env_continuous.reset().tolist() for i in range(1000)]</pre><p>Plot distribution of these observations</p><pre>import matplotlib<br>from matplotlib import pyplot as plt<br>from sklearn import mixture<br>from matplotlib import cm<br>import logging<br>import numpy as np<br><br># Set the logging level for matplotlib.font_manager to WARNING to suppress DEBUG messages<br>logging.getLogger(&#39;matplotlib.font_manager&#39;).setLevel(logging.WARNING)<br><br><br>n_components = 7<br><br>model = mixture.GaussianMixture(n_components=n_components,<br>                                             covariance_type=&#39;diag&#39;,<br>                                             reg_covar=1e-5,<br>                                             warm_start=True)<br><br>model.fit(init_obs)<br>xmin, ymin = env_continuous.observation_space.low<br>xmax, ymax = env_continuous.observation_space.high<br>ystep = (ymax - ymin) / 200.0<br>xstep = (xmax - xmin) / 200.0<br>x, y = np.mgrid[xmin:xmax:xstep, ymin:ymax:ystep]<br>pos = np.dstack((x, y)).reshape(-1, 2)<br>clipped_log_prob = np.clip(model.score_samples(pos), -20, 2)<br>z = np.exp(clipped_log_prob)<br>pdf_estimation = np.reshape(z, x.shape)/n_components<br>matplotlib.rcParams.update({&#39;font.size&#39;: 13})<br>fig, ax = plt.subplots(subplot_kw={&quot;projection&quot;: &quot;3d&quot;})<br># Plot the surface.<br>surf = ax.plot_surface(x, y, pdf_estimation, rstride=1, cstride=1, cmap=&#39;coolwarm&#39;, edgecolor=&#39;none&#39;)<br>ax.view_init(elev=50., azim=50)<br></pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*yAlS60n1YcqPof2HqpVoYg.png" /></figure><h4>Policies</h4><p><strong>The policy</strong> is considered any mechanism that automatically decides the next action <em>a</em> given particular state <em>s</em>. In the majority of RL setups, all the training process takes place to form/distill the <strong><em>best possible</em></strong> policy.</p><p>A policy can be:</p><ol><li><em>Deterministic</em>, in which case it is denoted by <em>μ</em>:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/0*b3pci1YgA4Cy_A4S" /></figure><p><a href="https://en.wikipedia.org/wiki/Neural_network_(machine_learning)">Neural networks</a> are used in reinforcement learning primarily because they excel at approximating complex functions and generalizing across high-dimensional and continuous state spaces, where traditional methods fall short. Their ability to learn from raw input data and adapt flexibly to various problems makes them indispensable for handling complex tasks in dynamic environments.</p><pre># torch to rescue...<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)<br>import torch<br>import torch.nn as nn<br>from torch.distributions.normal import Normal</pre><p>Useful parameters of the environment</p><pre># Get dimensions and action limits from the environment<br>obs_dim = env_continuous.observation_space.shape[0]<br>act_dim = env_continuous.action_space.shape[0]<br>act_limit = env_continuous.action_space.high[0]<br><br>mu_policy = nn.Sequential(<br>              nn.Linear(obs_dim, 64),<br>              nn.ReLU(),<br>              nn.Linear(64, 64),<br>              nn.ReLU(),<br>              nn.Linear(64, act_dim),<br>              nn.Tanh()<br>            )<br><br>from torchsummary import summary<br>summary(mu_policy, (1, obs_dim))</pre><pre>----------------------------------------------------------------<br>        Layer (type)               Output Shape         Param #<br>================================================================<br>            Linear-1                [-1, 1, 64]             192<br>              ReLU-2                [-1, 1, 64]               0<br>            Linear-3                [-1, 1, 64]           4,160<br>              ReLU-4                [-1, 1, 64]               0<br>            Linear-5                 [-1, 1, 1]              65<br>              Tanh-6                 [-1, 1, 1]               0<br>================================================================<br>Total params: 4,417<br>Trainable params: 4,417<br>Non-trainable params: 0<br>----------------------------------------------------------------<br>Input size (MB): 0.00<br>Forward/backward pass size (MB): 0.00<br>Params size (MB): 0.02<br>Estimated Total Size (MB): 0.02<br>----------------------------------------------------------------</pre><pre># &lt; Diplay helpers&gt;<br>from IPython import display<br>import matplotlib<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br># &lt;/ Diplay helpers&gt;<br><br>def generate_action_deterministic(obs):<br>    with torch.no_grad():<br>        obs_tensor = torch.as_tensor(obs, dtype=torch.float32) # convert to tensor<br>        action_tensor = mu_policy(obs_tensor) # actual policy feedfoward<br>        return act_limit * action_tensor.numpy() # scale to the action space<br><br>obs = env_continuous.reset()<br><br># &lt; Diplay helpers&gt;<br>img = plt.imshow(env_continuous.render(mode = &#39;rgb_array&#39;)) # only call this once<br>for _ in range(100):<br>    img.set_data(env_continuous.render(mode = &#39;rgb_array&#39;)) # just update the data<br>    display.display(plt.gcf())<br>    display.clear_output(wait=True)<br>    # &lt;/ Diplay helpers&gt;<br><br>    action = generate_action_deterministic(obs)<br>    obs, _, _, _ = env_continuous.step(action)<br><br>obs_dim = env_continuous.observation_space.shape[0]<br>act_dim = env_continuous.action_space.shape[0]<br>act_limit = env_continuous.action_space.high[0]<br>mu_policy = nn.Sequential(<br>              nn.Linear(obs_dim, 64),<br>              nn.ReLU(),<br>              nn.Linear(64, 64),<br>              nn.ReLU(),<br>              nn.Linear(64, act_dim),<br>              nn.Tanh()<br>            )<br><br>from torchsummary import summary<br>summary(mu_policy, (1, obs_dim))</pre><pre>----------------------------------------------------------------<br>        Layer (type)               Output Shape         Param #<br>================================================================<br>            Linear-1                [-1, 1, 64]             192<br>              ReLU-2                [-1, 1, 64]               0<br>            Linear-3                [-1, 1, 64]           4,160<br>              ReLU-4                [-1, 1, 64]               0<br>            Linear-5                 [-1, 1, 1]              65<br>              Tanh-6                 [-1, 1, 1]               0<br>================================================================<br>Total params: 4,417<br>Trainable params: 4,417<br>Non-trainable params: 0<br>----------------------------------------------------------------<br>Input size (MB): 0.00<br>Forward/backward pass size (MB): 0.00<br>Params size (MB): 0.02<br>Estimated Total Size (MB): 0.02<br>---</pre><pre># &lt; Diplay helpers&gt;<br>from IPython import display<br>import matplotlib<br>import matplotlib.pyplot as plt<br>%matplotlib inline<br># &lt;/ Diplay helpers&gt;<br><br>def generate_action_deterministic(obs):<br>    with torch.no_grad():<br>        obs_tensor = torch.as_tensor(obs, dtype=torch.float32) # convert to tensor<br>        action_tensor = mu_policy(obs_tensor) # actual policy feedfoward<br>        return act_limit * action_tensor.numpy() # scale to the action space<br><br>obs = env_continuous.reset()<br><br># &lt; Diplay helpers&gt;<br>img = plt.imshow(env_continuous.render(mode = &#39;rgb_array&#39;)) # only call this once<br>for _ in range(100):<br>    img.set_data(env_continuous.render(mode = &#39;rgb_array&#39;)) # just update the data<br>    display.display(plt.gcf())<br>    display.clear_output(wait=True)<br>    # &lt;/ Diplay helpers&gt;<br><br>    action = generate_action_deterministic(obs)<br>    obs, _, _, _ = env_continuous.step(action)<br># Define a function to generate actions deterministically from observations using the trained policy network<br># Update the environment visualization with the new state after each action</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*Shk2v9e-phHK9EUTsXmEQA.png" /></figure><p><em>2. Stochastic</em>, in which case it is denoted by <em>π</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/0*ssOCPCigAtynJVDx" /></figure><p>In such policies, the next action is usually sampled from a multivariate Gaussian distribution which is described by a mean vector, <em>μ</em>, and a covariance matrix, <em>Σ</em>. In other words, for a <strong>single observation</strong> <em>o</em>, a stochastic policy <em>μ</em> <strong>does not always produce the exact same action</strong> <em>a</em>.</p><p>Basically, the action is being produced using the following scheme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/0*tUfy-GTaER1yZuuY" /></figure><p>where <em>μ_θ</em> and <em>σ_θ</em> are standard function approximator schemes (e.g., neural networks) that map a given observation to a mean vector and standard deviation, respectively. <em>z</em> is a zero mean, unit-variance Gaussian, i.e.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*9MWlggmTf-1DVtej4FcZUg.png" /></figure><pre>def mlp(sizes, activation, output_activation=nn.Identity):<br>    layers = []<br>    for j in range(len(sizes)-1):<br>        act = activation if j &lt; len(sizes)-2 else output_activation<br>        layers += [nn.Linear(sizes[j], sizes[j+1]), act()]<br>    return nn.Sequential(*layers)<br><br>class GaussianMLPActor(nn.Module):<br><br>    def __init__(self, obs_dim, act_dim, hidden_sizes, activation, act_limit):<br>        super().__init__()<br>        self.net = mlp([obs_dim] + list(hidden_sizes), activation, activation) # build backbone network<br>        self.mu_layer = nn.Linear(hidden_sizes[-1], act_dim) # head of the mean vector<br>        self.log_std_layer = nn.Linear(hidden_sizes[-1], act_dim) # head of the log std vector<br>        self.act_limit = act_limit<br><br>    def forward(self, obs, deterministic=False):<br>        net_out = self.net(obs)<br>        mu = self.mu_layer(net_out)<br>        log_std = self.log_std_layer(net_out)<br>        log_std = torch.clamp(log_std, -20, 2)<br>        std = torch.exp(log_std)/20 # retrieve the std vector and scale<br><br>        pi_distribution = Normal(mu, std)<br>        if deterministic:<br>            # Only used for evaluating policy at test time.<br>            pi_action = mu<br>        else:<br>            pi_action = pi_distribution.rsample()<br>       <br>        pi_action = torch.tanh(pi_action)<br>        pi_action = self.act_limit * pi_action<br><br>        return pi_action</pre><p><strong>Q</strong>: Why do we output <strong>log standard deviations</strong> instead of standard deviations directly?</p><p><strong>A</strong>: This is because log stds are free to take on any values in (-∞,∞), while stds must be non-negative. It’s easier to train parameters if you don’t have to enforce those kinds of constraints. The standard deviations can be obtained immediately from the log standard deviations by exponentiating them, so we do not lose anything by representing them this way.</p><pre>pi = GaussianMLPActor(obs_dim, act_dim, (256,256), nn.ReLU, act_limit)<br><br>def generate_action_stochastic(obs, deterministic=False):<br>    with torch.no_grad():<br>        obs_tensor = torch.as_tensor(obs, dtype=torch.float32) # convert to tensor<br>        a = pi(obs_tensor, deterministic)<br>        return act_limit * a.numpy()<br><br>obs = env_continuous.reset()<br><br># &lt; Diplay helpers&gt;<br>img = plt.imshow(env_continuous.render(mode = &#39;rgb_array&#39;)) # only call this once<br>for _ in range(100):<br>    img.set_data(env_continuous.render(mode = &#39;rgb_array&#39;)) # just update the data<br>    display.display(plt.gcf())<br>    display.clear_output(wait=True)<br>    # &lt;/ Diplay helpers&gt;<br><br>    action = generate_action_stochastic(obs, deterministic=False)<br>    obs, _, _, _ = env_continuous.step(action)</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*h4OZfqbP5KNQxWD7opb_6Q.png" /></figure><p>Behavior visualization of a Deterministic and a Stochastic policy for the same observation</p><pre>random_obs = env_continuous.observation_space.sample() # single observation<br>print(f&#39;Observation: {random_obs}&#39;)<br>d_actions = [generate_action_stochastic(random_obs, True)[0] for _ in range(10000)]<br>s_actions = [generate_action_stochastic(random_obs, False)[0] for _ in range(10000)]</pre><pre>Observation: [0.5013754  0.01522708]</pre><pre>import numpy as np<br>fig, (ax1, ax2) = plt.subplots(1, 2)<br>fig.suptitle(&#39;Deterministic vs Stochastic policy for the same observation&#39;)<br>ax1.title.set_text(&#39;Deterministic policy action&#39;)<br>ax1.hist(d_actions, bins=100, density=True, facecolor=&#39;b&#39;, alpha=0.75)<br>ax2.title.set_text(&#39;Stochastic policy action&#39;)<br>ax2.hist(s_actions, bins=100, density=True, facecolor=&#39;g&#39;, alpha=0.75)<br>fig.tight_layout()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*ufNhyrlW2E5kq5UWVz73mg.png" /></figure><h4>The Reinforcement Learning Formalisim</h4><p>Putting everything together, we can now define the underlying Markov Decision Process (MDP) that governs the RL setups along with policy parameters <em>θ</em> that we attempt to optimize in response to such interactions with the MDP.</p><figure><img alt="MDP.png" src="https://cdn-images-1.medium.com/proxy/1*A6CrwmLPOfy-O6wYiZqraw.png" /></figure><p><strong>Remark</strong>: The name Markov Decision Process refers to the fact that the system obeys the <a href="https://en.wikipedia.org/wiki/Markov_property">Markov property</a>: transitions only depend on the most recent state and action, and no prior history.</p><p>Putting everything together we can now express a real-world decision-making problem as an MDP is a 5-tuple, <strong><em>&lt; S, A, R, P, ρ₀ &gt;</em></strong>, where</p><ul><li><strong><em>S</em></strong> is the set of all valid states,</li><li><strong><em>A</em></strong> is the set of all valid actions,</li><li><strong>R</strong> : <strong><em>S x A x S → ℝ</em></strong> is the reward function, with <em>rₜ = ℛ(sₜ, aₜ, sₜ ₊ ₁)</em>,</li><li><strong><em>P : S x A → 𝒫(S)</em></strong> is the transition probability function, with <strong><em>P(s’|s,a)</em></strong> being the probability of transitioning into state <em>s’</em> if you start in state <em>s</em> and take action <em>a</em>,</li><li>and <strong><em>ρ₀</em></strong> is the starting state distribution.</li></ul><h4>Objective of an RL algorithm trying to solve an MDP</h4><p>Mathematically speaking, RL algorithm attempts to <strong>maximize the expected return</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*4ZFQCqOD2lVgODuPa7ALug.png" /></figure><p>where <strong><em>P(τ|π)</em></strong> denotes the probability of following a trajectory <em>τ</em> given i) the distribution of initial states <strong><em>ρ₀(s₀)</em></strong>, ii) the transition dynamics <strong><em>p(sₜ₊₁ |sₜ,aₜ)</em></strong>, and 3) the policy <strong><em>π(aₜ|sₜ)</em></strong>, i.e.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/0*_RQn_-wjQztActRT" /></figure><p>In a nutshell, the RL agent attempts to find the optimal policy according to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/0*uL800sDBIrZ9KI3c" /></figure><h4>Value Functions</h4><p>Probably the most intuitive way to tackle the previously formed RL problem is to be able to “predict”, at any given state <em>s</em>, the forward return following any policy <em>π</em>. Having this function, which is called the value function and is denoted with V, we could just apply it to pick the action that leads to state with the highest V value. This observation led to the definition of a family of functions that play a crucial role in any state-of-the-art RL algorithm and methodology.</p><p>Therefore, the value function <em>V ⷫ(s)</em> for any state <em>s</em> is the expected return from this point and onwards always act according to policy <em>π</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*mvb-Kl3TEefq5jZuxqU0Hg.png" /></figure><p>Another, important function that is usually estimated in the majority of the Q-learning-based algorithms is the action-value function or simply the <em>Q</em> function. <em>Q ⷫ(s, a)</em> provides the expected return if you start in state <em>s</em>, take an arbitrary action <em>a</em> (which may not have come from the policy <em>π</em>) and then forever after act accordingly to policy <em>π</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*KWpK4sm1cPsUhWUK46OzMA.png" /></figure><p><em>Notice: Such function has practical importance as it can be used as an Oracle in any state s to rank a list of possible (either exhaustively or not) actions.</em></p><p>Now, the holy grail in the estimation of these functions is to be able to calculate the version of these functions where instead of any policy the optimal policy is followed. Therefore, we have:</p><p>The optimal Value Function <em>V*(s):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*uQLxQYdgHCUIbVWf-4t_kA.png" /></figure><p>The optimal Action-Value Function <em>Q*(s,α):</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*eIp_rO9qpbKT3wnecC1Ksw.png" /></figure><p>Value function (for any <em>π</em> and optimal one) can be calculated directly from <em>Q</em> (corresponding versions) using the following formulas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*iokIPQffuCWKLPCJwWydtA.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*23Leu9EvoL1ShCFUWLzX8w.png" /></figure><p><strong>Example</strong>:</p><p><em>The cells of the grid correspond to the states of the environment. At each cell, four actions are possible: north, south, east, and west, which deterministically cause the agent to move one cell in the respective direction on the grid. Actions that would take the agent off the grid leave its location unchanged but also result in a reward of −1. Other actions result in a reward of 0, except those that move the agent out of the special states A and B. From state A, all four actions yield a reward of +10 and take the agent to A’. From state B, all actions yield a reward of +5 and take the agent to B’.</em></p><figure><img alt="gridworld_setup.png" src="https://cdn-images-1.medium.com/proxy/1*s_W3bpbcFDdkBC2H9MKEvw.png" /></figure><p>Implement basic functions of the example (gridworld) environment:</p><pre>import numpy as np<br><br>    <br>def reset_gridworld(grid_size):<br>    return np.random.randint(0, grid_size), np.random.randint(0, grid_size), 0<br><br>def step_gridworld(i, j, a, grid_size):<br>    <br>    done=False<br>    <br>    # End cases<br>    if i==0 and j==1:<br>        done = True<br>        i=4<br>        j=1<br>        r=10<br>    elif i==0 and j==3:<br>        done = True<br>        i=2<br>        j=3<br>        r=5<br>    else:<br>        r=0<br>        # Usual cases<br>        if a==0:<br>            if i&gt;0:<br>                i = i-1<br>            else:<br>                r = -1<br>        elif a==1:<br>            if j&lt;grid_size-1:<br>                j = j +1<br>            else:<br>                r = -1<br>        elif a==2:<br>            if i&lt;grid_size-1:<br>                i = i + 1<br>            else:<br>                r = -1  <br>        else:<br>            if j&gt;0:<br>                j = j - 1<br>            else:<br>                r = -1  <br>    <br>    <br>    <br>    return i, j, r, done, []<br><br>    <br>def random_policy():<br>    return np.random.randint(0, 4)<br><br>grid_size = 5<br>gamma=0.9 # discount factor</pre><p>Recursive definition of <em>V</em> and <em>Q</em> functions</p><p>One of the most important concepts in RL, is the recursive definition of <em>V</em> and <em>Q</em> for a given π policy, also known as <a href="https://en.wikipedia.org/wiki/Bellman_equation#Example">Bellman equations</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*13mC9yssVRO8zME8TpF7MQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*KP1p8tLQ_J0rJkfP8f8xZA.png" /></figure><p>Bellman backup update for <em>V</em> function:</p><p><em>The above definition gives rise to the Bellman update rule, using elements of a single transition &lt;s, a, s’, r&gt; (or a batch of them to utilize properly the GPU acceleration).</em></p><p>Supposing the Reinforcement Learning (RL) agent finds itself in state <em>s</em>, we can attempt to estimate (probably poorly) the value function for that state <em>Vₜ(s)</em>. Following the execution of an action <em>a</em>, the agent receives a reward <em>r</em> and observes a subsequent state <em>s’</em>. From this new state, we can once again endeavor to estimate the value function, denoted as <em>Vₜ(s’)</em>.</p><p>If our initial estimate was accurate, we would expect that <em>Vₜ(s)</em> should be equal to <em>r + γV(s’)</em>, in line with the Bellman equation for <em>V</em>. However, especially in the early stages of estimating <em>V</em>, this equality is often not met. This exact discrepancy can be used to update our belief about <em>Vₜ ₊ ₁(s’)</em> as follows, i.e.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*N-RHKBM63aJJAPtRkqkIGw.png" /></figure><pre>def update_V(V, i, j, i_new, j_new, r, alpha, gamma):<br>    # V[i][j] = (1-alpha)*V[i][j] + alpha*(r+gamma*V[i_new][j_new]) #Same but not so intuitive<br>    V[i][j] = V[i][j] + alpha*(r+gamma*V[i_new][j_new] - V[i][j])<br>    return V</pre><p><strong>By performing the aforementioned update, we introduce problem-specific information (environmental reward, transition dynamics, etc.) to the estimation of <em>V</em>.</strong></p><p><strong>Bellman backup update for Q function:</strong></p><p>Applying the same rationale as before we can build the <em>Q</em> function update rule as follows:</p><pre>def update_Q(Q, V, i, j, a, i_new, j_new, r, alpha, gamma):<br>    Q[i][j][a] = Q[i][j][a] + alpha*(r+gamma*V[i_new][j_new] - Q[i][j][a])<br>    return Q</pre><p><strong>Remark:</strong> <em>The Bellman equations for the optimal value functions are:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*a7C_DWgSa0DekPShRCbu7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*IBlrgd_1gUn-NjfrHjEZgw.png" /></figure><p>Traverse the state space of the gridworld environment for several iterations (or usually till convergence):</p><pre>alpha=0.001 # learning rate<br>V = np.zeros((grid_size,grid_size))<br>Q = np.zeros((grid_size,grid_size,4))<br><br>_, _, step = reset_gridworld(grid_size)<br>num_episodes = 0<br>iters = 100000<br>for _ in range(iters):<br>    for i in range(grid_size):<br>        for j in range(grid_size):<br>            a = random_policy()<br>            i_new, j_new, r, _, _ = step_gridworld(i, j, a, grid_size)<br>            V = update_V(V, i, j, i_new, j_new, r, alpha, gamma)<br>            Q = update_Q(Q, V, i, j, a, i_new, j_new, r, alpha, gamma)<br>            <br>print(f&#39;Interactions: {iters*grid_size**2}&#39;)<br>print(V)</pre><pre>Interactions: 2500000<br>[[ 3.19324279  8.77001388  4.54629958  5.3349368   1.59413702]<br> [ 1.42915797  3.0199958   2.30160951  1.90415015  0.56377454]<br> [-0.01660401  0.74142253  0.68673492  0.36518305 -0.36990489]<br> [-0.97053076 -0.46175153 -0.3473766  -0.59081432 -1.1660239 ]<br> [-1.85667916 -1.3710515  -1.22470326 -1.43090768 -1.96513105]]</pre><p>A more “natural” way to traverse the usual unknown states of the MDP:</p><pre>alpha=0.001 # learning rate<br>V = np.zeros((grid_size,grid_size))<br>Q = np.zeros((grid_size,grid_size,4))<br><br>i, j, step = reset_gridworld(grid_size)<br>num_episodes = 0<br>iters = 2500000<br>for _ in range(iters):<br>    a = random_policy()<br>    <br>    i_new, j_new, r, done,_ = step_gridworld(i, j, a, grid_size)<br>    <br>    V = update_V(V, i, j, i_new, j_new, r, alpha, gamma)<br>    Q = update_Q(Q, V, i, j, a, i_new, j_new, r, alpha, gamma)<br>    <br>    i = i_new<br>    j = j_new<br>    step += 1<br>    if done:<br>        i, j, step = reset_gridworld(grid_size)<br>        num_episodes += 1<br><br>print(f&#39;Interactions: {iters}&#39;)<br>print(num_episodes)<br>print(V)</pre><pre>Interactions: 2500000<br>76794<br>[[ 3.38673907  8.79365183  4.34822205  5.35077983  1.50495382]<br> [ 1.54038472  3.0962439   2.2386308   1.9079165   0.61835289]<br> [ 0.09711395  0.78287881  0.67745412  0.41813178 -0.37245924]<br> [-0.93745292 -0.42071666 -0.35538295 -0.5462242  -1.12583598]<br> [-1.8561151  -1.3357404  -1.23597269 -1.40621535 -1.98120504]]</pre><p>What it means to have the optimal <em>Q*</em> function</p><p>You may query this function at any given state <em>s</em> with some action <em>a</em> and accurately predict the expected cumulative reward:</p><pre>for i in range(grid_size):<br>        opt_actions = np.argmax(Q[i], axis=1)<br>        opt_arrows = []<br>        for j in range(grid_size):<br>            if opt_actions[j]==0:<br>                opt_arrows.append(&#39;\u2191&#39;)<br>            elif opt_actions[j]==1:<br>                opt_arrows.append(&#39;\u2192&#39;)<br>            elif opt_actions[j]==2:<br>                opt_arrows.append(&#39;\u2193&#39;)<br>            else:<br>                opt_arrows.append(&#39;\u2190&#39;)<br>        print(opt_arrows)</pre><pre>[&#39;→&#39;, &#39;→&#39;, &#39;←&#39;, &#39;←&#39;, &#39;←&#39;]<br>[&#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;←&#39;]<br>[&#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;]<br>[&#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;]<br>[&#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;, &#39;↑&#39;]</pre><p><strong>Advantage Functions</strong>:</p><p>Usually, instead of assessing an action on a given state in an absolute manner (<em>Q ⷫ(s, a)</em>), it is useful to describe how good is that action against an average action from that state (<em>V ⷫ(s)</em>). Thus the concept of advantage function was born:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ZmWrcZt2KC-23-SRBKhXCA.png" /></figure><p>Mathematically speaking, the advantage function <em>A ⷫ(s, a)</em> corresponding to a policy <em>π</em> describes how much better it is to take a specific action <em>a</em> in state <em>π</em>, over randomly selecting an action according to <em>π(·|s)</em>, assuming you act according to <em>π</em> forever after.</p><h4>Acknowledgments</h4><p>The article is based on <a href="https://spinningup.openai.com/en/latest/index.html">SpinningUp</a> content and “<a href="https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf">Reinforcement Learning, An Introduction</a>” by Richard S. Sutton and Andrew G. Barto.</p><p>Big thanks to <a href="https://medium.com/@athpets8">Athanasios Petsanis</a> for his helpful comments on the original draft of this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8254944a7ed3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Monster of Distribution Shift in Offline RL and How to Pacify it]]></title>
            <link>https://medium.com/@athanasios.kapoutsis/the-monster-of-distribution-shift-in-offline-rl-and-how-to-pacify-it-4ea9a5db043?source=rss-7283e71e9e82------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ea9a5db043</guid>
            <category><![CDATA[awacs]]></category>
            <category><![CDATA[distribution-shift]]></category>
            <category><![CDATA[cql]]></category>
            <category><![CDATA[offline-rl]]></category>
            <dc:creator><![CDATA[Athanasios Kapoutsis]]></dc:creator>
            <pubDate>Thu, 23 Jun 2022 12:50:56 GMT</pubDate>
            <atom:updated>2022-06-23T14:43:13.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-4925szhaHRLxuj1LJHSw.png" /><figcaption>Original image from <a href="https://www.flickr.com/photos/tangyauhoong/">Yau Hoong Tang</a></figcaption></figure><h3>Distribution Shift</h3><h4>Empirical Risk Minimization</h4><p>In the standard fitting framework, we try to minimize the error in our estimation f_θ⁢(x) using tuples {x,y} sampled from the problem’s domain x∼p⁢(x) and y∼p(y|x), respectively. Therefore the fitting problem usually is represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G23Zzi7yl9EF074v99YltA.png" /></figure><p>Assuming an expressive enough model (e.g., deep neural network) and an effective learning technique (e.g., adam), it is expected to assume that f_θ⁢(x) will “match” y for x∼p⁢(x). But what about x∼q(x)? Theoretically, the above optimization procedure assures that the error will be small only if samples x are sampled from the same distribution p⁢(x). Technically, with the recent advancements both in size and the learning techniques for the deep neural networks, the above is no longer considered a blocking factor (e.g., [<a href="https://arxiv.org/abs/1808.08750">1</a>]).</p><h4>Offline RL Q-learning</h4><p>First of all, what is offline RL? There are numerous resources explaining offline RL in great detail, e.g., [<a href="https://medium.com/@sergey.levine/decisions-from-data-how-offline-reinforcement-learning-will-change-how-we-use-ml-24d98cb069b0">this medium article</a>], [<a href="https://arxiv.org/abs/2203.01387">2</a>] and [<a href="https://arxiv.org/abs/2005.01643">3</a>]. To cut a long story short, offline RL deals with the problem of acquiring optimized policies for a given problem without having the ability to interact with the environment to collect data according to the so-far developed policy. Our only source of information is a dataset of previously collected transitions that should be carefully “distilled” to lead to an optimized policy for the problem at hand. This dataset has been collected by a (usually unknown) policy, called behavior policy π_β, which can be either human-controlled actions, a rule-based policy, previously learned RL policies, or all the above.</p><p>Therefore, in the offline RL framework, we have a learning scheme similar to the previous subsection. Following any Q-learning scheme, the target values for the bellman update are calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-ChQqa1MHAiLHdIHjnRxA.png" /></figure><p>where π_{new} denotes the currently evaluated policy. Later, during the Q function update, the following objective will be pursued:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqLvxWtD8kySuzthIGs90Q.png" /></figure><p>Notice that, in the model-free offline RL, we are forced to use samples from π_β(a|s) to be able to incorporate the offline collected reward signal r⁢(s,a) into the Bellman update cycle. As we discussed in the previous subsection, a good accuracy is expected when</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbpQLkBU4jNmdkaCjEuhug.png" /></figure><p>However, in offline RL, we do not want to perform behavioral cloning [<a href="https://arxiv.org/abs/2204.05618">4</a>], but rather to process the data collected with π_β(a|s) and produce a better, optimized policy.</p><h4>The “Malicious” Actor</h4><p>Ok, the setup is not the best possible, but, as we discussed in the empirical risk minimization, usually, we offload this task to the advanced generalization abilities of the deep neural networks. We could gather a large and diverge enough dataset 𝒟={(s,a,r,s′)} and then the generalization abilities of deep neural networks, utilized inside the backbone of the RL algorithms, are going to do the rest, right?</p><p>Unfortunately, an inherent feature of the Q learning framework acts against that. Apart from learning the Q function, usually, a policy with respect to Q function is generated as well, according to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BkuQRMIaOOObA0r8e_paQ.png" /></figure><p>Thus, not only the distribution of states is not the one that generated the samples to fit on, but now the states are produced to receive the biggest possible value of the estimated Q function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJy3kWFmsgLBD1jEbUq-2g.png" /><figcaption>Maximization on estimated Q (orange line) technically leads us to areas with the largest positive error</figcaption></figure><p>The previous figure demonstrates why this process can be pretty problematic. For ease of visualization and comprehension, we investigate the values of Q for a specific s, i.e., Q⁢(s,a)=Q_s⁢(a). Also, a scalar action value is assumed, however, the same problem exists in greater dimensions (actually, in higher dimensions, such a problem tends to exacerbate due to the immense formed state-space). The blue line represents the form of the true (unknown) Q function, and the orange line depicts its current estimation based on the recorded data points (green dots). As it is expected, estimated Q is pretty accurate around areas dense in datapoints, while usually tends to miss the true Q around areas with little to no information, producing equally possible positive or negative errors. Now here comes the important part. If we select new points according to a policy similar to eq. (4), then we tend also to select points where the error from the true Q has the largest positive value, also missing the true maximum points, which, however, is the least of our worries.</p><p>Correspondingly, in the offline Q-learning scheme, the actor chooses the state-action pairs with the largest value of the current estimation of Q, favoring positively erroneous estimated values. In turn, these unreliable values are used to update the Q estimation, following equations (2)-(3), further diverging the estimation of Q from its true function. Given that the Q function is not allowed to collect more data around these values, the perfect trap has been set. The actor can avoid solving the task at hand by entering a “vicious cycle” of updating the Q-function with positively erroneous values from areas with little to no actual data (out-of-distribution state-action pairs).</p><p>The following figure showcases such an incident. The different colors correspond to different sizes on the collected samples from the mujoco environment HalfCheetah-v2, and the Q-learning algorithm was the state-of-the-art SAC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFI3iIHVsJiapDO8qNSYKw.png" /><figcaption>Distribution shift problem as reported in [<a href="https://arxiv.org/abs/1906.00949">5</a>]</figcaption></figure><p>It is obvious that the actor believes that a great performance has been achieved (left subfigure); however, the actual performance (right subfigure) of the learned policy has gotten even worse from the initial random policy. Keep an eye on how efficient this “malicious” actor is in finding these out-of-distribution actions! Even for up to 1 million transitions, there are no signs of improvement in the actual performance.</p><p>Therefore, especially in an offline RL setup where no new interactions with the environment are allowed, we should find a way to tackle the problem of “lazy” agents that, instead of solving the assigned problem, “fool” Q-function and eventually solve a completely different/useless setup.</p><h3>Offline RL Algorithms to Alleviate Distribution Shift</h3><h4>Explicit Policy Constraint Methods</h4><p>A direct remedy for this problem is to “constraint” the actor updates (eq. <a href="#S1.E4">4</a>) as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_gbUPtKMOx08DKFU3wYGQ.png" /></figure><p>where 𝒟_{K⁢L} is the KL-divergence between the two distributions. In other words, this class of algorithms [<a href="https://arxiv.org/abs/1812.02900">6</a>],[<a href="https://arxiv.org/abs/1907.00456">7</a>], restrains actor to state-action pairs that are “ϵ-far” away from the behavior policy π_β.</p><p>The problem with such a class of approaches is that we usually don’t know the behavior policy π_β(a|s) used to gather the database transitions. Therefore, an extra mechanism should usually be put in motion to estimate such policy, inducing some more estimation errors. The second issue has to do with the fact that although we did bound the new policy π_{new}(a|s) around the behavior policy π_β(a|s) we cannot derive a theoretical bound about the error when sampling from that policy, therefore probably such a constraint is not “pessimistic enough”. At the same time, such a bound could also be “too pessimistic” and not allow the discovery of substantial better policies within our reach.</p><p>Therefore, instead of just penalizing the difference between π_{new} and π_β, a better approach would be to find the so-called best <strong>in-support</strong> policy that, of course, concentrates around areas with more samples but assigns high-probabilities only to state-action pairs with large Q-values. This feature is paramount as it allows the newly discovered policy to deviate from the behavior policy, but only in areas rich with samples.</p><h4>Implicit Policy Constraint Methods</h4><blockquote><strong>AWAC: Advantage-Weighted Actor Critic</strong></blockquote><p>As shown in [<a href="https://www.aaai.org/ocs/index.php/AAAI/AAAI10/paper/viewFile/1851/2264">8</a>], the constraint optimization in eq. (<a href="#S2.E5">5</a>) can be transformed into the following unconstrained optimization problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aUWkuSPHDPhjLrS6TeFEzA.png" /></figure><p>Such a metric can be approximated via weighted max likelihood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12ockv7oUHQLyyNpWBSK_Q.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcJEjn0Le4qPxkJnwPMF7Q.png" /></figure><p>can be approximated using a critic. Conceptually, the policy generation of eq. (<a href="#S2.E6">6</a>) is a weighted behavior cloning, i.e.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DtGIAkhP_ObYf2j47f21A.png" /></figure><p>where the weight w⁢(s, a) depends on how good the actions really are. In other words, this imitates the actions in the dataset, but it is imitating more the “good” actions than the “bad” ones.</p><p>Advantage-Weighted Actor Critic (AWAC) [<a href="https://arxiv.org/abs/2006.09359">9</a>] utilizes the aforementioned policy generation and estimates the</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcJEjn0Le4qPxkJnwPMF7Q.png" /></figure><p>using a Q-function estimator. This Q-function is fitted using a bootstrapped regression, where the following loss is minimized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhFkaY-fPqHHioQxl0wwZA.png" /></figure><p>An important feature of this approach is the fact that it performs extremely well in cases of offline training with online fine-tuning: the prior collected data is used to provide a starting point that mitigates challenges due to exploration and sample efficiency, while the online training enables the agent to perfect the desired skill.</p><p>The problem with this kind of family of approaches (e.g., [<a href="https://arxiv.org/abs/2006.09359">9</a>],[<a href="https://arxiv.org/abs/1910.00177">10</a>]) is that we still might query out-of-distribution (OOD) actions during the course of training. We should note that indeed the formulation of eq. (<a href="#S2.E6">6</a>), with an appropriate choice of λ, will respect the constraint between the two policies, but only at convergence. We might still end up with OOD sampling without bounds for every single iteration.</p><blockquote><strong>IQL: Implicit Q-Learning</strong></blockquote><p><strong>Motivation.</strong> Can we avoid all these out-of-distribution actions in the Q-update? Ok, if the problem is the values queried from π_θ in eq. (<a href="#S2.E7">7</a>) then let’s avoid that by estimating the</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uo-fjQZ7ky58_iIJ5r0msw.png" /></figure><p>only with the collected state-action pairs from the database, i.e.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIfkhcu4eHMnEUN0gNTl-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n2tCc7PJY8TsGWyEweC8pA.png" /></figure><p>Unfortunately, the above estimation will always yield the Q function for the behavior policy π_β and not for the newly generated policy; therefore, it cannot be used.</p><p>Assume the case of single pair (s, a) along a recorded trajectory, probably s has only been visited once taking only a. But, there might be other states nearby that are similar and where different actions were taken, as shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMcUr-V9MfAn3GjSytYlNA.png" /><figcaption>States blending when regressing in MDPs</figcaption></figure><p>Thus, because of that, when regressing on the Q-function (eq. <a href="#S2.E7">7</a>), information from nearby states with different actions leaks to the current target update for (s_i, a_i) and forms a distribution. These generalization abilities actually form a histogram with respect to the values of V⁢(s) and when the MSE of eq. (<a href="#S2.E8">8</a>) is applied, actually we calculating the:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3CmAE7hfNdd1o0E5f7UmA.png" /></figure><p>as shown in the orange dashed line of the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9a6-KzbqUJUlnkh-Z4mkpw.png" /><figcaption>V(s) histogram</figcaption></figure><p>So now the question becomes: Is there any other form for the loss function that can steer us towards the evaluation of the best policy that is also supported by the collected data (red dashed line in the previous figure)?</p><p><strong>IQL Algorithm</strong> That’s exactly the gist of IQL algorithm [<a href="https://arxiv.org/abs/2110.06169">11</a>]. IQL replaces the MSE loss in eq. (<a href="#S2.E8">8</a>) with the expectile (squared upper quantile), defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L41VxtiL1IpfNYczsPbcpw.png" /></figure><p>with the following geometric representation (right subfigure):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ws6MmsheRuuYrl2sR8ypBA.png" /><figcaption>MSE vs Expectile</figcaption></figure><p>Conceptually, IQL “tilts” the loss function to penalize positive errors a lot less than negative ones. Such a loss function will result in the right upper end of the distribution in “V(s) histogram” figure.</p><p><strong>Note:</strong> The source of our initial problem was the overestimation of Q (see subsection <a href="#S1.SS3">1.3</a>), and now IQL has developed an algorithm that rewards positive error in Q. Is this gonna infuriate our “monster”?</p><p>Actually no! IQL can keep the monster “pacified”, due to the fact that all these (s,a) pairs are actually taken from the database 𝒟.</p><p>Formally, IQL critic regression is equivalent with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSesfl5Rnj0LF871g2hwdA.png" /></figure><p>where Ω is a <strong>better</strong> but still <strong>in-support</strong> of behavior policy π_β. Essentially, we regress at the <strong>best</strong> action we <strong>have seen</strong> from the recorded states, which are similar to the current state. Moreover, precisely because this is done in each state, we don’t expect just to copy the best trajectory in the dataset but rather to find improved policies in the support of the collected data.</p><p>The picture is completed with an “implicit” policy update according to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKg_8FA0qECqeKEN2u7x6w.png" /></figure><h4>Regularization Offline RL Algorithms</h4><p>This class of methods, instead of somehow constraining the actor, attempts to directly repair these overestimated actions in the Q function, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NOqbaxmeZ72fPIjlwPGCng.png" /><figcaption>Directly repair positive erroneous Q values</figcaption></figure><p>“The obvious” way to achieve this is to augment the regular Q update of eq. (<a href="#S2.E7">7</a>) by adding an extra term that penalizes large Q-values, i.e.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ly6pRdbA8PUdKdLb9UkiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ho2xCk7dYbcGWvNIF3Xutw.png" /></figure><p>The problem with this approach is that, in practice, such an objective tends to be too pessimistic, as it attempts to lower all the values of the Q function, independently of how close it is to their actual (unknown) true Q^π.</p><blockquote><strong>CQL: Conservative Q-Learning</strong></blockquote><p>To mitigate this issue, the authors of [<a href="https://arxiv.org/abs/2006.04779">12</a>] construct an alternative bound as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*laK8u-xDZNIWG8uo-_3_8A.png" /></figure><p>At first glance, it might seem odd to add a similar term with the opposite sign. However, the definitions of the two expectations are not the same. The newly introduced term</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sKuAEWG8fpBC33HNdRrQQ.png" /></figure><p>attempts to reward large Q values, but only if these values have been sampled from the dataset 𝒟. In the corner — and also wanted — case, where all large values of Q come from (s,a) pairs sampled from the dataset, then the first two terms more or less cancel out. In that case, the third term, which is the regular bellman backup update, completely takes over to perform the Q-function regression. Conceptually, this is a desired situation, as this setup now is not favorable for the monster of distribution shift, and it is time to fully exploit the bellman update without regrets (large Q-values penalization). On the other hand, if the large values are not from the dataset, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uay9uUVFEjQs3LhJZJu02g.png" /></figure><p>is going to push them down and, at the same time,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9sKuAEWG8fpBC33HNdRrQQ.png" /></figure><p>is going to push up Q-values that come from 𝒟. In the upcoming iterations, μ(a|s) is more likely to select these previously increased Q-values from 𝒟.</p><p>Therefore, these two first terms are like out-of-distribution values “hunters”, that, in collaboration, find and then eliminate these values. When their support is no longer needed (all values are in the support of the behavior policy), these two hunters cancel each other out to allow the seamless appliance of bellman backup on the Q-value.</p><p>Unfortunately, now is no longer guaranteed that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQ5hAOX6HzG_VDgUlholtg.png" /></figure><p>for all (s,a) pairs. However, it is guaranteed [12] that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QuG3GfezxWIBcIEEHnpmw.png" /></figure><p>for all s∈𝒟, which is more than fine for the task of avoiding overestimating the value of the current policy.</p><p>The policy update of CQL follows the standard Q-learning rule on the previously estimated Q-function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aV53GxLKKsOEbCqmKiiFQg.png" /></figure><h3>Acknowledgments</h3><p>The article is heavily based on <a href="https://medium.com/u/da92225b83d5">Sergey Levine</a>’s course <a href="https://rail.eecs.berkeley.edu/deeprlcourse/">Deep Reinforcement Learning</a> at UC Berkeley.</p><p>Big thanks to <a href="https://medium.com/u/fd7ae341fea4">Dimitrios Vamvakas</a> for his helpful comments on the original draft of this article.</p><h3>References</h3><p><strong>[1]</strong> R. Geirhos, C. R. Temme, J. Rauber, H. H. Schütt, M. Bethge and F. A. Wichmann (2018) <em>Generalisation in humans and deep neural networks</em>. <em>Advances in neural information processing systems</em> 31.</p><p><strong>[2]</strong> R. F. Prudencio, M. R. Maximo and E. L. Colombini (2022) <em>A survey on offline reinforcement learning: taxonomy, review, and open problems</em>. <em>arXiv preprint arXiv:2203.01387</em>.</p><p><strong>[3]</strong> S. Levine, A. Kumar, G. Tucker and J. Fu (2020) <em>Offline reinforcement learning: tutorial, review, and perspectives on open problems</em>. <em>arXiv preprint arXiv:2005.01643</em>.</p><p><strong>[4]</strong> A. Kumar, J. Hong, A. Singh and S. Levine (2022) <em>When should we prefer offline reinforcement learning over behavioral cloning?</em>. <em>arXiv preprint arXiv:2204.05618</em>.</p><p><strong>[5]</strong> A. Kumar, J. Fu, M. Soh, G. Tucker and S. Levine (2019) <em>Stabilizing off-policy q-learning via bootstrapping error reduction</em>. <em>Advances in Neural Information Processing Systems</em> 32.</p><p><strong>[6]</strong> S. Fujimoto, D. Meger and D. Precup (2019) <em>Off-policy deep reinforcement learning without exploration</em>. In International Conference on Machine Learning, pp. 2052–2062.</p><p><strong>[7]</strong> N. Jaques, A. Ghandeharioun, J. H. Shen, Ferguson, A. Lapedriza, N. Jones, S. Gu and R. Picard (2019) <em>Way off-policy batch deep reinforcement learning of implicit human preferences in dialog</em>. <em>arXiv preprint arXiv:1907.00456</em>.</p><p><strong>[8]</strong> J. Peters, K. Mulling and Y. Altun (2010) <em>Relative entropy policy search</em>. In Twenty-Fourth AAAI Conference on Artificial Intelligence.</p><p><strong>[9]</strong> A. Nair, A. Gupta, M. Dalal and S. Levine (2020) <em>Awac: accelerating online reinforcement learning with offline datasets</em>. <em>arXiv preprint arXiv:2006.09359</em>.</p><p><strong>[10]</strong> X. B. Peng, A. Kumar, G. Zhang and S. Levine (2019) <em>Advantage-weighted regression: simple and scalable off-policy reinforcement learning</em>. <em>arXiv preprint arXiv:1910.00177</em>.</p><p><strong>[11]</strong> I. Kostrikov, A. Nair and S. Levine (2021) <em>Offline reinforcement learning with implicit q-learning</em>. <em>arXiv preprint arXiv:2110.06169</em>.</p><p><strong>[12]</strong> A. Kumar, A. Zhou, G. Tucker and S. Levine (2020) <em>Conservative q-learning for offline reinforcement learning</em>. <em>Advances in Neural Information Processing Systems</em> 33, pp. 1179–1191.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ea9a5db043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DARP: Divide Areas Algorithm for Optimal Multi-Robot Coverage Path Planning]]></title>
            <link>https://medium.com/@athanasios.kapoutsis/darp-divide-areas-algorithm-for-optimal-multi-robot-coverage-path-planning-2fed77b990a3?source=rss-7283e71e9e82------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fed77b990a3</guid>
            <category><![CDATA[coverage-path-planning]]></category>
            <category><![CDATA[darp]]></category>
            <category><![CDATA[sweeping]]></category>
            <category><![CDATA[multi-robot]]></category>
            <category><![CDATA[area-division]]></category>
            <dc:creator><![CDATA[Athanasios Kapoutsis]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 08:14:49 GMT</pubDate>
            <atom:updated>2022-06-15T18:35:06.462Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the fundamental problems in robotics is determining an optimal path involving all points of a given area of interest while avoiding sub-areas with specific characteristics (e.g., obstacles, no-fly zones, etc.). In the literature, this problem is often referred to as coverage path planning (CPP), but can also be found as sweeping, exhaustive geographical search, area patrolling, etc. This problem is directly related to a plethora of robotic applications, such as vacuum cleaning robots, seabed mapping, demining robots, automated harvesters, planetary exploration, and search and rescue operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rz4zufs-yCP3dUVi0-iDA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/6NUlOHM40w8">Jelleke Vanooteghem</a> on <a href="https://unsplash.com/s/photos/robots">Unsplash</a></figcaption></figure><h3>Multi-Robot Coverage Path Planning (mCPP) | Problem Definition</h3><p>Such a problem is usually defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*EQk4j53I2tqOI593TSUvKQ.png" /><figcaption>Coverage Path Planning (CPP) problem formulation</figcaption></figure><h4><strong><em>Given</em></strong>:</h4><blockquote>1) An area of interest</blockquote><blockquote>2) Robots’ initial positions</blockquote><h4><strong><em>Objective</em></strong>:</h4><blockquote>Design robot paths that <strong>completely cover</strong> this area of interest in the <strong>minimum possible time</strong></blockquote><p>Usually, complete coverage is needed to reconstruct the underlying environment (e.g., seabed, ground morphology, cm-level mapping, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MEWKm8LRoRXGjuintHZJTA.png" /><figcaption>Combine robots’ measurements to generate accurate representations of the environment</figcaption></figure><p>Of course, this can even be achieved by a single robot moving randomly in the space after a (probably) long period of time. However, the limited battery capabilities of autonomous vehicles, in addition to the constantly increased areas that need to be covered/monitored, have motivated the deployment of several autonomous devices with advanced path planning mechanisms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*xhl08AClxtWQccAAwFZfnA.png" /><figcaption>Suboptimal path generation.</figcaption></figure><h4>What are the key attributes that affect the performance?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KDnJNb6rG2opQNWxIRDMg.png" /><figcaption>mCPP key attributes</figcaption></figure><p><strong>The <em>bad news</em> is that the mCPP setup is at least NP-hard [</strong><a href="https://link.springer.com/article/10.1007/s10472-009-9120-2"><strong>1</strong></a><strong>]! </strong>Ok, mCPP is hard, but <strong>what about single robot CPP</strong>?</p><h3>Single robot Coverage Path Planning Problem</h3><p>Design the trajectory for a single robot to cover the whole operational area in the minimum possible time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*anakR-MqpdDjdNMu7Ijtog.png" /><figcaption>Single robot Coverage Path Planning setup</figcaption></figure><blockquote>Good news at last! There exists a dedicated O(n) algorithm, called <strong>Spanning-Tree Coverage (STC)</strong> [<a href="https://link.springer.com/article/10.1023/A:1016610507833">2</a>], that computes the optimal robot path under some mild discretization assumptions, where n denotes the size of the area.</blockquote><h4>Spanning-Tree Coverage (STC) Algorithm in a nutshell</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*ydDguhoKViyRXO5SjZDRLg.png" /><figcaption>STC algorithm in a nutshell</figcaption></figure><p>Apart from being able to tackle the CPP setup in linear time with respect to the size of the grid, STC also designs a coverage path that</p><ol><li>finishes in the starting position</li><li>is actually valid from any starting point inside the operational area</li></ol><p>Both features are of paramount importance. The first one eases the utilization of the generated trajectory as a patrolling path that can be executed continuously, enabling efficient <a href="https://dspace.mit.edu/bitstream/handle/1721.1/72576/Rus_Persistent%20robotic.pdf%3Bjsessionid%3D51E53761E974A9CDA71B1C4527464BFA?sequence%3D1">persistent coverage</a>. The latter enables the deployment of the mobile robot in different locations without having to change a thing in the mission plan!</p><h3><strong><em>Can the STC algorithm be useful in the multi-robot CPP domain?</em></strong></h3><h4>Yes! → <strong>Opt_MSTC Algorithm</strong> [<a href="https://ieeexplore.ieee.org/document/1641951">3</a>]</h4><blockquote><strong>Opt_MSTC Algorithm </strong>[<a href="https://ieeexplore.ieee.org/document/1641951">3</a>]</blockquote><blockquote>1. Extract a single path using STC algorithm</blockquote><blockquote>2. Each robot follows the segment that starts from its initial position till it reaches the starting position of any other robot</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*5uysLoJILAbGbyXUOYI7gA.png" /><figcaption>Opt_MSTC Algorithm</figcaption></figure><p><strong><em>Advantages:</em></strong></p><p>+O(n) independent of the number of robots</p><p>+non-backtracking solution</p><p>+complete coverage</p><p>+no mismatch between the current position and starting location</p><p><strong><em>Disadvantage:</em></strong></p><p>-Uneven robot trajectories. Highly dependent on the initial positions of the robots</p><p>The following illustration depicts the influence of the initial positions of the robots on their resulting paths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*xGhwAkIXihTMRadduF-kLA.png" /><figcaption>Opt_MSTC Algorithm with different initial positions for the robots</figcaption></figure><p>It is worth mentioning that the structure of the spanning tree can be tuned to favor a multi-robot setup with specific initial positions. However, there is no analytical methodology to completely remove the effect of the initial position of the robots on the resulted quality of the solution.</p><h4>Relax backtracking constrain</h4><p>Recognizing such an inefficient task allocation, many algorithms have been proposed to mitigate the effect of robots’ initial positions by relaxing the backtracking constrain of the original mCPP setup. The most representative approach is <strong>Multi-robot Forest Coverage (MFC)</strong> [<a href="https://ieeexplore.ieee.org/document/5629446">4</a>], a polynomial-time heuristic algorithm capable of constructing spanning trees for each robot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*ZB8difoxyTWZnEhTIxC0bA.png" /><figcaption>Multirobot Forest Coverage (MFC) Algorithm in action</figcaption></figure><p><strong><em>Advantages:</em></strong></p><p>+complete coverage</p><p>+no mismatch between the current position and starting location</p><p>+significant improvement over Opt_MSTC</p><p>+improved fairness among robots’ paths</p><p><strong><em>Disadvantages:</em></strong></p><p>-produced solution can be at most 16 times greater than the optimal one</p><p>-backtracking solution</p><blockquote><strong>In simple words, this family of approaches demonstrated that it was beneficial to sacrifice the non-backtracking property in exchange for more balanced robot paths.</strong></blockquote><h3>Exploit STC in mCPP domain with area division</h3><p>STC algorithm can optimally tackle the single-robot CPP problem under some mild discretization assumptions. <strong><em>How can we utilize this effectively?</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*uIiU490-yyqmaloLhWbxQQ.png" /></figure><blockquote><strong><em>Main idea</em></strong>: Define areas for each robot, and then apply STC algorithm to each one of them.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*k-tD66qXr9cjmZOULZmaNg.png" /></figure><p>By design, the STC paths inside these areas are going to be optimal, with respect to the optimality conditions defined earlier. But the catch here is that these paths are only optimal for the divided subparts, and the overall mCPP problem might not be appropriately tackled. Therefore, any such division should meet the following <strong><em>area division objectives</em></strong> to constitute an optimal solution after the appliance of the STC algorithm inside the separate robot regions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQuPiYNnetKMO_fOwFtd1g.png" /><figcaption>From the original mCPP to area division objectives</figcaption></figure><p>Having translated the original mCPP setup to an equivalent area division setup, we should now shift our attention to the algorithms/methodologies that could address such a setup.</p><h4>Voronoi space partitioning</h4><p>Probably the first approach that comes to mind is the <a href="https://en.wikipedia.org/wiki/Voronoi_diagram">Voronoi space partition</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdbgUQneVAjOt9qkzqyYjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*CM4Lsii8oER-2KndNQtWcA.png" /><figcaption>Voronoi partition for grd space</figcaption></figure><p><strong>How many of the area division objectives have been met?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIMfj5ETrkDO2J7ehXesvQ.png" /></figure><p>By applying Voronoi space partition, several conditions are already met, however,</p><blockquote><strong>the failure to construct equal regions, independently of the robots’ initial positions (3rd objective) is a big deal!</strong></blockquote><p>Technically, such a methodology would be pretty similar to Opt_MSTC [3], and the overall quality of the solution would strongly depend on the initial positions of the robots.</p><p>Let’s see this with an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNGt2N8wXtZa_gLj1H2KQg.png" /></figure><p>The final image graphically illustrates the Voronoi space partition based on the Euclidean distance matrices. The cyan robot will cover 32 cells, while the red robot will only cover 4 cells. Assuming that both robots have the same moving and sensing capabilities and can operate simultaneously, the above grid will be covered in 32 x [the time need to scan one grid cell] (completion time for the robot with the longer task).</p><blockquote>Let’s now assume that we have <strong><em>some other evaluation metric</em></strong> (not the Euclidean one), as it is depicted below:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXMMCDyupPcMAu09zfSudQ.png" /></figure><p>Using this evaluation metric instead of the Euclidean distance results in a fair assignment of 18 cells per robot, reducing the overall completion time by 43%. With the above assignment matrix, we may now apply “blindly” the STC algorithm in each robot territory and ensure that we reached the optimal solution for the original mCPP setup.</p><blockquote><em>The takeaway message is that </em><strong><em>Voronoi partitioning</em></strong><em> coupled with </em><strong><em>some other metric function</em></strong><em> can satisfy the previously defined area-division objectives and therefore tackle the original mCPP problem.</em></blockquote><blockquote>But how can we find such a metric function that strongly depends on the area morphology and the initial positions of the robots?</blockquote><h3>Divide Areas based on Robots’ Initial Positions (DARP)</h3><p>That’s exactly the goal of Divide Areas based on Robot’s Initial Positions (DARP) algorithm [<a href="https://link.springer.com/article/10.1007/s10846-016-0461-x">5</a>].</p><h4>Core idea:</h4><blockquote>&gt; Retain the<strong> assignment process</strong> from <strong>Voronoi partitioning</strong> and</blockquote><blockquote>&gt; <strong>Tune each robot’s metric function</strong> to meet the 3rd (<strong>equal division</strong>) objective <strong>without violating the others</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DK2GPeYi7DaKIjW3EGd62w.png" /></figure><p>DARP algorithm stems from 2 elements:</p><h4><strong><em>1. There is a metric to evaluate area equality</em></strong>:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaqM36DVSgoWPhi6bM4TFA.png" /></figure><p>&gt; [<strong><em>Important]</em></strong><em> </em>The number of cells that should be assigned to each robot is <strong>known apriori.</strong></p><h4>2. Update robots’ metric tables using a multiplier:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m4y6s4e-gpfInTVm50CptQ.png" /></figure><p>Combining these two elements, we can construct DARP algorithm version 0.5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltDgVswgcfCg8s0k4YKHAw.png" /></figure><p>In essence, the DARP algorithm follows a <a href="https://en.wikipedia.org/wiki/Coordinate_descent"><strong>cyclic coordinate descent</strong></a> optimization scheme updating each robots’ territory separately but towards achieving the overall mCPP objectives.</p><p><strong><em>Advantages:</em></strong></p><p>+convergence guarantees from the coordinate descent algorithms</p><p>+fast optimization procedure</p><p>+very easy to implement</p><p><strong><em>Disadvantages:</em></strong></p><p>-Spatial connectivity inside each robot’ territory is not guaranteed</p><h4>Deal with spatial disconnectivity</h4><p>Although in the original Voronoi partitioning, spatial connectivity was guaranteed by design, now, in some cases is violated. This phenomenon is due to the fact that now <strong><em>the metric function for each robot</em></strong>, over which the assignment process is implemented, <strong><em>is no longer a distance function</em></strong>. For example, the following figure illustrates the initial partitioning (left-hand side) based on the Euclidean distance, and the subfigure on the right-hand side illustrates the assignment after some iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nukXovpf2H9ZZnzdqfw8Q.png" /><figcaption>Spatially disconnected partitions can now be formed</figcaption></figure><p>It is evident that the purple region is disconnected, and therefore with such an assignment, the non-backtracking guarantee is now at risk. To tackle this issue, an extra connectivity matrix is introduced. The rationale behind the calculation of this connectivity matrix is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dx7Mw4afNmZnw8px3m1VIQ.png" /></figure><p>In essence, the DARP algorithm incentivizes closed shape regions around the robot’s initial position and attempts to eliminate all the others, as is graphically illustrated in the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7uSOXd8hZ4G8ywNxNvWVSg.png" /><figcaption>Reward closed shape regions around the robot’s initial positions and penalize all the others.</figcaption></figure><p>The following pseudocode presents the DARP algorithm [<a href="https://link.springer.com/article/10.1007/s10846-016-0461-x">5</a>], which also encapsulates the connectivity matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCm52UJd9JmogwiYoq9JCg.png" /><figcaption>DARP algorithm [5] pseudocode</figcaption></figure><p>At a glance, the operation of the DARP algorithm coupled with STC for each robot region is illustrated in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40_ka3Zpc26GQIwyJDJgcA.png" /><figcaption>DARP+STC fundamental steps</figcaption></figure><p>During the optimization process and depending on the difficulty of the mCPP setup, robots’ territories are expected to change formation several times till the convergence to a fair and spatially connected division:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Yo9zPAwuv90U4X2Nia-aIA.gif" /><figcaption>Assigned cells per robot vs. Current assignment matrix</figcaption></figure><h4>Beyond fair division</h4><p>The DARP algorithm, as defined in version 1.0 pseudocode, is tuned to provide equal-area division among the operational robots. However, there are cases where a custom-defined percentage of coverage is more preferable. Such cases could include scenarios with heterogeneous robots, different battery levels, or other human-imposed reasons (e.g., underutilize a specific robot to be readily available for a follow-up mission). To cope with such custom-defined percentages of coverage, the following change in the objective function should take place:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ksu8lcxvhcQ9ZHcMx-zltA.png" /></figure><p>In a nutshell, compared to DARP version 1.0, only the update rule for the ith robot is going to change to encompass the robot-specific percentage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-UsLyVwnkhFXeYjLymFRA.png" /></figure><p>An example of such a path-planning with 3 robots with 50%, 30%, and 20% requested percentages of coverage is illustrated in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*ohcNoIbm3sWLPGnnJ_4big.png" /><figcaption>Proportional division in mCPP setup</figcaption></figure><h3>Material</h3><p><strong>Paper</strong>: <a href="https://zenodo.org/record/2591050#.YS4gg44zYuV">Zenodo</a></p><p><strong>GitHub repositories</strong>: <a href="https://github.com/athakapo/DARP">Java</a>, <a href="https://github.com/alice-st/DARP-Python">Python</a></p><p><strong>GUI demo</strong>: <a href="https://www.youtube.com/watch?v=LrGfvma41Ak">YouTube</a></p><p><strong>ROS integration</strong>: <a href="http://wiki.ros.org/area_division">Wiki</a></p><h3>Acknowledgments</h3><p>Big thanks to Savvas Apostolidis and Aliki Stefanopoulou for their helpful comments on the original draft of this article.</p><h3>References</h3><p><em>[1] Rekleitis, I., New, A.P., Rankin, E.S. and Choset, H., 2008. Efficient boustrophedon multi-robot coverage: an algorithmic approach. Annals of Mathematics and Artificial Intelligence</em></p><p><em>[2] Gabriely, Y. and Rimon, E., 2001. Spanning-tree based coverage of continuous areas by a mobile robot. Annals of mathematics and artificial intelligence</em></p><p><em>[3] Agmon, N., Hazon, N. and Kaminka, G.A., 2006, May. Constructing spanning trees for efficient multi-robot coverage. ICRA 2006</em></p><p><em>[4] Zheng, X., Koenig, S., Kempe, D. and Jain, S., 2010. Multirobot forest coverage for weighted and unweighted terrain. IEEE Transactions on Robotics</em></p><p><em>[5] Kapoutsis, A.C., Chatzichristofis, S.A. and Kosmatopoulos, E.B., 2017. DARP: divide areas algorithm for optimal multi-robot coverage path planning. Journal of Intelligent &amp; Robotic Systems</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fed77b990a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>