-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.py
62 lines (50 loc) · 2.14 KB
/
helper.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
62
import random
import collections
import torch
import numpy as np
from IPython.display import HTML
from base64 import b64encode
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
"""
memory to save the state, action, reward sequence from the current episode.
"""
class Memory:
def __init__(self, len):
self.rewards = collections.deque(maxlen=len)
self.state = collections.deque(maxlen=len)
self.action = collections.deque(maxlen=len)
self.is_done = collections.deque(maxlen=len)
def update(self, state, action, reward, done):
# if the episode is finished we do not save to new state. Otherwise we have more states per episode than rewards
# and actions whcih leads to a mismatch when we sample from memory.
if not done:
self.state.append(state)
self.action.append(action)
self.rewards.append(reward)
self.is_done.append(done)
def sample(self, batch_size):
"""
sample "batch_size" many (state, action, reward, next state, is_done) datapoints.
"""
n = len(self.is_done)
idx = random.sample(range(0, n-1), batch_size)
return torch.Tensor(self.state)[idx].to(device), torch.Tensor(self.action)[idx].to(device), \
torch.Tensor(self.state)[1+np.array(idx)].to(device), torch.Tensor(self.rewards)[idx].to(device), \
torch.Tensor(self.is_done)[idx].to(device)
def reset(self):
self.rewards.clear()
self.state.clear()
self.action.clear()
self.is_done.clear()
def select_action(model, env, state):
state = torch.Tensor(state).to(device)
with torch.no_grad():
values = model(state)
action = values.cpu().numpy()
return action
def update_parameters(current_model, target_model):
target_model.load_state_dict(current_model.state_dict())
def show_video(video_path, video_width = 400):
video_file = open(video_path, "r+b").read()
video_url = f"data:video/mp4;base64,{b64encode(video_file).decode()}"
return HTML(f"""<video autoplay="true" loop="true" width={video_width} controls><source src="{video_url}"></video>""")