Implement the epsilon-soft on-policy Monte Carlo control algorithm for finding improved policies in a model-free reinforcement learning setting.
Given a collection of episodes (each a sequence of (state, action, reward) tuples), estimate the action-value function Q(s, a) and derive an epsilon-soft policy.
The algorithm should:
- Use first-visit Monte Carlo to estimate Q(s, a) by averaging returns from the first visit to each (state, action) pair within each episode
- After processing each episode, update the policy for visited states to be epsilon-soft with respect to the current Q estimates
- In an epsilon-soft policy, the greedy action gets probability 1 - epsilon + epsilon/|A|, and all other actions get epsilon/|A|
- When there are ties in Q-values for a state, prefer the action with the smallest index
Your function should return the final Q-values and the epsilon-soft policy as 2D lists, both rounded to 4 decimal places.
Args:
- episodes: List of episodes. Each episode is a list of (state, action, reward) tuples where states and actions are zero-indexed integers.
- n_states: Total number of states
- n_actions: Total number of actions available in each state
- gamma: Discount factor (default 0.9)
- epsilon: Exploration parameter for epsilon-soft policy (default 0.1)
Returns:
- Tuple of (Q, policy) where Q and policy are 2D lists of shape (n_states, n_actions), both rounded to 4 decimal places.