使用 Q-Learning 和函数逼近求解 GridWorld

Solving GridWorld using Q-Learning and function approximation

我正在研究简单的 GridWorld(3x4,如 Russell & Norvig Ch. 21.2 中所述)问题;我已经使用 Q-Learning 和 QTable 解决了它,现在我想使用函数逼近器而不是矩阵。

我正在使用 MATLAB 并尝试了神经网络和决策树,但没有得到预期的结果,即发现了错误的策略。我已经阅读了一些关于该主题的论文,但其中大部分都是理论性的,并没有过多地关注实际实施。

我一直在使用离线学习,因为它更简单。我的方法是这样的:

  1. 用 16 个输入二进制单元初始化决策树(或 NN)- 一个对应网格中的每个位置加上 4 个可能的动作(上、下、左、右)。
  2. 进行大量迭代,为每个迭代保存训练集中的 qstate 和计算出的 qvalue。
  3. 使用训练集训练决策树(或 NN)。
  4. 擦除训练集并从步骤 2 开始重复,使用刚刚训练的决策树(或 NN)计算 qvalues。

好像简单得不像真的,确实没有得到预期的结果。这是一些 MATLAB 代码:

retrain = 1;
if(retrain) 
    x = zeros(1, 16); %This is my training set
    y = 0;
    t = 0; %Iterations
end
tree = fitrtree(x, y);
x = zeros(1, 16);
y = 0;
for i=1:100
    %Get the initial game state as a 3x4 matrix
    gamestate = initialstate();
    end = 0;
    while (end == 0)
        t = t + 1; %Increase the iteration

        %Get the index of the best action to take
        index = chooseaction(gamestate, tree);

        %Make the action and get the new game state and reward
        [newgamestate, reward] = makeaction(gamestate, index);

        %Get the state-action vector for the current gamestate and chosen action
        sa_pair = statetopair(gamestate, index);

        %Check for end of game
        if(isfinalstate(gamestate))
            end = 1;
            %Get the final reward
            reward = finalreward(gamestate);
            %Add a sample to the training set
            x(size(x, 1)+1, :) = sa_pair;
            y(size(y,  1)+1, 1) = updateq(reward, gamestate, index, newgamestate, tree, t, end);
        else
            %Add a sample to the training set
            x(size(x, 1)+1, :) = sa_pair;
            y(size(y, 1)+1, 1) = updateq(reward, gamestate, index, newgamestate, tree, t, end);
        end

        %Update gamestate
        gamestate = newgamestate;
    end
end

它有一半时间选择随机动作。 updateq函数是:

function [ q ] = updateq( reward, gamestate, index, newgamestate, tree, iteration, finalstate )

alfa = 1/iteration;
gamma = 0.99;

%Get the action with maximum qvalue in the new state s'
amax = chooseaction(newgamestate, tree);

%Get the corresponding state-action vectors
newsa_pair = statetopair(newgamestate, amax);    
sa_pair = statetopair(gamestate, index);

if(finalstate == 0)
    X = reward + gamma * predict(tree, newsa_pair);
else
    X = reward;
end

q = (1 - alfa) * predict(tree, sa_pair) + alfa * X;    

end

如有任何建议,我们将不胜感激!

问题是在离线 Q-Learning 中你需要重复收集数据的过程至少 n 次,其中 n取决于您要建模的问题。如果分析每次迭代计算的 qvalues 并思考一下,就会立即清楚为什么需要这样做。

在第一次迭代中,您仅学习最终状态,在第二次迭代中,您还学习倒数第二个状态,在第三次迭代中,您还学习倒数第二个状态,依此类推。您正在学习从最终状态到初始状态,传播回 qvalues。在 GridWorld 示例中,结束游戏所需的最小访问状态数为 6.

最后,正确的算法变成:

  1. 用 16 个输入二进制单元初始化决策树(或 NN)- 一个对应网格中的每个位置加上 4 个可能的动作(上、下、左、右)。
  2. 进行大量迭代(对于这个 GridWorld 示例,30 个游戏就足够了),在训练集中为每个游戏保存 qstate 和计算出的 qvalue。
  3. 使用训练集训练决策树(或 NN)。
  4. 擦除训练集。
  5. 从步骤 2 开始重复,使用刚刚训练好的决策树(或 NN)计算 qvalues,至少 n,其中n 取决于你的问题。对于这个 GridWorld 示例,n 是 6,但是如果您重复该过程 7-8 次,您将获得所有状态的更好结果。