Skip to contents

This vignette explains what the package computes and why. Each method is described mathematically, illustrated with a small example that recomputes the package’s result by hand, and assessed with its advantages and disadvantages. The Get Started vignette shows the workflow, Comparing the Approaches applies all distances to the same data, and the benchmark article compares their predictive performance.

What the package does

A case base is a set of solved cases 𝒞={(xj,yj)}j=1n\mathcal{C} = \{(x_j, y_j)\}_{j=1}^n: covariates xjx_j (e.g. age, sex, tumour stage) and an outcome yjy_j (a class, a number, or a censored survival time (tj,δj)(t_j, \delta_j)). Case-based reasoning (CBR) answers a new problem xqx_q by the similar cases of the case base, in four steps (Aamodt & Plaza, 1994):

Step Mathematical task Functions
Retrieve find Nk(xq)N_k(x_q), the kk cases with the smallest d(xq,xj)d(x_q, x_j) get_similar_cases(), calc_distance_matrix(), explain_match()
Reuse predict yqy_q from {yj:j∈Nk(xq)}\{y_j : j \in N_k(x_q)\} predict_outcome(), predict_survival(), get_counterfactual_cases()
Revise measure how good the predictions are on test cases evaluate(), evaluate_survival(), check_ph()
Retain add and remove cases, find noisy and redundant cases add_cases(), remove_cases(), assess_cases()

Everything depends on the distance dd. The package’s idea (Dippon et al., 2002) is to learn dd from a statistical model of the outcome: a regression model, a boosted model or a random forest is fitted to the case base, and two cases are close if the model considers them alike. The Gower distance is included as a model-free baseline.

Why the distance must be learned

Take the naive distance, the mean absolute difference of the features, dL1(xi,xj)=1p∑k=1p|xik−xjk|. d_{L_1}(x_i, x_j) = \frac{1}{p}\sum_{k=1}^p |x_{ik} - x_{jk}|. It has three problems:

  1. Categorical features. |xik−xjk||x_{ik} - x_{jk}| is not defined for sex or tumour type.
  2. Scale. Measuring age in months instead of years multiplies its contribution by 12. Features with large numbers dominate.
  3. Relevance. Every feature counts equally. For lung cancer survival, the performance status matters more than the patient’s city, but dL1d_{L_1} cannot know that.

Standardising the features solves the second problem, but not the third. Only knowledge of the outcome can tell which features matter, and how much. A statistical model of the outcome contains exactly this knowledge.

Regression models: distances in contribution space

Definition

LinearModel, LogisticModel and CoxModel fit a regression model with the rms package. Its linear predictor is a sum over model terms tt (a variable, a spline of a variable, an interaction, …): η(x)=∑tct(x),ct(x)=Xt(x)β̂t, \eta(x) = \sum_t c_t(x), \qquad c_t(x) = X_t(x)\,\hat\beta_t , where Xt(x)X_t(x) are the columns of the design matrix that belong to term tt and β̂t\hat\beta_t their estimated coefficients. We call ct(x)c_t(x) the contribution of term tt. The distance of two cases is the L1L_1 distance of their contributions: d(xi,xj)=∑t|ct(xi)−ct(xj)| \boxed{\; d(x_i, x_j) = \sum_t \left| c_t(x_i) - c_t(x_j) \right| \;} For main effects this is the weighted distance of Dippon et al. (2002):

  • numeric feature kk: ck(x)=β̂kxkc_k(x) = \hat\beta_k x_k, so the term adds |β̂k||xik−xjk||\hat\beta_k|\,|x_{ik} - x_{jk}|;
  • categorical feature kk with level coefficients β̂k(l)\hat\beta_k^{(l)} (zero for the reference level): the term adds |β̂k(xik)−β̂k(xjk)||\hat\beta_k^{(x_{ik})} - \hat\beta_k^{(x_{jk})}|, which is zero for equal levels.

All three problems of the naive distance are solved: categorical features enter through their coefficients, the coefficient scales inversely with the unit of the feature, and features without effect get a coefficient near zero.

What a distance means

By the triangle inequality, the distance bounds the difference of the linear predictors: |η(xi)−η(xj)|≤d(xi,xj). \lvert \eta(x_i) - \eta(x_j) \rvert \le d(x_i, x_j). The linear predictor has a meaning on the scale of the model, so the distance has one too:

Model η(x)\eta(x) d(xi,xj)≤δd(x_i, x_j) \le \delta means
LinearModel expected outcome E[y∣x]E[y \mid x] expected outcomes differ by at most δ\delta (in units of yy)
LogisticModel log-odds log⁡P(y=1∣x)P(y=0∣x)\log \frac{P(y=1 \mid x)}{P(y=0 \mid x)} odds ratio between the cases in [e−δ,eδ][e^{-\delta}, e^{\delta}]
CoxModel log relative hazard hazard ratio between the cases in [e−δ,eδ][e^{-\delta}, e^{\delta}]

For example, two patients at Cox distance 0.10.1 have hazards that differ by at most e0.1−1≈10%e^{0.1} - 1 \approx 10\%.

A worked example

We fit a Cox model for the survival of lung cancer patients.

lung2 <- na.omit(lung[, c("time", "status", "age", "sex", "ph.ecog", "ph.karno", "wt.loss")])
lung2$status <- lung2$status - 1
lung2$sex <- factor(lung2$sex, labels = c("male", "female"))

cox <- CoxModel$new(Surv(time, status) ~ age + sex + ph.ecog, lung2)
cox$fit()
beta <- coef(cox$model_fit)
beta
##         age  sex=female     ph.ecog 
##  0.01347899 -0.57204879  0.45638532

Older age and a worse performance status (ph.ecog, 0 = fully active to 3 = bedridden half the day) increase the hazard; women have a lower hazard. Now take two patients:

pair <- lung2[c("19", "149"), ]
pair
##     time status age    sex ph.ecog ph.karno wt.loss
## 19    61      1  56 female       2       60      10
## 149   31      1  82   male       0      100      27

By hand, the distance is the sum of three terms:

by_hand <- c(age     = abs(beta[["age"]] * (pair$age[1] - pair$age[2])),
             sex     = abs(beta[["sex=female"]] * ((pair$sex[1] == "female") - (pair$sex[2] == "female"))),
             ph.ecog = abs(beta[["ph.ecog"]] * (pair$ph.ecog[1] - pair$ph.ecog[2])))
by_hand
##       age       sex   ph.ecog 
## 0.3504537 0.5720488 0.9127706
sum(by_hand)
## [1] 1.835273

explain_match() reports the same terms, sorted by their share of the distance, and calc_distance_matrix() the same total:

knitr::kable(cox$explain_match(pair[1, ], pair[2, ]), digits = 3)
term query_contribution case_contribution distance share
ph.ecog 0.913 0.000 0.913 0.497
sex -0.572 0.000 0.572 0.312
age 0.755 1.105 0.350 0.191
cox$calc_distance_matrix(pair[1, ])[rownames(lung2) == "149", ]
## [1] 1.835273

Why not just compare risk scores?

The two patients have almost the same linear predictor, i.e. the same predicted risk:

eta <- predict(cox$model_fit, newdata = pair, type = "lp")
eta
##         19        149 
## 0.05765668 0.06738851
abs(diff(eta))
##        149 
## 0.00973183

The 56-year-old woman with a poor performance status and the 82-year-old man who is fully active have the same risk for different reasons. A distance based only on |η(xi)−η(xj)||\eta(x_i) - \eta(x_j)| would treat them as identical cases; in contribution space they are far apart, because each term is compared on its own. Cases retrieved in contribution space are similar in risk and in the reasons for the risk, which is what makes them useful as precedents.

Scale invariance

Measuring age in months changes the coefficient by a factor of 1/12, and the distance not at all:

lung_months <- transform(lung2, age = age * 12)
cox_months <- CoxModel$new(Surv(time, status) ~ age + sex + ph.ecog, lung_months)
cox_months$fit()
max(abs(cox_months$calc_distance_matrix() - cox$calc_distance_matrix()))
## [1] 4.440892e-16

Non-linear effects and interactions

Any rms term is allowed, e.g. a restricted cubic spline rcs(age, 4) or an interaction sex * ph.ecog. The contribution ct(x)c_t(x) is then a non-linear function, and equal differences in a variable count differently in different ranges: below, the eight years between 50 and 58 and between 72 and 80 give different distances. All columns of an interaction belong to one term, so the term is compared as a whole.

cox_rcs <- CoxModel$new(Surv(time, status) ~ rcs(age, 3) + sex + ph.ecog, lung2)
cox_rcs$fit()
ages <- data.frame(age = c(50, 58, 72, 80), sex = factor("male", levels(lung2$sex)), ph.ecog = 1)
age_distance <- function(a, b) sum(cox_rcs$explain_match(ages[a, ], ages[b, ])$distance)
c("50 vs 58" = age_distance(1, 2), "72 vs 80" = age_distance(3, 4))
##   50 vs 58   72 vs 80 
## 0.01245924 0.23738336

Advantages and disadvantages

Advantages

  • Each feature is weighted by its estimated effect on the outcome; irrelevant features get (almost) no weight.
  • Independent of the units of the features; categorical features need no ad-hoc coding.
  • The distance has a meaning on the outcome scale (difference of expected outcome, log odds ratio, log hazard ratio).
  • Fully explainable: explain_match() decomposes each distance into model terms.
  • The model can be checked with the usual tools (check_ph(), residuals, rms::validate()), and variables can be selected before the distance is used.
  • Fast and deterministic: computing all distances costs O(nmT)O(n\,m\,T) for nn cases, mm queries and TT terms.

Disadvantages

  • The distance is only as good as the model. A misspecified model (wrong functional form, missing interactions, violated proportional hazards) gives a misleading distance.
  • Non-linear effects and interactions must be specified by the user.
  • A feature that acts only through an interaction that is not in the model gets no weight.
  • With few cases or correlated features, the coefficients, and hence the weights, are unstable.
  • Two levels of a factor with similar coefficients are treated as nearly identical, even if they are different in substance.
  • LogisticModel supports binary outcomes only.

Random forests: distances from the trees

RFModel fits a random forest with ranger (classification, regression or survival). A forest of TT trees partitions the feature space TT times; each tree sends a case down to one terminal node (leaf). Let ℓt(x)\ell_t(x) be the leaf of case xx in tree tt. The partitions are chosen to separate the outcomes, so cases in the same leaf have similar outcomes, and the forest finds non-linear effects and interactions by itself.

Proximity distance

The proximity (Breiman, 2002) is the share of trees in which two cases share a leaf, and the distance is derived from it: p(xi,xj)=1T∑t=1T1[ℓt(xi)=ℓt(xj)],d(xi,xj)=1−p(xi,xj). p(x_i, x_j) = \frac{1}{T}\sum_{t=1}^T 1\left[\ell_t(x_i) = \ell_t(x_j)\right], \qquad d(x_i, x_j) = \sqrt{1 - p(x_i, x_j)}. A tiny forest of three trees shows the computation:

rf3 <- ranger::ranger(Species ~ ., iris, num.trees = 3, write.forest = TRUE, seed = 1)
cases <- iris[c(51, 53, 78, 101), -5]
leaves <- terminal_nodes(cases, rf3)
dimnames(leaves) <- list(rownames(cases), paste("tree", 1:3))
leaves
##     tree 1 tree 2 tree 3
## 51      19      3     15
## 53      26      9     15
## 78      26      9     14
## 101      8     10     10
# proximity of case 51 and case 53: share of trees with the same leaf
mean(leaves["51", ] == leaves["53", ])
## [1] 0.3333333
round(as.matrix(proximity_distance(cases, rfObject = rf3)), 3)
##       1     2     3 4
## 1 0.000 0.816 1.000 1
## 2 0.816 0.000 0.577 1
## 3 1.000 0.577 0.000 1
## 4 1.000 1.000 1.000 0

Out-of-bag and RF-GAP proximities

A tree is grown on a bootstrap sample until its leaves are small, so cases that were used to grow the tree (in-bag) tend to share leaves with each other. For training cases, the original proximity is therefore too optimistic. Two variants avoid this (set_distance_method("Proximity", proximity_type = ...)):

  • OOB: only trees in which both cases are out-of-bag are counted.
  • RF-GAP (Rhodes, Cutler & Moon, 2023): for a query qq and a training case jj, p(q,j)=1|Sq|∑t∈Sqcj(t)1[ℓt(xj)=ℓt(xq)]|Mq(t)|, p(q, j) = \frac{1}{|S_q|}\sum_{t \in S_q} \frac{c_j(t)\, 1\left[\ell_t(x_j) = \ell_t(x_q)\right]}{|M_q(t)|}, where SqS_q are the trees in which qq is out-of-bag (all trees for new data), cj(t)c_j(t) is the in-bag count of jj in tree tt, and |Mq(t)||M_q(t)| is the total in-bag count of the leaf of qq.

The RF-GAP proximities of a query sum to one over the training cases, and the proximity-weighted mean of the training outcomes is the forest’s prediction. Retrieval with RF-GAP therefore uses exactly the notion of similarity of the forest’s predictions. Because the proximities are small, RF-GAP distances lie close to 1; only their order matters.

Depth distance

The proximity is all-or-nothing: two cases in neighbouring leaves count as far apart as two cases at opposite ends of the tree. The depth distance (Englund & Verikas, 2012) counts the edges gt(xi,xj)g_t(x_i, x_j) between the leaves of the two cases, i.e. the sum of their distances to their deepest common ancestor, averaged over the trees: d(xi,xj)=1T∑t=1Tgt(xi,xj). d(x_i, x_j) = \frac{1}{T}\sum_{t=1}^T g_t(x_i, x_j). In this tree, g(A,B)=2g(A, B) = 2, g(A,C)=3g(A, C) = 3 and g(A,D)=5g(A, D) = 5, while the proximity only knows that AA shares a leaf with none of them:

              root
            /      \
          n1        n2
         /  \      /  \
       n3    C    D    E
      /  \
     A    B

The finer resolution matters for retrieval. For a query, many training cases share no leaf with it at all: they are tied at proximity distance 1, and their order is arbitrary. The depth distance still ranks them:

set.seed(1)
rf <- RFModel$new(Species ~ ., iris[-51, ], num.trees = 100)
rf$fit()
d_depth <- rf$calc_distance_matrix(iris[51, ])[, 1]
rf$set_distance_method("Proximity")
d_prox <- rf$calc_distance_matrix(iris[51, ])[, 1]
c(cases_at_maximal_proximity_distance = sum(d_prox == 1),
  distinct_proximity_distances = length(unique(d_prox)),
  distinct_depth_distances = length(unique(d_depth)))
## cases_at_maximal_proximity_distance        distinct_proximity_distances 
##                                  73                                  36 
##            distinct_depth_distances 
##                                  71

The depth distance is the default of RFModel.

Explaining a forest match

There are no coefficients, but the paths of two cases through a tree diverge at one split. explain_match() counts the split variables at which the paths diverge over the trees; attribute same_leaf is the proximity.

rf$set_distance_method("Depth")
knitr::kable(rf$explain_match(iris[51, ], iris[78, ]), digits = 3)
variable n_trees share
Petal.Length 52 0.642
Petal.Width 25 0.309
Sepal.Length 2 0.025
Sepal.Width 2 0.025

Advantages and disadvantages

Advantages

  • No model specification: non-linear effects and interactions are found automatically.
  • Mixed feature types, any monotone transformation of a feature gives the same forest.
  • RF-GAP retrieves exactly the cases the forest’s prediction is based on.

Disadvantages

  • The distance has no unit and no interpretation on the outcome scale; explanations are counts of split variables, not effects.
  • Trees split more often on features with many possible split points (Strobl et al., 2007), so continuous features, including irrelevant ones, get much weight in the distance, especially on small data sets (see Comparing the Approaches).
  • It depends on the random seed and on tuning parameters (num.trees, mtry, min.node.size).
  • The original proximity is biased for training cases (OOB and RF-GAP fix this) and coarse (many ties); RF-GAP distances are all close to 1.
  • More expensive: O(nmT)O(n\,m\,T) for TT trees (typically hundreds), and the in-bag counts take O(nT)O(n\,T) memory.
  • OOB and RF-GAP proximities are tied to the cases the forest was grown on: after add_cases() or remove_cases(), the forest must be refitted.

Gradient boosting: distances in SHAP space

Why the forest approach does not carry over

A boosted model (BoostModel, fitted with xgboost) is also an ensemble of trees, but a different one. The trees are fitted one after another, each to the errors of the previous ones, and added up: f(x)=f0+ν∑m=1Mhm(x), f(x) = f_0 + \nu \sum_{m=1}^M h_m(x), where hm(x)h_m(x) is the value of the leaf of xx in tree mm and ν\nu the learning rate. The trees are small, and they are not exchangeable: the first trees capture the main effects, the last ones small corrections or noise. Counting shared leaves, as the proximity does, would weight every tree equally and ignore the leaf values.

SHAP values as contributions

Instead, BoostModel uses the additive structure of the prediction. SHAP values (Lundberg et al., 2020) split the prediction of a case into one contribution per feature, f(x)=ϕ0+∑k=1pϕk(x), f(x) = \phi_0 + \sum_{k=1}^p \phi_k(x), where ϕ0\phi_0 is the average prediction and ϕk(x)\phi_k(x) is the contribution of feature kk, computed exactly for trees (TreeSHAP). The contributions are on the margin scale of the model: the outcome for regression, the log odds for classification, the log relative hazard for the Cox objective. The distance is the L1L_1 distance of the SHAP vectors: d(xi,xj)=∑k=1p|ϕk(xi)−ϕk(xj)| \boxed{\; d(x_i, x_j) = \sum_{k=1}^p \left| \phi_k(x_i) - \phi_k(x_j) \right| \;} This is the contribution-space distance of the regression models, with the features as terms. It has the same interpretation: |f(xi)−f(xj)|≤d(xi,xj)|f(x_i) - f(x_j)| \le d(x_i, x_j), so for the Cox objective ede^{d} bounds the hazard ratio of the two cases. For a factor, the SHAP values of its dummy columns are summed; for a multi-class model, the SHAP values of all classes are used.

The link to the regression distance

For a linear model f(x)=β0+∑kβkxkf(x) = \beta_0 + \sum_k \beta_k x_k with independent features, the SHAP values are ϕk(x)=βk(xk−x‾k)\phi_k(x) = \beta_k (x_k - \bar x_k), and |ϕk(xi)−ϕk(xj)|=|βk||xik−xjk|, \left|\phi_k(x_i) - \phi_k(x_j)\right| = |\beta_k|\,|x_{ik} - x_{jk}| , which is exactly the weighted distance of Dippon et al. (2002). The SHAP distance therefore generalises the regression distance to models that learn non-linear effects and interactions by themselves. With a linear booster, BoostModel reproduces LinearModel:

fml_iris <- Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width
lin <- LinearModel$new(fml_iris, iris)
lin$fit()
lin_boost <- BoostModel$new(fml_iris, iris, nrounds = 2000,
                            params = list(booster = "gblinear", eta = 1, lambda = 0, alpha = 0,
                                          updater = "shotgun", feature_selector = "cyclic"))
lin_boost$fit()
max(abs(lin$calc_distance_matrix(iris[1:5, ]) - lin_boost$calc_distance_matrix(iris[1:5, ])))
## [1] 2.185652e-05

With trees (the default), the SHAP values of a feature are step functions of the feature and may depend on the other features. For the two patients from above:

boost <- BoostModel$new(Surv(time, status) ~ age + sex + ph.ecog, lung2,
                        nrounds = 100, params = list(eta = 0.05, max_depth = 2))
boost$fit()
phi <- boost$shap_values(pair)
phi
##            age        sex     ph.ecog
## [1,] 0.1270603 -0.2169538  0.63126487
## [2,] 0.9718791  0.1984745 -0.05248616
## attr(,"bias")
## [1] 0.002923822
# the SHAP values add up to the model's log relative hazard
rowSums(phi) + attr(phi, "bias")
## [1] 0.5442952 1.1207913
knitr::kable(boost$explain_match(pair[1, ], pair[2, ]), digits = 3)
term query_contribution case_contribution distance share
age 0.127 0.972 0.845 0.435
ph.ecog 0.631 -0.052 0.684 0.352
sex -0.217 0.198 0.415 0.214
c(distance = sum(abs(phi[1, ] - phi[2, ])),
  difference_of_log_hazards = abs(diff(rowSums(phi))))
##                  distance difference_of_log_hazards 
##                 1.9439981                 0.5764961

The distance is much larger than the difference of the predicted log hazards: as in the Cox model, the patients’ differences partly cancel in the prediction, and the distance keeps them apart.

Advantages and disadvantages

Advantages

  • Non-linear effects and interactions are learned, as with a forest, but the distance keeps the meaning of the regression distance: it bounds the difference of the predictions on the outcome, log-odds or log-hazard scale.
  • Explanations per feature, in the same form as for the regression models; for a linear model, the regression distance is a special case.
  • Retrieval is cheap: the SHAP values are computed once per case, and the distance costs O(nmp)O(n\,m\,p). New cases need no refit.
  • Deterministic without row or column subsampling.

Disadvantages

  • The SHAP values are step functions: a small difference that crosses a split counts fully, a large one within a leaf not at all.
  • SHAP values share interaction effects between the features involved, so two cases can have similar SHAP values from different feature values.
  • The distance inherits the boosted model’s overfitting: on small data sets, irrelevant features get weight, and the neighbourhoods are less stable under resampling than for the other distances (see Comparing the Approaches). The model must be tuned and regularised.
  • Needs the suggested package xgboost.

Tuning. Every split of the model is part of the distance, so choose the number of rounds and the depth by cross-validation, not by default. A model with many rounds fits splits in irrelevant features, and those splits become distance. xgboost::xgb.cv() with early stopping does this on a design matrix with the same features:

X <- model.matrix(~ age + sex + ph.ecog - 1, lung2)
label <- ifelse(lung2$status == 1, lung2$time, -lung2$time)  # Cox: censored < 0
set.seed(1)
cv <- xgboost::xgb.cv(params = list(objective = "survival:cox", eta = 0.05,
                                    max_depth = 2, nthread = 1),
                      data = xgboost::xgb.DMatrix(X, label = label),
                      nrounds = 1000, nfold = 5, early_stopping_rounds = 20,
                      verbose = 0)
nrounds <- which.min(cv$evaluation_log$test_cox_nloglik_mean)
nrounds
## [1] 28
boost_tuned <- BoostModel$new(Surv(time, status) ~ age + sex + ph.ecog, lung2,
                              nrounds = nrounds,
                              params = list(eta = 0.05, max_depth = 2))
boost_tuned$fit()

Repeat this for max_depth from 1 to 3 and keep the best. On small data sets like this one, cross-validation itself is noisy; the distance then stays unstable even when tuned.

The Gower distance: a model-free baseline

The Gower (1971) distance of two cases is a weighted mean of per-variable distances in [0,1][0, 1]: d(xi,xj)=∑kwkδijksijk∑kwkδijk,sijk={|xik−xjk|/Rknumeric, Rk the range of feature k|rik−rjk|/(Lk−1)ordered factor with ranks r and Lk levels1[xik≠xjk]unordered factor, d(x_i, x_j) = \frac{\sum_k w_k\, \delta_{ijk}\, s_{ijk}}{\sum_k w_k\, \delta_{ijk}}, \qquad s_{ijk} = \begin{cases} \lvert x_{ik} - x_{jk} \rvert / R_k & \text{numeric, } R_k \text{ the range of feature } k\\ \lvert r_{ik} - r_{jk} \rvert / (L_k - 1) & \text{ordered factor with ranks } r \text{ and } L_k \text{ levels}\\ 1[x_{ik} \ne x_{jk}] & \text{unordered factor,} \end{cases} where δijk=0\delta_{ijk} = 0 if feature kk is missing in one of the cases and 1 otherwise, and wkw_k are user-given weights (default 1). By hand, for the two patients from above:

gower <- GowerModel$new(Surv(time, status) ~ age + sex + ph.ecog, lung2)
gower$fit()
R_age <- diff(range(lung2$age)); R_ecog <- diff(range(lung2$ph.ecog))
by_hand <- c(age     = abs(pair$age[1] - pair$age[2]) / R_age,
             sex     = as.numeric(pair$sex[1] != pair$sex[2]),
             ph.ecog = abs(pair$ph.ecog[1] - pair$ph.ecog[2]) / R_ecog)
mean(by_hand)
## [1] 0.7571059
gower_distance(pair[, c("age", "sex", "ph.ecog")], ranges = gower$model_fit$ranges)
##           1
## 2 0.7571059
knitr::kable(gower$explain_match(pair[1, ], pair[2, ]), digits = 3)
variable query_value case_value weight distance share
sex female male 1 0.333 0.440
ph.ecog 2 0 1 0.222 0.294
age 56 82 1 0.202 0.266

The two patients that the Cox model found to be equally at risk are far apart for both distances; but the Gower distance weights the sex difference (1) as much as a difference over the full age range, without knowing that sex has a smaller effect on survival than ECOG.

Advantages

  • No model and no outcome needed: works for exploratory retrieval and as a sanity check of the model-derived distances.
  • Transparent, deterministic, handles missing values pair by pair.
  • Weights can encode expert knowledge.

Disadvantages

  • All features count equally unless weighted by hand. Irrelevant or noise features dilute the distance (see the benchmark).
  • Numeric differences are scaled by the range, so a single outlier compresses all other differences.
  • No interpretation on the outcome scale.

Reuse: predictions from the retrieved cases

Let Nk(q)N_k(q) be the kk nearest cases of query qq and dqjd_{qj} their distances. With weighted = TRUE, case jj gets the tricube weight wqj=(1−(dqj/hq)3)3,hq=1.0001⋅maxj∈Nk(q)dqj, w_{qj} = \left(1 - \left(d_{qj}/h_q\right)^3\right)^3, \qquad h_q = 1.0001 \cdot \max_{j \in N_k(q)} d_{qj}, so that close cases count more and the farthest of the kk cases still counts a little; otherwise wqj=1w_{qj} = 1. predict_outcome() predicts

  • classes: p̂l(q)=∑j∈Nk(q)wqj1[yj=l]/∑j∈Nk(q)wqj\hat p_l(q) = \sum_{j \in N_k(q)} w_{qj}\, 1[y_j = l] \big/ \sum_{j \in N_k(q)} w_{qj}, and the class with the largest p̂l(q)\hat p_l(q);
  • numeric outcomes: the weighted mean ŷ(q)=∑jwqjyj/∑jwqj\hat y(q) = \sum_j w_{qj}\, y_j \big/ \sum_j w_{qj}.

For survival endpoints, predict_survival() computes the (weighted) Kaplan–Meier estimate of the kk nearest cases (Lowsky et al., 2013): Ŝ(t∣q)=∏s≤t(1−∑j∈Nk(q)wqj1[tj=s,δj=1]∑j∈Nk(q)wqj1[tj≥s]). \hat S(t \mid q) = \prod_{s \le t} \left(1 - \frac{\sum_{j \in N_k(q)} w_{qj}\, 1[t_j = s,\ \delta_j = 1]}{\sum_{j \in N_k(q)} w_{qj}\, 1[t_j \ge s]}\right).

The number of cases kk trades bias against variance: few cases give noisy predictions, many cases include cases that are not similar. It should be chosen on held-out data with evaluate() / evaluate_survival().

get_counterfactual_cases() reuses the case base in a different way: it returns the nearest cases with a different outcome (Keane & Smyth, 2020). Together with explain_match(), they show what distinguishes the query from cases that turned out differently.

Revise: evaluating the predictions

evaluate() and evaluate_survival() score the predictions for mm test cases:

Endpoint Measure Definition Better
class accuracy 1m∑q1[ŷ(q)=yq]\frac{1}{m}\sum_q 1[\hat y(q) = y_q] higher
class Brier score 1m∑q∑l(p̂l(q)−1[yq=l])2\frac{1}{m}\sum_q \sum_l (\hat p_l(q) - 1[y_q = l])^2 lower
class log loss −1m∑qlog⁡p̂yq(q)-\frac{1}{m}\sum_q \log \hat p_{y_q}(q) lower
numeric RMSE, MAE 1m∑q(ŷ(q)−yq)2\sqrt{\frac{1}{m}\sum_q (\hat y(q) - y_q)^2}, 1m∑q|ŷ(q)−yq|\frac{1}{m}\sum_q \lvert\hat y(q) - y_q\rvert lower
survival Uno’s C concordance of the risk 1−Ŝ(τ∣q)1 - \hat S(\tau \mid q) with the observed times, weighted for censoring (Uno et al., 2011) higher
survival IBS 1tmax−tmin∫BS(t)dt\frac{1}{t_{\max} - t_{\min}}\int \mathrm{BS}(t)\,dt lower

with the censoring-weighted Brier score (Graf et al., 1999) BS(t)=1m∑q[Ŝ(t∣q)21[tq≤t,δq=1]Ĝ(tq−)+(1−Ŝ(t∣q))21[tq>t]Ĝ(t)], \mathrm{BS}(t) = \frac{1}{m}\sum_q \left[\frac{\hat S(t \mid q)^2\, 1[t_q \le t,\ \delta_q = 1]}{\hat G(t_q-)} + \frac{(1 - \hat S(t \mid q))^2\, 1[t_q > t]}{\hat G(t)}\right], where Ĝ\hat G is the Kaplan–Meier estimate of the censoring distribution of the training data. A Brier score of 0.25 is what an uninformative prediction of 50% achieves.

Retain: maintaining the case base

add_cases() and remove_cases() change the case base. Regression models and the Gower distance do not need to be refitted: the distance of new cases is computed with the fitted coefficients (ranges); refit with refit = TRUE when the case base has changed a lot.

assess_cases() judges each case ii by its kk nearest other cases Nk(i)N_k(i) (leave one out). Case jjsolves case ii if j∈Nk(i)j \in N_k(i) and both have the same outcome (same class; for numeric outcomes |yi−yj|≤|y_i - y_j| \letolerance; for survival outcomes the same event status at horizon). With the reachability set R(i)={j:j solves i}R(i) = \{j : j \text{ solves } i\} and the coverage set C(i)={i′:i solves i′}C(i) = \{i' : i \text{ solves } i'\}:

  • noisy (Wilson, 1972): the majority of Nk(i)N_k(i) (the mean, for numeric outcomes) disagrees with yiy_i. Noisy cases are mislabelled or exceptional; removing them usually improves predictions.
  • pivotal (Smyth & Keane, 1995): R(i)=∅R(i) = \emptyset. No other case solves ii; removing it loses competence.
  • auxiliary: some j∈R(i)j \in R(i) covers everything ii covers, C(i)∪{i}⊆C(j)∪{j}C(i) \cup \{i\} \subseteq C(j) \cup \{j\}. The case is redundant and can be removed to keep the case base small.
assessment <- cox$assess_cases(k = 10, horizon = 365)
table(category = assessment$category, noisy = assessment$noisy, useNA = "ifany")
##            noisy
## category    FALSE TRUE <NA>
##   pivotal       0    1    0
##   auxiliary    95   57    0
##   other         7   12    0
##   <NA>          0    0   41

Cases censored before the horizon have no known outcome and are not assessed (NA). Most cases are auxiliary: the case base is redundant, as is typical. Noisy cases are the patients whose survival differs from that of similar patients.

Choosing an approach

Regression (Cox, linear, logistic) Boosting (SHAP) Random forest (depth, proximity, RF-GAP) Gower
Weights the features by estimated effect on the outcome learned effect on the outcome number of splits (favours continuous features) scale (equal or user weights)
Irrelevant features small weight, shrinking with more cases substantial weight on small data substantial weight on small data full weight
Needs an outcome yes yes yes no
Non-linear effects, interactions if specified (splines, *) automatic automatic no
Distance unit outcome scale (log HR, log OR, yy) outcome scale (margin) none share of features
Explanation contribution per term SHAP value per feature split variables where paths diverge per-feature difference
Assumptions model correctly specified (e.g. PH) objective (e.g. PH); tuning few none
Deterministic yes yes (no subsampling) no (seed) yes
Cost per pair number of terms number of features number of trees number of features
Retain without refitting yes yes depth and original proximity: yes; OOB, RF-GAP: no yes

Some rules of thumb:

  • Start with the regression model when the outcome is well described by a regression model, or when the distance must be explained and defended (e.g. to clinicians). Check the model first; the distance inherits its assumptions.
  • Use gradient boosting with the SHAP distance when the relationships are complex but the distance should keep a meaning on the outcome scale and be explained per feature. Regularise the model and check the stability of the neighbours.
  • Use a random forest when the relationships are complex or unknown, when there are many features, or when the regression model does not fit well. Prefer RF-GAP when the retrieved cases should explain the forest’s prediction, the depth distance for a finer ranking of the neighbours.
  • Use the Gower distance as a baseline, when there is no outcome, or when the features were chosen by experts and are all relevant.
  • Compare them on held-out data with evaluate() / evaluate_survival(). In the benchmark article, the predictive performance of the distances is similar; with irrelevant features, the Gower distance loses the most accuracy.

References