-
Notifications
You must be signed in to change notification settings - Fork 28
/
Experience_replay.py
47 lines (38 loc) · 1.25 KB
/
Experience_replay.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
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 11:50:29 2018
data formulation: (s[i], a[i], r[i])
@author: mengxiaomao
"""
from collections import deque
import random
import numpy as np
class ReplayBuffer(object):
def __init__(self, buffer_size):
self.buffer_size = buffer_size
self.count = 0
self.buffer = deque()
def add(self, s, a, r):
for i in range(len(s)):
experience = (s[i], a[i], r[i])
if self.count < self.buffer_size:
self.buffer.append(experience)
self.count += 1
else:
self.buffer.popleft()
self.buffer.append(experience)
def size(self):
return self.count
def sample_batch(self, batch_size):
minibatch = []
if self.count < batch_size:
minibatch = random.sample(self.buffer, self.count)
else:
minibatch = random.sample(self.buffer, batch_size)
batch_s = [d[0] for d in minibatch]
batch_a = [d[1] for d in minibatch]
batch_r = [d[2] for d in minibatch]
return batch_s, batch_a, batch_r
def clear(self):
self.buffer.clear()
self.count = 0