colinrmitchell.com

Blog

Haskell levmar curve-fitting example

Posted Friday, May 20th 2016 in Programming - Permalink

It took me a little while to wrap my head around the levmar package from Hackage. I was mostly confused about how the independent variables were used in the types of the levmar function parameters. I was unable to find a simple example on the internet, so I want to post one here.

This is an easy-to-use function that I wrote that will do generic curve fitting for a set of data that has one independent variable. The first parameter is a list of tuples that stands for the data points. The second parameter is an integer specifying how many parameters are present in our non-linear model. The third parameter is our model: a function that takes a set of parameters and a value to a value. The function will return the best-fit set of parameters for this function.

import qualified Numeric.LinearAlgebra.Data as LA
import Numeric.LevMar

fitCurve :: [(Double, Double)] -> Int -> (LA.Vector Double -> Double -> Double) -> LA.Vector Double
fitCurve ds pc f =
   let model ps = LA.fromList $ map (\x -> f ps x) $ map fst ds :: LA.Vector Double
       results = 
         levmar 
            model 
            Nothing 
            (LA.fromList . take pc $ cycle [1.0]) 
            (LA.fromList $ map snd ds) 
            1000 
            defaultOpts 
            mempty
   in case results of
      Left err -> error $ show err
      Right (params, _, _) -> params


List Posts Newest Posts Page 1Next Page