From 3f5bf5985d3da0e4d01cd9c126cb781cb6fc28ef Mon Sep 17 00:00:00 2001 From: Alberto Ruiz Date: Wed, 3 Feb 2010 17:53:51 +0000 Subject: updated examples, removed Util module --- examples/pca2.hs | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) (limited to 'examples/pca2.hs') diff --git a/examples/pca2.hs b/examples/pca2.hs index 8c20370..c38857c 100644 --- a/examples/pca2.hs +++ b/examples/pca2.hs @@ -9,33 +9,31 @@ import Control.Monad(when) type Vec = Vector Double type Mat = Matrix Double -sumColumns m = constant 1 (rows m) <> m +-- Vector with the mean value of the columns of a matrix +mean a = constant (recip . fromIntegral . rows $ a) (rows a) <> a --- Vector with the mean value of the columns of a Mat -mean x = sumColumns x / fromIntegral (rows x) +-- covariance matrix of a list of observations stored as rows +cov x = (trans xc <> xc) / fromIntegral (rows x - 1) + where xc = x - asRow (mean x) --- covariance matrix of a list of observations as rows of a matrix -cov x = (trans xc <> xc) / fromIntegral (rows x -1) - where xc = center x - center m = m - constant 1 (rows m) `outer` mean m type Stat = (Vec, [Double], Mat) --- 1st and 2nd order statistics of a dataset (mean, eigenvalues and eigenvectors of cov) +-- 1st and 2nd order statistics of a dataset (mean, eigenvalues and eigenvectors of cov) stat :: Mat -> Stat -stat x = (m, toList s, trans v) where +stat x = (m, toList s, trans v) where m = mean x - (s,v) = eigSH' (cov x) + (s,v) = eigSH' (cov x) --- creates the compression and decompression functions from the desired reconstruction +-- creates the compression and decompression functions from the desired reconstruction -- quality and the statistics of a data set pca :: Double -> Stat -> (Vec -> Vec , Vec -> Vec) pca prec (m,s,v) = (encode,decode) where encode x = vp <> (x - m) decode x = x <> vp + m - vp = takeRows n v + vp = takeRows n v n = 1 + (length $ fst $ span (< (prec'*sum s)) $ cumSum s) - cumSum = tail . scanl (+) 0.0 + cumSum = tail . scanl (+) 0.0 prec' = if prec <=0.0 || prec >= 1.0 then error "the precision in pca must be 0