Add potential-based reward shaping to an episode

Why it matters Shaping is how RL engineers make sparse-reward tasks such as robot grasping or agent tool use learnable.

Sparse rewards make learning slow. Potential-based shaping adds a hint F = gamma * phi(s') - phi(s) that speeds up learning without changing which policy is optimal.

Write shaped_rewards(rewards, states, phi, gamma, dones). rewards and dones have length T, states has length T + 1 (states[t + 1] is where step t lands), phi is a dict or list mapping a state to its potential. For each t return rewards[t] + gamma * phi[states[t + 1]] - phi[states[t]], except that the potential of the landing state counts as 0 when dones[t] is true. Return a numpy array.

Signaturedef shaped_rewards(rewards, states, phi, gamma, dones)

Example

shaped_rewards([0, 0, 1], [0, 1, 2, 3], [0, 1, 2, 5], 1.0, [False, False, True]) gives array([1., 1., -1.]).

Understand the idea

When the only reward comes at the very end, an agent may wander for ages before stumbling on it. Reward shaping adds small hints along the way. The danger is that hints can be gamed: an agent may learn to collect hint points instead of finishing the task. Potential-based shaping avoids this. Give each state a potential (for example "minus distance to the goal") and reward the change in potential.

Example with gamma 1 and potentials 0, 1, 2 along a path: each step forward earns +1 bonus. The last step reaches the goal (terminal, potential 0), so its bonus is 0 - 2 = -2, and with the real reward of 1 the shaped reward is -1. The total bonus over the episode is -phi(start), a constant.

Rule: r' = r + gamma * phi(s') - phi(s), with phi(terminal) = 0.

This is a safe way to add progress rewards for LLM agents and robots.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleshaped_rewards([0, 0, 1], [0, 1, 2, 3], [0, 1, 2, 5], 1.0, [False, False, True])
  • Sample 2: discountshaped_rewards([0, 0], ['a', 'b', 'goal'], {'a': 1.0, 'b': 3.0, 'goal': 10.0}, 0.9, [False, True])
  • Test 3: mid episode resetshaped_rewards([1, 0, 0], [0, 1, 0, 1], [2, 4], 0.5, [True, False, False])