1 #' @include b_Algorithm.R
3 #' @title K Nearest Neighbors Algorithm
5 #' @description K Nearest Neighbors Algorithm.
6 #' Inherits \code{\link{Algorithm}}
8 #' @field k Number of neighbors to consider. Default: \code{n^(2/3)}
10 KnearestNeighbors = setRefClass(
11 Class = "KnearestNeighbors",
17 contains = "Algorithm",
20 predictOne = function(X, Y, x)
22 "Find the neighbors of one row, and solve a constrained linear system to obtain weights"
24 distances = sqrt(apply(X, 1, function(z)(return (sum((z-x)^2)))))
25 rankedHistory = sort(distances, index.return=TRUE)
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)
30 return (sum(x * weight))
32 predict_noNA = function(XY, x)
34 X = XY[,names(XY) != "Measure"]
38 else if (length(XY[["Measure"]]) == 1)
44 res = c(res, predictOne(X, Y, x[i,]))