Skip to content

Automatic differentiation (a.k.a algorithmic differentiation) in reverse mode for elm

License

Notifications You must be signed in to change notification settings

rajasharan/elm-automatic-differentiation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Automatic differentiation in reverse mode for elm

This library calculates the paritial derivatives of a multi-variable function using the method of automatic differentiation in reverse mode. The result is returned as a dictionary of keys and their corresponding derivative values (gradient vector).

Usage

Install

elm-package install rajasharan/elm-automatic-differentiation

Import

import Dict exposing (Dict)
import AD.Reverse as AD
  exposing
    ( pow, sqr, exp
    , add, mul
    , (|+|), (|.|), (|*|), (|^|)
    , autodiff
    )

API usage

-- build a computation graph for your function, for e.g.,
-- f(x,y) = (x+y)^2 . e^(2.(y+1)) + sin (x+y)^2
f : Float -> Float -> AD.Node
f x y =
  let
      a = AD.Variable "x" x
      b = AD.Variable "y" y
      u = pow (a |+| b) (AD.Const 2)
      v = (b |+| AD.Const 1)
      w = sqr (exp v)
      z = u |*| w |+| AD.sin u
  in
      z

-- result is a dictionary of keys and their corresponding derivative values
result : Dict String Float
result = autodiff (f 3 2)

-- [("x",4044.1999630459845),("y",24215.639637682732)]
-- this means:
-- ∂f/∂x = 4044.19996 at (x=3, y=2)
-- ∂f/∂y = 24215.6396 at (x=3, y=2)

Another example

-- g(x) = x^2
g : Float -> AD.Node
g x =
  let
      a = AD.Variable "x" x
  in
      a |^| (AD.Const 2)

result2 = autodiff (g 6)
-- [("x", 12)]
-- ∂g/∂x = 12 at (x=6)

Further Reading

The MIT License (MIT)

About

Automatic differentiation (a.k.a algorithmic differentiation) in reverse mode for elm

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages