| Title: | Case Based Reasoning |
|---|---|
| Description: | Case-based reasoning is a problem-solving methodology that involves solving a new problem by referring to the solution of a similar problem in a large set of previously solved problems. The key aspect of Case Based Reasoning is to determine the problem that "most closely" matches the new problem at hand. This is achieved by defining a family of distance functions and using these distance functions as parameters for local averaging regression estimates of the final result. The optimal distance function is chosen based on a specific error measure used in regression estimation. This approach allows for efficient problem-solving by leveraging past experiences and adapting solutions from similar cases. The underlying concept is inspired by the work of Dippon J. et al. (2002) <doi:10.1016/S0167-9473(02)00058-0>. |
| Authors: | Simon Mueller [aut, cre], PD Dr. Juergen Dippon [ctb] |
| Maintainer: | Simon Mueller <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.5.0 |
| Built: | 2026-11-23 04:40:50 UTC |
| Source: | https://github.com/cran/CaseBasedReasoning |
dist
Converts a distance vector into an object of class dist
asDistObject(x, n, method) as_dist_object(x, n, method)asDistObject(x, n, method) as_dist_object(x, n, method)
x |
data vector |
n |
length of x |
method |
method description |
Root class for common functionality of this package
Root class for common functionality of this package
modelthe statistical model
datatraining data
model_fittrained object
formulaObject of class formula or character describing the model fit
termsterms of the formula (term labels, e.g. "rcs(age, 3)")
variablesvariables used by the terms of the formula
endpointTarget variable
dist_matrixA matrix with distances
order_matrixA matrix with the order indices for similar cases search
endPointDeprecated: use endpoint instead.
distMatDeprecated: use dist_matrix instead.
orderMatDeprecated: use order_matrix instead.
new()
Initialize object for searching similar cases
CBRBase$new(formula, data)
formulaObject of class formula or character describing the model fit
dataTraining data of class data.frame
fit()
Fit the Model
CBRBase$fit()
calc_distance_matrix()
Calculates the distance matrix
CBRBase$calc_distance_matrix(query = NULL)
queryQuery data of class data.frame
get_similar_cases()
Extracts similar cases
CBRBase$get_similar_cases( query, k = 1, add_distance = TRUE, merge = FALSE, exclude_self = FALSE )
queryQuery data of class data.frame
knumber of similar cases
add_distanceAdd distance to result data.frame
mergeAdd query data to matched cases data.frame
exclude_selfExclude training cases whose row name equals the query's row name. Use this when the query rows are taken from the training data, so that a case is not returned as its own nearest neighbour.
predict_survival()
Predict survival curves from the k most similar
training cases: a Kaplan-Meier estimate over the retrieved
cases of each query (Lowsky et al., 2013). Only for survival
endpoints (Surv(time, status)).
CBRBase$predict_survival(query, k = 10, times = NULL, weighted = FALSE)
queryQuery data of class data.frame
knumber of similar cases
timestime points; default: the event times of the training data
weightedIf TRUE, cases are weighted with a
tricube kernel of their distance to the query.
A matrix of survival probabilities with one row per
query and one column per time point (attribute times).
evaluate_survival()
Evaluate survival predictions from retrieved cases on test
data: Uno's concordance index and the IPCW (integrated)
Brier score. Use it to choose k and the distance
method on held-out data.
CBRBase$evaluate_survival( test, k = 10, times = NULL, tau = NULL, weighted = FALSE )
testTest data with the endpoint columns
knumber of similar cases
timestime points for the Brier score; default: 20 points between the 10% and 90% quantile of the training event times
tautime horizon for the concordance index (risk score
); default: the largest of times
weightedpassed to predict_survival()
A list with c_index (Uno's C), ibs
(integrated Brier score) and brier (data.frame with
the Brier score at each time).
get_counterfactual_cases()
Counterfactual cases: the nearest training cases whose outcome differs from the query's outcome ("native counterfactuals", Keane & Smyth, 2020).
The query's outcome is taken from its endpoint columns if
present, otherwise it is predicted from its k_outcome
most similar cases (majority class, mean, or majority
event status). A training case is a counterfactual if
classification endpoint: its class differs;
numeric endpoint: its outcome differs by at least
min_diff (default: standard deviation of the
training outcome);
survival endpoint: its event status at
horizon differs (event before horizon vs.
followed beyond horizon; cases censored before
horizon are not used).
CBRBase$get_counterfactual_cases( query, k = 1, horizon = NULL, min_diff = NULL, k_outcome = 10 )
queryQuery data of class data.frame
knumber of counterfactual cases per query
horizontime horizon for survival endpoints (default: median training event time)
min_diffminimum outcome difference for numeric endpoints
k_outcomenumber of similar cases used to predict the query's outcome if it is not given
A data.frame like get_similar_cases() with the
additional column queryOutcome.
explain_match()
Explain why a training case is similar to a query. For regression models: the contribution of each term to the linear predictor of query and case, and its share of the distance. For random forests: in the trees where query and case end in different terminal nodes, the split variable at which their paths diverge.
CBRBase$explain_match(query, case)
queryOne query case (data.frame with one row)
caseOne case (data.frame with one row), e.g. a row
returned by get_similar_cases()
A data.frame with one row per term (regression) or variable (random forest).
clone()
The objects of this class are cloneable with this method.
CBRBase$clone(deep = FALSE)
deepWhether to make a deep clone.
Lowsky, D. J. et al. (2013). A K-nearest neighbors survival probability prediction method. Statistics in Medicine, 32(12), 2062–2069. doi:10.1002/sim.5673
Uno, H. et al. (2011). On the C-statistics for evaluating overall adequacy of risk prediction procedures with censored survival data. Statistics in Medicine, 30(10), 1105–1117. doi:10.1002/sim.4154
Graf, E. et al. (1999). Assessment and comparison of prognostic classification schemes for survival data. Statistics in Medicine, 18(17-18), 2529–2545.
Keane, M. T. and Smyth, B. (2020). Good Counterfactuals and Where to Find Them: A Case-Based Technique for Generating Counterfactuals for Explainable AI. ICCBR 2020, LNCS 12311, 163–178. doi:10.1007/978-3-030-58342-2_11
Cox-Beta Model for Case-Based-Reasoning
Cox-Beta Model for Case-Based-Reasoning
Regression beta coefficients obtained from a CPH regression model fitted on the training data are used for building a weighted distance measure between train and test data. Afterwards, we will use these weights for calculating a (n x m)-distance matrix, where n is the number of observations in the training data, and m is the number of observations of the test data. The user can use this distance matrix for further cluster analysis or for extracting for each test observation k (= 1,...,l) similar cases from the train data. We use the rms-package for model fitting, variable selection, and checking model assumptions. If the user omits the test data, this functions returns a n x n-distance matrix.
CaseBasedReasoning::CBRBase -> CaseBasedReasoning::RegressionModel -> CoxModel
modelthe statistical model
model_paramsrms arguments
CaseBasedReasoning::CBRBase$calc_distance_matrix()CaseBasedReasoning::CBRBase$evaluate_survival()CaseBasedReasoning::CBRBase$explain_match()CaseBasedReasoning::CBRBase$get_counterfactual_cases()CaseBasedReasoning::CBRBase$get_similar_cases()CaseBasedReasoning::CBRBase$initialize()CaseBasedReasoning::CBRBase$predict_survival()CaseBasedReasoning::RegressionModel$fit()CaseBasedReasoning::RegressionModel$print()CaseBasedReasoning::RegressionModel$variable_selection()check_ph()
Check proportional hazard assumption graphically
CoxModel$check_ph()
clone()
The objects of this class are cloneable with this method.
CoxModel$clone(deep = FALSE)
deepWhether to make a deep clone.
This function returns for each observation the pairwise sum of edges between the corresponding terminal nodes over each tree in the random forest.
depth_distance(x, y = NULL, rfObject)depth_distance(x, y = NULL, rfObject)
x |
A data.frame with the same columns as in the training data of the RandomForest model |
y |
A data.frame with the same columns as in the training data of the RandomForest model |
rfObject |
|
library(ranger) rf <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) depth_distance(x = iris[, -5], rfObject = rf)library(ranger) rf <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) depth_distance(x = iris[, -5], rfObject = rf)
Distance calculation based on RandomForest Proximity or Depth
distanceRandomForest( x, y = NULL, rfObject, method = "Proximity", threads = NULL ) distance_random_forest( x, y = NULL, rfObject, method = "Proximity", threads = NULL, proximity_type = c("original", "oob", "rfgap") )distanceRandomForest( x, y = NULL, rfObject, method = "Proximity", threads = NULL ) distance_random_forest( x, y = NULL, rfObject, method = "Proximity", threads = NULL, proximity_type = c("original", "oob", "rfgap") )
x |
a data.frame |
y |
a second data.frame |
rfObject |
|
method |
distance calculation method, Proximity (Default) or Depth. |
threads |
number of threads to use. The previous RcppParallel thread setting is restored on exit. |
proximity_type |
type of proximity for |
a dist or a matrix object with pairwise distance of
observations in x vs y (if not null)
library(ranger) # proximity pairwise distances rf.fit <- ranger(Species ~ ., data = iris, num.trees = 500, write.forest = TRUE) distance_random_forest(x = iris[, -5], rfObject = rf.fit, method = "Proximity", threads = 1) # depth distance for train versus test subset set.seed(1234L) learn <- sample(1:150, 100) test <- (1:150)[-learn] rf.fit <- ranger(Species ~ ., data = iris[learn, ], num.trees = 500, write.forest = TRUE) distance_random_forest(x = iris[learn, -5], y = iris[test, -5], rfObject = rf.fit, method = "Depth")library(ranger) # proximity pairwise distances rf.fit <- ranger(Species ~ ., data = iris, num.trees = 500, write.forest = TRUE) distance_random_forest(x = iris[, -5], rfObject = rf.fit, method = "Proximity", threads = 1) # depth distance for train versus test subset set.seed(1234L) learn <- sample(1:150, 100) test <- (1:150)[-learn] rf.fit <- ranger(Species ~ ., data = iris[learn, ], num.trees = 500, write.forest = TRUE) distance_random_forest(x = iris[learn, -5], y = iris[test, -5], rfObject = rf.fit, method = "Depth")
first two columns are terminal node IDs; If an ID pair do not appear in a tree -1 is inserted
edges_between_terminal_nodes(rfObject)edges_between_terminal_nodes(rfObject)
rfObject |
|
a matrix object with pairwise terminal node edge length
library(ranger) rf.fit <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) edges_between_terminal_nodes(rf.fit)library(ranger) rf.fit <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) edges_between_terminal_nodes(rf.fit)
Generates a uniform grid over the distribution of the time2event variable, calculates closest point and returns this point for each input time2event element. Memory consumption will increase when performing the randomForest model with many unique time2event values. Therefore, we offer a reduction of the time2event values by choosing closest elements in a grid.
generate_grid(t2e, grid_length = 250)generate_grid(t2e, grid_length = 250)
t2e |
numeric vector with time2event values |
grid_length |
number of grid elements |
a list with new_t2e and grid_error
Linear Regression Model for Case-Based-Reasoning
Linear Regression Model for Case-Based-Reasoning
CaseBasedReasoning::CBRBase -> CaseBasedReasoning::RegressionModel -> LinearModel
modelthe statistical model
CaseBasedReasoning::CBRBase$calc_distance_matrix()CaseBasedReasoning::CBRBase$evaluate_survival()CaseBasedReasoning::CBRBase$explain_match()CaseBasedReasoning::CBRBase$get_counterfactual_cases()CaseBasedReasoning::CBRBase$get_similar_cases()CaseBasedReasoning::CBRBase$initialize()CaseBasedReasoning::CBRBase$predict_survival()CaseBasedReasoning::RegressionModel$fit()CaseBasedReasoning::RegressionModel$print()CaseBasedReasoning::RegressionModel$variable_selection()clone()
The objects of this class are cloneable with this method.
LinearModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Logistic Regression Model for Case-Based-Reasoning
Logistic Regression Model for Case-Based-Reasoning
CaseBasedReasoning::CBRBase -> CaseBasedReasoning::RegressionModel -> LogisticModel
modelthe statistical model
CaseBasedReasoning::CBRBase$calc_distance_matrix()CaseBasedReasoning::CBRBase$evaluate_survival()CaseBasedReasoning::CBRBase$explain_match()CaseBasedReasoning::CBRBase$get_counterfactual_cases()CaseBasedReasoning::CBRBase$get_similar_cases()CaseBasedReasoning::CBRBase$initialize()CaseBasedReasoning::CBRBase$predict_survival()CaseBasedReasoning::RegressionModel$fit()CaseBasedReasoning::RegressionModel$print()CaseBasedReasoning::RegressionModel$variable_selection()clone()
The objects of this class are cloneable with this method.
LogisticModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Predict method for CoxModel
## S3 method for class 'CoxModel' predict(object, newdata, k = 1, ...)## S3 method for class 'CoxModel' predict(object, newdata, k = 1, ...)
object |
A |
newdata |
Query data of class data.frame |
k |
Number of similar cases to return |
... |
Additional arguments (currently unused) |
A data.frame of similar cases
Predict method for LinearModel
## S3 method for class 'LinearModel' predict(object, newdata, k = 1, ...)## S3 method for class 'LinearModel' predict(object, newdata, k = 1, ...)
object |
A |
newdata |
Query data of class data.frame |
k |
Number of similar cases to return |
... |
Additional arguments (currently unused) |
A data.frame of similar cases
Predict method for LogisticModel
## S3 method for class 'LogisticModel' predict(object, newdata, k = 1, ...)## S3 method for class 'LogisticModel' predict(object, newdata, k = 1, ...)
object |
A |
newdata |
Query data of class data.frame |
k |
Number of similar cases to return |
... |
Additional arguments (currently unused) |
A data.frame of similar cases
Predict method for RFModel
## S3 method for class 'RFModel' predict(object, newdata, k = 1, ...)## S3 method for class 'RFModel' predict(object, newdata, k = 1, ...)
object |
An |
newdata |
Query data of class data.frame |
k |
Number of similar cases to return |
... |
Additional arguments (currently unused) |
A data.frame of similar cases
Print method for CoxModel
## S3 method for class 'CoxModel' print(x, ...)## S3 method for class 'CoxModel' print(x, ...)
x |
A |
... |
Additional arguments (currently unused) |
Print method for LinearModel
## S3 method for class 'LinearModel' print(x, ...)## S3 method for class 'LinearModel' print(x, ...)
x |
A |
... |
Additional arguments (currently unused) |
Print method for LogisticModel
## S3 method for class 'LogisticModel' print(x, ...)## S3 method for class 'LogisticModel' print(x, ...)
x |
A |
... |
Additional arguments (currently unused) |
Print method for RFModel
## S3 method for class 'RFModel' print(x, ...)## S3 method for class 'RFModel' print(x, ...)
x |
An |
... |
Additional arguments (currently unused) |
Random forest proximities between the observations in x and
y, converted to the distance by default.
proximity_distance( x, y = NULL, rfObject, as_dist = TRUE, type = c("original", "oob", "rfgap") )proximity_distance( x, y = NULL, rfObject, as_dist = TRUE, type = c("original", "oob", "rfgap") )
x |
a new dataset. For |
y |
a second new dataset (Default: NULL) |
rfObject |
|
as_dist |
Bool, convert proximity |
type |
proximity type: |
Three types of proximity are available:
"original"Breiman's proximity: the share of trees in which two observations share a terminal node. In-sample proximities are inflated because observations are counted in the trees they were trained on.
"oob"Only trees in which the training observation (and, for in-sample queries, the query) is out-of-bag are used.
"rfgap"RF-GAP proximities (Rhodes, Cutler & Moon, 2023):
for query and training observation ,
, where are the trees in which
is out-of-bag (all trees for new data), is the in-bag count
of and the total in-bag count in 's leaf.
For each query the proximities sum to 1, and the proximity-weighted
average of the training outcomes reproduces the forest's (out-of-bag)
prediction for regression forests.
"oob" and "rfgap" need the in-bag counts: fit the forest
with keep.inbag = TRUE and pass the forest's training data as
x (same rows, same order). If y is NULL, the training
data is also used as query (in-sample proximities).
For type = "original": a dist object (if y is
NULL) or a matrix with pairwise proximities (or distances, see
as_dist) of observations in x (rows) vs y (columns). For the other
types always a matrix; RF-GAP proximities are not symmetric.
Rhodes, J. S., Cutler, A. and Moon, K. R. (2023). Geometry- and Accuracy-Preserving Random Forest Proximities. IEEE Transactions on Pattern Analysis and Machine Intelligence, 45(9), 10947–10959. doi:10.1109/TPAMI.2023.3263774
library(ranger) rf <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) proximity_distance(x = iris[, -5], rfObject = rf) set.seed(1234L) learn <- sample(1:150, 100) test <- (1:150)[-learn] rf <- ranger(Species ~ ., data = iris[learn, ], num.trees = 500, write.forest = TRUE, keep.inbag = TRUE) proximity_distance(x = iris[learn, -5], y = iris[test, -5], rfObject = rf) proximity_distance(x = iris[learn, -5], y = iris[test, -5], rfObject = rf, type = "rfgap")library(ranger) rf <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) proximity_distance(x = iris[, -5], rfObject = rf) set.seed(1234L) learn <- sample(1:150, 100) test <- (1:150)[-learn] rf <- ranger(Species ~ ., data = iris[learn, ], num.trees = 500, write.forest = TRUE, keep.inbag = TRUE) proximity_distance(x = iris[learn, -5], y = iris[test, -5], rfObject = rf) proximity_distance(x = iris[learn, -5], y = iris[test, -5], rfObject = rf, type = "rfgap")
Transform trees of a ranger-object to a matrix
ranger_forests_to_matrix(rfObject)ranger_forests_to_matrix(rfObject)
rfObject |
|
a matrix object with
Column 1: tree ID
Column 2: node ID
Column 3: child node ID 1
Column 4: child node ID 2
library(ranger) rf.fit <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) forest_matrix <- ranger_forests_to_matrix(rf.fit)library(ranger) rf.fit <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) forest_matrix <- ranger_forests_to_matrix(rf.fit)
Root class for Regression Models, e.g., CPH, logistic, and linear regression
Root class for Regression Models, e.g., CPH, logistic, and linear regression
CaseBasedReasoning::CBRBase -> RegressionModel
model_paramsrms arguments
weightsWeights for distance calculation
CaseBasedReasoning::CBRBase$calc_distance_matrix()CaseBasedReasoning::CBRBase$evaluate_survival()CaseBasedReasoning::CBRBase$explain_match()CaseBasedReasoning::CBRBase$get_counterfactual_cases()CaseBasedReasoning::CBRBase$get_similar_cases()CaseBasedReasoning::CBRBase$initialize()CaseBasedReasoning::CBRBase$predict_survival()print()
Prints information of the initialized object
RegressionModel$print()
variable_selection()
Fast backward variable selection with penalization (rms::fastbw)
RegressionModel$variable_selection(update = FALSE, ...)
updateIf TRUE, restrict the model's formula and terms to the
selected variables. The model must then be fitted again with $fit().
...Further arguments passed to rms::fastbw, e.g.
rule or sls.
Character vector of the selected (retained) variables.
fit()
Fit the regression model
RegressionModel$fit()
clone()
The objects of this class are cloneable with this method.
RegressionModel$clone(deep = FALSE)
deepWhether to make a deep clone.
RandomForest Model for Searching Similar Cases
RandomForest Model for Searching Similar Cases
This class uses the proximity or depth matrix of the RandomForest algorithm as a similarity matrix of training and query observations. By default all cases with at least one missing values are dropped from learning, calculating the distance matrix and searching for similar cases.
CaseBasedReasoning::CBRBase -> RFModel
modelthe statistical model
model_paramsmodel arguments
dist_methodDistance method
proximity_typeProximity type for dist_method = "Proximity":
"original", "oob" or "rfgap"
(see proximity_distance).
print()
Prints information of the initialized object
RFModel$print()
new()
Initialize a RandomForest object for searching similar cases.
RFModel$new(formula, data, ...)
formulaObject of class formula or character describing the model fit.
dataTraining data of class data.frame
...ranger RandomForest arguments. write.forest is always
set to TRUE; verbose defaults to FALSE.
fit()
Fit the RandomForest
RFModel$fit()
set_distance_method()
Set the distance method. Available are Proximity and Depth
RFModel$set_distance_method(method = "Depth", proximity_type = "original")
methodDistance calculation method (default: Depth)
proximity_typeProximity type for method = "Proximity":
"original" (default), "oob" or "rfgap". The
latter two use the forest's in-bag counts; for a query given to
get_similar_cases() or calc_distance_matrix() the query is
treated as new data, without a query (calc_distance_matrix()) the
in-sample, out-of-bag version is computed.
clone()
The objects of this class are cloneable with this method.
RFModel$clone(deep = FALSE)
deepWhether to make a deep clone.
Englund, C. and Verikas, A. (2012). A novel approach to estimate proximity in a random forest: An exploratory study. Expert Systems with Applications, 39(17), 13046–13050. doi:10.1016/j.eswa.2012.05.094
Summary method for CoxModel
## S3 method for class 'CoxModel' summary(object, ...)## S3 method for class 'CoxModel' summary(object, ...)
object |
A |
... |
Additional arguments (currently unused) |
Summary method for LinearModel
## S3 method for class 'LinearModel' summary(object, ...)## S3 method for class 'LinearModel' summary(object, ...)
object |
A |
... |
Additional arguments (currently unused) |
Summary method for LogisticModel
## S3 method for class 'LogisticModel' summary(object, ...)## S3 method for class 'LogisticModel' summary(object, ...)
object |
A |
... |
Additional arguments (currently unused) |
Summary method for RFModel
## S3 method for class 'RFModel' summary(object, ...)## S3 method for class 'RFModel' summary(object, ...)
object |
An |
... |
Additional arguments (currently unused) |
Extracts for each observation and for each tree in the forest the terminal node id. The index of terminal nodes are starting with 1, e.g., the root node has id 1
terminalNodes(x, rfObject) terminal_nodes(x, rfObject)terminalNodes(x, rfObject) terminal_nodes(x, rfObject)
x |
a data.frame |
rfObject |
|
Matrix with terminal node IDs for all observations in x (rows) and trees (columns)
library(ranger) rf.fit <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) dfNodes <- terminal_nodes(iris[, -5], rf.fit)library(ranger) rf.fit <- ranger(Species ~ ., data = iris, num.trees = 5, write.forest = TRUE) dfNodes <- terminal_nodes(iris[, -5], rf.fit)
Computes .
weightedDistance(x, y = NULL, weights = NULL) weighted_distance(x, y = NULL, weights = NULL)weightedDistance(x, y = NULL, weights = NULL) weighted_distance(x, y = NULL, weights = NULL)
x |
a numeric matrix |
y |
a second numeric matrix with the same columns as |
weights |
a vector of weights, one per column (default: all 1) |
a dist object (if y is NULL) or a
nrow(x) x nrow(y) matrix
x <- as.matrix(iris[1:5, 1:4]) weighted_distance(x) weighted_distance(x, as.matrix(iris[6:7, 1:4]), weights = c(1, 1, 2, 2))x <- as.matrix(iris[1:5, 1:4]) weighted_distance(x) weighted_distance(x, as.matrix(iris[6:7, 1:4]), weights = c(1, 1, 2, 2))