如何用R中的网格绘制非线性决策边界? [英] How to plot non-linear decision boundaries with a grid in R?
问题描述
我在 stats.stackexchange.com.在这里,应用于您的数据集.
库(类)设置种子(pi)X <- t(replicate(1000, runif(2)))g <- ifelse(apply(X, 1, sum) <= 1, 0, 1)xnew <- cbind(rep(seq(0, 1, length.out=50), 50),rep(seq(0, 1, length.out=50), each=50))m <- knn(X, xnew, g, k=15, prob=TRUE)概率 <- attr(m, "概率")概率 <- ifelse(m=="1", 概率, 1-概率)prob15 <- 矩阵(概率,50)par(mar=rep(3, 4))轮廓(唯一(xnew[,1]),唯一(xnew[,2]),prob15,水平=0.5,标签="", xlab='', ylab='', 轴=假, lwd=2.5, asp=1)标题(xlab=表达式(斜体('X')[1]),ylab=表达式(斜体('X')[2]),line=1, family='serif', cex.lab=1.5)点(X,bg=ifelse(g==1,#CA002070",#0571B070"),pch=21)gd <- expand.grid(x=unique(xnew[, 1]), y=unique(xnew[, 2]))点(gd,pch=20,cex=0.4,col=ifelse(prob15 > 0.5,#CA0020",#0571B0"))盒子()
(更新:我改变了调色板,因为蓝色/黄色/紫色的东西非常可怕.)
I find this particular graph in ISLR (Figure 2.13) or ESL very well done. I can't guess how the authors would have made this in R. I know how to get the orange and blue points very easily. The main confusion is the background dots and the purple line.
Any ideas?
Here is some sample code to get the yellow and orange points with a grey grid. How do I get an arbitrary non-linear curve in purple and then color the grid according to the curve?
set.seed(pi)
points = replicate(100, runif(2))
pointsColored = ifelse(apply(points, 2, sum) <= 1, "orange", "blue")
# Confound some
pointsColored[sample.int(length(pointsColored), 10)] = "orange"
plot(x=points[1, ], y=points[2, ])
grid(nx=100, ny=100)
# Plot points over the grid.
points(x=points[1, ], y=points[2, ], col=pointsColored)
As I indicated in my comment, a solution was provided by @chl here on stats.stackexchange.com. Here it is, applied to your data set.
library(class)
set.seed(pi)
X <- t(replicate(1000, runif(2)))
g <- ifelse(apply(X, 1, sum) <= 1, 0, 1)
xnew <- cbind(rep(seq(0, 1, length.out=50), 50),
rep(seq(0, 1, length.out=50), each=50))
m <- knn(X, xnew, g, k=15, prob=TRUE)
prob <- attr(m, "prob")
prob <- ifelse(m=="1", prob, 1-prob)
prob15 <- matrix(prob, 50)
par(mar=rep(3, 4))
contour(unique(xnew[, 1]), unique(xnew[, 2]), prob15, levels=0.5,
labels="", xlab='', ylab='', axes=FALSE, lwd=2.5, asp=1)
title(xlab=expression(italic('X')[1]), ylab=expression(italic('X')[2]),
line=1, family='serif', cex.lab=1.5)
points(X, bg=ifelse(g==1, "#CA002070", "#0571B070"), pch=21)
gd <- expand.grid(x=unique(xnew[, 1]), y=unique(xnew[, 2]))
points(gd, pch=20, cex=0.4, col=ifelse(prob15 > 0.5, "#CA0020", "#0571B0"))
box()
(UPDATE: I changed the colour palette because the blue/yellow/purple thing was pretty hideous.)
这篇关于如何用R中的网格绘制非线性决策边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!