Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Reinforcement Learning: Exploration vs Exploitation

Reinforcement Learning: Exploration vs Exploitation

In the world of reinforcement learning, an agent (Agent) is like an explorer who continuously learns and grows in an unknown environment. It faces a core dilemma that runs throughout: should itexplore (Exploration) the unknown, seeking new paths that may bring higher rewards, or should itexploit (Exploitation) the known best strategy, steadily obtaining the maximum known reward? This "exploration-exploitation trade-off" (Exploration-Exploitation Trade-off) is one of the most fundamental and critical challenges in reinforcement learning algorithm design. Understanding and properly handling this dilemma is the path every agent must take to grow from a novice to a master.


What are exploration and exploitation?

Let's first understand these two core concepts through an everyday analogy.

Imagine you have to choose a restaurant for lunch every day.

The goal of a reinforcement learning agent is not to win a particular lunch, but toobtain the greatest long-term satisfaction (cumulative reward) across countless lunch choices.. If you only exploit and never explore, you may never discover that better new restaurant, and your long-term reward cannot be optimal. If you only explore and never exploit, you may waste a lot of time and money on bad restaurants and fail to enjoy the known best choice.


Why is a trade-off needed?

The reason exploration and exploitation require a trade-off lies in the environment'suncertaintyand the incompletenessof the agent's knowledge。

  1. : limited information: The agent initially knows nothing about the environment; it must collect data through exploration to build a cognitive model of the world (states, actions, rewards, transition probabilities).
  2. Opportunity cost: Exploring unknown actions may yield lower immediate rewards (or even penalties), which amounts to paying a cost for acquiring information. If you explore too much, you sacrifice a great deal of short-term gain that could otherwise be obtained.
  3. Dynamics of the optimal solution: In a non-stationary environment, the optimal strategy may change over time. Even if the agent finds the current optimal strategy, it still needs to keep exploring to some degree to adapt to environmental changes and prevent the strategy from becoming outdated.

Therefore, a good reinforcement learning algorithm must find a dynamic balance between "using existing knowledge to gain rewards" and "exploring the unknown to improve knowledge".


Common exploration strategies

How can exploration mechanisms be integrated into algorithms? Here are several classic methods:

ε-Greedy Strategy (ε-Greedy)

This is the simplest and most commonly used exploration strategy. The agent, most of the time (with probability 1-ε) chooses the action it currently believes to be optimal (exploitation), but with a small probability ε(e.g., 5%) chooses an action completely at random (exploration).

Example

import

numpy

as

np

def

epsilon_greedy

(

q_values

,

epsilon

=

0.1

)

:

   

"""
    Implement the ε-Greedy strategy.
    Args:
        q_values: an array representing the Q-value estimate of each action in the current state.
        epsilon: the exploration probability, between 0 and 1.
    Returns:
        selected_action: the index of the action selected according to the strategy.
    """

    n_actions

=

len

(

q_values

)

   

   

Explore with probability epsilon (random selection).

   

if

np.

random

.

random

(

)

<

epsilon:

        selected_action

=

np.

random

.

randint

(

n_actions

)

   

Exploit with probability 1-epsilon (choose the action with the largest Q-value).

   

else

:

       

If multiple actions have the same Q-value, choose one at random.

        selected_action

=

np.

random

.

choice

(

np.

where

(

q_values

==

np.

max

(

q_values

)

)

[

0

]

)

   

   

return

selected_action

Example: Suppose in a certain state, the Q-value estimates of three actions are [1.5, 2.8, 2.3]

state_q_values

=

[

1.5

,

2.8

,

2.3

]

for

i

in

range

(

10

)

:

    action

=

epsilon_greedy

(

state_q_values

,

epsilon

=

0.2

)

   

print

(

f

"Selection {i+1}: action {action} (Q-value: {state_q_values[action]:.1f})"

)

Advantages: Simple and easy to understand, easy to implement. Disadvantages: Exploration is completely random and uses no existing information (for example, although an action is not optimal, its Q-value is close to optimal, yet its probability of being explored is the same as a bad action with a very low Q-value).

Upper Confidence Bound (UCB) Algorithm

UCB is a "smarter" exploration strategy. Its core idea is to add an "uncertainty bonus" to each action's estimate. The fewer times an action has been tried, the greater its uncertainty, and the higher this bonus term, thereby encouraging the agent to try it.

The action selection formula is usually: [ a_t = \arg\max_a \left[ Q(a) + c \sqrt{\frac{\ln t}{N_t(a)}} \right] ]

Where:

Example

import

numpy

as

np

import

math

class

UCB:

   

def

init

(

self

,

n_actions

,

c

=

2

)

:

       

self

.

n_actions

=

n_actions

       

self

.

c

=

c  

exploration parameter

       

self

.

Q

=

np.

zeros

(

n_actions

)

 

action value estimate

       

self

.

N

=

np.

zeros

(

n_actions

)

 

action selection count

       

self

.

total_steps

=

0

   

   

def

select_action

(

self

)

:

       

self

.

total_steps

=

1

       

Ensure each action is selected at least once.

       

if

np.

any

(

self

.

N

==

0

)

:

            action

=

np.

random

.

choice

(

np.

where

(

self

.

N

==

0

)

[

0

]

)

       

else

:

           

Compute the UCB value of each action: Q(a) + c * sqrt(ln(t) / N(a))

            ucb_values

=

self

.

Q

self

.

c

sqrt

(

np.

log

(

self

.

total_steps

)

/

self

.

N

)

            action

=

np.

argmax

(

ucb_values

)

       

return

action

   

   

def

update

(

self

,

action

,

reward

)

:

       

"""Update the value estimate of an action"""

       

self

.

N

[

action

]

=

1

       

Incrementally update the Q-value: NewEstimate = OldEstimate + (1/N) * (Target - OldEstimate)

       

self

.

Q

[

action

]

=

(

reward -

self

.

Q

[

action

]

)

/

self

.

N

[

action

]

Simulate a multi-armed bandit problem, where each arm has a different true reward probability.

true_means

=

[

0.1

,

0.5

,

0.9

]

 

The true average rewards of the three arms.

n_actions

=

len

(

true_means

)

bandit

=

UCB

(

n_actions

,

c

=

2

)

total_reward

=

0

for

step

in

range

(

1000

)

:

    action

=

bandit.

select_action

(

)

   

Simulate pulling a bandit arm, receiving reward 1 with a certain probability, and 0 otherwise.

    reward

=

1

if

np.

random

.

random

(

)

<

true_means

[

action

]

else

0

    bandit.

update

(

action

,

reward

)

    total_reward +

=

reward

print

(

f

"Total reward obtained by the UCB strategy after 1000 steps: {total_reward}"

)

print

(

f

"Number of times each action was selected: {bandit.N}"

)

print

(

f

"Q-value estimates of each action: {bandit.Q}"

)

Advantages: Exploration is more purposeful, prioritizing actions with high uncertainty (few trials), enabling faster convergence to the optimal action. Disadvantages: Requires maintaining the number of times each action is selected, which may not be applicable when the action space is continuous or huge.

Thompson Sampling

This is a probabilistic method based on Bayesian ideas. For each action's reward distribution (e.g., the parameter of a Bernoulli distribution θ_a) the agent maintains a prior distribution (such as a Beta distribution). At each step, the agentsamplesa possible reward parameter θ_a, then chooses the action with the largest sampled value to execute. After receiving the true reward, it updates that action's posterior distribution based on the result.

Process description:

  1. Initialization: For each action, a assume the probability of obtaining a reward θ_a follows a Beta(α=1, β=1) distribution, which is a uniform prior.
  2. samples: At each step, from each action a 's current Beta(α_a, β_a) distribution, independently sample a value θ_a'。
  3. Choice: Execute the action with the θ_a' largest sampled value.
  4. update: If a reward is obtained r=1, increment that action's α by 1; if the reward is 0 r=0, then increment β by 1. This is equivalent to updating the Bayesian posterior distribution with the observed data.

Advantages: Naturally balances exploration and exploitation, with excellent theoretical properties and often outstanding performance in practice. Disadvantages: Requires assuming the form of the reward distribution, and computation may be more complex than ε-Greedy.


Dynamic balance of exploration and exploitation

In practical applications, exploration strategies are often not static but dynamically adjusted as the agent's learning progresses.

This dynamic adjustment process mimics the human learning process of "from broad attempts to continuous refinement".


Practical exercise: Comparing different strategies

Let's design a simple experiment to compare the performance of ε-Greedy and UCB strategies on the classic "multi-armed bandit" problem.

Task:

  1. Create a bandit with 5 arms, whose true reward probabilities are [0.1, 0.2, 0.8, 0.5, 0.3]。
  2. Implement the ε-Greedy (ε=0.1) and UCB (c=2) strategies respectively.
  3. Let each strategy run for 2000 steps, recording the immediate reward and cumulative reward at each step.
  4. Plot the curve of cumulative reward over time steps, and observe which strategy obtains higher total rewards faster and more stably.

Reflection: