R 中的欺诈检测
Tim Verdonck
Professor Data Science at KU Leuven
MASS 包中的 Animals 数据集包含28 种动物的平均脑重和体重 library(MASS)
data("Animals")
body brain
Mountain beaver 1.35 8.1
Cow 465.00 423.0
Grey wolf 36.33 119.5
Goat 27.66 115.0
X <- data.frame(log_body = log(Animals$body), log_brain = log(Animals$brain))
箱线图:体重与脑重的对数

马氏(广义)距离:观测到中心的距离,考虑协方差矩阵。

马氏距离:到中心的距离,考虑协方差矩阵。

经典马氏距离:用样本均值估计位置,用样本协方差矩阵估计散布
通过将马氏距离与由卡方分布得到的阈值比较,检测多变量离群点
在二维中,可构造相应的97.5% 容差椭球:其点的马氏距离不超过该阈值
animals.clcenter <- colMeans(X) animals.clcov <- cov(X) rad <- sqrt(qchisq(0.975, df = ncol(X)))library(car) ellipse.cl <- data.frame(ellipse(center = animals.clcenter, shape = animals.clcov,radius = rad, segments = 100, draw = FALSE)) colnames(ellipse.cl) <- colnames(X)fig <- fig + geom_polygon(data=ellipse.cl, color = "dodgerblue", fill = "dodgerblue", alpha = 0.2) + geom_point(aes(x = animals.clcenter[1], y = animals.clcenter[2]), color = "blue", size = 6)

Rousseeuw 的最小协方差行列式(MCD)是常用的稳健多变量位置与散布估计量。
使用 MCD 的位置与散布稳健估计
library(robustbase)
animals.mcd <- covMcd(X)
# 位置的稳健估计
animals.mcd$center
# 散布的稳健估计
animals.mcd$cov
将这些稳健的位置信息和散布带入马氏距离的定义,可得到稳健距离,并据此构建稳健容差椭球。
library(robustbase) animals.mcd <- covMcd(X) ellipse.mcd <- data.frame(ellipse(center = animals.mcd$center, shape = animals.mcd$cov, radius = rad, segments = 100, draw = FALSE)) colnames(ellipse.mcd) <- colnames(X)fig2 <- fig + geom_polygon(data = ellipse.mcd, color = "red", fill = "red", alpha = 0.3) + geom_point(aes(x = animals.mcd$center[1], y = animals.mcd$center[2]), color = "red", size = 6)

MCD 对象直接得到的经典马氏距离。plot(animals.mcd, which = "dd")


R 中的欺诈检测