(self, D, K, hidden_layer_sizes)
| 44 | # approximates pi(a | s) |
| 45 | class PolicyModel: |
| 46 | def __init__(self, D, K, hidden_layer_sizes): |
| 47 | # learning rate and other hyperparams |
| 48 | lr = 1e-4 |
| 49 | |
| 50 | # create the graph |
| 51 | # K = number of actions |
| 52 | self.layers = [] |
| 53 | M1 = D |
| 54 | for M2 in hidden_layer_sizes: |
| 55 | layer = HiddenLayer(M1, M2) |
| 56 | self.layers.append(layer) |
| 57 | M1 = M2 |
| 58 | |
| 59 | # final layer |
| 60 | layer = HiddenLayer(M1, K, lambda x: x, use_bias=False) |
| 61 | self.layers.append(layer) |
| 62 | |
| 63 | # get all params for gradient later |
| 64 | params = [] |
| 65 | for layer in self.layers: |
| 66 | params += layer.params |
| 67 | |
| 68 | # inputs and targets |
| 69 | X = T.matrix('X') |
| 70 | actions = T.ivector('actions') |
| 71 | advantages = T.vector('advantages') |
| 72 | |
| 73 | # calculate output and cost |
| 74 | Z = X |
| 75 | for layer in self.layers: |
| 76 | Z = layer.forward(Z) |
| 77 | action_scores = Z |
| 78 | p_a_given_s = T.nnet.softmax(action_scores) |
| 79 | |
| 80 | selected_probs = T.log(p_a_given_s[T.arange(actions.shape[0]), actions]) |
| 81 | cost = -T.sum(advantages * selected_probs) |
| 82 | |
| 83 | # specify update rule |
| 84 | grads = T.grad(cost, params) |
| 85 | updates = [(p, p - lr*g) for p, g in zip(params, grads)] |
| 86 | |
| 87 | # compile functions |
| 88 | self.train_op = theano.function( |
| 89 | inputs=[X, actions, advantages], |
| 90 | updates=updates, |
| 91 | allow_input_downcast=True |
| 92 | ) |
| 93 | self.predict_op = theano.function( |
| 94 | inputs=[X], |
| 95 | outputs=p_a_given_s, |
| 96 | allow_input_downcast=True |
| 97 | ) |
| 98 | |
| 99 | def partial_fit(self, X, actions, advantages): |
| 100 | X = np.atleast_2d(X) |
nothing calls this directly
no test coverage detected