-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
32 lines (26 loc) · 887 Bytes
/
utils.py
File metadata and controls
32 lines (26 loc) · 887 Bytes
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
import torch
from collections import deque
import random
import numpy as np
class ReplayBuffer:
def __init__(self, capacity):
self.buffer = deque(maxlen=capacity)
def store(self, state, action, reward, next_state, done):
self.buffer.append((state, action, reward, next_state, done))
def sample(self, batch_size):
samples = random.sample(self.buffer, batch_size)
states, actions, rewards, next_states, dones = zip(*samples)
return (
np.stack(states),
np.array(actions),
np.array(rewards),
np.stack(next_states),
np.array(dones),
)
def __len__(self):
return len(self.buffer)
def save_model(agent, filepath):
torch.save(agent.state_dict(), filepath)
def load_model(agent, filepath):
agent.load_state_dict(torch.load(filepath))
agent.eval()