我正在使用 R 编写一个简单的网格世界 q-learning 程序。这是我的网格世界
这个简单的网格世界有 6 个状态,其中状态 1 和状态 6 是开始和结束状态。我避免添加火坑、墙壁、风,以使我的网格世界尽可能简单。对于奖励矩阵,我的起始状态值为-0.1,结束状态为 +1,其余状态为 0。起始状态的 -0.1 奖励是为了阻止代理回到起始位置。
#Reward and action-value matrix
Row=state(1:6)
Column=actions(1:4)[Left,Right,Down,Up in that order]
我在 R 中编写了我的程序及其工作,但是当当前状态大于第 4 行时,在查找下一个状态时出现问题。Q 矩阵在第 4 行之后不会更新。
#q-learning example
#https://en.wikipedia.org/wiki/Q-learning
# 2x3 grid world
# S for starting grid G for goal/terminal grid
# actions left right down up
# 4 5 6 state
#########
# [0,0,G]
# [S,0,0]
#########
# 1 2 3 state
#setting seed
set.seed(2016)
#number of iterations
N=10
#discount factor
gamma=0.9
#learning rate
alpha=0.1
#target state
tgt.state=6
#reward matrix starting grid has -0.1 and ending grid has 1
R=matrix( c( NA, 0, NA, 0,
-0.1, 0, NA, 0,
0, NA, NA, 1,
NA, 0,-0.1, NA,
0, 1, 0, NA,
0, NA, 0, NA
),
nrow=6,ncol=4,byrow = TRUE)
#initializing Q matrix with zeros
Q=matrix( rep( 0, len=dim(R)[1]*dim(R)[2]), nrow = dim(R)[1],ncol=dim(R)[2])
for (i in 1:N) {
## for each episode, choose an initial state at random
cs <- 1
## iterate until we get to the tgt.state
while (1) {
## choose next state from possible actions at current state
## Note: if only one possible action, then choose it;
## otherwise, choose one at random
next.states <- which(R[cs,] > -1)
if (length(next.states)==1)
ns <- next.states
else
ns <- sample(next.states,1)
## this is the update
Q[cs,ns] <- Q[cs,ns] + alpha*(R[cs,ns] + gamma*max(Q[ns, which(R[ns,] > -1)]) - Q[cs,ns])
## break out of while loop if target state is reached
## otherwise, set next.state as current.state and repeat
if (ns == tgt.state) break
cs <- ns
Sys.sleep(0.5)
print(Q)
}
}
目前,当我的算法启动代理时,总是从 state-1 开始。在第一个状态(R 的第一行)有两个动作 Right(R(1,2)) 或 Up(R(1,4))。如果随机选择一个动作说Up (R(1,4)),那么智能体移动到下一个状态作为动作 Q(4,action)。
但是现在考虑状态 4(第四行或 R)它有两个动作 Right-R(4,2) 和 Down-R(4,3) 这会导致我的算法出现问题,如果随机选择一个动作说,Right。从逻辑上讲,它应该移动到第 5 个状态,但我上面的代码使用动作 2 作为下一个状态。因此,它没有进入第 5 个状态,而是进入第 2 个状态。
最后,如果状态和动作矩阵的维度相同(mxm),我的算法将完美运行,但在我的问题中,我的状态和动作矩阵不同(mxn)。我试图找到解决此问题的方法,但未能找到一种合乎逻辑的方法来找到 $max(Q(s',a'))$ 的下一个状态,目前我被卡住了吗?