7

I'm looking to perform classification on data with mostly categorical features. For that purpose, Euclidean distance (or any other numerical assuming distance) doesn't fit.

I'm looking for a kNN implementation for [R] where it is possible to select different distance methods, like Hamming distance. Is there a way to use common kNN implementations like the one in {class} with different distance metric functions?

I'm using R 2.15

1
  • 2
    Have you looked through the packages knn and kknn and MTSKNN ? Sep 11, 2012 at 11:27

1 Answer 1

8

As long as you can calculate a distance/dissimilarity matrix (in whatever way you like) you can easily perform kNN classification without the need of any special package.

# 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])

If anybody knows a better way of finding the most common value in a vector than the dirty line above, I'd be happy to know.

The drop=FALSE argument is needed to preserve the subset of NN as matrix in the case k=1. If not it will be converted to a vector and apply will throw an error.

3
  • 2
    As to "better way," this is cute but probably not any better: 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 Sep 11, 2012 at 13:49
  • That is nicer. Since this is a trivial task I was hoping there is a basic, fast and direct method for it, e.g. most.common.value(foo).
    – Backlin
    Sep 11, 2012 at 13:55
  • 1
    oops: it should be rle(sort(foo)) Sep 11, 2012 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.