การสุ่มตัวอย่างจาก PER buffer
ก่อนที่จะนำคลาส Prioritized Experience Buffer ไปใช้เทรน agent ได้ ยังต้องเขียน method .sample() ให้ครบก่อน method นี้รับขนาดของตัวอย่างที่ต้องการสุ่มเป็น argument และคืนค่า transition ที่ถูกสุ่มมาในรูปแบบ tensors พร้อมกับ index ใน memory buffer และค่า importance weight
มี buffer ที่มี capacity 10 โหลดไว้ให้แล้วในสภาพแวดล้อมการทำงาน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Deep Reinforcement Learning ด้วย Python
คำแนะนำการฝึกหัด
- คำนวณความน่าจะเป็นในการสุ่มตัวอย่างของแต่ละ transition
- สุ่ม index ที่สอดคล้องกับ transition ในตัวอย่าง โดย
np.random.choice(a, s, p=p)จะสุ่มตัวอย่างขนาดsแบบมีการคืน (with replacement) จาก arrayaตามความน่าจะเป็นใน arrayp - คำนวณค่า importance weight ของแต่ละ transition
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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))