我已经从knn
函数中获得了一系列建模的类标签。我有一个包含基本数值训练数据的数据框架,以及另一个用于测试数据的数据框架。我该如何为knn
函数返回的值绘制决策边界?我需要在一个锁定的机器上复制我的发现,因此请尽量避免使用第三方库。
我只有两个类标签,“橙色”和“蓝色”。它们在带有训练数据的简单2D图上绘制。同样,我只是想围绕knn
函数的结果绘制一个边界。
代码:
library(class)n <- 100set.seed(1)x <- round(runif(n, 1, n))set.seed(2)y <- round(runif(n, 1, n))train.df <- data.frame(x, y)set.seed(1)x.test <- round(runif(n, 1, n))set.seed(2)y.test <- round(runif(n, 1, n))test.df <- data.frame(x.test, y.test)k <- knn(train.df, test.df, classes, k=25)plot(test.df, col=k)
classes
只是一个由之前代码确定的类标签向量。
如果需要,以下是我工作的完整代码:
library(class)n <- 100set.seed(1)x <- round(runif(n, 1, n))set.seed(2)y <- round(runif(n, 1, n))# ============================================================# Bayes Classifier + Decision Boundary Code# ============================================================classes <- "null"colours <- "null"for (i in 1:n){ # P(C = j | X = x, Y = y) = prob # "当X是某个x,Y是某个y时,类(C)是橙色(j)的概率" # 两个影响分类的预测变量:x, y # 如果x和y都小于50,则有90%的概率是橙色(分组) # 如果x和y都大于50,或者其中一个大于50,分组为蓝色 # 算法倾向于选择成功概率更高的分组,然后使用该颜色绘图 # 当prob(如上所述)为50%时,绘制边界 percentChance <- 0 if (x[i] < 50 && y[i] < 50) { # 95%的概率是橙色,5%的概率是蓝色 # 因此贝叶斯决策边界在x < 50和y < 50时分配为橙色 # "colours"是决策边界分组,不是绘图分组 percentChance <- 95 colours[i] <- "orange" } else { percentChance <- 10 colours[i] <- "blue" } if (round(runif(1, 1, 100)) > percentChance) { classes[i] <- "blue" } else { classes[i] <- "orange" }}boundary.x <- seq(0, 100, by=1)boundary.y <- 0for (i in 1:101){ if (i > 49) { boundary.y[i] <- -10 # 为了视觉一致性,真实值为0 } else { boundary.y[i] <- 50 }}df <- data.frame(boundary.x, boundary.y)plot(x, y, col=classes)lines(df, type="l", lty=2, lwd=2, col="red")# ============================================================# K-Nearest neighbour code# ============================================================#library(class)#n <- 100#set.seed(1)#x <- round(runif(n, 1, n))#set.seed(2)#y <- round(runif(n, 1, n))train.df <- data.frame(x, y)set.seed(1)x.test <- round(runif(n, 1, n))set.seed(2)y.test <- round(runif(n, 1, n))test.df <- data.frame(x.test, y.test)k <- knn(train.df, test.df, classes, k=25)plot(test.df, col=k)
回答:
在网格上获取类概率预测,并在P=0.5处(或您希望的任何截止点)绘制等高线。这也是Venables和Ripley的经典MASS教科书以及Hastie、Tibshirani和Friedman的《统计学习的元素》中使用的方法。
# 类标签:简单地从原点计算距离classes <- ifelse(x^2 + y^2 > 60^2, "blue", "orange")classes.test <- ifelse(x.test^2 + y.test^2 > 60^2, "blue", "orange")grid <- expand.grid(x=1:100, y=1:100)classes.grid <- knn(train.df, grid, classes, k=25, prob=TRUE) # 注意最后一个参数prob.grid <- attr(classes.grid, "prob")prob.grid <- ifelse(classes.grid == "blue", prob.grid, 1 - prob.grid)# 绘制边界contour(x=1:100, y=1:100, z=matrix(prob.grid, nrow=100), levels=0.5, col="grey", drawlabels=FALSE, lwd=2)# 添加测试数据集的点points(test.df, col=classes.test)
另见在CrossValidated上基本相同的问题。