autograd_gradient.py

View page source

Calculate Gradient Using Autograd

Syntax

      grad cmpad.autograd.gradient ( algo )
      grad . setup ( option )
      g = grad ( x )

Purpose

This uses Autograd to implement a py_fun_obj that computes the gradient of the last component of values computed by algo .

algo

This is a py_fun_obj where the input and output vectors have type autograd.numpy.array with float elements . The last range space component, computed by algo , defines the scalar function that the gradient is for.

grad

This is a py_fun_obj where the input and output vectors have elements of type float .

x

This is a numpy vector of float with length option [ 'n_arg' ] . It is the argument value at which to compute the gradient.

g

This is a numpy vector of float with length option [ 'n_arg' ] . It is the value of the gradient ad x .

Example

The file xam_grad_autograd.py contains an example and test using this class.

Source Code

#
# imports
import autograd
#
# gradient
class gradient :
   #
   def __init__(self, algo) :
      self.algo   = algo
      self.option = None
   #
   def option(self) :
      return self.optiion
   #
   def domain(self) :
      return self.option['n_arg']
   #
   def range(self) :
      return self.option['n_arg']
   #
   def func(self, x) :
      y = self.algo(x)
      return y[-1]
   #
   def setup(self, option) :
      assert type(option) == dict
      assert 'n_arg' in option
      #
      # self.option
      self.option = option
      #
      # self.algo
      self.algo.setup(option)
      #
      # self.grad
      self.grad = autograd.grad(self.func)
   #
   # call
   def __call__(self, x) :
      n_arg   = self.option['n_arg']
      assert len(x) == n_arg
      ax = autograd.numpy.array(x, dtype=float)
      g = self.grad( ax )
      return g