質問

I am trying to use SVD decomposition to calculate a covariance matrix however it is not working correctly. I have built the following function.

Can anyone help point me to the mistake I have made.

Thanks in advance

svdcov = function(x){
           svdmat = svd(x)


## d is the singular values sometimes denoted as s
## u is left singular
## v is right singular
dvec = matrix(data=NA,nrow=length(x),ncol=1)
dvec[,1] = svdmat$d
covmat = t(t(svdmat$v%*%dvec)%*%t(svdmat$u)%*%svdmat$u)%*%t(dvec)%*%svdmat$v   
        colnames(covmat) = colnames(x)
        rownames(covmat) = colnames(x)
        return(covmat)

}
役に立ちましたか?

解決

The singular value decomposition is X=UDV'. If you want to compute X'X, that would be (UDV')'(UDV'), i.e., VDU'UDV', i.e., V D^2 V' (U is orthogonal and D diagonal).

f <- function(x) { 
  s <- svd(x)
  v <- s$v
  d <- diag(s$d)  # It is a vector: transform it to a diagonal matrix
  v %*% d^2 %*% t(v)
}
x <- matrix( rnorm(200), nc=4 )
stopifnot( all( abs( f(x) - t(x) %*% x ) < 1e-12 ) )

To have the variance matrix, you still need to subtract the mean of all the columns, and divide by the number of observations.

stopifnot( all( abs( 
    var(x) - 
    f(scale(x, scale=FALSE)) / (nrow(x)-1)
  ) < 1e-12
) )
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top