K最近邻

K-Nearest-Neighbour

我正在尝试使用 R 的 class 库中的 knn 函数。它给我一个错误,即 "train" 与 [= 的长度不同19=].

分别打印 train 和 class 的长度后,我发现 train 的长度为 100(按需),class 的长度为 2(按预期)。如果我理解正确,cl 或 class 是标签的分解向量。我的标签只是 "orange" 和 "blue"。我按照文档中的示例进行操作,但错误仍然存​​在。我的代码有什么明显的错误吗?感谢任何帮助。

library(class)

x <- runif(100, 1, 100)
y <- runif(100, 1, 100)
train.df <- data.frame(x, y)

x.test <- runif(100, 1, 100)
y.test <- runif(100, 1, 100)
test.df <- data.frame(x.test, y.test)

cl <- factor(c(rep("orange", 100), rep("blue", 100)))

knn(train.df, test.df, cl, k=3, prob=TRUE)

cl 是 200 个元素长。尝试为每个 class 调用 rep 50 次。

library(class)

x <- runif(100, 1, 100)
y <- runif(100, 1, 100)
train.df <- data.frame(x, y)

x.test <- runif(100, 1, 100)
y.test <- runif(100, 1, 100)
test.df <- data.frame(x.test, y.test)

cl <- factor(c(rep("orange", 50), rep("blue", 50)))

knn(train.df, test.df, cl, k=3, prob=TRUE)