Created
November 21, 2022 11:57
-
-
Save jdh30/e1bf3c5bed85484a00496e3a1a49c5cc to your computer and use it in GitHub Desktop.
Gradient descent function minimization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let rec fixedPoint f x = | |
let fx = f x in | |
if fx = x then x else fixedPoint f fx | |
let ∂ fxs f xs (i, xi) = | |
let () = xi + δ @ Array.Unsafe.set xs i in | |
let f2 = (f xs - fxs) / δ in | |
let () = xi @ Array.Unsafe.set xs i in | |
f2 | |
let ∇ f xs = Array.mapi (∂ (f xs) f xs) xs | |
let descend α β f df (λ, xs, fxs) = | |
let xs2 = Array.map2 [a, b → a-b] xs (Array.map [x → λ*x] (df xs)) in | |
let fxs2 = f xs2 in | |
if fxs2 ≥ fxs then α*λ, xs, fxs else β*λ, xs2, fxs2 | |
let minimize f df xs = | |
let _, xs, _ = fixedPoint (descend 0.5 1.1 f df) (1, xs, f xs) in | |
xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment