|
| 1 | +#' Two stage covariate filtering |
| 2 | +#' |
| 3 | +#' The `covariance_filter` returns a set of covariates for land use land cover change |
| 4 | +#' (LULCC) models based on a two-stage variable selection: a first statistical fit |
| 5 | +#' estimates a covariate's quality for a given prediction task. A second step selects |
| 6 | +#' all variables below a given correlation threshold: We iterate over a correlation |
| 7 | +#' matrix ordered in the first step. Starting within the leftmost column, all rows (i.e. |
| 8 | +#' candidates) greater than the given threshold are dropped from the full set of |
| 9 | +#' candidates. This candidate selection is retained and used to select the next column, |
| 10 | +#' until no further columns are left to investigate. The columns that were iterated over |
| 11 | +#' are those returned as a character vector of selected variable names. |
| 12 | +#' |
| 13 | +#' @param data A data.table of target variable and candidate covariates to be filtered; |
| 14 | +#' wide format with one predictor per column. |
| 15 | +#' @param result_col Name of the column representing the transition results (0: no |
| 16 | +#' trans, 1: trans) |
| 17 | +#' @param rank_fun Optional function to compute ranking scores for each covariate. |
| 18 | +#' Should take arguments (x, y, weights, ...) and return a single numeric value |
| 19 | +#' (lower = better). Defaults to polynomial GLM p-value ranking. |
| 20 | +#' @param weights Optional vector of weights to be used in the ranking function. Defaults to |
| 21 | +#' class-balanced weights |
| 22 | +#' @param corcut Numeric threshold (0-1) for correlation filtering. Covariates with correlation |
| 23 | +#' coefficients above this threshold will be filtered out. Default is 0 (no filtering). |
| 24 | +#' @param ... Additional arguments passed to rank_fun. |
| 25 | +#' |
| 26 | +#' @return A set of column names (covariates) to retain |
| 27 | +#' |
| 28 | +#' @details |
| 29 | +#' The function first ranks covariates using the provided ranking function (default: |
| 30 | +#' quasibinomial polynomial GLM). Then, it iteratively removes highly (Pearson) |
| 31 | +#' correlated variables based on the correlation cutoff threshold, preserving variables |
| 32 | +#' in order of their ranking. See |
| 33 | +#' <https://github.com/ethzplus/evoland-plus-legacy/blob/main/R/lulcc.covfilter.r> for |
| 34 | +#' where the concept came from. The original author was Antoine Adde, with edits by |
| 35 | +#' Benjamin Black. A similar mechanism is found in <https://github.com/antadde/covsel/>. |
| 36 | +#' |
| 37 | +#' @name covariance_filter |
| 38 | +#' |
| 39 | +#' @export |
| 40 | + |
| 41 | +covariance_filter <- function( |
| 42 | + data, |
| 43 | + result_col = "result", |
| 44 | + rank_fun = rank_poly_glm, |
| 45 | + weights = compute_balanced_weights(data[[result_col]]), |
| 46 | + corcut = 0.7, |
| 47 | + ... |
| 48 | +) { |
| 49 | + # Early return for single covariate |
| 50 | + if (ncol(data) == 1) { |
| 51 | + return(data) |
| 52 | + } |
| 53 | + |
| 54 | + data.table::setDT(data) |
| 55 | + |
| 56 | + # Validate binary outcome |
| 57 | + stopifnot( |
| 58 | + "corcut must be between 0 and 1" = corcut >= 0 && corcut <= 1 |
| 59 | + ) |
| 60 | + |
| 61 | + # Compute ranking scores for all covariates (vectorized where possible) |
| 62 | + scores <- vapply( |
| 63 | + data[, -..result_col], |
| 64 | + rank_fun, |
| 65 | + FUN.VALUE = numeric(1), |
| 66 | + y = data[[result_col]], |
| 67 | + weights = weights, |
| 68 | + ... |
| 69 | + ) |
| 70 | + |
| 71 | + # Sort by scores (lower = better/more significant) |
| 72 | + ranked_order <- names(sort(scores)) |
| 73 | + |
| 74 | + # If no correlation filtering needed, return ranked predictors |
| 75 | + if (corcut == 1) { |
| 76 | + return(ranked_order) |
| 77 | + } |
| 78 | + |
| 79 | + # Compute correlation matrix once |
| 80 | + cor_mat <- abs(cor(data[, ..ranked_order], use = "pairwise.complete.obs")) |
| 81 | + |
| 82 | + # Iteratively select covariates based on correlation threshold |
| 83 | + select_by_correlation(cor_mat, corcut) |
| 84 | +} |
| 85 | + |
| 86 | + |
| 87 | +#' @describeIn covariance_filter Default ranking function using polynomial GLM. Returns |
| 88 | +#' the lower p value for each of the polynomial terms |
| 89 | +#' @param x A numeric vector representing a single covariate |
| 90 | +#' @param y A binary outcome vector (0/1) |
| 91 | +#' @param weights Optional weights vector |
| 92 | +#' @keywords internal |
| 93 | +rank_poly_glm <- function(x, y, weights = NULL, ...) { |
| 94 | + fit <- glm.fit( |
| 95 | + x = cbind(1, poly(x, degree = 2, simple = TRUE)), |
| 96 | + y = y, |
| 97 | + family = quasibinomial(), |
| 98 | + weights = weights |
| 99 | + ) |
| 100 | + |
| 101 | + # Get p-values for linear and quadratic terms |
| 102 | + coef_summary <- summary.glm(fit)$coefficients |
| 103 | + |
| 104 | + # Return minimum p-value (most significant term) |
| 105 | + min(coef_summary[2:3, 4], na.rm = TRUE) |
| 106 | +} |
| 107 | + |
| 108 | + |
| 109 | +#' @describeIn covariance_filter Compute class-balanced weights for imbalanced binary |
| 110 | +#' outcomes; returns a numeric vector |
| 111 | +#' @param trans_result Binary outcome vector (0/1) |
| 112 | +#' @param legacy Bool, use legacy weighting? |
| 113 | +#' @keywords internal |
| 114 | +compute_balanced_weights <- function(trans_result, legacy = FALSE) { |
| 115 | + n_total <- length(trans_result) |
| 116 | + n_trans <- sum(trans_result) |
| 117 | + n_non_trans <- sum(!trans_result) |
| 118 | + |
| 119 | + # Compute inverse frequency weights |
| 120 | + weights <- numeric(n_total) |
| 121 | + |
| 122 | + if (legacy) { |
| 123 | + # I found this weighting in evoland-plus-legacy, but the models wouldn't converge |
| 124 | + # https://github.com/ethzplus/evoland-plus-legacy/blob/main/R/lulcc.splitforcovselection.r |
| 125 | + # This is actually just setting the underrepresented class to the rounded imbalance ratio |
| 126 | + weights[!trans_result] <- 1 |
| 127 | + weights[trans_result] <- round(n_non_trans / n_trans) |
| 128 | + return(weights) |
| 129 | + } |
| 130 | + |
| 131 | + # This is the heuristic in scikit-learn, n_samples / (n_classes * np.bincount(y)) |
| 132 | + # https://scikit-learn.org/stable/modules/generated/sklearn.utils.class_weight.compute_class_weight.html #nolint |
| 133 | + # This weighting maintains the exact imbalance ratio |
| 134 | + weights[trans_result] <- n_total / (2 * n_trans) |
| 135 | + weights[!trans_result] <- n_total / (2 * n_non_trans) |
| 136 | + |
| 137 | + weights |
| 138 | +} |
| 139 | + |
| 140 | + |
| 141 | +#' @describeIn covariance_filter Implements the iterative selection procedure. |
| 142 | +#' @param cor_mat Absolute correlation matrix |
| 143 | +#' @param corcut Correlation cutoff threshold |
| 144 | +#' @keywords internal |
| 145 | +select_by_correlation <- function(cor_mat, corcut) { |
| 146 | + var_names <- colnames(cor_mat) |
| 147 | + |
| 148 | + # Early return if all correlations are below threshold |
| 149 | + if (all(cor_mat[lower.tri(cor_mat)] < corcut)) { |
| 150 | + return(var_names) |
| 151 | + } |
| 152 | + |
| 153 | + selected <- character(0) |
| 154 | + remaining_idx <- seq_along(var_names) |
| 155 | + |
| 156 | + while (length(remaining_idx) > 0) { |
| 157 | + # Select the first remaining variable (highest ranked) |
| 158 | + current_var <- remaining_idx[1] |
| 159 | + selected <- c(selected, var_names[current_var]) |
| 160 | + |
| 161 | + # Find variables with correlation <= corcut with current variable |
| 162 | + # (excluding the variable itself) |
| 163 | + keep_idx <- which(cor_mat[remaining_idx, current_var] <= corcut) |
| 164 | + remaining_idx <- remaining_idx[keep_idx] |
| 165 | + } |
| 166 | + |
| 167 | + selected |
| 168 | +} |
0 commit comments