<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alireza Shamsoshoara on Medium]]></title>
        <description><![CDATA[Stories by Alireza Shamsoshoara on Medium]]></description>
        <link>https://medium.com/@a.shamsoshoara?source=rss-e911bcf50f54------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HXOYVhkoTBQUnFyhd8svQg.jpeg</url>
            <title>Stories by Alireza Shamsoshoara on Medium</title>
            <link>https://medium.com/@a.shamsoshoara?source=rss-e911bcf50f54------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:26:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a.shamsoshoara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[DQN: when a table is not enough]]></title>
            <link>https://medium.com/@a.shamsoshoara/dqn-when-a-table-is-not-enough-f00ea28fc09f?source=rss-e911bcf50f54------2</link>
            <guid isPermaLink="false">https://medium.com/p/f00ea28fc09f</guid>
            <category><![CDATA[double-dqn]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[deepreinforcementlearning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[dqn]]></category>
            <dc:creator><![CDATA[Alireza Shamsoshoara]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 07:24:18 GMT</pubDate>
            <atom:updated>2026-11-25T07:24:18.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T60bE5jUDZ3C71I7eUwGIw.png" /></figure><h3><em>From a lookup table to a neural network, followed through one real gradient step. Part 2 of </em><a href="https://medium.com/@a.shamsoshoara/rl-from-zero-reinforcement-learning-built-from-scratch-6f7472215597"><em>RL From Zero</em></a><em>.</em></h3><p><a href="https://medium.com/@a.shamsoshoara/q-learning-watch-a-table-learn-one-experience-at-a-time-82f20585f257">Part 1</a> ended with one picture to keep: an experience arrives, the agent builds a target, and a prediction moves toward it. In FrozenLake you could point to the exact table cell that moved.</p><p>This part keeps that picture and removes the cell.</p><p>The task is MountainCar. The agent still learns action values, and its target is still a reward plus the best value it expects next. But the values now come out of a small neural network, and one update moves the whole network. That single change brings two new problems, and DQN is mostly the pair of fixes for them.</p><p>Every number below comes from the actual training run behind the trained agent at the end of this article. The <a href="https://alirezashamsoshoara.github.io/blog/rl-from-zero/dqn/">interactive version</a> lets you step through those recorded updates and drive the car with every saved checkpoint.</p><h3>A state you cannot put in a table</h3><p>A car sits in a valley between two hills. The flag is on top of the right hill, and the engine is too weak to drive straight up. The only way out is to rock back and forth: go up the left slope, roll down, and use that speed to climb the right one.</p><pre>state      position in [-1.2, 0.6], velocity in [-0.07, 0.07]<br>start      position in [-0.6, -0.4], velocity 0<br>actions    push left, no push, push right<br>reward     -1 every step<br>ends       flag reached (position &gt;= 0.5), or 200 steps pass</pre><p>Every step costs −1, including the step that reaches the flag, so fewer steps means a better return.</p><p>In FrozenLake, the agent visited the same 16 squares again and again, and each had its own row in the table. Here, position and velocity are real numbers. The car almost never lands on exactly the same state twice.</p><p>You could chop the map into cells and keep a table anyway. But then each cell learns alone: a correction near one state teaches its neighbors nothing, even though a car at position −0.501 and one at −0.500 are in nearly the same situation. What we want is a function that gives similar answers for similar states.</p><h3>Replace the table with a function</h3><p>DQN keeps the Q-learning target and swaps the table for a neural network that takes a state and returns one value per action:</p><pre>Q(s, a; theta)  ~  expected return after action a in state s</pre><p>Here <em>theta</em> is the network’s weights. In this run the two inputs are rescaled to the range −1 to 1, then pass through two hidden layers of 128 units each, then out to three values. That is 17,283 weights and biases, and <strong>every one of them is shared by every state</strong>.</p><p>The target from Part 1 survives almost unchanged. What changes is how a prediction moves toward it. A table could nudge one cell. A network can only adjust its weights, so the update becomes a small step of gradient descent on the squared gap:</p><pre>target = r + gamma * (1 - terminated) * max_a&#39; Q(s&#39;, a&#39;; theta)<br>loss   = (target - Q(s, a; theta))^2<br>theta  &lt;- theta - learning_rate * gradient of loss</pre><p>The target is treated as a fixed number: no gradient flows through it. In practice the run averages the loss over a minibatch of 64 transitions and uses the Adam optimizer.</p><p>Because every state shares the same weights, that step changes the value of states the update never looked at. That is the point of using a network. It is also the source of the trouble.</p><h3>One real update, by hand</h3><p>Here is the very first gradient update of the run, at step 20,000. Until then the car only explored at random. The network has never been trained, so its outputs are small numbers near zero.</p><p>The update draws 64 stored transitions. Follow one of them: stored 3,606 steps earlier, the car was on the left slope at position −1.115, moving right at 0.0145, and the stored action was push left.</p><p>DQN in this run uses the Double DQN target, which splits the look-ahead in two. The online network, the one being trained, chooses the next action. A second copy, the <strong>target network</strong> with weights <em>theta⁻</em>, scores it:</p><pre>a*     = argmax_a&#39; Q(s&#39;, a&#39;; theta)<br>target = r + gamma * (1 - terminated) * Q(s&#39;, a*; theta-)</pre><p>At the next state, the online network’s three values are −0.1231 (left), −0.1478 (none) and −0.3092 (right), so it picks left. Before the first sync, the target network is an exact copy, so it also scores left at −0.1231:</p><pre>target   = -1 + 0.99 * (1 - 0) * (-0.1231) = -1.122<br>TD error = -1.122 - (-0.1229) = -0.999</pre><p>After one Adam step, Q(s, left) has moved from −0.1229 to −0.1424. That is about 2% of the way to the target: the step averages 64 samples, and a learning rate of 0.00025 asks for a small move.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0h-xGwXr9H5AJHBEfYEfJg.gif" /></figure><p><em>One recorded update, opening on its result: the change in value across the whole position and velocity map. Then it steps through collect, look ahead, target, error and step.</em></p><p>Now look at the change map. One update changed the value of every one of the 4,032 cells on the map, by up to 0.022. In Part 1, one update changed exactly one cell.</p><p>A goal transition is the one place the target does not look ahead. Update 32 contains one, a step that crossed the flag at position 0.501. Its target is just the reward:</p><pre>target = -1 + 0.99 * (1 - 1) * (anything) = -1</pre><p>Every other target bootstraps from the network itself, which is why reaching the flag at all matters so much here.</p><p>What does a value mean? If the car is T steps from the flag, its discounted return is −(1 − 0.99^T) / 0.01. A value near −63 means roughly 100 steps to go. A car that never reaches the flag approaches −100.</p><h3>Two problems a network brings</h3><p>Part 1 warned that a network would bring two difficulties: updates that affect many states, and targets that move as the network learns. DQN answers each with one idea.</p><p><strong>Consecutive experience is nearly identical.</strong> Within an episode, each state is a tiny step from the last. Training on experience in the order it arrives would keep pushing the shared weights toward the patch of the map the car is in right now. <strong>Experience replay</strong> stores the last 100,000 transitions and trains on a random minibatch of 64 every 4 steps. In five updates I checked, none of the 64 samples came from the episode the car was driving at the time. Over the whole run, each transition was sampled about 15 times on average.</p><p><strong>The target moves with every step.</strong> The target is built from the network’s own predictions. If the same weights produced both, every update would also move the target. The <strong>target network</strong> is a frozen copy that computes targets, refreshed from the online network every 250 updates:</p><pre>every 250 updates:  theta- &lt;- theta</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hr0bN_iXAA6l9tF8mmkYZg.png" /></figure><p><em>Recorded from the run. Vertical lines mark target syncs.</em></p><p>In the first 250 updates, the online network learns to predict the frozen targets, which drift to −1.27 by update 250: one step of cost plus a small guess. Then the copy lands. The targets jump to −2.23, because they now bootstrap from a network that has learned that one step costs about 1, and the loss jumps from 0.0084 to 0.94. Each sync lets the values look roughly one step further ahead. By about update 29,000, after about 115 syncs, the average target has fallen past −60. Later it rises again, to about −34 by the end of training, as the car reaches the flag in fewer steps.</p><p><strong>Why Double DQN?</strong> Plain DQN lets the target network both choose and score the next action, with a max over its values. A max over noisy estimates tends to pick the ones that happen to be too high, so that target is biased upward. Double DQN chooses with the online network and scores with the target network. Because the target network lags behind, their errors only partly overlap, so the bias usually shrinks. It does not disappear, and nothing here measures how much it shrank.</p><h3>The update in code</h3><p>These excerpts come from the <a href="https://github.com/AlirezaShamsoshoara/RL-from-zero/tree/f1563be804410939adf0b45ff93fd6f09f589cc3/deepQN">RL-from-zero DQN source, pinned to one revision</a>. They are excerpts, not standalone programs.</p><p><strong>Uniform replay, excerpt from </strong>ReplayBuffer.sample<strong>.</strong> Every stored transition is equally likely, whatever its age.</p><pre>indices = np.random.randint(0, self.size, size=batch_size)<br>return {<br>    &quot;obs&quot;: torch.as_tensor(self.obs[indices], device=self.device),<br>    &quot;actions&quot;: torch.as_tensor(self.actions[indices], device=self.device),<br>    &quot;rewards&quot;: torch.as_tensor(self.rewards[indices], device=self.device),<br>    &quot;next_obs&quot;: torch.as_tensor(self.next_obs[indices], device=self.device),<br>    &quot;dones&quot;: torch.as_tensor(self.dones[indices], device=self.device),<br>}</pre><p><strong>One update, adapted from </strong>DQNAgent.update<strong>.</strong> The batch checks, the non-finite-loss check and the returned statistics are omitted.</p><pre>obs, next_obs = self._encode(obs), self._encode(next_obs)<br>actions = actions_raw.long()<br>action_values = self.q_network(obs).gather(1, actions.unsqueeze(1)).squeeze(1)<br>with torch.no_grad():<br>    if self.double_dqn:<br>        next_actions = self.q_network(next_obs).argmax(dim=1, keepdim=True)<br>        next_target_values = (<br>            self.target_q_network(next_obs).gather(1, next_actions).squeeze(1)<br>        )<br>    else:<br>        next_target_values = self.target_q_network(next_obs).max(dim=1).values<br>    targets = rewards + self.gamma * (1.0 - dones) * next_target_values<br>loss = F.mse_loss(action_values, targets)<br>self.optimizer.zero_grad()<br>loss.backward()<br>if self.max_grad_norm &gt; 0:<br>    nn.utils.clip_grad_norm_(self.q_network.parameters(), self.max_grad_norm)<br>self.optimizer.step()<br>self.train_steps += 1<br>if self.train_steps % self.target_update_interval == 0:<br>    self.update_target_network()</pre><p>gather picks Q(s, a) for the action actually taken. Inside no_grad, the online network chooses and the target network scores, so no gradient flows into the target. The done mask comes only from true termination: a step cut off by the 200-step limit still looks ahead, because the task did not end, the clock did.</p><h3>The hard part: finding the flag at all</h3><p>Until some transition reaches the flag, every target is “−1 plus a guess,” and the network has nothing to learn except that time passes.</p><p>Reaching the flag by accident is hard. Random actions that change every step mostly cancel out, and the car jiggles near the bottom of the valley. What works is commitment: push one way long enough to build a swing, then the other. The repository’s own probe ran 500 fully random episodes per setting. Independent random actions reached the flag 0 times. Holding each random action for 20 to 60 steps reached it 64 times, 30 to 70 steps 43 times, and 50 to 80 steps only 8 times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*on6MTvcafsBSG_-zUqPBQA.png" /></figure><p><em>From the interactive version’s exploration lab, which runs the MountainCar equations in the browser with its own random numbers, not the training run. With this seed, 71 of 500 episodes reached the flag.</em></p><p>So the training recipe explores with <strong>held random pulses</strong>: with probability p, it starts a random action and keeps it for 20 to 60 steps; otherwise it takes the network’s greedy action. In the first 20,000 steps every action is random, and in those 104 warm-up episodes the car reached the flag 20 times. After that, epsilon falls from 1 to 0.02 over the next 100,000 steps. Because a pulse lasts many steps, p cannot equal epsilon. With an average hold of H steps the code uses p = epsilon / (H(1 − epsilon) + epsilon), so that epsilon is roughly the fraction of random steps. When the trained agent is tested, it never holds an action.</p><h3>Watching training</h3><p>The run saved a checkpoint every 5,000 steps. Here is the value map at one checkpoint every 10,000 steps, with the greedy policy’s push shown as arrows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2gTenDpWA1gI4jaUXpkJw.gif" /></figure><p><em>Saved checkpoints from the real run. Darker blue means a higher value, fewer steps from the flag; gray marks states the run had not reached.</em></p><p>Two things stand out. The values take shape long before the policy works: the greedy car reaches the flag from at most 1 of 11 test starts until step 90,000, where it suddenly succeeds from all of them. And learning is not monotonic: at step 110,000 it reaches the flag from only 3 of 11, recovering by step 140,000. One likely cause is that shared weights let an improvement in one region damage another, while the targets keep moving. This is why the repository keeps checkpoints and selects one instead of trusting the last.</p><p>The network also outputs a value for every state, including fast-moving states near the walls that the car never reached. At the selected checkpoint, 156 unvisited cells have values above −1, which is impossible for a state that has not reached the flag. Where data is missing, a network’s confident-looking number is a guess.</p><h3>The real repository run</h3><p>Everything above comes from one run of the repository’s recommended recipe, unchanged. Before using it, I re-ran that recipe with the locked dependencies on one CPU thread and compared all 61 saved checkpoints tensor by tensor. All 61 matched exactly, so the minibatches and targets above are the ones that trained this agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*jtAjpXMqTnOEBXYafA6cNA.gif" /></figure><p><em>The committed repository GIF, rendered by Gymnasium from the selected checkpoint with greedy actions. It shows the three highest-return episodes of eight, so it is a showcase, not a success rate.</em></p><p>The selected checkpoint was saved at step 251,392, where the average return of the previous 20 training episodes peaked at −96.05. Evaluated greedily on 200 new starts, with no action holds and no filtering, it reached the flag in all 200, with a mean return of −100.46 and a standard deviation of 9.21, above the environment’s −110 threshold for solving the task. Those starts vary the car’s position, not the physics, and this is one training seed: the same seed’s earlier recipes reached the flag 0 times.</p><p>To reproduce it, in a fresh environment:</p><pre>git clone https://github.com/AlirezaShamsoshoara/RL-from-zero.git<br>cd RL-from-zero<br>git checkout f1563be804410939adf0b45ff93fd6f09f589cc3<br>uv venv .venv-dqn --python 3.12<br>source .venv-dqn/bin/activate<br>uv sync --active<br>WANDB_MODE=offline OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \<br>  uv run --active python -m deepQN.main train \<br>  --config deepQN/configs/mountaincar_exploration.yaml</pre><h3>What these results do not show</h3><ul><li><strong>A small loss is not a good policy.</strong> The loss was 0.0071 after 100 updates, while greedy checkpoints from that stage reached the flag from none of the 11 test starts.</li><li><strong>A value is not a chance of success.</strong> It is a discounted sum of −1 rewards; −63 means about 100 steps to go.</li><li><strong>Close is not calibrated.</strong> The network’s starting values average −66.31 against an actual discounted return of −63.25 on one set of test seeds: about 3 points pessimistic.</li><li><strong>DQN has no convergence guarantee.</strong> Function approximation, bootstrapping and off-policy data together, the combination Sutton and Barto call the deadly triad, can diverge. Replay and target networks often make it work in practice, though this repository’s earlier recipes failed with both in place.</li><li><strong>This is not an ablation.</strong> The successful recipe changed input scaling, learning rate, target cadence, training length, exploration, warm-up and checkpoint selection at once.</li></ul><h3>Next: learn how to act directly</h3><p>DQN acts by taking the argmax over its value estimates, and it explores by mixing in random pulses from outside. Part 3 changes what the network learns: A3C trains a policy that outputs action probabilities directly, so exploration comes from sampling that policy, with a critic beside it and several workers learning in parallel instead of replaying old experience. Keep the picture: a prediction, a target, and one step toward it. The critic will look familiar.</p><h3>References and companion material</h3><ul><li><a href="https://alirezashamsoshoara.github.io/blog/rl-from-zero/dqn/">Interactive DQN companion</a>: step through recorded updates, the exploration lab, and every saved checkpoint.</li><li>Mnih and colleagues, <em>Playing Atari with Deep Reinforcement Learning</em> (2013), <a href="https://arxiv.org/abs/1312.5602">arXiv:1312.5602</a>, and <em>Human-level control through deep reinforcement learning</em>, <em>Nature</em> (2015), <a href="https://doi.org/10.1038/nature14236">doi:10.1038/nature14236</a>.</li><li>van Hasselt, Guez and Silver, <em>Deep Reinforcement Learning with Double Q-learning</em> (2016), <a href="https://arxiv.org/abs/1509.06461">arXiv:1509.06461</a>.</li><li>Lin, <em>Self-improving reactive agents based on reinforcement learning, planning and teaching</em> (1992), <a href="https://doi.org/10.1007/BF00992699">doi:10.1007/BF00992699</a>, where experience replay comes from.</li><li>Sutton and Barto, <em>Reinforcement Learning: An Introduction</em>, second edition, <a href="http://incompleteideas.net/book/the-book-2nd.html">the authors’ book page</a>; Section 11.3 names the deadly triad.</li><li><a href="https://github.com/AlirezaShamsoshoara/RL-from-zero/blob/f1563be804410939adf0b45ff93fd6f09f589cc3/deepQN/dqn/agent.py">Pinned RL-from-zero DQN source</a> and <a href="https://gymnasium.farama.org/environments/classic_control/mountain_car/">Gymnasium MountainCar documentation</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f00ea28fc09f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Q-learning: watch a table learn, one experience at a time]]></title>
            <link>https://medium.com/@a.shamsoshoara/q-learning-watch-a-table-learn-one-experience-at-a-time-82f20585f257?source=rss-e911bcf50f54------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f20585f257</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[q-learning]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Alireza Shamsoshoara]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 07:36:56 GMT</pubDate>
            <atom:updated>2026-11-18T07:36:56.860Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mI9JZQywHj6qsbVXuhvDSg.png" /></figure><p><em>From a zero-filled table to delayed reward, exploration, and a real FrozenLake agent. Part 1 of RL-from-zero.</em></p><p>A Q-learning agent does not begin with a route to the goal. It begins with a table of guesses.</p><p>Every row is a state. Every column is an action. Their intersection asks: <strong>How much discounted future reward could taking this action lead to?</strong> The agent acts, sees what happened, and revises the entry for that experience.</p><p>There is no neural network hiding in this example. Its small, local corrections are enough to demonstrate some of reinforcement learning’s most important ideas: exploration, bootstrapping, off-policy targets, and the difference between a successful policy and a fully learned value function.</p><p>The <a href="https://alirezashamsoshoara.github.io/blog/rl-from-zero/q-learning/">interactive companion article</a> lets you inspect individual transitions and run a separate learner. This version explains the same mechanism without requiring any interactive controls.</p><h3>First, give the table a world</h3><p>Our teaching world is a deterministic four-by-four FrozenLake-style map:</p><pre>S F F F<br>F H F H<br>F F F H<br>H F F G</pre><p>S marks the start, F a safe tile, H a hole, and G the goal. States are numbered 0 through 15, left to right across each row. Four action columns follow <strong>Left, Down, Right, Up</strong>.</p><p>Entering the goal gives reward <strong>1</strong>. Every other transition gives <strong>0</strong>. A hole or the goal truly ends the episode. A boundary can keep the agent in its current cell without ending the task. Actions do not slip to a different direction.</p><p>Position is enough to identify the state here. That is not a universal rule: a different task may also need velocity, inventory, or time remaining to predict its next outcome.</p><p>Write the value of an action as Q(s, a). The table initially has no evidence favoring one direction over another. In the repository, its construction is straightforward.</p><p><strong>Table construction, inside </strong>QLearningAgent.__init__<strong>. This excerpt belongs to the surrounding class, not a standalone training program.</strong></p><pre>import numpy as np<br>self.Q = np.zeros((self.n_states, self.n_actions), dtype=np.float32)</pre><p>The teaching world needs a 16-by-4 table. The repository’s larger default FrozenLake task needs 64-by-4. Both use the same tabular idea.</p><h3>Three knobs, three different jobs</h3><ul><li><strong>Alpha, the learning rate</strong>, determines how much of a correction is applied now.</li><li><strong>Gamma, the discount</strong>, determines how later reward counts relative to nearer reward.</li><li><strong>Epsilon, the exploration probability</strong>, determines how training collects experience.</li></ul><p>These are not interchangeable ways to make an agent more adventurous. Alpha changes learning, gamma changes the objective, and epsilon changes the behavior that supplies data.</p><p>The teaching recording uses alpha <strong>0.1</strong>, gamma <strong>0.95</strong>, epsilon <strong>0.3</strong>, and seed <strong>7</strong>. It contains <strong>120 episodes and 843 actual transitions</strong>, including wall moves, revisits, holes, and goals. No successful route is prescribed to it.</p><p>Its first three episodes take 12, 5, and 4 moves, respectively, and all end in holes. Those failures are part of the learning story, not footage removed to make the learner look successful.</p><h3>Reward is not return</h3><p>A reward is the immediate feedback from one transition. A return adds the rewards that follow, with discounting:</p><pre>G_t = r_(t+1) + gamma * r_(t+2) + gamma^2 * r_(t+3) + ...</pre><p>The first reward counts fully; each additional step adds another factor of gamma. True termination ends the sum. When gamma is below one, an otherwise identical reward contributes more if received sooner.</p><p>Q-learning aims to estimate the expected return from an action followed by optimal behavior. A Q-value is therefore not generally a success percentage. Its scale depends on rewards and discounting, and its current estimate can be incomplete or wrong.</p><p>The agent does not wait to observe the entire future before updating. Instead, it combines a reward it just received with an estimate already in its table. Learning partly from another estimate is <strong>bootstrapping</strong>.</p><h3>The update in three lines</h3><p>For a continuing transition, read the next state’s row and take its maximum. For true termination, add no continuation.</p><pre>target   = reward + gamma * (1 - terminated) * max_a&#39; Q(s&#39;, a&#39;)<br>TD error = target - Q(s, a)<br>Q_new    = Q_old + alpha * TD error</pre><p>Here terminated is 1 when the task truly ends and 0 otherwise. s&#39; is the observed next state. <strong>TD</strong> means temporal difference: the gap between the current estimate and this new, one-step target.</p><p>A positive gap raises the estimate. A negative gap lowers it. A zero gap leaves it unchanged. With alpha 0.1, the agent takes one tenth of the correction rather than replacing its prediction with the target.</p><p><strong>Only the experienced state-action entry is updated.</strong> Reading the next row does not rewrite it, and one move does not replace the entire current row.</p><h3>The first useful reward</h3><p>The recording begins with a random exploration action: <strong>Up from state 0</strong>. The boundary keeps the agent in place. Reward, old estimate, and next maximum are zero, so the update is also zero.</p><p>The first goal does not arrive until <strong>episode 29</strong>. The agent takes <strong>Right from state 14 to state 15</strong>. Right is action index 2. This particular action was chosen by randomly breaking a tie among maximal values, not by the epsilon exploration branch.</p><p>Goal entry earns 1 and terminates. The update is:</p><pre>target = 1<br>TD error = 1 - 0 = 1<br>Q_new(14, Right) = 0 + 0.1 * 1 = 0.1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lt6107LOb4yKRetP-pSEQ.gif" /></figure><p><em>This short clip shows the first goal transition in the recorded teaching run. It is not a complete training episode or a benchmark result.</em></p><p>Now one final action has a positive estimate. The start has not instantly learned a route. Earlier actions were observed before that estimate existed, and reaching the goal does not retroactively replay them.</p><h3>How zero reward can still teach something</h3><p>In <strong>episode 70</strong>, the agent revisits <strong>state 13, Right, state 14</strong>. This safe move gives reward 0, but state 14 now has a best estimate of 0.1.</p><pre>target = 0 + 0.95 * 0.1 = 0.095<br>TD error = 0.095 - 0 = 0.095<br>Q_new(13, Right) = 0 + 0.1 * 0.095 = 0.0095</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_xg-of80htuvdkORIBYiw.gif" /></figure><p><em>This is a later recorded revisit. The intervening episodes supplied its next-state estimate; these two clips are not consecutive transitions in a new zero-table run.</em></p><p>The correction comes entirely from predicted continuation, not an extra reward for a safe tile. Later visits can carry the information farther back. In this recording, a start-state action first gains value in <strong>episode 103</strong>, becoming approximately <strong>2.863e-6</strong>.</p><p>That is small, but nonzero. The interactive display uses scientific notation so a tiny estimate is not mistaken for an exact zero. These episode numbers describe one fixed-seed teaching run, not a universal learning budget.</p><p>Zero immediate reward alone does not imply a zero update. What matters is the <strong>TD error</strong>, which also includes the current estimate. A zero residual can mean that both prediction and target are still missing useful downstream evidence; it does not certify convergence.</p><h3>Exploration and greedy ties are different</h3><p>Epsilon-greedy training selects a uniformly random action with probability epsilon. Otherwise, it selects a maximizing action. When several actions tie, the repository randomly chooses among those maxima during training.</p><p>An action can therefore look random for two different reasons:</p><ol><li>The epsilon exploration branch chose it.</li><li>The greedy branch broke a tie among equally valued actions.</li></ol><p>Tie-breaking is not an epsilon event. Conversely, the exploration branch can pick a currently best action, so epsilon is not the probability of making a visibly different choice.</p><p>For deterministic evaluation, the repository uses the first argmax and neither consumes randomness nor advances the exploration counter.</p><p><strong>Action selection, excerpt from </strong>act<strong> after state validation.</strong></p><pre>if deterministic:<br>    return int(np.argmax(self.Q[state]))<br>self.global_step += 1<br>if np.random.rand() &lt; self.epsilon():<br>    return int(np.random.randint(self.n_actions))<br>candidates = np.flatnonzero(self.Q[state] == np.max(self.Q[state]))<br>return int(np.random.choice(candidates))</pre><p>The browser experiments keep epsilon fixed until a control changes. The repository’s training recipe instead decays it with training steps. Decay can shift collection toward exploitation, but too-rapid decay can leave useful routes undiscovered.</p><h3>Why the target is off-policy</h3><p>Suppose the next exploratory action will be Down, while Right has the largest next-state Q-value. Q-learning still uses Right’s value in its target.</p><p>The data-collecting behavior can explore, but the update evaluates the <strong>best continuation</strong>. That separation makes Q-learning off-policy. SARSA, by contrast, uses the value of the next action actually selected.</p><p>Off-policy does not mean data coverage becomes irrelevant. Unobserved state-action pairs cannot teach the table what their outcomes are.</p><p>The <a href="https://github.com/AlirezaShamsoshoara/RL-from-zero/blob/27ea78dc267363afec2d447f1ba0278bfccdf89e/Qlearning/ql/agent.py">pinned agent implementation</a> maps this distinction directly into code.</p><p><strong>One-cell update, excerpt after index and reward validation.</strong></p><pre>target = float(tr.r) + (<br>    0.0 if tr.done else self.gamma * float(np.max(self.Q[next_state]))<br>)<br>td_error = target - float(self.Q[state, action])<br>updated = float(self.Q[state, action]) + self.alpha * td_error<br>self.Q[state, action] = updated</pre><p>Transition.done means true termination in this implementation. Returned statistics expose the target, residual, and updated value, which explain the correction more clearly than reward alone.</p><h3>A loop stopping is not always a task ending</h3><p>A goal or hole truly ends FrozenLake. Suppress the future term, but still learn from that terminal reward.</p><p>An external interaction cap can instead interrupt an underlying continuing task. Retain bootstrap from the <strong>final observed next state</strong>, not the reset state of the next episode. The repository updates first, then stops its loop.</p><p>If a deadline is intrinsic to the task, it may be a genuine terminal event. A finite-horizon state may also need time remaining. Decide what the task means before deciding its mask; a library’s loop-stop flag is not the whole objective.</p><h3>The real repository task: FrozenLake 8×8</h3><p>The small world makes arithmetic inspectable. <a href="https://github.com/AlirezaShamsoshoara/RL-from-zero/blob/27ea78dc267363afec2d447f1ba0278bfccdf89e/Qlearning/configs/frozenlake.yaml">RL-from-zero’s default recipe</a> runs the same tabular idea in Gymnasium’s deterministic <strong>FrozenLake-v1 8×8</strong> environment.</p><p>It has <strong>64 states and four actions</strong>, with goal-only reward 1 and terminal holes. The recipe uses alpha <strong>0.1</strong>, gamma <strong>0.99</strong>, a <strong>200-step cap</strong>, and <strong>5,000 training episodes</strong>. Its seed is 42, and exploration decays from 1 to 0.05. NumPy performs the learning on CPU; PyTorch is used for checkpoint serialization, not a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*sQ8QKPmM2bhfu8lEk303cg.gif" /></figure><p><em>Native Gymnasium rendering from the repository’s committed GIF. It contains three selected repeats of the saved policy, not AI-generated footage or the small browser experiment.</em></p><p>The saved Q-table was selected at <strong>training episode 1,011</strong>, using a ten-episode training-return window. A subsequent unfiltered evaluation reached the goal in <strong>200 of 200 episodes</strong>, each taking <strong>16 moves</strong>, without updating the table.</p><p>All repetitions used the <strong>same fixed map and start state</strong>. They establish repeatability of that policy here, not independent-map generalization, slippery-dynamics robustness, shortest-path optimality, or convergence of every entry.</p><p>To reproduce the repository recipe, use a separate working copy and a fresh named environment. Training writes new checkpoints; it is not required merely to replay an existing trusted table.</p><pre>uv venv .venv-qlearning-medium<br>source .venv-qlearning-medium/bin/activate<br>uv sync --active<br><br>WANDB_MODE=offline OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \<br>  uv run --active python -m Qlearning.main train \<br>  --config Qlearning/configs/frozenlake.yaml</pre><p>The <a href="https://github.com/AlirezaShamsoshoara/RL-from-zero/blob/27ea78dc267363afec2d447f1ba0278bfccdf89e/Qlearning/README.md">repository README</a> explains checkpoint evaluation, headless rendering, and GIF export. Keep an evaluator’s complete episode report separate from a selected showcase.</p><h3>What a successful route does not prove</h3><p>Finite discounted tabular Q-learning has convergence results under assumptions including bounded rewards, repeated state-action coverage, and suitable learning rates. Along each pair’s updates, a standard requirement is that learning rates sum to infinity while their squares sum to a finite value.</p><p>A constant alpha of 0.1 does not satisfy that decreasing-rate condition. It can be useful in practice, but a finite run and a successful greedy route do not prove every Q-value converged. Separate observed policy performance from coverage and theory.</p><p>A table is wonderfully transparent, but it needs an entry for every state-action pair and does not generalize a correction to separately indexed similar states. <strong>DQN</strong> keeps the reward-plus-continuation idea and replaces the lookup table with a neural network. Shared parameters and moving bootstrapped targets introduce new stability problems; a tabular convergence argument does not simply carry over.</p><p>Before adding that complexity, keep one picture: <strong>an experience arrives, a target is formed, and one estimate moves toward it</strong>. Here, you can point to the exact cell.</p><h3>References and companion material</h3><ul><li><a href="https://alirezashamsoshoara.github.io/blog/rl-from-zero/q-learning/">Interactive Q-learning companion</a>: recorded exploration, Q-table inspection, and an independent parameter experiment.</li><li>Watkins and Dayan, <em>Q-learning</em> (1992), <a href="https://doi.org/10.1007/BF00992698">doi:10.1007/BF00992698</a>.</li><li>Sutton and Barto, <em>Reinforcement Learning: An Introduction</em>, second edition, <a href="http://incompleteideas.net/book/the-book-2nd.html">canonical book page</a>, especially Chapter 6.</li><li><a href="https://github.com/AlirezaShamsoshoara/RL-from-zero/blob/27ea78dc267363afec2d447f1ba0278bfccdf89e/Qlearning/ql/agent.py">Pinned RL-from-zero source</a>.</li><li><a href="https://gymnasium.farama.org/environments/toy_text/frozen_lake/">Gymnasium FrozenLake documentation</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f20585f257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RL From Zero: Reinforcement Learning, Built from Scratch]]></title>
            <link>https://medium.com/@a.shamsoshoara/rl-from-zero-reinforcement-learning-built-from-scratch-6f7472215597?source=rss-e911bcf50f54------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f7472215597</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Alireza Shamsoshoara]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 07:13:47 GMT</pubDate>
            <atom:updated>2026-11-18T07:13:47.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>RL From Zero: reinforcement learning, built from scratch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eek8ffQgHEobdefGMEnFcQ.gif" /></figure><p><em>Thirteen reinforcement learning algorithms, implemented from scratch and explained one idea at a time. Every tile above is a trained agent.</em></p><p>Reinforcement learning is easy to describe and surprisingly hard to see. An agent acts, collects a reward, and slowly gets better. The interesting part happens in between: a value estimate that moves a little, a gradient that points somewhere useful, a target that keeps shifting while the agent learns.</p><p>RL From Zero is a series that makes those steps visible. Each post takes one algorithm from my open-source <a href="https://github.com/AlirezaShamsoshoara/RL-from-zero">RL-from-zero repository</a> and walks through how it actually learns, from its first update to a trained agent.</p><h3>What is in the repository</h3><p>Every algorithm is implemented from scratch in its own self-contained package, with the same command-line interface, YAML configuration, and optional Weights &amp; Biases tracking. Each one comes with a trained agent, and the animation above shows all of them in their own environments:</p><ul><li><strong>Tabular methods:</strong> Q-learning on FrozenLake, plus two multi-agent variants: Independent Q-learning on LineWorld and Nash Q-learning on Grid Soccer.</li><li><strong>Deep value-based learning:</strong> DQN, with a Double DQN option, on MountainCar.</li><li><strong>Policy gradients and trust regions:</strong> PPO on CartPole and TRPO on Acrobot.</li><li><strong>Actor-critic methods:</strong> A3C on LunarLander, DDPG on LunarLander Continuous, TD3 on MountainCar Continuous, and SAC on Pendulum.</li><li><strong>Offline RL:</strong> IQL (Implicit Q-Learning), trained from a fixed Pendulum dataset.</li><li><strong>Multi-agent deep RL:</strong> MAPPO on MultiWalker and MADDPG on Simple Spread.</li></ul><h3>What each post includes</h3><ul><li><strong>The core idea first</strong>, in plain language, before any equation.</li><li><strong>Figures and animations</strong> that show the algorithm learning, one step at a time.</li><li><strong>The math, worked through</strong> with real numbers from a recorded run.</li><li><strong>The matching code</strong> from the repository, and the commands to train and evaluate it yourself.</li><li><strong>The real environment</strong>, with the trained agent and a clear note on what the results do and do not show.</li></ul><h3>Where it starts</h3><p>The series begins at the simplest end: a table of Q-values. Part 1, <a href="https://alirezashamsoshoara.github.io/blog/rl-from-zero/q-learning/"><em>Q-learning: watch a table learn</em></a>, follows one experience into one changed table cell, then shows how exploration and a delayed reward turn many small updates into a policy. The version on my blog is interactive, so you can step through every update yourself.</p><p>Later posts build from there, toward methods that replace the table with a neural network, learn a policy directly, and coordinate several agents at once.</p><h3>Try it yourself</h3><p>The code is open source under the MIT license. To train the first agent:</p><pre>git clone https://github.com/AlirezaShamsoshoara/RL-from-zero.git<br>cd RL-from-zero<br>uv venv .venv<br>uv sync<br>source .venv/bin/activate<br>python -m Qlearning.main train --config Qlearning/configs/frozenlake.yaml</pre><p>Every other algorithm follows the same pattern: a YAML config, a train command, and a demo command that replays the saved agent.</p><h3>Follow the series</h3><p>The <a href="https://alirezashamsoshoara.github.io/blog/rl-from-zero/">RL From Zero page</a> on my blog lists every post in reading order. Follow me here on Medium to get each new part as it comes out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f7472215597" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>