<?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 Devanshi Kashyap on Medium]]></title>
        <description><![CDATA[Stories by Devanshi Kashyap on Medium]]></description>
        <link>https://medium.com/@devanshik1906?source=rss-280ff39e65a5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4RBJZh4VkN4A04ic</url>
            <title>Stories by Devanshi Kashyap on Medium</title>
            <link>https://medium.com/@devanshik1906?source=rss-280ff39e65a5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:19:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devanshik1906/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[My Exploration of RL Concepts, Q-learning, DQN and a MountainCar Finale]]></title>
            <link>https://medium.com/@devanshik1906/my-exploration-of-rl-concepts-q-learning-dqn-and-a-mountaincar-finale-2da1b3eb5055?source=rss-280ff39e65a5------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da1b3eb5055</guid>
            <category><![CDATA[mountain-car]]></category>
            <category><![CDATA[deep-q-network]]></category>
            <category><![CDATA[deepreinforcementlearning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Devanshi Kashyap]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 18:09:12 GMT</pubDate>
            <atom:updated>2025-10-08T18:09:12.048Z</atom:updated>
            <content:encoded><![CDATA[<p>We learn most things in life by making mistakes, getting feedback (success/failure), and then trying again and again until we reach our goal. Well, Reinforcement Learning (RL) brings this human learning process into computers, by letting them learn and improve on their own, just like us!</p><p>Table of Contents:</p><ol><li>What is RL?</li><li>Keywords and Processes</li><li>The Blueprint: Markov Decision Process (MDP)</li><li>Comparing ML Types: Supervised, Unsupervised, and RL</li><li>Types of RL Algorithms</li><li>Q-learning and DQN</li><li>Implementing MountainCar with DQN</li><li>Concluding Thoughts</li></ol><h3>What is RL?</h3><p>Reinforcement learning is a way for machines to learn by taking ‘actions’ in a particular ‘state’ of an ‘environment’, making ‘observations’, and gradually performing better actions through ‘feedback’.</p><p>Instead of being told what the right answer is, they discover strategies for success by trial-and-error.</p><figure><img alt="Relationship between AI, ML, RL and DL (Venn Diagram)" src="https://cdn-images-1.medium.com/max/1024/1*qQxafLPEyeuiZRln_Q1_6w.png" /></figure><p>As we know, ML is a core subset of AI. Within that comes</p><p>1.<em> Reinforcement Learning</em> [‘strategy’ for learning through trial and error]<br>2. <em>Deep Learning</em> [gives us a powerful computer ‘brain,’ called a neural network]</p><p>When we put them together, we get <em>Deep Reinforcement Learning</em> (DRL), where the neural networks learn using the trial-and-error process.</p><p>→ Reinforcement Learning is mainly used in cases where the problem we are solving is not related to an “existing” dataset, but it has an environment to live in, where it creates its own data. for eg: A city for self-driving cars.</p><p>No matter how much you feed all the traffic rules into the machine, it’s impossible to predict all the variables or unforeseen situations. This is why, the main goal here is to “<em>minimize the errors</em>” and not predict all the moves.</p><h3>Keywords and Processes in RL</h3><p>Let’s understand RL better by taking an everyday example.</p><p>You are a student and you’re starving after back-to-back lectures, and the only way to get food on campus is the canteen.</p><p>The problem is, it’s always packed, and if you want a seat, you will have to wait at least 10 mins and then be ready to sprint as soon as someone stands up. Each time you try, you note three things.</p><ul><li>How long you waited</li><li>How good the food was</li><li>How much time you have left before your next class</li></ul><p>Over time, you try different strategies to know how you can get food quickly and still make it to class on time.</p><p>Now, using the definition I mentioned earlier, let’s identify what each RL keyword means w.r.t. our canteen example.</p><ol><li><strong><em>Agent</em> </strong>— the one who perform actions (learner)</li></ol><p>In our example, it’s you!</p><p>2<em>.</em><strong><em> Environment</em></strong> — The “world” in which the agent behaves and makes choices.</p><p>Here, it’s the campus canteen and the crowd there.</p><p>3.<strong><em> State</em></strong> — this is the current situation that describes where exactly the agent is inside the environment.</p><p>Here, it could be how hungry you are or the amount of time you got before class, or how crowded the canteen is.</p><p>4.<strong><em> Action</em></strong> — its the decision that the agent makes.</p><p>Here, it is scanning for people who look ready to leave, or waiting near tables.</p><p>5.<strong><em> Feedback (Reward/Punishment)</em></strong> — The response the agent gets after taking an action. It’s positive (reward) for reaching the goal or negative (punishment) for failing to reach the goal. The reward varies on how fast the goal was achieved. The lesser time taken, the higher the reward is and vice versa.</p><p>Here, getting food quickly and making class on time will result in a reward, whereas losing time and going hungry will result in punishment.</p><p>6.<strong><em> Policy</em></strong> — It’s the agent’s overall strategy, i.e., the set of rules/patterns it uses to choose actions based on the state it is currently in.</p><p>Here, it is the plan you develop overtime, for eg — reaching the canteen asap after a big lecture ends.</p><p>Repeat. The agent repeats this entire process, and learns from each round and improves its policy. So, in our example, you use your past experiences to try new ways to get a seat and the food faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yr5j1ImUkb0-xJbTPe3SDw.png" /><figcaption>RL Process Flowchart</figcaption></figure><p>Once our agent knows how to reach the target — getting a seat and food in this case, it has two options for future actions:</p><ul><li><strong><em>Exploitation</em></strong>: Now that the agent knows how to reach the target, it always does that action since it thinks that’s what will give the highest reward (based on its experience so far).</li></ul><p>Here, it will be you always going to the table that got you food fastest last week.</p><ul><li><strong><em>Exploration</em></strong>: Trying new actions, even if its not sure that it will be the best. This is so that you can discover better rewards later.</li></ul><p>Here, you waiting by a different table today to see if it gets you food faster is exploration.</p><p>RL agents usually start with higher exploration rates, trying every option to learn what works best. Gradually, as they get smarter, this exploration rate is tuned down and they focus on exploiting the best moves that they found.</p><h3>The Blueprint: Markov Decision Process (MDP)</h3><p>Markov process depends on the “Markov property,” which models situations such that the next step depends only on the current step and not on how you got there.</p><blockquote>“Future depends only on the present, not the past.”</blockquote><p>MDP is the ‘blueprint’ for our RL agent. It doesn’t solve the problem, but gives it a structure by defining all possible states, available actions, and rules for rewards. Our agent’s job is to use this blueprint to find the best possible path to reach the target (optimal policy).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*HfOoG4nXUSAwGLXXoQT6wQ.png" /><figcaption>Markov Decision Process</figcaption></figure><h3>Comparing ML Types: Supervised, Unsupervised, and RL</h3><p>Now that we know what RL is, let’s see how it stands apart from other machine learning types like supervised and unsupervised learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UCEGsLUmrfOK6aGQeJjNHQ.png" /><figcaption>Difference between Supervised, Unsupervised and Reinforcement Learning</figcaption></figure><h3>Types of RL Algorithms</h3><p>Before learning the algorithms, it’s really important that we learn what Q-function is first, in context of all the terminologies we have learnt so far.</p><p>To know that, let’s see how to calculate ‘Rt’ which is the discounted sum of all the individual rewards ( r ) over time ( t ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*ywaJkQzH_B98wt3qjHIJcQ.png" /></figure><p>‘γ’ (<em>gamma</em>) here lies between [0, 1] and represents the discount factor (patience level).</p><p>If its low (eg: 0.1) that means our agent is impulsive. It’s like saying <em>“I would rather have 10 bucks now instead of 100 rupees in the future</em>”.</p><p>If its higher (eg: 0.99), it means our agent is patient and says “<em>I’ll have 100 bucks in the future because its a higher reward</em>”.</p><p>So, what exactly does Q-function do?</p><p>It captures the “expected” total future reward an agent in state “s” can receive by performing an action “a”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*aZtvnNzLiCIrfPOhNSX2Zg.png" /></figure><p>Now that we understand what the Q-function represents, let’s see how reinforcement learning algorithms use these ideas in practice through two fundamental approaches:</p><h4><strong><em>Value Learning</em></strong></h4><p>The main goal here is to figure out how “good” or “valuable” each situation is.</p><ol><li>Find Q(s, a): You first learn the <strong><em>Q-function</em></strong>, that calculates a “score” or “Q-value” for every possible action (a) in every state (s).</li><li>Find a:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*p5-BtZ1yi1VnJ-2nrlHSBg.png" /></figure><p>This says “<em>Action (a) that I chose is the one that gives the maximum possible Q-value w.r.t my current state.</em>”</p><p>The agent calculates the score for all actions and greedily picks the best one.</p><p>In summary, it rates every action which is possible for a given state and then picks the one which has the highest rating.</p><h4>Policy Learning</h4><p>This strategy does not assign a score, but instead learns a policy π(s) which is a set of rules for what to do in a given situation (state)</p><ol><li>Find π(a|s):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*e-ENnuaDofODSstuAX2TKw.png" /></figure><p>This formula tells us the probability that our agent will take a specific <strong>action (At​ = a)</strong> given that it is in a specific <strong>state (St ​= s)</strong>, under the policy π at time t.</p><p>2. Sample a ∼ π(s): This means, “<em>I will sample my next </em><strong><em>‘a’</em></strong><em> based on the strategy given by my </em><strong><em>policy (π)</em></strong><em> for the current </em><strong><em>‘s’</em></strong><em>.</em>” The policy might give a probability for each action (e.g., “70% chance you should go left, 30% chance you should go right”).</p><p>Simply put, the agent is like a chess player who has memorized a guidebook. It doesn’t score every possible move but it just knows the best move to make in a given situation based on the strategy given in that guidebook.</p><h3>Q-learning and DQN</h3><h4>Q-learning (The foundation)</h4><p>It is the ‘foundational’ algorithm (Watkins, 1989) for learning a value function. The main goal is to learn the “quality” (Q-value) of every possible action in every possible state.</p><ul><li>It is a type of value learning algorithm.</li></ul><p>Q-Learning stores these Q-values in a simple spreadsheet-like structure called a “<strong>Q-Table”</strong>.</p><p>It has a row for every possible state and a column for every possible action. Each cell in the table holds a numerical score (Q-value) for that specific state-action pair. Higher the Q-value, higher is the satisfaction rate.</p><p>Circling back to our canteen example, it’s q-table will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Z2NvLiGu2yK-KHzSZEhy9g.png" /></figure><p>The agent constantly updates the scores in this Q-table (while exploring) using the <strong>Bellman Equation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*LRtTvLnI6zYlPZgERe2afg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*s3FmzINH8UokJnD2PbpGdg.png" /></figure><h4>DQN (The POWERFUL Upgrade)</h4><p>To handle worlds with millions of states, we replace the Q-table with a deep neural network. This combination is called a Deep Q-Network (DQN).</p><p>We can use deep neural networks in place of q-tables in the following ways:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k3Gc-Qu6vwULZOLgFmgNLw.png" /></figure><p><em>Experience Replay </em>— a DQN agent stores its experiences (state, action, reward, next_state) in a “memory bank.” It then learns by replaying random samples of these past experiences, which makes the training process much more stable and efficient than a simple Q-table.</p><p><strong><em>DQN working</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bNSOZyXlBO_-b2ypVaYeuA.png" /></figure><p>This helps the DQN to master complex tasks, from classic control problems to video games.</p><h3>Implementing MountainCar with DQN</h3><p>To see DQN in action, I decided to solve the classic Reinforcement Learning challenge: MountainCar.</p><p>MountainCar is a built-in setup from python’s gymnasium library.</p><p>The problem at hand is, our agent’s (the car) accelerator isn’t strong enough to drive uphill to reach the target. So, our agent needs to learn to take a negative action (going left, i.e. away from target) to gain momentum and then accelerating in the right direction to reach the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*31PtRDT-u0GCjZPKmxBQuw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*vpeRmhnVhuHHHAZ8j4v4JQ.png" /></figure><p>Let’s start by importing the necessary libraries</p><pre># imports and environment setups<br>import gymnasium                # RL environments<br>import numpy as np              # numbers and arrays<br>import torch                    # PyTorch (tensors + training)<br>import torch.nn as nn           # neural network layers<br>import torch.optim as optim     # optimizers like Adam<br>from collections import deque   # fast queue for replay buffer<br>import random                   # random choices<br>import matplotlib.pyplot as plt # plotting</pre><p>Now we will define our q-network</p><pre># defining our Q-network: a small 3-layer neural network<br>class QNetwork(nn.Module):<br>    def __init__(self, state_size, action_size):<br>        super(QNetwork, self).__init__()<br>        # blueprint (layers): input -&gt; hidden -&gt; hidden -&gt; output<br>        self.fc1 = nn.Linear(state_size, 64)  # takes the game state<br>        self.fc2 = nn.Linear(64, 64)          # processes information<br>        self.fc3 = nn.Linear(64, action_size) # outputs a score (Q-value) per action<br><br>    def forward(self, x):<br>        # the flow: pass state through layers with ReLU, then get Q-values<br>        x = torch.relu(self.fc1(x))<br>        x = torch.relu(self.fc2(x))<br>        return self.fc3(x)  # final Q-values for each action</pre><p>Let’s create a Memory Bank for Our Agent (Experience Replay)</p><pre># replay buffer: stores and samples experiences for training<br>class ReplayBuffer:<br>    def __init__(self, capacity):<br>        self.buffer = deque(maxlen=capacity)<br><br>    def push(self, state, action, reward, next_state, done):<br>        # save one experience tuple<br>        self.buffer.append((state, action, reward, next_state, done))<br><br>    def sample(self, batch_size):<br>        # pick a random mini-batch<br>        batch = random.sample(self.buffer, batch_size)<br>        states, actions, rewards, next_states, dones = zip(*batch)<br>        return (np.array(states), np.array(actions), np.array(rewards),<br>                np.array(next_states), np.array(dones))<br><br>    def __len__(self):<br>        return len(self.buffer)</pre><ul><li>(<em>mix up the agent’s past experiences so the model learns from a variety of situations, not just similar, back-to-back ones</em>)</li></ul><p>Setting up the Experiment</p><pre># initialization<br>import gymnasium<br><br>env = gymnasium.make(&#39;MountainCar-v0&#39;)   # create environment<br>state_size = env.observation_space.shape[0]  # 2 values (position, velocity)<br>action_size = env.action_space.n             # 3 actions (push left, no push, push right)<br><br>q_network = QNetwork(state_size, action_size)   # main network<br>target_network = QNetwork(state_size, action_size)  # target network for stable training<br>target_network.load_state_dict(q_network.state_dict())  # start equal<br><br>optimizer = optim.Adam(q_network.parameters(), lr=0.0005)  # learning rate<br><br># simple replay buffer<br>replay_buffer = deque(maxlen=2000)  # store past experiences (s, a, r, s&#39;, done)<br><br># training hyperparameters<br>batch_size = 64          # how many experiences to learn from at a time<br>gamma = 0.99             # how much we value future rewards (discount)<br><br>epsilon = 1.0            # start exploring a lot (random actions)<br>epsilon_min = 0.01       # lowest exploration<br>epsilon_decay = 0.9995   # slowly explore less over episodes<br><br>update_target_every = 10 # copy weights to target net every 10 episodes<br>num_episodes = 2000      # how many episodes to train</pre><ul><li><em>set up the game, the two networks, learning settings, and the memory.</em></li></ul><p>The Training Loop!</p><pre>reward_history = []  # track total reward per episode to see learning progress<br><br>for episode in range(num_episodes):<br>    state, info = env.reset()<br>    total_reward = 0<br>    done = False<br><br>    while not done:<br>        # epsilon-greedy: pick random action with prob epsilon, else best action<br>        if np.random.rand() &lt; epsilon:<br>            action = env.action_space.sample()  # explore<br>        else:<br>            with torch.no_grad():               # exploit          <br>                # no training when choosing action<br>                s = torch.tensor(state, dtype=torch.float32).unsqueeze(0)<br>                q_values = q_network(s)         # get Q-values<br>                action = torch.argmax(q_values, dim=1).item()  # pick best<br><br>        # step the env<br>        next_state, reward, terminated, truncated, info = env.step(action)<br>        done = terminated or truncated<br>        total_reward += reward<br><br>        # save to replay buffer<br>        replay_buffer.append((state, action, reward, next_state, done))<br>        state = next_state<br><br>        # learn only when we have enough samples<br>        if len(replay_buffer) &gt;= batch_size:<br>            # sample a batch<br>            batch = random.sample(replay_buffer, batch_size)<br>            states, actions, rewards, next_states, dones = zip(*batch)<br><br>            # convert to tensors<br>            states = torch.tensor(states, dtype=torch.float32)<br>            actions = torch.tensor(actions, dtype=torch.int64).unsqueeze(1)<br>            rewards = torch.tensor(rewards, dtype=torch.float32).unsqueeze(1)<br>            next_states = torch.tensor(next_states, dtype=torch.float32)<br>            dones = torch.tensor(dones, dtype=torch.float32).unsqueeze(1)<br><br>            # current Q(s,a)<br>            q_values = q_network(states).gather(1, actions)<br><br>            # target: r + gamma * max_a&#39; Q_target(s&#39;, a&#39;) for non-terminal<br>            with torch.no_grad():<br>                max_next_q = target_network(next_states).max(dim=1, keepdim=True)[0]<br>                target_q = rewards + (1 - dones) * gamma * max_next_q<br><br>            # loss and update<br>            loss = nn.MSELoss()(q_values, target_q)<br>            optimizer.zero_grad()<br>            loss.backward()<br>            optimizer.step()<br><br>    # decay exploration after each episode<br>    epsilon = max(epsilon_min, epsilon * epsilon_decay)<br><br>    # update target network sometimes for stability<br>    if (episode + 1) % update_target_every == 0:<br>        target_network.load_state_dict(q_network.state_dict())<br><br>    reward_history.append(total_reward)<br><br>    # print every 20 eps<br>    if (episode + 1) % 20 == 0<br>    print(f&quot;Episode {episode + 1}, Total Reward: {total_reward}, Epsilon: {epsilon:.3f}&quot;)<br>  </pre><ul><li><em>In each episode, the agent chooses actions, observes the results, and stores these experiences in its memory and after every move, it replays a random amount of these memories to train its neural network, making its future decisions slightly smarter.</em></li></ul><p>Over time, the agent explores less and depends more on what it has learned already, getting better at solving the game.</p><p>Now let’s look at our output!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0QUY2dwNEsRBYf5cDt_LA.png" /></figure><p>Here’s how our agent looked at different checkpoints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*uw5txQMxTEN0dWjRXRRvFA.gif" /><figcaption>EPISODE 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gu5ragIE45PAtLy3WpL1jg.gif" /><figcaption>EPISODE 500</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ZwrlP66unFD48Gk4boVO5Q.gif" /><figcaption>EPISODE 1500</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KPdEI-Gm1Fnv2b5pMJ3f2g.gif" /><figcaption>EPISODE 2000</figcaption></figure><p>Plotting Rewards Over Episodes:</p><pre>plt.figure(figsize=(20, 10))<br>plt.plot(reward_history)<br>plt.xlabel(&#39;Episode&#39;)<br>plt.ylabel(&#39;Total Reward&#39;)<br>plt.title(&#39;DQN on MountainCar&#39;)<br>plt.show()</pre><p>I used Matplotlib library to plot the agent’s performance, turning the list of rewards from each episode into a line graph which shows its learning progress over time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NH22phwWivuKtGDja2VREw.png" /></figure><h4>My opinion on this experiment</h4><p>Honestly, watching the output was a real rollercoaster. After reading the theory, I had this idea in my head that once the agent got its first successful reward (episode 1560), the graph would shoot up in a nice clean line.</p><blockquote>But Reinforcement Learning isn’t simple like that.</blockquote><p>As you can see from my output and graph, my agent had its first breakthrough at 1560, but then it’s performance went up and down like crazy. It had a great run of -169, then dumbed down and failed after 2 more steps. My agent got stuck because its epsilon (exploration rate) dropped so low, it didn’t have enough confidence to find a better solution. So, the success of our agent depends mostly on how we set up the rules and learning process.</p><p>But even with this instability, the upward trend is very clear. So, it *did* learn, and was able to reach the target quite a few times, towards the end (which felt like a huge win to me!)</p><p>Note: The time limit i set was -200. So as long as the reward is greater than that, it means my agent reached the target.</p><h3>Concluding Thoughts:</h3><p>My journey into RL began with a simple question “How do these self-driving cars that are so hyped rn even work?”, so I began to explore RL, and I was hooked in this trial-and-error process because it just felt so ‘human’.</p><p>So, why isn’t RL talked about as much as other fields amongst beginners? I think it’s because it can come off as intimidating. It doesn’t start with a nice, organized dataset, so you often have to build a whole interactive environment for the agent to learn in. And as my results show, this training is really unstable and requires a lot of patience and tweaking.</p><p>That’s exactly why I wanted to write this blog. To document my own journey from literal zero knowledge to a working (a lil clumsy) agent and show that it’s a really rewarding challenge to take on!</p><p>I hope curious learners like me found this blog helpful and feel inspired to start their own exploration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da1b3eb5055" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>