k_nearest_neighbors: K-nearest neighbors

View source: R/deepML.r

k_nearest_neighborsR Documentation

K-nearest neighbors

Description

K-nearest neighbors

Usage

k_nearest_neighbors(object, ...)

## S3 method for class 'formula'
k_nearest_neighbors(formula, data, query, k = 1L, ...)

## Default S3 method:
k_nearest_neighbors(x, y, query, k = 1L, ...)

Arguments

object

R object.

...

Optional arguments.

formula

A model formula.

data

A data frame, containing the variables in formula. Neither a matrix nor an array will be accepted.

query

A vector or matrix containing the test or query instances the response is to be determined.

k

The number of nearest neighbors of feature samples chosen to extract the response.

x

A matrix or data frame with feature values.

y

A vector of categorical or continuous outcomes for x.

Details

The response of k-nearest neighbors is either the majority class of k neighbors for a categorical response or the mean of k neighbors for a continuous outcome.

Value

A named list with the response and a matrix with class-probability distributions where appropriate for query.

See Also

distance.

Other Machine Learning: cross_validation_split(), decision_tree(), moving_average(), naive_bayes(), naive_forecast(), predict.decisiontree(), predict.kmeans(), predict.naivebayes()

Examples

  df <- data.frame(height = c(158, 158, 158, 160, 160, 163, 163, 160, 163, 165, 165, 165, 168, 168, 168, 170, 170, 170),
                   weight = c(58, 59, 63, 59, 60, 60, 61, 64, 64, 61, 62, 65, 62, 63, 66, 63, 64, 68),
                   size = as.factor(c(rep("M", 7), rep("L", 11))),
                   cont = sample(20, 18))
  query <- setNames(c(161, 61), c("height", "weight")) # query instance
  query <- data.frame(height = c(161, 183, 161), weight = c(61, 77, 55)) # query data frame
  knn <- k_nearest_neighbors(size ~ height + weight, df, query, k = 3L)
  knn$response
  knn$probability


stschn/deepANN documentation built on June 25, 2024, 7:27 a.m.