gpt4 book ai didi

r - ggplot中KNN模型的轮廓?

转载 作者:行者123 更新时间:2023-12-01 08:39:52 25 4
gpt4 key购买 nike

我有一个使用 contour 绘制的 KNN 模型功能。这是我正在做的事情的一个简单示例(基于 this Purdue exam ):

library(class)
library(nnet)

TrainC<-read.table("http://miner.chem.purdue.edu/Exam1/TrainC.dat")
names(TrainC)<-c("x1","x2","y")

K=15

p <- as.matrix(TrainC[, -3])
xp <- seq(min(TrainC$x1), max(TrainC$x1), length = 50); np <- length(xp)
yp <- seq(min(TrainC$x2), max(TrainC$x2), length = 50)
tp<-TrainC$y

yhat <- knn(p, p, tp, k = K)

plot(TrainC[, 1], TrainC[, 2], xlab = "x1", ylab = "x2", col=as.numeric(TrainC$y)+1)
pt <- expand.grid(x1 = xp, x2 = yp)
Z <- knn(p, pt, tp, k = K)
zp<-class.ind(Z)[,1] - class.ind(Z)[,2]

contour(xp, yp, matrix(zp, np), add = T, levels = 0, labex = 0)

我的问题是:如何在 ggplot 中制作相同的图?特别是,我该如何做 contour ?

最佳答案

d <- transform(melt(matrix(zp, np)), xp=xp[X1], yp=yp[X2])
ggplot(d, aes(xp, yp, z=value)) +
geom_contour() +
geom_point(aes(x1, x2, colour=y, z=NULL), data=TrainC)

关于r - ggplot中KNN模型的轮廓?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4730799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com