I need to calculate the correlation matrix on vectors contained in a 5 GB csv file. Each row contains one observation for each random variable. For this, I wrote the following:
let getCorrMatrix data =
let getMatrixInfo nCol (count,crossProd:float array array,sumVector:float array,sqVector:float array) (newLine:float array) =
for i in 0..(nCol-1) do
sumVector.[i]<-sumVector.[i]+newLine.[i]
sqVector.[i]<-sqVector.[i]+(newLine.[i]*newLine.[i])
for j in (i+1)..(nCol-1) do
crossProd.[i].[j-(i+1)]<-crossProd.[i].[j-(i+1)]+newLine.[i]*newLine.[j]
let newCount = count+1
(newCount,crossProd,sumVector,sqVector)
let nCol = data|>Seq.head|>Seq.length
let matrixStart = Array.init nCol (fun i -> Array.create (nCol-i-1) 0.0)
let sumVector = Array.init nCol (fun _ -> 0.0)
let sqVector = Array.init nCol (fun _ -> 0.0)
let init = (0,matrixStart,sumVector,sqVector)
let (count,crossProd,sum,sq) =
data
|>PSeq.fold(getMatrixInfo nCol) init
let averages = sum|>Array.map(fun s ->s/(float count))
let std = Array.zip3 sum sq averages
|> Array.map(fun (elemSum,elemSq,av)-> let temp = elemSq-2.0*av*elemSum+float(count)*av*av
sqrt (temp/(float count-1.0)))
let rec getCorr i j =
if i=j then
1.0
elif i<j then
(crossProd.[i].[j-(i+1)]-averages.[i]*sum.[j]-averages.[j]*sum.[i]+(float count*averages.[i]*averages.[j]) )/((float count-1.0)*std.[i]*std.[j])
else
getCorr j i
let corrMatrix = Array2D.init nCol nCol (fun i j -> getCorr i j)
corrMatrix
I tested it against calculating R and it matches. Since I plan to use this again and again, if you have some feedback (or error), we will be very grateful. (Note that I am posting this because I thought it might be useful to others as well.)
thank
source
share