I am trying to train a DQN to play the 8puzzle game.
I have implemented a batched gameboards, so I am not using ReplayMemory
.
Here's training process:
finished_counts = torch.tensor(0, device=device)
pbar = tqdm(range(int(1e4)))
for e in pbar:
q_values = net(board) # board: Tensor with shape [10000, 3, 3]
# choose action randomly or by q_values
if np.random.rand() < 0.5:
actions = torch.randint(0, 4, (board.size(0),)).to(device)
else:
actions = torch.argmax(q_values, dim=1)
# reward: -100 for hit the wall, 10 for win, 0 for else
reward, next_board = move(board, actions)
next_q = net(next_board).detach()
next_q[reward == 10] = 0 # ignore next_q if already win
desired_q = q_values.clone().detach()
distance = manhattan(next_board)
desired_q[:, actions] = (reward - distance) + next_q[:, actions] * q_decay # q_decay = 0.9
# set metrics
pbar.set_postfix({
'avg distance': f'{torch.mean(distance):.2f}',
'finished': str(finished_counts.cpu().item()),
})
# compute loss and backwards
# HuberLoss for criterion
optimizer.zero_grad()
loss = criterion(q_values, desired_q)
loss.backward()
optimizer.step() # Adam(lr=1e-4)
board = next_board
finished = distance == 0
board = board[~finished]
finished_counts += finished.sum()
What I obeserved is, the avg distance
is remaing around 12.67
, and finished_counts
increasing in linear rate, which may attributed to random action.
My question is:
- Is it ok to not use ReplayMemory?
- Am I calculate the
q_values
anddesired_q
correct? - Why is the network not learning anything?