Nearest-Person and Nearest-Case Binary Probability Estimators
Source:R/neighbor_probability.R
fit.neighbor.probability.RdEstimates the probability of a binary outcome at a point from the outcomes
of its nearest neighbors, with one of three estimators. The ordinary
nearest-neighbor estimator uses the k nearest people. The two
nearest-case estimators instead extend the neighborhood until it contains
k cases. All three are computed by the same single-threaded C++
code, which handles one query point at a time and never forms the matrix
of all pairwise distances.
Usage
fit.neighbor.probability(
X = NULL,
y,
method = c("knn", "case_raw", "case_corrected"),
k = NULL,
k.grid = NULL,
distances = NULL,
metric = c("euclidean", "chebyshev", "linf.simplex"),
normalization = c("none", "sum", "max"),
id = NULL,
group = NULL,
foldid = NULL,
selection = c("min", "one.se", "locality.one.se"),
search = c("auto", "ann", "brute"),
eps = 0
)Arguments
- X
Numeric matrix with one training record per row. Supply either
Xordistances.- y
Binary responses, with
NAfor unanswered outcomes.- method
"knn","case_raw", or"case_corrected".- k
Fixed positive integer neighborhood size. Counts people for
"knn"and cases for the other methods. Corrected sizes must be at least two. Omit for cross-validation usingfoldid.- k.grid
Optional candidate sizes for cross-validation. If omitted, use every size up to the minimum feasible training count across folds.
- distances
Optional square, nonnegative training dissimilarity matrix in record order. Positive infinity denotes an unreachable record. No graph or powered path distances are constructed internally.
- metric
Coordinate distance:
"euclidean","chebyshev", or"linf.simplex". The last computes exact intrinsic Euclidean-length paths on the nonnegative max-normalized surface, using dgraphs' C++ solver. Paths can cross intermediate faces; this is not Chebyshev distance.- normalization
Row normalization:
"none","sum", or"max". The latter two require nonnegative rows with positive mass. Supply already-computed distances withnormalization = "none". Normalization changes coordinates, not the distance definition: Euclidean distances on max-normalized profiles are ambient chords, not intrinsic paths on the cube surface. Usemetric = "linf.simplex"for those paths, withnormalization = "max". Alternatively,"none"requires nonnegative rows whose maxima equal one withinsqrt(.Machine$double.eps); admitted rows are divided by their maxima. Sum normalization is rejected for intrinsic coordinate input.- id
Unique nonmissing record IDs. Defaults to row numbers as strings. Supply persistent IDs to obtain ordering invariant to row permutations.
- group
Nonmissing participant IDs, defaulting to
id.- foldid
Optional fold vector or matrix (one repeat per column). Every participant must stay in one fold per repeat. Missing outcomes are excluded from scoring, but their groups still obey the split.
- selection
Minimum Brier error, largest size within one standard error (
"one.se"), or smallest such size ("locality.one.se").- search
Neighbor search:
"auto"uses ANN for Euclidean coordinates and brute force otherwise;"ann"explicitly requests the ANN kd-tree;"brute"is the exhaustive reference backend. ANN requires ambient Euclidean coordinates, including normalized coordinates. Intrinsic surface search always exhausts eligible candidates using one query's workspace, with no all-pairs distance matrix.- eps
Nonnegative ANN approximation tolerance, default zero (exact). Positive values require ANN. The distance approximation guarantee does not bound probability error or case stopping ranks after exclusions.
Value
A neighbor.probability.fit with selected k,
method, backend = "C++", candidate scores, folds, and the
metric, distance.backend, and training data needed for
prediction. No training predictions are computed
during fitting; predict(fit) computes leave-participant-out values.
Details
Rank answering training records by distance, then by the SHA-256 hash of
paste0("nearest-cases-v1|", id). Hash collisions use ID order. Keep only
the closest answering record per participant, before inspecting its outcome.
Exclude the query's entire participant when its group is supplied.
If \(T_k\) is the rank including the kth case, the estimates are
\(K^{-1}\sum_{j=1}^K y_{(j)}\), \(k/T_k\), and
\((k-1)/(T_k-1)\). No clipping, pseudocount or automatic baseline fallback
is applied. Insufficient reachable people or cases return NA.
The number of cases reachable can depend on the query when a participant's
visits have discordant outcomes.
ANN expands candidate neighborhoods until the requested people or cases are available. Exact search completes the boundary before applying the ID tie rule. Approximate search sorts retrieved candidates by exact distance; for each retrieved participant it also checks all answering visits, keeping the closest. It can miss other participants and tied records. Approximate boundary diagnostics describe retrieved participants, not a complete shell. Available people/cases diagnostics still describe the full training set. Intrinsic surface search prepares sparse training profiles once per prediction call or CV split and streams a complete eligible distance row for each query. It uses dgraphs' shared intrinsic solver directly, without constructing a sample graph, limiting paths to endpoint faces, or truncating candidate neighbors. All three estimators share the same participant and tie rules. Per-pair worst-case work is quadratic in the number of features present in either profile. Distance workspace is linear in training records.
Trees are reused across queries and sizes, and across participants within each CV split. They are rebuilt for each prediction call and are not stored in the serializable fit. CV retains one tree or sparse intrinsic profile cache per split and repeat; a new prediction call rebuilds its cache. Native caches are released on return or error from prediction or tuning.
Tuning averages losses within participant, then across repeats, then across
participants. Its standard error is the standard deviation of those
participant losses divided by the square root of the number of people.
Candidates with any unsupported validation prediction are unselectable.
Numerical ties within 1e-14 favor larger sizes for minimum-error
selection. The tuning score is not an independent performance estimate;
use external participant-held outer folds for assessment.
This implementation matches the sPTB study's prediction arithmetic and minimum-error tuning when there is one record per participant, the same distances, IDs and folds. The repeated-record policy is an explicit extension. At a tied distance the prefix can split a tied shell, as in that study.
Examples
X <- matrix(0:11, ncol = 1)
y <- rep(c(0, 1, 1), 4)
fit <- fit.neighbor.probability(X, y, method = "case_corrected", k = 2)
predict(fit, newdata = matrix(c(1.5, 5.5), ncol = 1))
#> 2
#> [1,] 1.0
#> [2,] 0.5
tuned <- fit.neighbor.probability(X, y, method = "knn",
foldid = rep(1:3, 4), k.grid = 1:4)
tuned$cv.table
#> k brier se valid selected
#> 1 1 0.5833333 0.1486471 TRUE FALSE
#> 2 2 0.5000000 0.1066004 TRUE FALSE
#> 3 3 0.5185185 0.1105485 TRUE FALSE
#> 4 4 0.5000000 0.1066004 TRUE TRUE
# Intrinsic surface neighbors can differ from ambient Euclidean neighbors.
profiles <- rbind(c(0, 1, 0, 0), c(1, 1, 1, 1))
surface <- fit.neighbor.probability(profiles, c(1, 0), k = 1,
metric = "linf.simplex", normalization = "max")
predict(surface, rbind(c(1, 0, 0, 0)))
#> 1
#> [1,] 0