data(iris)

n <- 100
x <- scale(iris[1:n,1:2])
y <- as.numeric(iris[1:n,5])-1
fisher <- data.frame(y=y,x1=x[,1],x2=x[,2])

# 0 = setosa
# 1 = versicolor

plot(x,col=y+1)

len <- 50
x1 <- seq(min(x[,1]),max(x[,1]),length=len)
x2 <- seq(min(x[,2]),max(x[,2]),length=len)
grille <- expand.grid(x1=x1,x2=x2)

library(caret)

model.knn <- knn3(as.factor(y)~x1+x2,data=fisher,k=1)
res.knn <- predict(model.knn,grille,type="class")
contour(x1,x2,matrix(as.numeric(res.knn)-1,len,len),levels=0.5,add=TRUE,col="green")

model.reg <- lm(y ~ x1+x2,data=fisher)
res.reg <- predict(model.reg,grille)
classif.reg <- rep(0,len*len)
classif.reg[res.reg > 0.5] <- 1
contour(x1,x2,matrix(classif.reg,len,len),levels=0.5,add=TRUE,col="blue")

Modifié le: vendredi 11 septembre 2020, 16:59