我想为具有3个输入变量和2个类的矩阵绘制LDA的决策边界。如果仅将2个输入变量赋给LDA,我可以找到一些用于绘制边界的代码,但是我发现的3个输入变量的代码给出了不正确的边界。
# With 2 input variables
attach(iris)
index=Species!="versicolor"
iris=iris[index,]
LDA <- lda(Species ~ Sepal.Length + Sepal.Width, data=iris)
GS <- 500
x1 <- seq(min(Sepal.Length), max(Sepal.Length), len=GS)
x2 <- seq(min(Sepal.Width), max(Sepal.Width), len=GS)
x <- expand.grid(x1, x2)
newdat <- data.frame(Sepal.Length=x[,1], Sepal.Width=x[,2])
lda.Ghat <- as.numeric(predict(LDA, newdata=newdat)$class)
plot(Sepal.Length,Sepal.Width,col=Species)
contour(x1, x2, matrix(lda.Ghat, GS,GS),
levels=c(1,2),add=TRUE,drawlabels=FALSE, col="red")
legend("topright",legend=c('setosa','virginica'),fill=c("black","green"))
# With 3 input variables
LDA <- lda(Species ~ Sepal.Length + Sepal.Width + Petal.Length,data=iris)
GS <- 500
x1 <- seq(min(Sepal.Length), max(Sepal.Length), len=GS)
x2 <- seq(min(Sepal.Width), max(Sepal.Width), len=GS)
x <- expand.grid(x1, x2)
newdat <-data.frame(Sepal.Length=x[,1],Sepal.Width=x[,2],Petal.Length=mean(Petal.Length))
lda.Ghat <- as.numeric(predict(LDA, newdata=newdat)$class)
plot(Sepal.Length,Sepal.Width,col=Species)
contour(x1,x2,matrix(lda.Ghat,GS,GS),levels=c(1,2),add=TRUE,drawlabels=FALSE,col="red")
legend("topright",legend=c('setosa','virginica'),fill=c("black","green"))