R中的Mahalonobis距离,误差:系统在计算上是奇异的 [英] Mahalonobis distance in R, error: system is computationally singular

查看:602
本文介绍了R中的Mahalonobis距离,误差:系统在计算上是奇异的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算从一组点到这些点的质心的多元距离.马氏距离似乎适用于此.但是,我得到一个错误(见下文).

I'd like to calculate multivariate distance from a set of points to the centroid of those points. Mahalanobis distance seems to be suited for this. However, I get an error (see below).

谁能告诉我为什么会出现此错误,以及是否有解决方法?

Can anyone tell me why I am getting this error, and if there is a way to work around it?

如果您下载坐标数据

If you download the coordinate data and the associated environmental data, you can run the following code.

require(maptools)
occ <- readShapeSpatial('occurrences.shp')
load('envDat.Rdata')

#standardize the data to scale the variables
dat <- as.matrix(scale(dat))
centroid <- dat[1547,]  #let's assume this is the centroid in this case

#Calculate multivariate distance from all points to centroid
mahalanobis(dat,center=centroid,cov=cov(dat))

Error in solve.default(cov, ...) : 
  system is computationally singular: reciprocal condition number = 9.50116e-19

推荐答案

马氏距离要求您计算协方差矩阵的逆.函数mahalanobis在内部使用solve,这是一种数值计算逆函数的方法.不幸的是,如果在逆计算中使用的一些数字很小,则会假设它们为零,从而导致它是一个奇异矩阵.这就是为什么它指定它们是 computationally 奇异的,因为给定不同的公差,矩阵可能不是奇异的.

The Mahalanobis distance requires you to calculate the inverse of the covariance matrix. The function mahalanobis internally uses solve which is a numerical way to calculate the inverse. Unfortunately, if some of the numbers used in the inverse calculation are very small, it assumes that they are zero, leading to the assumption that it is a singular matrix. This is why it specifies that they are computationally singular, because the matrix might not be singular given a different tolerance.

解决方案是在假设其为零时设置公差.幸运的是,mahalanobis允许您将此参数(tol)传递给solve:

The solution is to set the tolerance for when it assumes that they are zero. Fortunately, mahalanobis allows you to pass this parameter (tol) to solve:

mahalanobis(dat,center=centroid,cov=cov(dat),tol=1e-20)
# [1] 24.215494 28.394913  6.984101 28.004975 11.095357 14.401967 ...

这篇关于R中的Mahalonobis距离,误差:系统在计算上是奇异的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆