Classification functions in linear discriminant analysis in R

前端 未结 3 1473
陌清茗
陌清茗 2020-12-19 03:30

After completing a linear discriminant analysis in R using lda(), is there a convenient way to extract the classification functions for each group?

Fro

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-19 03:59

    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)
    }
    

    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.

提交回复
热议问题