Book Image

Haskell Data Analysis Cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis Cookbook

By: Nishant Shukla

Overview of this book

Table of Contents (19 chapters)
Haskell Data Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

A best-fit line is drawn through five points using linear regression

Getting ready

Install the appropriate library using cabal as follows:

$ cabal install statistics-linreg

How to do it…

  1. Import the following packages:

    import Statistics.LinearRegression
    import qualified Data.Vector.Unboxed as U
  2. 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]
  3. The resulting linear equation...