diff options
Diffstat (limited to 'examples/pca1.hs')
-rw-r--r-- | examples/pca1.hs | 15 |
1 files changed, 7 insertions, 8 deletions
diff --git a/examples/pca1.hs b/examples/pca1.hs index 775bb4c..58b5577 100644 --- a/examples/pca1.hs +++ b/examples/pca1.hs | |||
@@ -8,15 +8,14 @@ import Control.Monad(when) | |||
8 | type Vec = Vector Double | 8 | type Vec = Vector Double |
9 | type Mat = Matrix Double | 9 | type Mat = Matrix Double |
10 | 10 | ||
11 | sumColumns m = constant 1 (rows m) <> m | ||
12 | 11 | ||
13 | -- Vec with the mean value of the columns of a Mat | 12 | -- Vector with the mean value of the columns of a matrix |
14 | mean x = sumColumns x / fromIntegral (rows x) | 13 | mean a = constant (recip . fromIntegral . rows $ a) (rows a) <> a |
14 | |||
15 | -- covariance matrix of a list of observations stored as rows | ||
16 | cov x = (trans xc <> xc) / fromIntegral (rows x - 1) | ||
17 | where xc = x - asRow (mean x) | ||
15 | 18 | ||
16 | -- covariance Mat of a list of observations as rows of a Mat | ||
17 | cov x = (trans xc <> xc) / fromIntegral (rows x -1) | ||
18 | where xc = center x | ||
19 | center m = m - constant 1 (rows m) `outer` mean m | ||
20 | 19 | ||
21 | -- creates the compression and decompression functions from the desired number of components | 20 | -- creates the compression and decompression functions from the desired number of components |
22 | pca :: Int -> Mat -> (Vec -> Vec , Vec -> Vec) | 21 | pca :: Int -> Mat -> (Vec -> Vec , Vec -> Vec) |
@@ -38,7 +37,7 @@ main = do | |||
38 | system("wget -nv http://dis.um.es/~alberto/material/sp/mnist.txt.gz") | 37 | system("wget -nv http://dis.um.es/~alberto/material/sp/mnist.txt.gz") |
39 | system("gunzip mnist.txt.gz") | 38 | system("gunzip mnist.txt.gz") |
40 | return () | 39 | return () |
41 | m <- fromFile "mnist.txt" (5000,785) | 40 | m <- loadMatrix "mnist.txt" -- fromFile "mnist.txt" (5000,785) |
42 | let xs = takeColumns (cols m -1) m -- the last column is the digit type (class label) | 41 | let xs = takeColumns (cols m -1) m -- the last column is the digit type (class label) |
43 | let x = toRows xs !! 4 -- an arbitrary test Vec | 42 | let x = toRows xs !! 4 -- an arbitrary test Vec |
44 | let (pe,pd) = pca 10 xs | 43 | let (pe,pd) = pca 10 xs |