-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.py
34 lines (26 loc) · 1.4 KB
/
memory.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
import random
import torch
import numpy as np
from collections import deque, namedtuple
class ReplayBuffer:
def __init__(self, action_size, buffer_size, batch_size, seed):
self.action_size = action_size
self.memory = deque(maxlen=buffer_size)
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.seed = random.seed(seed)
def add(self, state, action, reward, next_state, done):
"""Add a new experience to memory."""
e = self.experience(state, action, reward, next_state, done)
self.memory.append(e)
def sample(self):
experiences = random.sample(self.memory, k=self.batch_size)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
states = torch.from_numpy(np.array([e.state for e in experiences if e is not None])).float().to(device)
actions = torch.from_numpy(np.array([e.action for e in experiences if e is not None])).float().to(device)
rewards = torch.from_numpy(np.array([e.reward for e in experiences if e is not None])).float().to(device)
next_states = torch.from_numpy(np.array([e.next_state for e in experiences if e is not None])).float().to(device)
dones = torch.from_numpy(np.array([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)
return (states, actions, rewards, next_states, dones)
def __len__(self):
return len(self.memory)