Skip to content

Instantly share code, notes, and snippets.

@thomvolker
Created August 23, 2024 14:28
Show Gist options
  • Save thomvolker/afdca959f92f29b410ca05c861caae75 to your computer and use it in GitHub Desktop.
Save thomvolker/afdca959f92f29b410ca05c861caae75 to your computer and use it in GitHub Desktop.

The following code shows how to obtain density ratio estimates that are regularized to $1$ instead of $0$ (or an estimated intercept).

pred_adapt <- function(nu, de, ce, sigma, lambda) {
  Knu <- densityratio::distance(as.matrix(nu), as.matrix(ce), TRUE) |> kernel_gaussian(sigma)
  Kde <- densityratio::distance(as.matrix(de), as.matrix(ce), TRUE) |> kernel_gaussian(sigma)

  Kdede <- crossprod(Kde) / nrow(Kde)
  Knunu <- colMeans(Knu)
  alpha <- solve(Kdede[-1, -1] + lambda * diag(ncol(Kde)-1), Knunu[-1] - Kdede[1, -1])
  alpha <- c(1, alpha)
  list(Knu = Knu, Kde = Kde, alpha = alpha)
}





r_adap <- pred_adapt(r$model_matrices$nu,
                     r$model_matrices$de,
                     r$model_matrices$ce,
                     r$sigma_opt,
                     r$lambda_opt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment