| 1 | #' @include b_Algorithm.R |
| 2 | |
| 3 | #' @title K Nearest Neighbors Algorithm |
| 4 | #' |
| 5 | #' @description K Nearest Neighbors Algorithm. |
| 6 | #' Inherits \code{\link{Algorithm}} |
| 7 | #' |
| 8 | #' @field k Number of neighbors to consider. Default: \code{n^(2/3)} |
| 9 | #' |
| 10 | KnearestNeighbors = setRefClass( |
| 11 | Class = "KnearestNeighbors", |
| 12 | |
| 13 | fields = c( |
| 14 | k = "numeric" |
| 15 | ), |
| 16 | |
| 17 | contains = "Algorithm", |
| 18 | |
| 19 | methods = list( |
| 20 | predictOne = function(X, Y, x) |
| 21 | { |
| 22 | "Find the neighbors of one row, and solve a constrained linear system to obtain weights" |
| 23 | |
| 24 | distances = sqrt(apply(X, 1, function(z)(return (sum((z-x)^2))))) |
| 25 | rankedHistory = sort(distances, index.return=TRUE) |
| 26 | n = length(Y) |
| 27 | k_ = ifelse(length(k) == 0 || k <= 0. || k > n, getKnn(n), as.integer(k)) |
| 28 | weight = ridgeSolve(matricize(X[rankedHistory$ix[1:k_],]), Y[rankedHistory$ix[1:k_]], LAMBDA) |
| 29 | |
| 30 | return (sum(x * weight)) |
| 31 | }, |
| 32 | predict_noNA = function(XY, x) |
| 33 | { |
| 34 | X = XY[,names(XY) != "Measure"] |
| 35 | K = ncol(XY) - 1 |
| 36 | if (K == 1) |
| 37 | X = as.matrix(X) |
| 38 | else if (length(XY[["Measure"]]) == 1) |
| 39 | X = t(as.matrix(X)) |
| 40 | Y = XY[,"Measure"] |
| 41 | x = matricize(x) |
| 42 | res = c() |
| 43 | for (i in 1:nrow(x)) |
| 44 | res = c(res, predictOne(X, Y, x[i,])) |
| 45 | return (res) |
| 46 | } |
| 47 | ) |
| 48 | ) |