python - 无法使用 Q-Learning 和函数逼近来学习 MountainCar

标签 python reinforcement-learning q-learning

我正在尝试使用 q-learning 实现线性函数近似来求解 MountainCar。我知道由于最优策略的螺旋形状,这个环境不能用线性函数完美地近似,但我得到的行为非常奇怪。

Returns

我不明白为什么奖励会上升,直到达到看似收敛的程度,然后开始下降

请找到我所附的代码。如果有人能让我知道我做错了什么,我会非常高兴。

初始化

import gym
import random
import os

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
 
class Agent:
    def __init__(self, gamma: float, epsilon: float, alpha:float, n_actions: int, n_steps:int=1):
        self.n_steps=n_steps
        self.gamma=gamma
        self.epsilon=epsilon
        self.alpha=alpha
        self.n_actions=n_actions
        self.state_action_values={}
        self.state_values={}
        self.w=None

    def get_next_action(self, state):
        raise NotImplementedError

    def update(self, state, action: int, reward, state_prime):
        raise NotImplementedError

    def reset(self):
        # Optional argument
        pass

Q-学习代理

class FunctionApproximationQLearning(Agent):
    def __init__(self, gamma, epsilon, alpha, n_actions, n_features):
        super().__init__(gamma, epsilon, alpha, n_actions)
        self.w = np.zeros((n_features, n_actions))

    def get_next_action(self, x):
        if random.random()>self.epsilon:
            return np.argmax(self._lr_predict(x))
        else:
            return np.random.choice(range(self.n_actions))

    def update(self, state, action, reward, state_prime, done):
        if not done:
            td_target = reward + self.gamma*np.max(self._lr_predict(state_prime))
        else:
            td_target = reward
        # Target definition
        target = self._lr_predict(state)
        target[action] = td_target
        # Function approximation
        self._lr_fit(state, target)

    def _lr_predict(self, x):
        # x should be (1, n_features)
        #x = np.concatenate([x, [1]])
        return x @ self.w

    def _lr_fit(self, x, target):
        pred = self._lr_predict(x)
        #x = np.concatenate([x, [1]])

        if len(x.shape)==1:
            x = np.expand_dims(x, 0)
        if len(target.shape)==1:
            target = np.expand_dims(target,1)
        self.w += self.alpha*((np.array(target)-np.expand_dims(pred, 1))@x ).transpose()

执行

env = gym.make("MountainCar-v0").env
state = env.reset()
agent = FunctionApproximationQLearning(gamma=0.99, alpha=0.001, epsilon=0.1,
                                       n_actions=env.action_space.n, 
                                       n_features=env.observation_space.shape[0])

rewards=[]
pos=[]
for episode in range(1000000):
    done = False
    cumreward=0
    poss=[]
    state = env.reset()
    action = agent.get_next_action(state)
    c=0

    while not done and c<500:
        action = agent.get_next_action(state)
        next_state, reward, done, _ = env.step(action)
        agent.update(state, action, reward, next_state, done)
        state = next_state
        cumreward+=reward
        c+=1
        poss=state[0]

    rewards.append(cumreward)  
    if np.mean(rewards[-100:])>950:
        break
    pos.append(np.max(poss))
    if episode % 100 == 0:
        clear_output(True)
        plt.plot(pd.Series(rewards).ewm(span=1000).mean())
        plt.title("Returns evolution")
        plt.xlabel("Episodes")
        plt.ylabel("Return")
        plt.show()

最佳答案

如果我错了,请告诉我,但您似乎正在尝试使用直接使用状态变量(即汽车位置和速度)作为特征的线性函数逼近器。在这种情况下,不仅不可能完美地逼近值(value)函数,而且也不可能逼近接近最优值(value)函数。因此,尽管你的数字似乎暗示了一些收敛,但我很确定事实并非如此。

二维玩具环境(例如 MountainCar)的一个非常好的功能是您能够绘制近似的 Q 值函数。在 Sutton & Barto 的书(chapter 8, Figure 8.10)中,您可以通过学习过程找到“cost-to-go”函数(可以从 Q 值轻松获得)。正如您所看到的,该函数与汽车位置和速度高度非线性。我的建议是绘制相同的成本函数并验证它们是否与书中所示的类似。

将线性函数逼近器与 Q 学习一起使用通常需要(除非在非常特殊的情况下)计算一组特征,因此您的逼近器相对于提取的特征是线性的,而不是原始特征。通过这种方式,您可以近似非线性函数(当然,相对于原始状态变量)。这个概念的扩展解释可以再次在 Sutton 和 Barto 的书 section 8.3 中找到。 .

关于python - 无法使用 Q-Learning 和函数逼近来学习 MountainCar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52107066/

相关文章:

artificial-intelligence - Q-learning 和 SARSA 有什么区别?

machine-learning - 不变奖励如何帮助训练?

python - .wav 文件不播放任何声音

python - 如何调整典型sk-learn数据挖掘方法的阈值以平衡精度和召回率?

python - 如何为 Pandas 数据框中的每一列制作一个seaborn distplot?

optimization - Q-学习值更新

python - 在Python中更改keras floatx(默认float类型)

python-3.x - 为什么要打开 openAI 健身房?

reinforcement-learning - Q-learning 和 SARSA 与贪婪选择等价吗?