使用MASS:lda()访问LDA中线性判别式的观察得分

时间:2012-09-19 13:23:39

标签: r cluster-analysis

library(MASS)
example(lda)
plot(z)

如何访问z中的所有点?我想知道LD1和LD2上每个点的值,取决于它们的Sp(c,s,v)。

2 个答案:

答案 0 :(得分:5)

您要查找的内容是作为predict()类对象的"lda"方法的一部分计算的(请参阅?predict.lda)。它作为x生成的对象的组件predict(z)返回:

## follow example from ?lda
Iris <- data.frame(rbind(iris3[,,1], iris3[,,2], iris3[,,3]),
                   Sp = rep(c("s","c","v"), rep(50,3)))
set.seed(1) ## remove this line if you want it to be pseudo random
train <- sample(1:150, 75)
table(Iris$Sp[train])
## your answer may differ
##  c  s  v
## 22 23 30
z <- lda(Sp ~ ., Iris, prior = c(1,1,1)/3, subset = train)

## get the whole prediction object
pred <- predict(z)
## show first few sample scores on LDs
head(z$x)

最后一行显示线性判别式

上对象分数的前几行
> head(pred$x)
          LD1        LD2
40  -8.334664  0.1348578
56   2.462821 -1.5758927
85   2.998319 -0.6648073
134  4.030165 -1.4724530
30  -7.511226 -0.6519301
131  6.779570 -0.8675742

这些分数可以这样绘制

plot(LD2 ~ LD1, data = pred$x)

产生以下图(对于此训练样本!)

lda scores plot

答案 1 :(得分:1)

调用函数plot(z)时,实际上是在调用函数plot.lda - 这是一个S3方法。基本上,对象z具有类lda

class(z)

我们可以查看正在使用的实际功能:

getS3method("plot", "lda")

事实证明这是相当复杂的。但关键点是:

x = z
Terms <- x$terms
data <- model.frame(x)
X <- model.matrix(delete.response(Terms), data)
g <- model.response(data)
xint <- match("(Intercept)", colnames(X), nomatch = 0L)
X <- X[, -xint, drop = FALSE]
means <- colMeans(x$means)
X <- scale(X, center = means, scale = FALSE) %*% x$scaling

我们不能像以前那样:

plot(X[,1], X[,2])

Proviso 可能有一种更简单的方式来获得你想要的东西 - 我只是不知道lda功能。