Why I get two different covariance matrix?
5 views (last 30 days)
Prof. Andrew Ng in his ML class says that we can calculate covariance matrix as: 1/m*X'*X .
examples are in rows of X,
X' is transpose of X,
and, m is number of examples.
And, covariance with cov function is:
As you can see, cov1 is different from cov2 !!!
What is the reasan for that? Do you have any idea?
Paul on 14 Jul 2022
Perhaps Prof. Ng has some additional assumptions about the data that aren't included in your question. To compute the covariance we have to subtract off the mean. As for whether or not the outer product should be scaled by 1/m or 1/(m-1) depends on assumptions about the underlying data. IIRC, if we know the data is drawn from a Normal distribution then divide by m (perhaps also for other distributions as well?), but typically we don't assume that and so divide by m-1 for unbiased estimation. As can be seen below, cov subtracts the mean and divides by m-1.
cov1=1/(size(X,1)-1)*(X-mean(X))'*(X - mean(X))
As for the second question
sigma=[6 2;2 3]; % cov matrix
[a1,v] = eig(sigma)
[a2,s,~] = svd(sigma)
we see that eig and svd just have a different order for the results.