ggplot 中 KNN 模型的轮廓?

发布于 2024-10-12 09:35:18 字数 863 浏览 1 评论 0原文

我有一个 KNN 模型,正在使用 contour 函数绘制它。这是我正在做的事情的一个简单示例(基于 this普渡大学考试):

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 中制作同样的图?特别是,我怎样才能做相当于轮廓的事情?

I have a KNN model which I am plotting using the contour function. This is a simple example of the kind of thing that I'm doing (based on 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)

My question is: how can I make this same plot in ggplot? In particular, how I can I do the equivalent of contour?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巷雨优美回忆 2024-10-19 09:35:18
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)
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)
葵雨 2024-10-19 09:35:18

在你的代码之后尝试这个:

library(ggplot2)

p <- ggplot(TrainC, aes(x1, x2))
p + geom_point(aes(colour = as.numeric(y) + 1))

df <- data.frame(x = rep(xp, np), y = rep(yp, each = np), z = zp)
p <- ggplot(df, aes(x, y, z = z))
p + stat_contour(bins = 1)

这是两个独立的图。不确定如何组合它们,但深入文档此处应该可以帮助您入门。

After your code try this:

library(ggplot2)

p <- ggplot(TrainC, aes(x1, x2))
p + geom_point(aes(colour = as.numeric(y) + 1))

df <- data.frame(x = rep(xp, np), y = rep(yp, each = np), z = zp)
p <- ggplot(df, aes(x, y, z = z))
p + stat_contour(bins = 1)

That's two separate plots. Not sure how to combine them but digging in the documentation here should get you started.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文