Читать книгу Mathematical Programming for Power Systems Operation - Alejandro Garcés Ruiz - Страница 40
Example 2.5
ОглавлениеPython allows calculating the gradient automatically using the module AutoGrad. It is quite intuitive to use. Consider the following script, which solves the same problem presented in the previous example:
import autograd.numpy as np from autograd import grad # gradient calculation def f(x): z = 10.0*x[0]**2 + 15*x[1]**2 + np.exp(x[0]+x[1]) return z g = grad(f) # create a funtion g that returns the gradient x = np.array([10.0,10.0]) t = 0.03 for k in range(50): dx = g(x) x = x -t*dx print('argmin:',x)
In this case, we defined a function f and its gradient g where (x, y) was replaced by a vector (x0, x1). The module NumPy was loaded using autograd.numpy to obtain a gradient function automatically. The code executes the same 50 iterations, obtaining the same result. The reader should execute and compare the two codes in terms of time calculation and results.