Sets the weights of the optimizer, from Numpy arrays. Should only be called after computing the gradients (otherwise the optimizer has no weights). Arguments: weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of
(self, weights)
| 105 | return grads |
| 106 | |
| 107 | def set_weights(self, weights): |
| 108 | """Sets the weights of the optimizer, from Numpy arrays. |
| 109 | |
| 110 | Should only be called after computing the gradients |
| 111 | (otherwise the optimizer has no weights). |
| 112 | |
| 113 | Arguments: |
| 114 | weights: a list of Numpy arrays. The number of arrays and their shape |
| 115 | must match number of the dimensions of the weights of the optimizer |
| 116 | (i.e. it should match the output of `get_weights`). |
| 117 | |
| 118 | Raises: |
| 119 | ValueError: in case of incompatible weight shapes. |
| 120 | """ |
| 121 | params = self.weights |
| 122 | if len(params) != len(weights): |
| 123 | raise ValueError('Length of the specified weight list (' + |
| 124 | str(len(weights)) + |
| 125 | ') does not match the number of weights ' |
| 126 | 'of the optimizer (' + str(len(params)) + ')') |
| 127 | weight_value_tuples = [] |
| 128 | param_values = K.batch_get_value(params) |
| 129 | for pv, p, w in zip(param_values, params, weights): |
| 130 | if pv.shape != w.shape: |
| 131 | raise ValueError('Optimizer weight shape ' + str(pv.shape) + |
| 132 | ' not compatible with ' |
| 133 | 'provided weight shape ' + str(w.shape)) |
| 134 | weight_value_tuples.append((p, w)) |
| 135 | K.batch_set_value(weight_value_tuples) |
| 136 | |
| 137 | def get_weights(self): |
| 138 | """Returns the current value of the weights of the optimizer. |