问题描述
使用 lda()
在R中完成线性判别分析后,是否有一种方便的方法来提取?
After completing a linear discriminant analysis in R using lda()
, is there a convenient way to extract the classification functions for each group?
在链接中,
Si = ci + wi1*x1 + wi2*x2 + ... + wim*xm
我们可以使用分类函数直接计算一些新观测值的分类分数。
We can use the classification functions to directly compute classification scores for some new observations.
我可以使用教科书公式从头开始构建它们,但这需要从lda分析中重建许多中间步骤。有办法从lda对象中获取事实之后的信息吗?
I can build them from scratch using textbook formulas, but that requires rebuilding a number of intermediate steps from the lda analysis. Is there a way to get them after the fact from the lda object?
已添加:
除非我仍然对布兰登的答案有误解(对不起混乱!),否则看来答案是否定的。大概大多数用户可以从 predict()
获得所需的信息,该信息基于 lda()
提供分类
Unless I'm still misunderstanding something in Brandon's answer (sorry for the confusion!), it appears the answer is no. Presumably the majority of users can get the information they need from predict()
, which provides classifications based on lda()
.
推荐答案
没有获取所需信息的内置方法,因此我编写了一个函数来实现:
There isn't a built-in way to get the information I needed, so I wrote a function to do it:
ty.lda <- function(x, groups){
x.lda <- lda(groups ~ ., as.data.frame(x))
gr <- length(unique(groups)) ## groups might be factors or numeric
v <- ncol(x) ## variables
m <- x.lda$means ## group means
w <- array(NA, dim = c(v, v, gr))
for(i in 1:gr){
tmp <- scale(subset(x, groups == unique(groups)[i]), scale = FALSE)
w[,,i] <- t(tmp) %*% tmp
}
W <- w[,,1]
for(i in 2:gr)
W <- W + w[,,i]
V <- W/(nrow(x) - gr)
iV <- solve(V)
class.funs <- matrix(NA, nrow = v + 1, ncol = gr)
colnames(class.funs) <- paste("group", 1:gr, sep=".")
rownames(class.funs) <- c("constant", paste("var", 1:v, sep = "."))
for(i in 1:gr) {
class.funs[1, i] <- -0.5 * t(m[i,]) %*% iV %*% (m[i,])
class.funs[2:(v+1) ,i] <- iV %*% (m[i,])
}
x.lda$class.funs <- class.funs
return(x.lda)
}
此代码遵循Legendre和Legendre的数值生态学(1998)中的公式,第625页,并匹配从第626页开始的工作示例的结果。
This code follows the formulas in Legendre and Legendre's Numerical Ecology (1998), page 625, and matches the results of the worked example starting on page 626.
这篇关于R中线性判别分析中的分类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!