在R中使用k-NN和分类值

Omr*_*374 5 r distance knn

我希望对具有大多数分类功能的数据进行分类.为此目的,欧几里德距离(或任何其他数字假定距离)不适合.

我在寻找[R]的kNN实现,可以选择不同的距离方法,如汉明距离.有没有办法使用常见的kNN实现,如{class}中具有不同距离度量函数的实现?

我正在使用R 2.15

Bac*_*lin 8

只要您可以计算距离/相异度矩阵(以您喜欢的任何方式),您就可以轻松执行kNN分类,而无需任何特殊包.

# Generate dummy data
y <- rep(1:2, each=50)                          # True class memberships
x <- y %*% t(rep(1, 20)) + rnorm(100*20) < 1.5  # Dataset with 20 variables
design.set <- sample(length(y), 50)
test.set <- setdiff(1:100, design.set)

# Calculate distance and nearest neighbors
library(e1071)
d <- hamming.distance(x)
NN <- apply(d[test.set, design.set], 1, order)

# Predict class membership of the test set
k <- 5
pred <- apply(NN[, 1:k, drop=FALSE], 1, function(nn){
    tab <- table(y[design.set][nn])
    as.integer(names(tab)[which.max(tab)])      # This is a pretty dirty line
}

# Inspect the results
table(pred, y[test.set])
Run Code Online (Sandbox Code Playgroud)

如果有人知道在矢量中找到最常见值的更好方法而不是上面的脏线,我很高兴知道.

drop=FALSE需要该参数来保留NN案例中作为矩阵的子集k=1.如果不是,它将被转换为向量apply并将引发错误.

  • 至于"更好的方式",这很可爱,但可能没有更好:`Rgames> foo < - c(1,1,2,3,4,5,5,5,5,6,4,4,3, 3,3)Rgames> bar <-rle(foo)Rgames> bar $ values [which.max(bar $ lengths)] [1] 5` (2认同)