<?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 Nikolaos Kokkinis Ntrenis on Medium]]></title>
        <description><![CDATA[Stories by Nikolaos Kokkinis Ntrenis on Medium]]></description>
        <link>https://medium.com/@nikoskokkini?source=rss-712f01e3509c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3FcIP51lp7FarASz8sNisg.jpeg</url>
            <title>Stories by Nikolaos Kokkinis Ntrenis on Medium</title>
            <link>https://medium.com/@nikoskokkini?source=rss-712f01e3509c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:29:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikoskokkini/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[Summary Review of Imitation Learning Algorithms.]]></title>
            <link>https://nikoskokkini.medium.com/summary-review-of-imitation-learning-algorithms-33ca1464233c?source=rss-712f01e3509c------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ca1464233c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[imitation-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Nikolaos Kokkinis Ntrenis]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 11:30:39 GMT</pubDate>
            <atom:updated>2021-12-16T11:30:39.806Z</atom:updated>
            <content:encoded><![CDATA[<p>Reinforcement learning has been successfully applied in domains where the reward function is well defined. But in real-world scenarios, typically it is not clear at all what the reward function should be. Also, manually designing and tweaking a reward function for a task is an incredibly difficult task, which comes with several drawbacks and potential for errors. Instead of attempting to learn from sparse rewards or a hand-crafted reward function, the agent in imitation learning (IL) is provided with a collection of demonstrations. Then it attempts to learn the best policy by imitating the expert’s decisions. The main component of IL is the environment, which is a Markov Decision Process (MDP) with an unknown reward function r(s, a). The agent takes various actions in this environment based on its policy π(a|s). For retrieving a better policy, the agent is using also expert’s demonstrations/trajectories τ = (s_0, a_0 , s_1 , a_1 , . . . ), where the actions are based on the expert optimal policy π^(*) (a|s). Imitation learning or learning from expert trajectories can be implemented in the following different ways.</p><p><strong>Behavioral Cloning:</strong> Behavior cloning (BC) [1] is the most basic form of an imitation learning technique, focusing on learning the expert’s policy through supervised learning techniques. The agent is provided with expert demonstrations as state-action pairs. It is assumed that these pairs are independent and identically distributed (i.i.d.) samples, to be able to be used in supervised learning methods. Behavioral cloning can be extremely effective in some applications. On the other hand, might be quite problematic in the vast majority of cases. The primary issue is the i.i.d. assumption. While supervised learning assumes that the state-action pairs are distributed independently and identically. The MDP breaks the i.i.d. assumption since the action in a given state generates the following state. This also implies that errors made by the agent in previous states are accumulated over to subsequent states. As a result, a slip made by the agent can easily place him in a state that the expert has never visited and therefore the agent was never trained on. In such states, the behavior of the agent is undefined and might result in fatal failures.</p><p><strong>Direct Policy Learning:</strong> Direct policy learning (DPL) [2] is a better version of behavioral cloning. This method presumes that the algorithm has access to interactive expert demonstrations during training. Similar to behavioral cloning, the agent collects some of the expert’s demonstrations and uses supervised learning techniques to learn a policy π(a|s). The agent will then roll out this policy in the environment in which it has been trained, and the expert will be consulted to evaluate the roll-out trajectory. As a result, the agent receives more training data, which is then fed back to the supervised learning method. This loop is repeated until convergence is reached.</p><p><strong>Inverse Reinforcement learning:</strong> This is the approach that will be further discussed in this blog post. Inverse reinforcement learning (IRL) [3] attempts to estimate the reward function of the environment based on the expert’s demonstrations. Then, using reinforcement learning to retrieve the optimal policy. This method learns a cost function that prioritizes some trajectories over others. Due to their bi-level optimization nature, many existing IRL methods must solve a series of computationally expensive reinforcement learning problems. As a result, they frequently fail to scale to large high-dimensional environments. Having the knowledge of the reward function is in some way more robust than the knowledge of expert policy. For example, if some part of the environment changes, behavior cloning will lead to sub-optimal behavior, while having knowledge of the reward function contains enough information to robustly adapt the agent’s behavior to still achieve the task. Additionally, in literature, IRL and inverse optimal control (IOC) are often used as synonyms. The most important difference is that optimal control talks about the cost function c(s, a) while IRL talks about reward function r(s, a).</p><p><strong>1. Generative Adversarial Imitation Learning (GAIL)</strong></p><p>Generative Adversarial Imitation Learning (GAIL) [4] is a model-free imitation learning algorithm, in the category of Inverse Reinforcement learning, that obtains significant performance gains over existing model-free methods in imitating expert trajectories in large high-dimensional environments. The algorithm is a combination of imitation learning and generative adversarial networks (GAN) [5]. GAIL characterize the given policy by running reinforcement learning on a cost function c ∈ C = RS×A learned by maximum causal entropy IRL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*rkKX8E0V_1HVZayLWU9jdw.png" /><figcaption>Equation 1</figcaption></figure><p>where H(π), E_π [−log π(a|s)] is the γ-discounted causal entropy [6] of the policy π, the c(s, a) is the cost for state action pair and Π is the set of all stationary stochastic policies. Maximum causal entropy IRL looks for a cost function c that assigns low cost to the expert policy and high cost to other policies, thereby allowing the expert policy to be found via a certain reinforcement learning procedure (RL: cost →policy):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*kwYeA5izPjqjK0e_IhdDbA.png" /><figcaption>Equation 2</figcaption></figure><p>This RL procedure maps a cost function to high-entropy policies that minimize the expected cumulative cost. Having such a large dimensional space of C, IRL can easily overfit when provided with a finite dataset. For this reason, it uses a convex cost function regularizer ψ: R^(S×A )→ hat(R), where hat(R) denote the extended real numbers R ∪ ∞. So (Equation 3) is the IRL cost function, which finds a cost function such that the expert performs better than all other policies, using the cost regularization term ψ (IRL: demonstration →cost) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*o29UkFWcRa6Q7K_5dJIrnQ.png" /><figcaption>Equation 3</figcaption></figure><p>As a total output, the agent is trying to learn a policy given by RL(c̃), this is the policy given by running reinforcement learning on the output of IRL. The optimal policy is obtained by running RL(IRLψ (π_E ))= RL ◦ IRLψ (π_E )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*kCXWbV3DIjv9j-_t2I3zcA.png" /><figcaption>Equation 4</figcaption></figure><p>where ρ_π = π(a|s)Σ_(τ=0 -&gt; τ=∞) γ^(t) P (st = s|π) is occupancy measure of a policy (distribution of state-action pair encountered while navigating the environment with this policy π). The ψ∗ is a convex conjugate of ψ, which regularized inverse reinforcement learning, implicitly, seeks a policy whose occupancy measure is close to the expert. If cost regularization didn’t exist at all, then the recovered policy will exactly match the expert occupancy measure. The expert trajectory distribution will be provided only as a finite set of samples, so in large environments, most of the expert occupancy measure values will be zero. As a result, having an exact occupancy measure matching will force the learned policy to never visit these unseen state-action pairs simply due to a lack of data.</p><p>Using linear cost function regularizer ψ with some chosen features of the states (e.g. Apprenticeship Learning [3]), having as a goal to find the policy performing better than the expert min_π max_(c ∈ C) E_π [c(s, a)] − E_(π_E) [c(s, a)] which leads to an imitation learning algorithm that exactly matches occupancy measures. However linear cost function regularizer is unmanageable in large environments and needs carefully tuning. For this reason, GAIL use the below regularizer which places a low penalty on cost functions <strong>c</strong> that assigns an amount of negative cost to expert state-action pairs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yXxW4FoKbngZ9MOjl4oesA.png" /><figcaption>Equation 5</figcaption></figure><p>An interesting property of GA regularizer is that it is an average over expert data and therefore can adjust to arbitrary expert datasets. On the other hand, a regularizer using linear apprenticeship is always fixed and cannot adapt to the data. The choice of regularizer ψ∗_(GA) draws the connection between imitation learning and generative adversarial networks, which trains a generative model G by having the discriminator D: S × A →(0, 1) to distinguish the distribution of data generated by G and the true data distribution. When D cannot distinguish data generated by G from the true data, then G has successfully matched the true data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*O_KYXTA1cvFZj1kLIhlIlA.png" /><figcaption>Equation 6</figcaption></figure><p>Equation 6 is the optimal negative log loss of the binary classification problem of distinguishing between state-action pairs of π and π_E. In this setting, the learner’s occupancy measure will be analogous to the data generated by G and the expert’s occupancy measure is analogous to the true data distribution. The discriminator function can be interpreted as a local cost function providing learning signals to the policy. It turns out that this optimal loss is the Jensen-Shannon divergence D_(JS) (ρ_π − ρ_(π_E)) = D_(KL) (ρ_π ||(ρ_π + ρ_(π_E) )/2) + D_(KL) (ρ_(π_E) ||(ρ_π + ρ_(π_E) )/2), which is a squared metric between distributions. Treating the causal entropy H as a policy regularizer, controlled by λ &gt; 0, we obtain a new imitation learning algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ybCrumxsRCICXjaC52OlfQ.png" /><figcaption>Equation 7</figcaption></figure><p>which minimizes a true metric between occupancy measures. Unlike linear apprenticeship learning algorithms, it can imitate expert policies exactly. GAIL relies crucially on the TRPO policy step to decrease (Equation 7) with respect to π(a|s). TRPO is a natural gradient step constrained to ensure that π_(θ_i +1) (a|s) doesn’t stray too far from π_(θ_i) (a|s), as measured by KL divergence between the two policies averaged over the states in the sampled trajectories. This carefully constructed step scheme ensures that divergence doesn’t occur due to high noise in estimating the gradient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*fhOWbIQxOviL67H49ommvw.png" /><figcaption>Figure 1: Flow of the GAIL algorithm. Solid and dotted arrows respectively represent (forward)<br>flow of information and (backward) flow of gradient.</figcaption></figure><p>IRL was traditionally defined as the act of finding a cost function such as the expert policy. Although, now IRL could be viewed as a procedure that tries to induce a policy that matches the expert’s occupancy measure (generative model).</p><p><strong>2 Sample-Efficient Imitation Learning via Generative Adversarial Nets<br>(SAM)</strong></p><p>Sample-Efficient Imitation Learning via Generative Adversarial Nets (SAM) [7] is a model-free imitation learning algorithm that combines deterministic policy gradients with an adversarial reward learning procedure having a significant increase in sample efficiency. Sample-efficient indicates limiting the number of agent-environment interactions. The interactions are decreased since the agent keeps experiential data in memory to perform policy updates. Therefore requires considerably fewer new samples (interactions) per iteration, as it can re-exploit the stored transitions. In addition, it doesn’t rely on any prepossessing to permit gains in sample efficiency. The SAM algorithm is based on DDPG and GAN algorithms, which bring the sample efficiency of off-policy actor-critic methods and leverage gradient information. GANs and actor-critic architectures can be both framed as bilevel optimization problems, each involving two competing components. In one problem, the policy is trained against the reward, while in the other, the policy is trained against the critic.</p><p>SAM is composed of three interconnected learning networks: a reward network (parameter φ), a policy network (parameter θ), and a critic network (parameter ψ). The reward network with parameter φ, operating as the discriminator. The cross-entropy loss for the reward network is derived as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*Ke0pUJS0rFV50VzvSxQcWw.png" /><figcaption>Equation 8</figcaption></figure><p>where R_(GP) (φ) is a penalty to improve the stability on the discriminator gradient and D_(φ) is the decoder. The reward network is trained on each iteration, firstly on the most recently collected mini-batch of π_θ (a|s). Then on mini-batches sampled from the replay buffer, D. As for the loss function is optimized by the critic L(ψ), which relies only on samples from replay buffer D. The loss functions incorporate three components: a 1-step Bellman residual L1(ψ), an n-step Bellman residual Ln (ψ) and a weight decay regularizer R_(WD(ψ))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*hTOUrf8o--B893ZvVmv64w.png" /><figcaption>Equation 9</figcaption></figure><p>where v ∈ [0, 1] is a hyperparameter that determines how much decay is used. Note that in SAM decay regularizer is used only on critics, not in the policy. Since with the use of the policy on the regularizer, the policy will have an appearance in two different optimization problems. The 1-step and n-step look-ahead are defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*ecCOJFabS2JJekRT4eaW5w.png" /><figcaption>Equation 10</figcaption></figure><p>where E_(s_t ∼ρ^β, α_t ∼β [·]) indicates transitions that have been sampled from the replay buffer D, using the off-policy β. Applying multi-step targets with suitably tuned n ∈ N often leads to faster learning and better stability as we have seen in RAINBOW (<a href="https://nikoskokkini.medium.com/summary-review-of-reinforcement-learning-algorithms-29c4f5eec461">link</a>). The target policy μ_θ is updated by taking gradient ascent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*YrT8KJzwTi7h2n8FEvYkiQ.png" /><figcaption>Equation 11</figcaption></figure><p>this policy gradient indicates the regions of the parameter space that have high similarity with the demonstrator trajectories. The exploration problem is treated as in DDPG, applying adaptive perturbation noise or sampled from an Ornstein-Uhlenbeck process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*A5mdd-qCThZUz4bb2QGiGA.png" /><figcaption>Equation 12</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*6YnHImrdlbHsGlM2PNqvhQ.png" /><figcaption>Figure 2: Flow of the SAM algorithm. Solid and dotted arrows respectively represent (forward)<br>flow of information and (backward) flow of gradient.</figcaption></figure><h3>References</h3><p>[1] Caude Sammut. “Behavioral Cloning”. In: Encyclopedia of Machine Learning. Ed. by Claude Sammut and Geoffrey I. Webb. Boston, MA: Springer US, 2010, pp. 93–97. isbn: 978–0–387- 30164–8. doi: 10.1007/978–0–387–30164–8_69. url: <a href="https://doi.org/10.1007/978-0-">https://doi.org/10.1007/978-0-</a>387–30164–8_69.</p><p>[2] Jessica Chemali and Alessandro Lazaric. “Direct policy iteration with demonstrations”. In: Twenty-Fourth International Joint Conference on Artificial Intelligence. 2015.</p><p>[3] Pieter Abbeel and Andrew Y Ng. “Apprenticeship learning via inverse reinforcement learning”. In: Proceedings of the twenty-first international conference on Machine learning. 2004, p. 1.</p><p>[4] Jonathan Ho and Stefano Ermon. “Generative adversarial imitation learning”. In: arXiv preprint arXiv:1606.03476 (2016).</p><p>[5] Ian J Goodfellow et al. “Generative adversarial networks”. In: arXiv preprint arXiv:1406.2661 (2014).</p><p>[6] Michael Bloem and Nicholas Bambos. “Infinite time horizon maximum causal entropy inverse reinforcement learning”. In: 53rd IEEE Conference on Decision and Control. IEEE. 2014, pp. 4911–4916.</p><p>[7] Lionel Blondé and Alexandros Kalousis. “Sample-efficient imitation learning via generative adversarial nets”. In: The 22nd International Conference on Artificial Intelligence and Statistics. PMLR. 2019, pp. 3138–3148.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ca1464233c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summary Review of Reinforcement Learning Algorithms]]></title>
            <link>https://nikoskokkini.medium.com/summary-review-of-reinforcement-learning-algorithms-29c4f5eec461?source=rss-712f01e3509c------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c4f5eec461</guid>
            <category><![CDATA[actor-critic]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[on-policy-algorithms]]></category>
            <category><![CDATA[off-policy-algorithms]]></category>
            <dc:creator><![CDATA[Nikolaos Kokkinis Ntrenis]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 12:18:42 GMT</pubDate>
            <atom:updated>2021-12-15T20:08:02.582Z</atom:updated>
            <content:encoded><![CDATA[<p>In the general framework of reinforcement learning (RL), exist an agent that each time step decides and executes an action a ∈ A to interact with the environment/simulator. Then the environment reacts by moving the agent from the present state of the environment sₜ∈ S, to the next state sₜ+1 ∈ S. During each step, the environment emits a scalar value signal, called reward rₜ ∈ R for reaching this state. Indicating on the agent if the chosen action results in a good or bad state. The interaction between the agent and the environment can continue forever or until some stop criteria would be satisfied. The main goal of the RL agent is to gather the largest amount of cumulative reward, which is called return R ∈ R.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*CJX3L1TTdYcQbdqvDOpgBg.png" /><figcaption>Return at timestep t (Equation 1)</figcaption></figure><p>where γ ∈ [0, 1] is the discount factor, Rt and rt are the return and reward function on time-step t. T ∈ R is the horizon of the MDP. To increase the return, the agent has to find an optimal policy. A policy is a function that outputs the action or the probability distribution over actions, in the case<br>of the policy being stochastic, that the agent should execute in the environment given its present state. Thus an optimal policy could be thought of as the best strategy employed by the agent to interact with the environment, in order to collect the biggest amount of cumulative rewards. Thus reinforcement learning algorithms try to discover the optimal policy, which increases the return of the agent during its interaction with the environment.</p><p>Moreover, the environment could be deterministic or stochastic. Deterministic means that the identical action of the agent been in the same state end up in identical next state. Stochastic environment, indicate that identical action of the agent in the same state won’t necessarily result in the same next state. Of course, these uncertainties have as result to make finding the optimal policy harder. The problem is commonly defined mathematically as a Markov decision process (MDP). An MDP is a way to represent the environment’s dynamics. It formulates the manner in which the environment will interact with the actions that the agent may take at a particular state.</p><p>An MDP, to be more precise, use the transition function. The transition probability function defines the resulting location of the agent on the environment. Having as input the present state of the agent and the actions that the policy has selected. In the scenario of a stochastic environment,<br>the transition function outputs the probability of transferring the agent to any of the next states. An MDP is also associated with the reward function. Collectively, the transition and reward functions are frequently referred to as the model of environment M = (p, r).</p><p>However, regularly doesn’t exist the transition and reward functions in all the environments. Hence, the agent can’t estimate the optimal policy using the MDP, because it is unknown. In the absence of those functions, when the MDP is unknown, the agent interacts with the environment and observes its responses in order to estimate the optimal policy. Over time, the agent gains an understanding of how the environment reacts to its actions, and it can thus begin to approximate the optimal policy. In this manner, the agent estimates the best way of behaving in an unfamiliar (or partially known) environment by interacting with it using a “trial-and-error” approach. The main split on RL is on-policy vs off-policy, in the context of this blog post are being reviewed and summarized several representative algorithms of RL.</p><h3>1. On Policy Algorithms</h3><p>In this section, we will focus on three on-policy learning algorithms which use policy gradient methods. Those methods depend on optimizing their unique policy with respect to the expected return using stochastic gradient ascent. Policy gradient methods can deal with continuous states and action space precisely the same way as the discrete ones. Convergence at least to a local optimum is guaranteed. Also, policy gradient methods could be used either in model-free or model-based environment settings as they’re a generic formulation.</p><p><strong>1.1 REINFORCE</strong></p><p>The REINFORCE [3] algorithm, also sometimes called as Monte-Carlo policy gradient or Vanilla Policy Gradient (VPG), is the simplest policy gradient method that relies on <strong>Qπ (s, a) ∈ R</strong> function. More complicated methods have been built and developed using REINFORCE, like the Trust Region Policy Optimization (TRPO) or the Proximal Policy Optimization (PPO).</p><p>In general, a policy gradient algorithm is a policy iteration approach, where policy is directly manipulated to reach the optimal policy that maximizes the expected return. This kind of algorithm is model-free reinforcement learning, so the environment dynamics or transition probability function aren’t known. Additionally, as it is depicted in (Figure 1), the use of the Mote-Carlo sampling from REINFORCE implies that the RL agent sample from the starting state to the goal state, rather than bootstrapping as Temporal Difference Learning and Dynamic programming doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4nxiMQs2gEA3nmwWFku0Q.png" /><figcaption>Figure 1: Difference between Monte-Carlo, Temporal-Difference Learning, and Dynamic program-<br>ming [4]</figcaption></figure><p>In REINFORCE, as in other policy gradient algorithms, the gradient steps aim to minimize loss function by incrementally modifying the policy network parameters. Thus the resulting loss function in the original REINFORCE algorithm is derived as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*o9QqUWDaA0BWDFPfJfcJWg.png" /><figcaption>Equation 2</figcaption></figure><p>where the log term is the log probability of taking some action <strong>a</strong> at some state <strong>s</strong>, and Rₜ is the return, the sum of the discounted rewards from the time-step <strong>t</strong> up until the end of the episode. In practice, the above loss function isn’t typically used as its performance is restricted by the high variance in the return <strong>R</strong> over entire episodes. To combat this, the advantage estimate function is introduced in place of the return function R. The advantage function is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*XUKFxqZzAJZ5q0JXr5QZGQ.png" /><figcaption>Equation 3</figcaption></figure><p>where V (sₜ) is a learned value function that estimates the value of a given state Q(sₜ, aₜ) is the Q-function at state t, also called as action-value function, which is formulated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*Ufmqm8_OGwze_TPsTW1tmA.png" /><figcaption>Equation 4</figcaption></figure><p>which indicates the value of state s and an action an under the policy π. The r is the reward received from transitioning from state st, into state sₜ+1 , by taking action <strong>a</strong>, and γ is the discount rate. Adding the advantage in the loss function (Equation 2) then becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*vvmLbAMhoKd_se7iZOKedg.png" /><figcaption>Equation 5</figcaption></figure><p>Since the value function is learned over time as more updates are performed, it introduces some margin bias caused by the imperfect estimates but decreases the overall variance as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*_ReDxAl1KFybWc48msBv2w.png" /><figcaption>Equation 6</figcaption></figure><p>Aₜ^(1) ∈ R is high bias, low variance, while the Aₜ^(∞)∈ R is unbiased, high variance. A technique called Generalized Advantage Estimation (GAE) [5] is employed to compute the advantage in the loss term:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*bOhizL0FYHLbUqpJO-DYQg.png" /><figcaption>Equation 7</figcaption></figure><p>This introduces a hyperparameter λ ∈ [0, 1] that might be utilized to tune the amount of variance vs bias in each update, where λ=1 leads to maximum variance and nil bias, and λ=0 leads to opposite results.</p><p><strong>1.2 Trust Region Policy Optimization (TRPO)</strong></p><p>Trust Region Policy Optimization (TRPO) [6] is analogous to the natural policy gradient method since it uses gradient ascent to retrieve policies that increase the return. Also, is effective for optimizing large nonlinear policies such as neural networks. TRPO could be applied to environments with continuous or discrete action spaces. It updates the policy by taking the widest step possible that enhances its performance. However, first-order optimization isn’t very accurate for curved areas. It could get overconfident and make poor decisions that will ruin the progress of the training. For this reason, it should satisfy a special constraint on how close the new and old<br>policies can be. The constraint is expressed by the use of Kullback-Leibler (KL) Divergence [7], which is a measure of distance between two probability distributions. This imposes a constraint that the KL divergence is bounded at every point within the state space <strong>S</strong>. The loss function of TPRO algorithm measure how new policy <strong>π_θnew</strong> performs in comparison to the previous policy<strong> π_θold</strong> using data from the old policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*ZorZ7iuRR2QTVP9lyuho8A.png" /><figcaption>Equation 8</figcaption></figure><p>where A(s,a) is advantage function (Equation 3) and D_KL (θ_old , θ_new ) is the mean of Kullback- Leibler divergence between policies across states visited by the old policy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*ETVO5mXqc4QHiSO13y-KOA.png" /><figcaption>Equation 9</figcaption></figure><p><strong>1.3 Proximal Policy Optimization (PPO)</strong></p><p>Proximal policy optimization (PPO) [8] is an on-policy optimization algorithm that performs multiple epochs of stochastic gradient ascent in every policy update. PPO has the stability and reliability of TRPO. However, it is much easier to implement and has higher sample complexity. There are 2 primary variants of PPO: PPO-Penalty and PPO-Clip.</p><p><strong>PPO-Penalty [8]</strong>: approximately solves a KL-constrained update, like TRPO. However, penalizes the KL-divergence among the objective function rather than creating a strict constraint. This variant of PPO automatically adjusts the penalty coefficient by updating parameter δ, over the course of training so that could be scaled appropriately.</p><p><strong>PPO-Clip [8]</strong>: relies on specialized clipping within the objective function to eliminate incentives for the new policy to diverge from the old policy. As a result, it doesn’t use at all the KL constraint in the objective function.</p><p>The approach of PPO-Clip will be explained more in this section since it introduces novelty using the clipping while the PPO-Penalty indicates an improved implementation of TRPO where on each iteration compute and update δ of the KL-Divergence consistent with the curvature of the surface.<br>To optimize its policy, PPO alternate between sampling data generated from the current policy. Thus, for improving its policy on the sampled data, it is performing several epochs of stochastic gradient ascent. The novel objective function that enables multiple epochs of mini-batch updates is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*eBEMA6VXDYtXaQMPvQhY6w.png" /><figcaption>Equation 10</figcaption></figure><p>The goal for this objective function is as follows. The second term, clip(kₜ (θ), 1-e, 1+e)Aₜ^ (π_θold), modifies the surrogate objective function by clipping the probability ratio, which discards the incentive for moving kₜ outside of the interval [1-e, 1+e]. The probability ratio kt is clipped depending on whether the advantage is positive or negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*qbLoaZ6h13DmYBz6BSDNtw.png" /><figcaption>Figure 2: The probability ratio kₜ , for a positive (left) and a negative (right) advantage function.<br>The red circle on each plot represents the optimization’s starting point.</figcaption></figure><p>When the output of the advantage function is positive (left plot on Figure 2), the objective function will increase if the action becomes more likely that is, since π_θnew (a|s) increases. Although the min places a proportional limit on how much the objective function can increase. When π_θnew (a|s)&gt; (1+e ) π_θold (a|s), the min kicks in and this term hits a ceiling of (1+e) * Aₜ^(π_θold) (s, a). As a result, the new policy doesn’t profit by going away from the previous policy. In the opposite case of a negative advantage function (right plot on Figure 2), the objective function will increase if the action becomes less likely that it is since π_θnew (a|s) decreases. Having the max on this term introduces a limit of the amount that the objective could increase. Since π_θnew (a|s) &lt; (1-e) π_θold (a|s), the max kicks in and this term hits a ceiling of (1-e) Aₜ^(π_θold) (s, a). Thus, again the new policy doesn’t profit by going far from the previous policy.</p><p>PPO uses a loss function that incorporates the policy surrogate and value function error terms. This objective can further be expanded by adding an entropy bonus term to provide sufficient exploration. Combining these terms, we obtain the following objective, which is maximized on each iteration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*huDi1PS0DMJFrN4VJ6ctDw.png" /><figcaption>Equation 11</figcaption></figure><p>where <strong>c1, c2</strong> ∈ R are coefficients, <strong>S</strong> ∈ [0, 1] denotes the entropy bonus and Lₜ^(VF) ∈ R is a squared error loss (V_θ (st) − Vₜ ^(target) )^2. PPO tries to optimize a stochastic policy in an on-policy way. This suggests that it explores by sampling actions according to the most recent version of its stochastic policy. The amount of randomness in action selection depends on both initial conditions and training procedures. Over the course of training, the policy generally becomes less random, because the update rule encourages it to exploit rewards that it is already found. This could cause the policy to get trapped in local optima.</p><h3><strong>2. Off-Policy Algorithms</strong></h3><p>In this section, we will concentrate on 3 Markov Decision Process off-policy algorithms. Off-policy reinforcement learning algorithms are able to learn a new target policy by the historical data obtained from different behavior policies — under of non-stationary episodic Markov Decision Processes. This is convenient for having parallel learning (which could facilitate speeds up the convergence) or continuous exploration with the utilization of additional behavioral policies.</p><p><strong>2.1 Q-learning</strong></p><p>Q-learning [9] is a model-free reinforcement learning. It can also be viewed as a technique of asynchronous dynamic programming (DP) [1]. It provides agents with the aptitude of learning to act optimally in Markovian domains by experiencing the residuals of actions. For any finite Markov decision process (FMDP), Q-learning is able to retrieve an optimal policy in the sense of maximizing the expected value of the total reward over the successive steps, starting from the current state. It is important to note that Q-learning can only be used in environments with discrete action spaces. The theory of dynamic programming (DP) [22, 23] assures that exist at least one optimal stationary policy π^∗ such that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*-Co_pd1Xv7kM5yOabDuIXw.png" /><figcaption>Equation 12</figcaption></figure><p>where p(s, a, s’) is the transition probability function and s, s’ depicts the state and next state accordingly. Using Dynamic programming (DP) instead of Q-learning will provide a variety of ways for calculating the optimal value function V^(∗) (s) and policy π^(∗) (a|s). However, DP assumes that the reward function and transition function are known. The task that is facing the Q-learning algorithm is to retrieve an optimal policy π^(∗) (a|s) without initially knowing reward and transition functions. Therefore the Q-function (or action-value) having the policy π(a|s) is derived as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*4wIVmqkttEVEOdG5nvNbyQ.png" /><figcaption>Equation 13</figcaption></figure><p>The optimal Q-function Q^(∗) (s, a) is formulated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*kxxeZpjsjt0IX_6cXC9s2g.png" /><figcaption>Equation 14</figcaption></figure><p>In other words, the Q value function is the expected discounted reward for executing action <strong>a</strong> at state <strong>s</strong> by following policy <strong>π</strong>. The objective of the Q-learning algorithm is to estimate the <strong>Q</strong> values to retrieve the optimal policy. The Q-learning agent is following a 5 step process as is depicted in (Figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*pziGC0tTQ7_4xXKNOGYQiQ.png" /><figcaption>Figure 3: Q-learning Algorithm</figcaption></figure><p>In addition, the Q-learning algorithm uses the action-replay process ARP (as described in the first implementation) where currently has the convenient name of Q-Table. Q-Table is a data structure used to compute the maximum expected future rewards for each action at any given state. Basically, this table will direct agent selection on the best action at each state. As a result, the Q-Learning algorithm tries to update the values of the Q-table. The equation to update the Q-table is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*BEtfU7TOvtFLsMbhURCmzg.png" /><figcaption>Equation 15</figcaption></figure><p>where lr ∈ R is the learning rate and max Q’ (s’, a’ ) is the maximum expected future reward given the next state s’ and all possible actions on the next state. The optimal Q-function follows a fundamental identity rule known as the Bellman equation [10]. This is based on the following hypothesis: if the optimal value Q^(∗) (s’, a’) of the next state s’ was known for all possible actions a’, then the optimal strategy is to choose the action a’ maximizing the r + Q^(∗) (s’, a’).</p><p><strong>2.2 Deep Q-learning (DQN)</strong></p><p>Deep Q-learning [11] is a deep neural network algorithm that is trained with a variant of the Q-learning [9] algorithm using stochastic gradient descent to update its weights. The basic idea behind several reinforcement learning algorithms is to estimate the action-value function Q(s, a), by using the Bellman equation as an iterative update</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*OzoAgCdNBAeHaFcanbI5bA.png" /><figcaption>Equation 16</figcaption></figure><p>Such value iteration algorithms converge to the optimal action-value function as i →∞ [1]. This approach is completely impractical in a real case scenario because the action-value function is estimated separately for each sequence, with no generalization. Instead, a function approximator is commonly used to estimate the action-value function Q(s, a; θ) ≈ Q∗ (s, a). In the machine learning community this is often a linear function approximator, but a non-linear function approximation, such as a neural network, may be used instead. A neural network function approximator with weights θ is considered as a Q-network. The Q-network is trained to minimize below loss functions L(θ) during each iteration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*zmXQ6akwG6vKujUH7va1Jg.png" /><figcaption>Equation 17</figcaption></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*KoWt3BcUzgqc2OXa0r7eZA.png" /><figcaption>Equation 18</figcaption></figure><p>is the target for each iteration i. Note that DQN is a model-free algorithm as it solves the reinforcement learning task directly using samples from the emulator, rather than explicitly constructing an estimate of the model.<br>It is also off-policy since it learns a greedy strategy to select the next action</p><p>a = max_a Q(s, a; θ), while following a behavior distribution that ensures sufficient exploration of the state space. In practice, the behavior distribution is commonly chosen by an e-greedy strategy that follows the greedy strategy with probability 1 -e  and selects a random action with probability e ∈ [0, 1]. DQN can’t be straightforwardly applied to continuous domains since it depends on finding the action that maximizes the Q(s, a) function, which in the continuous-valued case requires an iterative optimization process at every step.</p><p>Additionally, to reduce the issues of correlated data and non-stationary distributions, DQN use an experience replay mechanism [12] at each time-step eₜ = (sₜ, aₜ, rₜ, sₜ+1 ) from a data-set D = (e_1, …, e_N ), N ∈ N. Agent randomly samples previous transitions and thus smooth the training<br>distribution over a large number of previous behaviors. After using the experience replay buffer, the agent chooses and executes an action based on an e-greedy policy. Randomizing the samples breaks the strong correlations between them, therefore reducing the variance of the updates. In general, DQN only stores the last N experience pairs in replay buffer and samples uniformly at random from D when updating. Uniform sampling offers the same weight to all transitions in the replay buffer.</p><p><strong>2.3 Combining Improvements in Deep Reinforcement Learning (Rainbow)</strong></p><p>Combining Improvements in Deep Reinforcement Learning (Rainbow) [13] algorithm is a Q-learning-based algorithm by Deepmind that combines six independent enhancements (double Q-learning, prioritized replay, dueling networks, noisy nets, multi-step learning, and distributional RL) on the DQN algorithm. Each of these features addresses a limitation and improves the overall performance of the agent on the benchmark suite of 57 Atari 2600 games from the Arcade Learning Environment [14]. The use of Double Q-learning is to reduce overestimation bias by decoupling the maximization performed to calculate the target value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*JV7M7aDJI5n87AyfKzCkXQ.png" /><figcaption>Equation 19</figcaption></figure><p>the term hat(θ) represents the parameters of a target network; a periodic copy of the online network which isn’t directly optimized. So, it is use the Q network (θ) to choose the best action with the argmax, and then the target network (hat(θ)) to get the value estimate. This decorrelates the noise<br>and avoids amplification.</p><p>DQN samples uniformly from the replay buffer which is wasteful. For this reason, RAINBOW is using a prioritized replay buffer. it is better to sample transitions with probability pₜ ∈ [0, 1] relative to the last encountered absolute TD error where the predicted reward diverges greatly from the expected reward and more recent transitions have a higher priority</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*YWV6ryG4RUH3ZSWaBpGbVg.png" /><figcaption>Equation 20</figcaption></figure><p>where ω is a hyper-parameter that determines the shape of the distribution. Note that stochastic transitions might also be favored to be stored on replay buffer, even when there’s little left to learn about them.</p><p>The dueling network that exists in RAINBOW is a neural network architecture designed for value-based RL. Dueling DQN alters the neural network’s architecture by splitting it into two separate estimators after convolution. A primary estimator is a single number, the state value V(s). The second estimator produces one number for each action, indicating how much worse an action is in comparison to the best action in a state. In Q-Learning, the target value is calculated solely on the current reward. In Multi-step Q-Learning, rewards from n ∈ N steps are added together, and the Q function value is only added at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*nUQCYzZDq_HEetNiVVoBrg.png" /><figcaption>Equation 21</figcaption></figure><p>Multi-step targets with suitably tuned n usually lead to faster learning [1]. Noisy nets propose a noisy linear layer that combines a deterministic and a noisy stream for better exploration of e-greedy policies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0Gf4mprInKm7FETIxTz1Pw.png" /><figcaption>Equation 22</figcaption></figure><p>where e^b ∈ R and e^w ∈ R are random variables and denote the element-wise product. This transformation can then be used in place of the standard linear y = b + W x. The main idea of Distributional RL is to work directly with the complete distribution of the return rather than with its expectation. Let’s suppose that the random variable Z(s, a) be the return obtained by starting from state <strong>s</strong>, performing action <strong>a</strong> from the current policy. Then the Q-function gets the form of:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*vqhlGWugzzlcLF36s5_JYA.png" /><figcaption>Equation 23</figcaption></figure><p>Instead of trying to minimize the error of Double Q-learning (Equation 19), which is basically a distance between expectations. Rainbow minimizes a distributional error using Kullbeck-Leibler divergence between the two distributions. So, Rainbow define the target distribution as</p><p>dₜ (n) =(rₜ^(n)+ γₜ^(n) z, p_(hat(θ)) (s’, a’)). The loss functions that it use is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*KtILOPSDf2i2YUZKRu6gNg.png" /><figcaption>Equation 24</figcaption></figure><p>where Φz is the projection onto z. Also, the KL loss might be more robust to noisy stochastic environments because the loss can continue to decrease, even when the returns are not deterministic. Rainbow variants prioritize transitions by the KL loss since this is what the algorithm is minimizing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*oeoFnDZsm3dJ47AIkp8Ztg.png" /><figcaption>Equation 25</figcaption></figure><h3>3. Actor-Critic, Off Policy Algorithms</h3><p>Actor-critic methods are Temporal-Difference (TD) [1] methods that have a separate memory structure to explicitly represent the policy independent of the value function. The policy structure is known as the actor because it is used to select actions. The estimated value function is known as the critic because it criticizes the actions made by the actor. Typically, the critic uses an approximation architecture and simulation to learn a state-value function V(s), which is then used to update the actor’s policy parameters and determine whether things have gone better or worse than expected. Such methods, as long as they are gradient-based, may have desirable convergence properties, in contrast to critic-only methods for which convergence is guaranteed in rather limited settings. They also hold the promise of delivering faster convergence (due to variance reduction) than actor-only methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*3EpAwcLT2MpZaWiHF0nCJQ.png" /><figcaption>Figure 4: Structure of actor-critic learning methods</figcaption></figure><p><strong>3.1 Deep Deterministic Policy Gradient (DDPG)</strong></p><p>Deep Deterministic Policy Gradient (DDPG) [2] is a model-free, off-policy actor-critic algorithm using deep function approximators. It could learn policies in high-dimensional, continuous action spaces. It uses off-policy data and the Bellman equation to learn the Q-function and based on that learn the policy. DDPG is based on the deterministic policy gradient (DPG) [15] algorithm. The DPG algorithm maintains a parameterized actor function μ(s|θμ ) which specifies the current policy by deterministically mapping states to a specific action. The critic Q(s, a) is learned using the Bellman equation as in Q-learning. The Bellman equation is the starting point for learning an approximator of Q^(∗) (s, a). As it happens in DQN, DDPG supposes the approximator is a neural network Q(s, a; θ) or Q_θ (s, a) with parameters θ. Then it is using the mean-squared Bellman error (MSBE) function, which indicates roughly how closely Q_θ comes to satisfying the Bellman<br>equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*HXNqDisvnSTL3OWu36OOWQ.png" /><figcaption>Equation 26</figcaption></figure><p>All standard algorithms that train a deep neural network to approximate the optimal Q-function Q∗(s, a) make use of an experience replay buffer. This is the set D = (e_1 , …, e_N ), N ∈ N of previous experiences, at each time-step eₜ = (sₜ , aₜ , rₜ , sₜ+1 ). In order for the algorithm to have stable behavior, the replay buffer should be large enough to contain a wide range of experiences. However, it may not always be good to keep everything.</p><p>Furthermore, Q-learning algorithms make use of target networks. The term in the loss function (Equation 26) r+γ maxa0 Q_θ (s’, a’) is called target. Since by minimizing the mean-squared Bellman error (MSBE) loss, DDPG is attempting to make the Q-function more similar to this target. The target, however, is dependent on the same parameters θ that the algorithm is trained on. The solution is to use a group of parameters that comes close to θ by using a second neural network called a target network. The parameters of the target network are denoted θ_targ. To be noted that the target neural network has a time delay from the Q_θ network when is needed to update its parameters θ_targ. The target network is simply copied over from the main network every some-fixed-number of steps in DQN-based algorithms. Polyak averaging is used in DDPG style algorithms to update the target network once per main network update.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*ouuDdTT3PSvu9YoDFGe7dQ.png" /><figcaption>Equation 27</figcaption></figure><p>where ρ is a hyperparameter between 0 and 1 (usually close to 1). DDPG wants to learn a deterministic policy μ_φ (s) which gives the action that maximizes Q_θ (s, a). Because the action space is continuous but assumes that the Q-function is differentiable with respect to action, DDPG performs a stochastic gradient ascent (with respect to policy parameters only) to solve</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*W8oCNxndqnPSUVyGmox3zg.png" /><figcaption>Equation 28</figcaption></figure><p>Putting it all together, Q-learning in DDPG is performed by minimizing the following MSBE loss with stochastic gradient descent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*FvT6pka44BOx18O6ecg3_Q.png" /><figcaption>Equation 29</figcaption></figure><p>where μ_φ_targ is the target policy. To construct an exploration policy μ’, DDPG add noise sampled from a noise process N to it is actor policy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*OL6RJ1mL8GpsUWcwLIYDRA.png" /><figcaption>Equation 30</figcaption></figure><p><strong>N</strong> can be chosen to suit the environment.</p><p><strong>3.2 Twin Delayed Deep Deterministic (TD3)</strong></p><p>In Q-learning, the value estimate is updated with a greedy target y = r + max_a’ Q(s’ , a’ ). However, if the target is susceptible to error (bias) e ∈ R, then the maximum over the value along with its error will generally be greater than the true maximum,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*TJWdzpMriC1v7LUvaur-8g.png" /><figcaption>Equation 31</figcaption></figure><p>This is a common mode of failure for the DDPG algorithm. The learned Q-function starts grossly overestimating Q-values. Then leads to sub-optimal policies updates and divergent behavior, since it tries to exploit the errors in the Q-function. Twin Delayed DDPG (TD3) [16] is an algorithm built on the DDPG using Double Q-learning that addresses this issue by introducing three new features: clipped double-Q learning, target policy smoothing, and “delayed” policy update. Together, these three features result in substantially improved performance of DDPG.</p><p>Using Clipped Double Q-learning, the value target can’t introduce any additional overestimation, as in the case of using just the standard Q-learning target approach. However, this update rule may induce an underestimation bias. This is far preferable to overestimation bias. Both Q-functions are using a single target. This target is calculated using whichever of the two Q-functions<br>will give the lower target value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*mP0pKBk56vTnc_qS8uk_pg.png" /><figcaption>Equation 32</figcaption></figure><p>and then both Loss functions are learned by using regression on this target:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*-L1SihkKFQ7PDG1F8GXzlA.png" /><figcaption>Equation 33</figcaption></figure><p>Using the smaller Q-function value for the target and regressing towards it helps to avoid Q-function overestimation bias. Also, as in DDPG the actor policy is learned just by maximizing Q_φ1 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*QA2j9qhwXoLieOsKnGnLuA.png" /><figcaption>Equation 34</figcaption></figure><p>However, the delayed policy updates feature of TD3 means that the actor policy is updated less frequently than the Q-functions. By sufficiently delaying the policy updates TD3 reduces the likelihood of repeating updates with respect to an unchanged critic. The less frequent policy updates will occur in the actor policy. Will result to estimate a value function V (s) with lower variance, and in principle, should emerge in higher quality policy updates.</p><p>Target policy smoothing essentially acts as a regularizer for the algorithm. Using the clipped noise, the target action is clipped to fall within the valid action range (all valid actions <strong>a</strong> satisfy a_Low ≤ a ≤ a_High ). As a result, the target actions are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*pJvGvlNN2-pbsGL8C_Llxg.png" /><figcaption>Equation 35</figcaption></figure><p>This addresses a specific failure mode in DDPG. If the Q-function approximator develops an inaccurate sharp peak for some actions, the policy will rapidly exploit that peak, resulting in brittle or incorrect behavior. This can be avoided by smoothing the Q-function over similar actions, which is what target policy smoothing is intended to do.</p><p><strong>3.3 Soft Actor-Critic (SAC)</strong></p><p>Soft Actor-Critic (SAC) [17] is an algorithm that optimizes a stochastic policy in an off-policy way. It is bridging the gap between stochastic policy optimization and DDPG-style methods. It is not a direct successor to TD3, despite the fact that both were released around the same time, but it integrates the clipped double-Q trick. The central feature of SAC is entropy regularization which provides a substantial improvement in exploration and robustness. The policy is trained to maximize a trade-off among expected return and entropy, which is a measure of the policy’s randomness. Entropy is closely related to the exploration-exploitation trade-off: increasing entropy leads to more exploration, which can speed up learning later on. It can also keep the policy from convergent to a local optimum. Entropy is a quantity that indicates how random a random variable is. Assume x ∈ R is a random variable with a probability mass function or density function P. The entropy H of x is calculated from its distribution P as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*uGjsvdK8Bvm5KzYjcZ84fQ.png" /><figcaption>Equation 36</figcaption></figure><p>In an entropy-regularized reinforcement learning environment, the policies are designed to maximize the expected future return, as well as the expected future entropy. As a result, this will maximize the value function V^π (s). The equation of the value function that includes the entropy is derived as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*vyhiLJnjuVhPdVFkh-m6tA.png" /><figcaption>Equation 37</figcaption></figure><p>where β &gt; 0 is a temperature parameter that determines the relative importance of the entropy term against the reward. Thus, parameter β controls the stochasticity of the optimal policy. More exploration corresponds to a higher β. Lower β values indicate greater exploitation. Subsequently, the Q function including the entropy term from every timestep except the first one will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*xvRWpgQUmieik7QWAWxmYg.png" /><figcaption>Equation 38</figcaption></figure><p>SAC also uses mean-squared Bellman error (MSBE) as a loss function for its policy π_θ. The loss function is incorporating a clipped double-Q-function Q_φ1, Q_φ2. During training, SAC selects the minimum Q-value between the two Q approximators. As a result, the loss function for the Q-networks in SAC is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*b44Zk4VMBu5km_nEedBvZg.png" /><figcaption>Equation 39</figcaption></figure><p>where the target is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*lq2gI-TUGnNGEVFdUNQHcg.png" /><figcaption>Equation 40</figcaption></figure><p>ã’ indicates that the next actions have to be sampled from the policy and not from the replay buffer D. SAC uses the reparameterization trick [18] to optimize the target policy. This trick is used to make sure that sampling from the policy πθ (·|s) is a differentiable process so that there are no problems in backpropagating the errors. Moreover, independent noise is added to achieve<br>better exploration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*7vPDbdgtlMrA85LFCPU7DA.png" /><figcaption>Equation 41</figcaption></figure><p>tanh in the SAC policy ensures that actions are bounded to a finite range, while σ_θ (s) describes the standard deviation which is parameterized by θ.</p><h3>References</h3><p>[1] Richard S Sutton and Andrew G Barto. Reinforcement learning: An introduction. MIT press, 2018.</p><p>[2] Timothy P Lillicrap et al. “Continuous control with deep reinforcement learning”. In: arXiv preprint arXiv:1509.02971 (2015).</p><p>[3] Ronald J Williams. “Simple statistical gradient-following algorithms for connectionist reinforcement learning”. In: Machine learning 8.3–4 (1992), pp. 229–256.</p><p>[4] Lilian Weng. Difference between Monte-Carlo, Temporal-Difference Learning, and Dynamic programming. url: https : / / lilianweng . github . io / lil — log / 2018 / 02 / 19 / a — long -peek-into-reinforcement-learning.html.</p><p>[5] John Schulman et al. “High-dimensional continuous control using generalized advantage estimation”. In: arXiv preprint arXiv:1506.02438 (2015).</p><p>[6] John Schulman et al. “Trust region policy optimization”. In: International conference on machine learning. PMLR. 2015, pp. 1889–1897.</p><p>[7] S. Kullback and R. A. Leibler. “On Information and Sufficiency”. In: The Annals of Mathematical Statistics 22.1 (1951), pp. 79–86. doi: 10.1214/aoms/1177729694. URL: <a href="https://doi.org/10.1214/aoms/1177729694.">https://doi.org/10.1214/aoms/1177729694.</a></p><p>[8] John Schulman et al. “Proximal policy optimization algorithms”. In: arXiv preprint arXiv:1707.06347 (2017).</p><p>[9] Christopher JCH Watkins and Peter Dayan. “Q-learning”. In: Machine learning 8.3–4 (1992), pp. 279–292.</p><p>[10] Richard Bellman. “Dynamic programming”. In: Science 153.3731 (1966), pp. 34–37.</p><p>[11] Volodymyr Mnih et al. “Playing atari with deep reinforcement learning”. In: arXiv preprint arXiv:1312.5602 (2013).</p><p>[12] Long-Ji Lin. Reinforcement learning for robots using neural networks. Tech. rep. Carnegie-Mellon Univ Pittsburgh PA School of Computer Science, 1993.</p><p>[13] Matteo Hessel et al. “Rainbow: Combining improvements in deep reinforcement learning”. In: Proceedings of the AAAI Conference on Artificial Intelligence. Vol. 32. 1. 2018.</p><p>[14] Marc G. Bellemare et al. “The Arcade Learning Environment: An Evaluation Platform for General Agents”. In: CoRR abs/1207.4708 (2012). arXiv: 1207.4708. url: <a href="http://arxiv/">http://arxiv</a>. org/abs/1207.4708.</p><p>[15] David Silver et al. “Deterministic policy gradient algorithms”. In: International conference on machine learning. PMLR. 2014, pp. 387–395.</p><p>[16] Scott Fujimoto, Herke Hoof, and David Meger. “Addressing function approximation error in actor-critic methods”. In: International Conference on Machine Learning. PMLR. 2018, pp. 1587–1596.</p><p>[17] Tuomas Haarnoja et al. “Soft actor-critic: Off-policy maximum entropy deep reinforcement learning with a stochastic actor”. In: International Conference on Machine Learning. PMLR. 2018, pp. 1861–1870.</p><p>[18] Diederik P Kingma and Max Welling. “Auto-encoding variational bayes”. In: arXiv preprint arXiv:1312.6114 (2013).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c4f5eec461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Machine learning (ML) and Reinforcement Learning (RL)]]></title>
            <link>https://nikoskokkini.medium.com/introduction-to-machine-learning-ml-and-reinforcement-learning-rl-5a51e3b58b70?source=rss-712f01e3509c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a51e3b58b70</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[taxonomy]]></category>
            <category><![CDATA[imitation-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nikolaos Kokkinis Ntrenis]]></dc:creator>
            <pubDate>Thu, 09 Sep 2021 18:51:06 GMT</pubDate>
            <atom:updated>2021-12-15T20:14:07.523Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Definition of Machine Learning</strong></h3><p>Machine learning (ML) [1] is the process of creating mathematical models using data X and labels Y (in the supervised problem settings) is defined as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*NOocJHIjkPc8NtokTx22ig.png" /></figure><p>where n, m are the number of samples and A, B represent the dimensionality of data and labels respectively. To help a computer learn without direct human instruction. Machine learning aims to identify patterns within given data, by using those patterns in new unfamiliar data the algorithms could produce accurate predictions and thus create a trained model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*bMl0HuZX_Nuzaefo28HnAw.png" /></figure><p>where θ = {θ0, …θk } ∈ H with k, H ∈ N is the set of possible parameters of the hypothesis hθ that is mapping x to y, as in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*_yF5mYWdWfANIIJsfVt-5w.png" /></figure><p>optimized w.r.t an objective/loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*1P2G9lRjS-YbFAeGzAwRag.png" /></figure><p>The loss functions quantify the variation between the predictions of the model being trained and the actual problem instances. Given feedback to the model how it should change the parameters θ for better mapping of x to y. Data abundance and the computational capacity of modern hardware has allowed such model to provide results of high accuracy.</p><h3><strong>Machine learning and Reinforcement learning Terms</strong></h3><p><strong>Supervised versus Unsupervised:</strong> The fundamental difference between supervised and unsupervised learning is that supervised learning [2] uses ground truth labels, or in other words, having prior knowledge of what the output values of our samples should be. Therefore, the goal of supervised learning is to define a function that, given a set of input data samples and desired outputs/labels, approximates the relationship between an input and an output. Contrary unsupervised learning [3], is using no label information during training. Allowing the algorithm to act on the new data without the support of label guidance. Here the task of an algorithm is to group unsorted information consistent with some similarities, patterns, and differences of the data. Thus the goal is to infer the natural structure which is present within a collection of data points. The two main forms of supervised learning algorithms are:</p><ol><li>Regression: mapping an input signal to a continuous output interval.</li><li>Classification: the output belongs to a discrete space that represents a set of predefined outcomes.</li></ol><p>On the other hand, the two major forms of unsupervised learning algorithms are:</p><ol><li>Clustering: Finding “clusters” of observations in a dataset that are identical to each other.</li><li>Association: looks for relationships that appear very frequently between a large collection of data points and uses them to discover the rules that govern them.</li></ol><p><strong>Online versus Offline learning:</strong> Many learning systems are often categorized as online or offline(or somewhere in-between). Online learning algorithms [4] work with data as soon as they’re available. Strictly online algorithms improve incrementally from each chunk of recent data when it arrives, then discard that data and don’t use it again. It is not a requirement, but it is commonly desirable for an online algorithm to forget older examples over time, so it can adapt to nonstationary populations. Stochastic gradient descent with back-propagation as employed in neural networks is an example of online learning. On the other hand, offline learning algorithms[5] work with data in bulk, from a dataset. Strictly offline learning algorithms need to be re-run from scratch to be able to learn from new or updated data. Support vector machines and random forests are strictly offline algorithms (although nowadays exist online variants of them [6]).</p><p>Online algorithms are more general and it is quicker to construct an offline algorithm from a strictly online one, just having a stored dataset. Nonetheless, the reversal is not feasible for a strictly offline algorithm. This doesn’t necessarily make them superior, often compromises are made in terms of sample efficiency, CPU cost, or accuracy when using an online algorithm. Approaches like mini-batches in neural network training are viewed as attempts to seek out common ground between online and offline algorithms.</p><p>In addition, experience replay, a typical Reinforcement learning technique, employed in Deep-Q-Networks among others, is an in-between approach. Although you need to store all the experience necessary to fully train an agent, in theory, typically you store a rolling history and sample from it.</p><p><strong>A Markov Decision Process</strong> (MDP) [7], is a discrete-time stochastic control process. Is formalized as a tuple (S, A, ρ0, p, r, γ), where S and A respectively denote the state and action spaces. The dynamics of MDP are defined by a transition distribution with conditional density p(s_t+1|s_t, a_t ), along with ρ0 ∈ [0, 1], the density of the distribution from which the initial state is sampled. Finally, γ ∈ [0, 1] denotes the discount factor, and r: S × A → R is the reward function. Although the analysis usually involves an infinite-horizon MDP, the MDPs employed in practice are episodic, with γ = 0 at episode termination.</p><p><strong>Reinforcement learning</strong> (RL)[8] is the field of sequential decision-making<br>under uncertainty. This family of algorithms consists of an agent (decision maker), an environment typically stated in the form of a Markov decision process (MDP), and a policy that indicates the best action that an agent should take given its current state. The agent interacts with a previously<br>unknown environment and receives rewards upon interaction according to its policy. The agent’s goal is to retrieve a policy that gathers the largest amount of cumulative reward. Reinforcement learning algorithms aim to find a balance between exploration (of uncharted territory) and exploitation (of current knowledge).</p><p><strong>Imitation Learning</strong> (IL) [11] is a sub-section of reinforcement learning<br>which addresses the problem of an agent learning to act in an environment in order to imitate the behavior of an expert demonstrator. No direct supervision is provided to the agent — it is never directly told what the optimal action is — nor does it receive a reinforcement signal from the environment upon interaction. Instead, the agent is provided with a set of trajectories to use as a guide for its learning process.</p><p><strong>Policy:</strong> A policy π: A × S → [0, 1] express the sequential decision-making process of the agent by defining a parameterized policy π_θ, for example, modeled via a neural network with parameter θ. We denote π_θ (a_t | s_t ) as the conditional probability density concentrated at the action a_t ∈ A when the agent is in state s_t ∈ S.</p><p><strong>On-policy versus Off-policy: </strong>On-policy algorithms work with an individual policy, often illustrated as π, and request any observations (state, action, reward, next state) to be generated using that policy. Off-policy algorithms work with two policies. The two policies types are the target and behavior policies. The policy which is being learned, called the target policy usually denoted as π, and the policy being followed that generates the observations called as behavior policy, usually denoted as μ: A × S → [0, 1] [12] or β: A × S → [0, 1] [8] within the literature. A common scenario for off-policy learning is to form observations by policy β, which has an exploring policy, then target policy π, which has a greedy policy, pick the finest actions which are selected by policy β on every time step. The relationship between on-policy and off-policy learning is that off-policy is usually a strict generalization of on-policy. We could make any off-policy algorithm into an identical on-policy one by setting π = β.</p><p><strong>Model-based versus Model-free: </strong>A model-based M = (p, r) reinforcement learning algorithm [8] tries to retrieve the optimal policy π^∗ (a_t|s_t) using transition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*9EijZZy53RuAZAGGESXWSQ.png" /></figure><p>and reward functions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-vxxtn0KGiarinCoZCp9Yg.png" /></figure><p>The agent might have access only to an approximation of those two functions, which could be learned during its interactions with the environment to enhance its estimate of the optimal policy. In other words, the policy defines the behavior of the agent, whereas, the transition probability and reward functions explain the dynamics of the environment. However, the optimal policy might never be found by the agent due to the approximations that exist for those two functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*iOceBp5ks4X_Bs-8vqT2qA.png" /><figcaption>Model-based RL</figcaption></figure><p>On the contrary, a model-free algorithm [8] tries to retrieve the optimal policy without using or estimating the dynamics (transition and reward functions) of the environment. In practice, it either estimates a value function V_π (s) ∈ R as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*J4vlylFuSQxlDcT3Ie5GaA.png" /></figure><p>or the policy π(a|s) directly from the interactions with the environment. A value function could be expressed as a function that evaluates the goodness/badness of states since it predicts the future reward from a given state. From the optimal value function Vπ^∗(s), an optimal policy π^∗ (a_t |s_t ) can be derived with respect to the value function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*rjo_qIyoUZEuCZyFdissAg.png" /><figcaption>Model-free RL</figcaption></figure><p><strong>Prediction versus Control </strong>The prediction problem in RL [8] is to estimate the value of a distinct state or state/action pair, given an environment and a policy. Nonetheless, the (optimal) control problem in RL is to discover the best fitting policy on the given environment. Solving the control problem when using value-based methods involves both estimating the value of being during a specific state (i.e. solving the prediction problem), and adjusting the policy to create higher-value choices supported by those estimates. This is called generalized policy iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*orwxtJKdt4hjshgvx5wtVQ.png" /><figcaption>Generalized policy iteration: Value V (s) and policy π(a|s) functions interact until they<br>are optimal and thus consistent with each other.</figcaption></figure><h3>References</h3><p>[1] Tom M Mitchell et al. “Machine learning”. In: (1997).<br>[2] Pádraig Cunningham, Matthieu Cord, and Sarah Jane Delany. “Supervised learning”. In:Machine learning techniques for multimedia. Springer, 2008, pp. 21–49.<br>[3] Trevor Hastie, Robert Tibshirani, and Jerome Friedman. “Unsupervised learning”. In: The elements of statistical learning. Springer, 2009, pp. 485–585.<br>[4] David Saad. On-line learning in neural networks. 17. Cambridge University Press, 2009.<br>[5] Michel Benaim. “The “off line learning approximation” in continuous time neural networks: An adiabatic theorem”. In: Neural Networks 6.5 (1993), pp. 655–665.<br>[6] Seyda Ertekin, Leon Bottou, and C Lee Giles. “Nonconvex online support vector machines”. In: IEEE Transactions on Pattern Analysis and Machine Intelligence 33.2 (2010), pp. 368–381.<br>[7] Ronald A Howard. “Dynamic programming and markov processes.” In: (1960).<br>[8] Richard S Sutton and Andrew G Barto. Reinforcement learning: An introduction. MIT press, 2018.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a51e3b58b70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Minimization using Genetic Algorithms]]></title>
            <link>https://nikoskokkini.medium.com/function-minimization-using-genetic-algorithms-be2690621d88?source=rss-712f01e3509c------2</link>
            <guid isPermaLink="false">https://medium.com/p/be2690621d88</guid>
            <category><![CDATA[genetic-algorithm]]></category>
            <dc:creator><![CDATA[Nikolaos Kokkinis Ntrenis]]></dc:creator>
            <pubDate>Fri, 07 Jun 2019 15:45:49 GMT</pubDate>
            <atom:updated>2019-06-08T20:30:17.620Z</atom:updated>
            <content:encoded><![CDATA[<p>We will see how we could benefit using Genetic Algorithms to find the minimum point of some functions.</p><p>We will focus on the minimization of the following function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*nMD4mF68fc2eWemX5vuRBA.png" /></figure><pre>def fitness(x,y):</pre><pre>    fitness=0</pre><pre>    firstTerm=-1*(abs(0.5*x*(math.sin(math.sqrt(abs(x))))))</pre><pre>    secondTerm=-1*(abs(y*math.sin(30*math.sqrt(abs(x/float(y))))))</pre><pre>    fitness= firstTerm+secondTerm</pre><pre>    return fitness</pre><p>Below we could see the 2D and 3D visualization of fitness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*XdyEmyB41iaNTlud7sb-Ig.png" /><figcaption>2D visualization of fitness function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*dQpmmNvV26YoV9F1VtzW2g.png" /><figcaption>3D visualization of fitness function</figcaption></figure><p>Using <a href="https://root.cern/">ROOT</a> we could visualize and localize very fast its global minimum just by clicking on the smallest point and getting their value of x,y (x=903 y=917 with fitness value: -1356.48268312).</p><p>In our example, we have x,y ∈[10,1000] but we will work with binary presentation of x,y. For this reason the research space S we will use two chains of 10 bits, each represent by numbers from 0 to 1023.</p><p>So, x,y ∈[0,1023] bits we will use the following mapping function to convert x,y ∈[0,1023] bits to x,y ∈[10,1000] ∈N.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*yRiRfdTtSzC31MrrHno0zA.png" /></figure><p>Now let’s see how we could use the Genetic Algorithm to find the minimum point but first some details about Genetic Algorithm.</p><pre>def MapNautalToSearchSpace(x):</pre><pre>     return int((x * 990)/1023)+10</pre><p><strong>Genetic Algorithm (GA) </strong>is a search-based optimization technique based on the principles of Genetics and Natural Selection. It is frequently used to find optimal or near-optimal solutions to difficult problems which otherwise would take a lifetime to solve. It is frequently used to solve optimization problems, in research, and in machine learning.</p><p>GAs were developed by John Holland and his students and colleagues at the University of Michigan, most notably David E. Goldberg and has since been tried on various optimization problems with a high degree of success.</p><p>In GAs, we have a pool or a population of possible solutions to the given problem. These solutions then undergo recombination and mutation (like in natural genetics), producing new children, and the process is repeated over various generations. Each individual (or candidate solution) is assigned a fitness value (based on its objective function value) and the fitter individuals are given a higher chance to mate and yield more fitter individuals. This is in line with the Darwinian Theory of Survival of the Fittest.</p><p>In this way we keep evolving better individuals or solutions over generations, till we reach a stopping criterion.</p><p>The GA algorithm has the following step:</p><ul><li><strong>Initialize a population N</strong></li><li><strong>Selection</strong>: selection of the individuals to evolve from</li><li><strong>Crossover</strong>: crossover of couples of parents</li><li><strong>Mutation</strong>: random mutations of the individuals</li></ul><p>P(t) − &gt; selection P’(t) − &gt; crossover P”(t) − &gt; mutation P”’(t) = P(t + 1)</p><h3><strong>1.Population</strong></h3><p>There are two primary methods to initialize a population in a GA:</p><ul><li><strong>Random Initialization</strong>: Populate the initial population with completely<br>random solutions.</li><li>Heuristic initialization: Populate the initial population using a known<br>heuristic for the problem.</li></ul><p>It has been observed that the entire population should not be initialized using a heuristic, as it can result in the population having similar solutions and very little diversity. It has been experimentally observed that the random solutions are the ones to drive the population to optimal. Therefore, with heuristic initialization, we just seed the population with a couple of good solutions, filling up the rest with random solutions rather than filling the entire population with heuristic based solutions.</p><pre>def InitPopulation():</pre><pre>   generations={}</pre><pre>   for i in range(population_size):</pre><pre>   randomx=random.randint(10,1000)</pre><pre>   randomy=random.randint(10,1000)</pre><pre>   fit=fitness(randx,randy)</pre><pre>   xbin=MapNaturaltoBits(randomx)</pre><pre>   ybin=MapNaturaltoBits(randomy)</pre><pre>   xy=str(xbin)+””+str(ybin)</pre><pre>   generations[i]={“xy”:xy,”fitness”:fit}</pre><pre>   return generations</pre><h3>2. <strong>Selection</strong></h3><p>We will use fitness based selection, so the children tend to replace the least fit individuals in the population. The selection of the least fit individuals may be done by tournament selection, fitness proportionate selection, etc. In our case we will use 5-tournament selection method.</p><p>In more details for<strong> 5-tournament selection </strong>is a method that we select randomly 5 individuals from our population and we select the one that has the best fitness value among the 5. We proceed this task until we get as many individuals as the number of our population.</p><pre>def tournament5(generationDictN):</pre><pre>   NewgenerationDictN={}</pre><pre>   for i in range(population_size):</pre><pre>       ktournament=[]</pre><pre>       bestNumber=0</pre><pre>       bestFitnessValue=0</pre><pre>       for j in range(5):</pre><pre>          randNum=generationDictN[random.randint(0,population_size-1)]</pre><pre>           ktournament.append(randNum)</pre><pre>           if( randNum[“fitness”]&lt;bestFitnessValue:</pre><pre>               bestFitnessValue=randNum[“fitness”]</pre><pre>               bestNumber=randNum[“xy”]</pre><pre>         NewgenerationDictN[i]={“xy”:bestNum,”fitness”:bestFit}</pre><pre>    return NewgenerationDictN</pre><h3>3. <strong>Crossover</strong></h3><p>The crossover operator is analogous to reproduction and biological crossover. In this more than one parent is selected and one or more off-springs are produced using the genetic material of the parents.</p><p>To do so, the population P’(t) will be divided in N/2 pairs and the crossover operation will be applied with probability “p_c” . In general there are 3 possible crossover methods:</p><ul><li><strong>One Point Crossover</strong>:In this one-point crossover, a random crossover point is selected and the tails of its two parents are swapped to get new off-springs.</li><li>Multi Point Crossover:is a generalization of the one-point crossover wherein alternating segments are swapped to get new off-springs.</li><li>Uniform Crossover:In a uniform crossover, we dont divide the chromosome into segments, rather we treat each gene separately.</li></ul><p>In our case we will use only the One Point Crossover. Which we will flip the chromosomes values. For example x1 ,y1 with the chromosome x50 ,y50 and get as result x1 ,y50 and x50 ,y1.</p><pre>def CrossOver(SelectedNumbersDict):</pre><pre>    ittNum=int(population_size/2)</pre><pre>    for i in range(ittNum):</pre><pre>        randnum=random.random()</pre><pre>        if (randnum&lt;= pc):</pre><pre>            num1=SelectedNumbersDict[i][“xy”]</pre><pre>            num2=SelectedNumbersDict[stopNum+i][“xy”]</pre><pre>            crossOver1=num1[0:10]+num2[10:20]</pre><pre>            crossOver2=num2[0:10]+num1[10:20]</pre><pre>            SelectedNumbersDict[i][“xy”]=crossOver1</pre><pre>            SelectedNumbersDict[stopNum+i][“xy”]=CrossOver2</pre><pre>    return SelectedNumbersDict</pre><h3>4. <strong>Mutation</strong></h3><p>Mutation may be defined as a small random tweak in the chromosome, to get a new solution. It is used to maintain and introduce diversity in the genetic population and is usually applied with a low probability “p_m”.</p><p>There are 5 mutation methods:</p><ul><li><strong>Bit Flip Mutation</strong>: In this bit flip mutation, we select one or more random bits and flip them. This is used for binary encoded GAs.</li><li>Random Resetting: is an extension of the bit flip for the integer representation. In this, a random value from the set of permissible values is assigned to a randomly chosen gene.</li><li>Swap Mutation:we select two positions on the chromosome at random, and interchange the values. This is common in permutation based encoding.</li><li>Scramble Mutation:In this, from the entire chromosome, a subset of genes is chosen and their values are scrambled or shuffled randomly.</li><li>Inversion Mutation:we select a subset of genes like in scramble mutation, but instead of shuffling the subset, we merely invert the entire string in the subset.</li></ul><p>We will use only Bit Flip Mutation method once we will be working with binary numbers.</p><pre>def Mutation(SelectedNumbersDict):</pre><pre>   for i in range(population_size):</pre><pre>      num=SelectedNumbersDict[i][“xy”]</pre><pre>      newNum=””</pre><pre>      for j in range(len(num)):</pre><pre>          randnum=random.random()</pre><pre>          if (randnum&lt;=pm):</pre><pre>               if (num[j]==’1&#39;):</pre><pre>                     newNum=newNum+str(0)</pre><pre>               else:</pre><pre>                     newNum=newNum+str(1)</pre><pre>          else:</pre><pre>                newNum=newNum+num[j]</pre><pre>      SelectedNumbersDict[i][“xy”]=newNum</pre><pre>   return SelectedNumbersDict</pre><h3>Results</h3><p>The individuals represent a possible solution as a string with binary values that can been split in 2 to represent x and y.</p><ul><li>Our population number N=100 and then we used the random initialization method.</li><li>The selection is done using tournament method with k = 5 individuals per tournament.</li><li>The crossover is done using the one-point crossover method with a mid-break policy.</li><li>The mutation is done using the bit flip mutation on each bit.</li></ul><p>Also, the worst individual of the next generation is replaced by the best of the previous one.</p><p><strong>The success rate of the algorithm after 10^3 , 10 ^4, and 10^5 fitness evaluations.</strong></p><p>The fitness evaluations of 10^3 = 100(Number of population)x10(Number of Generation)=10^3 . So for 10^3 the iterations will be 10, for 10^4 the iterations are 100 and for the 10^5 the iterations are 1000.</p><p>As success rate i have calculate the number of executions where the algorithm found the optimal solution divided by the total number of executions. For example if the number of iterations was 10 and i found the best solution in 4th the success rate is 4/10=0.4 . So the smaller the success rate means that we had found the optimal solution more early.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDA16wUmkerXhChl6T_04Q.png" /><figcaption>without Crossover probability, 0.1 Mutation probability</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AR9uolMUCVOwzmFOodk72w.png" /><figcaption>with Crossover probability, 0.1 Mutation probability</figcaption></figure><h3>Conclusion</h3><p>In general, a higher mutation probability leads to a higher average fitness and lower standard deviation. Interestingly, using crossover, make the results slightly worst compared to pure evolution by mutation.</p><p>Also, the size n of the population is very important and with a too small population the convergence of the individuals to the best one is too quick and freezes the research in sub optimal spaces. Finally, the execution time grows linearly with the size of the population.</p><p><a href="https://github.com/NickKok/Function-Minimization-using-Genetic-Algorithms">Code</a> on GitHub.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be2690621d88" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>