我希望对大部分特征为分类的数据进行分类。为此,欧几里得距离(或任何其他假定距离的数值)并不适合。
我正在寻找一个[R]中的kNN实现,可以选择不同的距离方法,如汉明距离。
是否有一种方法可以使用常见的kNN实现(如{class}中的实现)来使用不同的距离度量函数?
我正在使用R 2.15
# 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])
如果有比上面那段代码更好的方法来查找向量中最常见的值,我很乐意知道。
drop=FALSE
参数需要在k=1
的情况下保留NN
子集作为矩阵。否则它将被转换为向量,并且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
- Carl Witthoftmost.common.value(foo)
。 - Backlinrle(sort(foo))
。 - Carl Witthoft
knn
、kknn
和MTSKNN
这些程序包? - Carl Witthoft