Skip to content

About

A tabular Q-learning agent for MountainCar-v0 with state discretization, epsilon-schedule experiments, value-function visualization, reward shaping, and a reward-hacking demonstration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

MountainCar Q-Learning

A tabular reinforcement-learning project that trains a Q-learning agent to solve Gym's MountainCar-v0 environment. The project studies continuous-state discretization, epsilon-greedy exploration, Q-table updates, policy evaluation, value-function visualization, and reward shaping.

The repository is prepared from a completed course assignment. The original code cells and their stored outputs were preserved exactly; only the notebook's explanatory Markdown was translated, reorganized, and polished for an English-language GitHub presentation.

Project Highlights

  • Implements tabular Q-learning from scratch.
  • Maps continuous position and velocity observations to discrete state buckets.
  • Compares constant, linear, logarithmic, and exponential epsilon schedules.
  • Demonstrates the trade-off between coarse and fine discretization grids.
  • Evaluates the learned policy over 100 episodes with exploration disabled.
  • Visualizes the learned state-value function as a three-dimensional surface.
  • Compares a sparse baseline reward, two shaped rewards, and a deliberately hacked objective.
  • Includes saved results from the original experiments for reproducible inspection without retraining.

Environment and Learning Rule

MountainCar-v0 contains an underpowered car in a valley. The car cannot drive directly up the right hill, so it must first move left, accumulate potential energy, and then reverse direction with enough momentum to reach the flag.

The observation contains two continuous variables:

Variable Range
Position [-1.2, 0.6]
Velocity [-0.07, 0.07]

The agent can select one of three actions: accelerate left, coast, or accelerate right. The Q-table is updated with

$$ Q(s,a) \leftarrow Q(s,a) + \alpha\left[r + \gamma\max_{a'}Q(s',a') - Q(s,a)\right]. $$

Main Training Run

The principal agent uses a 40 x 40 state grid, exponential epsilon decay, a learning rate of 0.05, a discount factor of 0.99, and seed 400.

The stored training log reports its first solution event at episode 288,136, with a 100-episode moving average of -109.99. The environment's solution threshold is -110.

Main training reward and epsilon curves

Greedy Evaluation

The trained agent was evaluated for 100 episodes with epsilon = 0.

Metric Score
Mean -120.38
Best -94.00
Worst -168.00

The best result demonstrates that the Q-table contains an efficient momentum-building policy. Variation across evaluation episodes shows that some initial position and velocity combinations still require additional oscillations.

Exploration Strategy Experiment

Four epsilon strategies were compared for 100,000 episodes using the same 40 x 40 grid and seed.

Strategy Mean Best Worst Logged solution event
Constant -114.72 -88.00 -184.00 No
Linear -133.90 -107.00 -151.00 No
Logarithmic -112.38 -106.00 -117.00 Episode 72,122
Exponential -133.38 -109.00 -200.00 No

Under this configuration, logarithmic decay provides the strongest and most stable evaluation results. Constant epsilon occasionally produces an excellent trajectory, but permanent random actions increase its variability. These results are empirical and depend on the selected hyperparameters and seed.

Moving-average comparison of epsilon strategies

Comparison of epsilon schedules

Individual diagnostic plots are also available in assets/results/.

Discretization Experiment

The project compares an overly coarse grid with an overly fine grid.

Grid Number of states Q-values Evaluation mean Best Worst
5 x 5 25 75 -200.00 -200.00 -200.00
100 x 100 10,000 30,000 -158.55 -117.00 -200.00

The 5 x 5 grid suffers from state aliasing: one table entry represents physically different observations that may require conflicting actions. The 100 x 100 grid preserves more detail but distributes experience across many entries, so 100,000 episodes are insufficient for reliable state visitation and convergence.

Comparison of state discretization grids

Learned Value Function

The notebook visualizes $V(s)=\max_a Q(s,a)$ only for visited states. Regions with negative velocity can receive high value because moving left is a useful stage of the optimal strategy: it stores energy that is later converted into rightward momentum.

Three-dimensional learned value function

Reward Shaping and Reward Hacking

Four reward modes were trained for 2,000 episodes. Success is measured independently by whether the car reaches the flag, rather than by the shaped reward used for learning.

Mode Learning signal Success rate in final 100 episodes
Original Environment reward 1%
Hacked Positive reward proportional to absolute velocity 0%
Shaping 1 Height and kinetic-energy potential 86%
Shaping 2 Strong kinetic term and right-side goal attraction 83%

Both shaped variants learn much faster than the sparse baseline in the stored experiment. The hacked objective encourages high-speed oscillation but never reaches the goal, demonstrating specification gaming: maximizing the written reward can fail to satisfy the intended task.

Reward-shaping and success-rate comparison

Reproducibility Notes

  • The experiments initialize NumPy and Gym action-space randomness with seed 400.
  • Environment resets derive deterministic episode-specific seeds from the base seed.
  • Runtime and exact learning curves can still vary across operating systems and library versions.
  • Gym emits maintenance and deprecation warnings in the saved output; these do not alter the recorded experiment results.
  • Packaging for this repository changed no code cell and no saved code output in the submitted notebook.

Assignment Analysis

The final notebook section contains ten ordered questions and answers covering:

  • continuous-state discretization;
  • state aliasing and the curse of dimensionality;
  • epsilon-greedy and alternative exploration policies;
  • the effects of learning rate and discount factor;
  • constant exploration and greedy evaluation;
  • sparse state visitation;
  • the MountainCar energy interpretation; and
  • reward hacking and its common forms.

Author

Faeze Mohammadi - 810103510

About

A tabular Q-learning agent for MountainCar-v0 with state discretization, epsilon-schedule experiments, value-function visualization, reward shaping, and a reward-hacking demonstration.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages