-
Notifications
You must be signed in to change notification settings - Fork 0
/
replayBuffer.py
61 lines (53 loc) · 2.64 KB
/
replayBuffer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Necessary Packages
import numpy as np
import random
from collections import namedtuple, deque
import torch
class ReplayBuffer:
def __init__(self, action_size, buffer_size, batch_size, seed, device):
"""
Only stores the last N experience tuples in the replay memory
Params
======
action_size (int): Dimension of each action (output_size)
buffer_size (int): Maximum size of buffer
batch_size (int): Size of each training batch
seed (int): Random seed
"""
self.action_size = action_size
self.memory = deque(maxlen=buffer_size) # initialize replay memory D with capacity N
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state",
"action",
"reward",
"next_state",
"done"]) # initialize acollection of experience tuple
self.seed = random.seed(seed)
self.device = device
def add(self, state, action, reward, next_state, done):
"""
Store the agent's experiences to the memory at eatch time-step.
e_t = (s_t, a_t, r_t, s_(t+1))
"""
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
def sample(self):
"""
Samples uniformly at random from D(D_t = {e_1, ..., e_t}) when performing update
This is where we prevent correlation
"""
# D
experiences = random.sample(self.memory, k=self.batch_size)
# Store in
states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(self.device)
actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(self.device)
rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(self.device)
next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(self.device)
dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(self.device)
# return D
return (states, actions, rewards, next_states, dones)
def __len__(self):
'''
Return the current size of internal memory
'''
return len(self.memory)