Q学习算法

警告
本文最后更新于 2023-11-22,文中内容可能已过时。

on-policy version

off-policy version

算法实现

Value update

需要使用behaviour进采行采样 每一个episode里面会对所有的样本行采样来计算$y_T$,这个是target网络计算来的值

policy update 主网络每次采样完成后进行参数更新,并达到一定次数后更新target网络的参数

代码

  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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import torch

import torch.nn as nn

import torch.nn.functional as F

  

device = torch.device("cuda" if torch.cuda.is_available else "cpu")

  

class NNet(nn.Module):

    def __init__(self,

                 n_actions,

                 n_features,

                 hidden_size=10,

                 ):

        super().__init__()

        self.fc1 = nn.Linear(n_features, hidden_size)

        self.fc1.weight.data.normal_(0, 0.3)   # initialization

        self.fc1.bias.data.normal_(0.1)   # initialization

  

        self.fc2 = nn.Linear(hidden_size, n_actions)

        self.fc2.weight.data.normal_(0, 0.3)   # initialization

        self.fc2.bias.data.normal_(0.1)   # initialization

  

    def forward(self, x):

        x = self.fc1(x)

        x = F.relu(x)

        return self.fc2(x)

  

from torch import optim

import numpy as np

  

class DeepQNetwork(object):

    def __init__(self,

                 n_actions,

                 n_features,

                 alpha=0.01,

                 reward_decay=0.9,

                 e_greedy=0.9,

                 hidden_size=10,

                 memory_size=500,

                 replace_iter=300,

                 e_greedy_increment=None

                 ):

        super().__init__()

        self.lr = alpha

        self.n_actions = n_actions

        self.n_features = n_features

        self.evalNet = NNet(n_actions=n_actions, n_features=n_features, hidden_size=hidden_size).to(dtype=torch.double)

        self.targetNet = NNet(n_actions=n_actions, n_features=n_features, hidden_size=hidden_size).to(dtype=torch.double)

  

        self.memory_size = memory_size

        self.replace_iter = replace_iter

        self.train_step_counter = 0

        self.gamma = reward_decay

        self.batch_size = 64

        self.epsilon_max = e_greedy

        self.epsilon = 0 if e_greedy_increment is not None else self.epsilon_max

  

        # initialize zero memory [s, a, r, s_]

        self.memory = np.zeros((self.memory_size, n_features * 2 + 2))

  

    def trainStep(self):

        if self.train_step_counter % self.replace_iter == 0:

            self.targetNet.load_state_dict(self.evalNet.state_dict())

            # print('\ntarget_params_replaced\n')

        # sample batch memory from all memory

        if self.memory_counter > self.memory_size:

            sample_index = np.random.choice(self.memory_size, size=self.batch_size)

        else:

            sample_index = np.random.choice(self.memory_counter, size=self.batch_size)

        #eval_optimizer = optim.SGD(self.evalNet.parameters(), lr=self.lr)

        eval_optimizer = optim.Adam(self.evalNet.parameters(), lr=self.lr)

  

        criterion = nn.MSELoss()

  

        eval_optimizer.zero_grad()

  

        # ------------------

        N_STATES = self.n_features

        b_memory = self.memory[sample_index, :]

        b_s = torch.DoubleTensor(b_memory[:, :N_STATES])

        b_a = torch.LongTensor(b_memory[:, N_STATES:N_STATES+1].astype(int))

        b_r = torch.DoubleTensor(b_memory[:, N_STATES+1:N_STATES+2])

        b_s_ = torch.DoubleTensor(b_memory[:, -N_STATES:])

  

        print(np.shape(b_a))

  

        # q_eval w.r.t the action in experience

        q_eval = self.evalNet(b_s).gather(1, b_a)  # shape (batch, 1)

        q_next = self.targetNet(b_s_).detach()     # detach from graph, don't backpropagate

        q_target = b_r + self.gamma * q_next.max(1)[0].view(self.batch_size, 1)   # shape (batch, 1)

        loss = criterion(q_eval, q_target)
  
        loss.backward()

        eval_optimizer.step()

        self.train_step_counter += 1

        return loss.item()

  

    def store_transition(self, s, a, r, s_):

        if not hasattr(self, 'memory_counter'):

            self.memory_counter = 0
  
        transition = np.hstack((s, [a, r], s_))

  
        index = self.memory_counter % self.memory_size

        self.memory[index, :] = transition

  

        self.memory_counter += 1

  

    def choose_action(self, observation):

        # to have batch dimension when feed into tf placeholder

        observation = observation[np.newaxis, :]

        observation = torch.tensor(observation, dtype=torch.double)

  

        if np.random.uniform() < self.epsilon:

            # forward feed the observation and get q value for every actions

            actions_value = self.evalNet(observation)

            action = np.argmax(actions_value.detach().numpy())

        else:

            action = np.random.randint(0, self.n_actions)

        return action
0%