|
| 1 | +# ------------------------------------------------------------------ |
| 2 | +# Licensed under the MIT License. See LICENSE in the project root. |
| 3 | +# ------------------------------------------------------------------ |
| 4 | + |
| 5 | +abstract type NearestNeighborsModel end |
| 6 | + |
| 7 | +struct KNNClassifier{M<:Metric} <: NearestNeighborsModel |
| 8 | + k::Int |
| 9 | + metric::M |
| 10 | + leafsize::Int |
| 11 | + reorder::Bool |
| 12 | +end |
| 13 | + |
| 14 | +KNNClassifier(k, metric=Euclidean(); leafsize=10, reorder=true) = KNNClassifier(k, metric, leafsize, reorder) |
| 15 | + |
| 16 | +struct KNNRegressor{M<:Metric} <: NearestNeighborsModel |
| 17 | + k::Int |
| 18 | + metric::M |
| 19 | + leafsize::Int |
| 20 | + reorder::Bool |
| 21 | +end |
| 22 | + |
| 23 | +KNNRegressor(k, metric=Euclidean(); leafsize=10, reorder=true) = KNNRegressor(k, metric, leafsize, reorder) |
| 24 | + |
| 25 | +function fit(model::NearestNeighborsModel, input, output) |
| 26 | + cols = Tables.columns(output) |
| 27 | + outnm = Tables.columnnames(cols) |> first |
| 28 | + outcol = Tables.getcolumn(cols, outnm) |
| 29 | + _checkoutput(model, outcol) |
| 30 | + (; metric, leafsize, reorder) = model |
| 31 | + data = Tables.matrix(input, transpose=true) |
| 32 | + tree = if metric isa MinkowskiMetric |
| 33 | + NN.KDTree(data, metric; leafsize, reorder) |
| 34 | + else |
| 35 | + NN.BallTree(data, metric; leafsize, reorder) |
| 36 | + end |
| 37 | + FittedModel(model, (tree, outnm, outcol)) |
| 38 | +end |
| 39 | + |
| 40 | +function predict(fmodel::FittedModel{<:NearestNeighborsModel}, table) |
| 41 | + (; model, cache) = fmodel |
| 42 | + tree, outnm, outcol = cache |
| 43 | + data = Tables.matrix(table, transpose=true) |
| 44 | + indvec, _ = NN.knn(tree, data, model.k) |
| 45 | + aggfun = _aggfun(model) |
| 46 | + ŷ = [aggfun(outcol[inds]) for inds in indvec] |
| 47 | + (; outnm => ŷ) |> Tables.materializer(table) |
| 48 | +end |
| 49 | + |
| 50 | +function _checkoutput(::KNNClassifier, x) |
| 51 | + if !(elscitype(x) <: DST.Categorical) |
| 52 | + throw(ArgumentError("output column must be categorical")) |
| 53 | + end |
| 54 | +end |
| 55 | + |
| 56 | +function _checkoutput(::KNNRegressor, x) |
| 57 | + if !(elscitype(x) <: DST.Continuous) |
| 58 | + throw(ArgumentError("output column must be continuous")) |
| 59 | + end |
| 60 | +end |
| 61 | + |
| 62 | +_aggfun(::KNNClassifier) = mode |
| 63 | +_aggfun(::KNNRegressor) = mean |
0 commit comments