-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDQN.py
More file actions
64 lines (50 loc) · 1.9 KB
/
DQN.py
File metadata and controls
64 lines (50 loc) · 1.9 KB
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
63
64
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
import numpy as np
from collections import namedtuple
import random
class hidden_unit(nn.Module):
def __init__(self, in_channels, out_channels, activation):
super(hidden_unit, self).__init__()
self.activation = activation
self.nn = nn.Linear(in_channels, out_channels)
def forward(self, x):
out = self.nn(x)
out = self.activation(out)
return out
class Q_learning(nn.Module):
def __init__(self, in_channels, hidden_layers, out_channels, unit = hidden_unit, activation = F.relu):
super(Q_learning, self).__init__()
assert type(hidden_layers) is list
self.hidden_units = nn.ModuleList()
self.in_channels = in_channels
prev_layer = in_channels
for hidden in hidden_layers:
self.hidden_units.append(unit(prev_layer, hidden, activation))
prev_layer = hidden
self.final_unit = nn.Linear(prev_layer, out_channels)
def forward(self, x):
out = x.view(-1,self.in_channels).float()
for unit in self.hidden_units:
out = unit(out)
out = self.final_unit(out)
return out
Transition = namedtuple('Transition',
('state', 'action', 'new_state', 'reward'))
class ReplayMemory(object):
def __init__(self, capacity):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, *args):
"""Saves a transition."""
if len(self.memory) < self.capacity:
self.memory.append(None)
self.memory[self.position] = Transition(*args)
self.position = (self.position + 1) % self.capacity
def sample(self, batch_size):
return random.sample(self.memory, batch_size)
def __len__(self):
return len(self.memory)