1
$\begingroup$

i want to calculate mahalanobis distance, from the formula and also theoretical explanation given here

https://www.machinelearningplus.com/statistics/mahalanobis-distance/

i tried to implement it with help of r, here is my simulated data, their covariance matrix and applied formula : l

ibrary(matlib)
calculus_score <- rnorm(20,12,3)
r_score  <-rnorm(20,15,7)
df <-data.frame(calculus_score,r_score)
data_vector =as.matrix(df[1,])
mean_vector =t(as.matrix(colMeans((df))))
x <- data_vector -mean_vector
cov = as.matrix(cov(df))
inv_r =inv(cov)
print(inv_r)
first_part =(x %*% inv_r)
last_part =(first_part %*% t(x))
print(sqrt(last_part))
print(mahalanobis(df, colMeans(df), cov(df)))

result is given :

> library(matlib)
> calculus_score <- rnorm(20,12,3)
> r_score  <-rnorm(20,15,7)
> df <-data.frame(calculus_score,r_score)
> data_vector =as.matrix(df[1,])
> mean_vector =t(as.matrix(colMeans((df))))
> x <- data_vector -mean_vector
> cov = as.matrix(cov(df))
> inv_r =inv(cov)
> print(inv_r)
                          
[1,] 0.08996774 0.02129345
[2,] 0.02129345 0.05771103
> first_part =(x %*% inv_r)
> last_part =(first_part %*% t(x))
> print(sqrt(last_part))
         1
1 1.131093
> print(mahalanobis(df, colMeans(df), cov(df)))
 [1] 1.2793708 3.8746218 0.6191061 0.2273994 7.8007252 0.6624168 1.0335179
 [8] 4.4952383 0.5713539 3.0517258 1.5961463 0.7668096 1.1018290 1.2884556
[15] 1.5785714 1.5660312 2.3136476 1.7095509 0.8067573 1.6567251

problem is that calculated distance for first row 1.131093 is difference from the value calculated based on built in function, am i making some errors? or there is different algorithms for calculatung mahalanobis distance?

$\endgroup$

1 Answer 1

3
$\begingroup$

?mahalanobis states that it returns the squared Mahalanobis distance and you are computing the Mahalanobis distance.

Doing

sqrt(1.2793708)

I get your manually computed value:

r$> sqrt(1.2793708)                                                             
[1] 1.131093
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.