探索與利用的平衡

使用 Python 的 Gymnasium 進行強化學習

Fouad Trad

Machine Learning Engineer

以隨機動作訓練

  • 代理在環境中探索
  • 不依學到的知識最佳化策略
  • 訓練完成後代理才運用知識

顯示代理位於環境中的圖片

使用 Python 的 Gymnasium 進行強化學習

探索—利用權衡

 

  • 兼顧探索與利用
  • 持續探索會阻礙策略精煉
  • 只顧利用會錯過尚未發現的機會

圖片顯示代理嘗試探索新動作以發現更多回饋,同時也嘗試利用其知識,但可能錯失部分回饋。

使用 Python 的 Gymnasium 進行強化學習

用餐選擇

餐廳餐桌的圖片。

使用 Python 的 Gymnasium 進行強化學習

Epsilon-greedy 策略

 

  • 以機率 epsilon 進行探索

圖示說明以機率 epsilon,代理會隨機選擇動作進行探索。

使用 Python 的 Gymnasium 進行強化學習

Epsilon-greedy 策略

 

  • 以機率 epsilon 探索
  • 以機率 1-epsilon 利用
  • 一邊使用知識,一邊持續探索

圖示說明以機率 epsilon 探索(隨機選動作),以機率 1 - epsilon 利用(選當前最佳動作)。

使用 Python 的 Gymnasium 進行強化學習

遞減式 epsilon-greedy 策略

 

  • 隨時間遞減 epsilon
  • 初期更多探索
  • 後期更多利用
  • 代理愈來愈依賴累積的知識

顯示 epsilon 隨時間下降的圖片。

使用 Python 的 Gymnasium 進行強化學習

以 Frozen Lake 實作

env = gym.make('FrozenLake', is_slippery=True)

action_size = env.action_space.n
state_size = env.observation_space.n
Q = np.zeros((state_size, action_size))

alpha = 0.1 gamma = 0.99 total_episodes = 10000

Frozen Lake 環境快照。

使用 Python 的 Gymnasium 進行強化學習

實作 epsilon_greedy()

def epsilon_greedy(state):

if np.random.rand() < epsilon: action = env.action_space.sample() # Explore
else: action = np.argmax(Q[state, :]) # Exploit return action
使用 Python 的 Gymnasium 進行強化學習

訓練 epsilon-greedy

epsilon = 0.9   # Exploration rate

rewards_eps_greedy = []
for episode in range(total_episodes):
    state, info = env.reset()
    terminated = False
    episode_reward = 0
    while not terminated:
        action = epsilon_greedy(state)
        new_state, reward, terminated, truncated, info = env.step(action)       
        Q[state, action] = update_q_table(state, action, new_state) 
        state = new_state

episode_reward += reward rewards_eps_greedy.append(episode_reward)
使用 Python 的 Gymnasium 進行強化學習

訓練遞減式 epsilon-greedy

epsilon = 1.0   # Exploration rate
epsilon_decay = 0.999
min_epsilon = 0.01

rewards_decay_eps_greedy = [] for episode in range(total_episodes): state, info = env.reset() terminated = False episode_reward = 0 while not terminated: action = epsilon_greedy(state) new_state, reward, terminated, truncated, info = env.step(action) episode_reward += reward Q[state, action] = update_q_table(state, action, new_state) state = new_state rewards_decay_eps_greedy.append(episode_reward)
epsilon = max(min_epsilon, epsilon * epsilon_decay)
使用 Python 的 Gymnasium 進行強化學習

策略比較

avg_eps_greedy= np.mean(rewards_eps_greedy)
avg_decay = np.mean(rewards_decay_eps_greedy)
plt.bar(['Epsilon Greedy', 'Decayed Epsilon Greedy'],
        [avg_eps_greedy, avg_decay], 
        color=['blue', 'green'])
plt.title('Average Reward per Episode')
plt.ylabel('Average Reward')
plt.show()

長條圖顯示:epsilon-greedy 的平均回饋約為 0.02,而遞減式 epsilon-greedy 約為 0.55。

使用 Python 的 Gymnasium 進行強化學習

一起來練習吧!

使用 Python 的 Gymnasium 進行強化學習

Preparing Video For Download...