시작하기무료로 시작하기

PER 버퍼에서 샘플링하기

에이전트를 학습시키기 위해 Prioritized Experience Buffer 클래스를 사용하려면, 아직 .sample() 메서드를 구현해야 합니다. 이 메서드는 추출하려는 샘플의 크기를 인수로 받아서, 샘플링된 전이를 tensors 형태로 반환하고, 해당 전이의 메모리 버퍼 내 인덱스와 중요도 가중치도 함께 돌려줍니다.

용량이 10인 버퍼가 미리 환경에 로드되어 있으니, 여기에서 샘플링해 보세요.

이 연습은 강의의 일부입니다

Python으로 배우는 Deep Reinforcement Learning

강의 보기

연습 안내

  • 각 전이에 해당하는 샘플링 확률을 계산하세요.
  • 샘플에 포함될 전이에 대응하는 인덱스를 추출하세요. np.random.choice(a, s, p=p) 는 확률 배열 p를 기준으로 배열 a에서 크기 s만큼 복원 추출합니다.
  • 각 전이에 해당하는 중요도 가중치를 계산하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

def sample(self, batch_size):
    priorities = np.array(self.priorities)
    # Calculate the sampling probabilities
    probabilities = ____ / np.sum(____)
    # Draw the indices for the sample
    indices = np.random.choice(____)
    # Calculate the importance weights
    weights = (1 / (len(self.memory) * ____)) ** ____
    weights /= np.max(weights)
    states, actions, rewards, next_states, dones = zip(*[self.memory[idx] for idx in indices])
    weights = [weights[idx] for idx in indices]
    states_tensor = torch.tensor(states, dtype=torch.float32)
    rewards_tensor = torch.tensor(rewards, dtype=torch.float32)
    next_states_tensor = torch.tensor(next_states, dtype=torch.float32)
    dones_tensor = torch.tensor(dones, dtype=torch.float32)
    weights_tensor = torch.tensor(weights, dtype=torch.float32)
    actions_tensor = torch.tensor(actions, dtype=torch.long).unsqueeze(1)
    return (states_tensor, actions_tensor, rewards_tensor, next_states_tensor,
            dones_tensor, indices, weights_tensor)

PrioritizedReplayBuffer.sample = sample
print("Sampled transitions:\n", buffer.sample(3))
코드 편집 및 실행