Guest User

Untitled

a guest
Dec 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. import Control.Monad (liftM)
  2. import Data.List (find)
  3.  
  4. -- Given a list it returns the consecutive pairs of items in the list
  5. pairs :: [a] -> [(a, a)]
  6. pairs values = zip values (tail values)
  7.  
  8.  
  9. -- Given a list, this function returns the first item whose difference
  10. -- between it and the previous item is less than `threshold`
  11. dropUntilStepSizeLessThan :: (Ord a, Num a) => a -> [a] -> Maybe a
  12. dropUntilStepSizeLessThan threshold infl = result
  13. where
  14. result = liftM snd resultPair
  15. resultPair = find stepSizeLessThan (pairs infl)
  16. stepSizeLessThan (a,b) = abs (a - b) < threshold
  17.  
  18.  
  19. -- This function returns the next step in the gradient descent algorithm
  20. next_x :: Num a => (a -> a) -> a -> a -> a
  21. next_x df gamma cur_x = cur_x - gamma * (df cur_x)
  22.  
  23.  
  24. -- Given the derivative of a function (df), the step size multiplier (gamma),
  25. -- the step size threshold (threshold) and a starting value,
  26. -- solve the function f for 0 using gradient descent
  27. grad_desc :: (Ord a, Num a) => (a -> a) -> a -> a -> a -> Maybe a
  28. grad_desc df gamma threshold start_x = dropUntilStepSizeLessThan threshold values
  29. where
  30. values = iterate next start_x
  31. next = next_x df gamma
  32.  
  33.  
  34. -- Example derivative
  35. df x = 4 * (x**3) - 9 * (x**2)
Add Comment
Please, Sign In to add comment