Approximating a linear regression
Given a list of points, we can estimate the best fit line using a handy library, Statistics.LinearRegression
.
It computes the least square difference between points to estimate the best fit line. An example of a linear regression of points can be seen in the following figure:
Getting ready
Install the appropriate library using cabal as follows:
$ cabal install statistics-linreg
How to do it…
Import the following packages:
import Statistics.LinearRegression import qualified Data.Vector.Unboxed as U
Create a series of points from their coordinates, and feed it to the
linearRegression
function, as shown in the following code snippet:main = do let xs = U.fromList [1.0, 2.0, 3.0, 4.0, 5.0] :: U.Vector Double let ys = U.fromList [1.0, 2.0, 1.3, 3.75, 2.25]::U.Vector Double let (b, m) = linearRegression xs ys print $ concat ["y = ", show m, " x + ", show b]
The resulting linear equation...