我有一个从1970年到2020年的时间序列数据集作为我的训练数据集,我还有另一个2021年的观测值,我现在要做的是使用马氏距离来识别训练数据集中2021年的10个最近邻居。我尝试了几个函数,如get.knn()和get.knnx(),但我无法将距离设置为马氏距离。有可以使用的功能吗?提前谢谢你!
-编辑
所以我尝试了mahalanobis()的函数,然后我得到了一个值列表,这些值是马氏距离吗?我可以对它们进行排序以获得前10名吗?
发布于 2021-11-20 13:45:26
背景
马氏距离衡量一个点离平均值有多远,以标准差衡量,参见Wikipedia。它使用特征值旋转坐标,并与主成分分析有关。交叉验证包含几个很好的解释,例如这个"bottom-to-top-explanation"或function (cholMaha,见下文)如何估计距离矩阵。
马氏距离与主成分分析的关系
让我们假设一个小的数据示例:
A <- data.frame(
x = c(-2.48, -4.03, 1.15, 0.94, 5.33, 4.72),
y = c(-3.92, -3.4, 0.92, 0.78, 3.44, 0.5),
z = c(-1.11, -2.18, 0.21, 0.34, 1.74, 1.12)
)然后,我们可以通过来自包biotools的D2.dist或上面提到的函数来估计马氏距离矩阵:
## Mahalanobis distance from package biotools
library("biotools")
# sqrt, because D2.dist returns squared version
sqrt(D2.dist(A, cov(A)))
## https://stats.stackexchange.com/questions/65705/pairwise-mahalanobis-distances
cholMaha <- function(X) {
dec <- chol( cov(X) )
tmp <- forwardsolve(t(dec), t(X) )
dist(t(tmp))
}
cholMaha(A)现在问题来了。我们还可以将马氏距离估计为主成分分析的重新缩放载荷(旋转数据)的欧几里德距离:
## derive Mahalanobis distance from principal components
pc <- prcomp(A) # principal components
AA <- scale(pc$x) # "upscale" all components to the same level
# Euclidean distance of rescaled PC transformed variables is identical to
# Mahalanobis distance
dist(AA)结果与上面两种方法相同。
分类算法的应用
现在可以在任何分类算法中使用这种关系。只需通过PCA旋转变换数据矩阵,并将其欧几里德距离拟合进去。
## Now apply this in any classification method, e.g. hclust
par(mfrow=c(1, 2))
# Euclidean distance of original variables
plot(hclust(dist(scale(A))), main="Euclidean")
# Euclidean distance of scaled principal components
# is equivalent to Mahalanobis distance; considers covariance
plot(hclust(dist(AA)), main="Mahalanobis")实际上,隐藏在变量中的小影响因素被放大,但不幸的是,也有随机误差。要详细了解这一点,请阅读交叉验证网站上的"My grandma cooks"答案。
https://stackoverflow.com/questions/69958224
复制相似问题