-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplay_memory.py
58 lines (47 loc) · 2.07 KB
/
replay_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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import random
import numpy as np
import torch
class ReplayMemory:
def __init__(self, capacity, seed):
random.seed(seed)
self.capacity = capacity
self.buffer = []
self.position = 0
# def push(self, state, action, reward, next_state, done):
# if len(self.buffer) < self.capacity:
# self.buffer.append(None)
# self.buffer[self.position] = (state, action, reward, next_state, done)
# self.position = (self.position + 1) % self.capacity
# def sample(self, batch_size):
# batch = random.sample(self.buffer, batch_size)
# state, action, reward, next_state, done = map(torch.stack, zip(*batch))
# return state, action, reward, next_state, done
def push(self, state, action, reward, next_state):
if len(self.buffer) < self.capacity:
self.buffer.append(None)
self.buffer[self.position] = (state, action, reward, next_state)
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
batch = random.sample(self.buffer, batch_size)
state, action, reward, next_state = map(torch.stack, zip(*batch))
# print(state.shape)
# print(action.shape)
# print(reward.shape)
# print(reward)
# print(next_state.shape)
return state.squeeze(dim=1), action.squeeze(dim=1), reward, next_state.squeeze(dim=1)
def __len__(self):
return len(self.buffer)
def save_buffer(self, env_name, suffix="", save_path=None):
if not os.path.exists('checkpoints/'):
os.makedirs('checkpoints/')
if save_path is None:
save_path = "checkpoints/sac_buffer_{}_{}".format(env_name, suffix)
print('Saving buffer to {}'.format(save_path))
with open(save_path, 'wb') as f:
pickle.dump(self.buffer, f)
def load_buffer(self, save_path):
print('Loading buffer from {}'.format(save_path))
with open(save_path, "rb") as f:
self.buffer = pickle.load(f)
self.position = len(self.buffer) % self.capacity