0

我想为具有 3 个输入变量和 2 个类的矩阵绘制 LDA 的决策边界。如果只向 LDA 提供 2 个输入变量,我可以找到一些用于绘制边界的代码,但是我为 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"))
4

0 回答 0