Skip to content

Instantly share code, notes, and snippets.

@mrecos
Created January 24, 2017 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrecos/660eabad8010ebf6fc2180520938d26b to your computer and use it in GitHub Desktop.
Save mrecos/660eabad8010ebf6fc2180520938d26b to your computer and use it in GitHub Desktop.
Analytical solution to Logistic Kernel Ridge Regression in R. Arguments: K = Gram or kernel matrix, y = response, lambda = regularizing coefficient
KRR_logit <- function(K,y, lambda){
#### Logistic KRR
# KRR_logit(K,presence)
N = nrow(K)
alpha = rep(1/N, N) # initialize alpha parameters
Kalpha = as.vector(K %*% alpha)
spec = 1 + exp(-Kalpha)
pi = 1 / spec
diagW = pi * (1 - pi)
e = (y - pi) / diagW
q = Kalpha + e
ident.N <- diag(rep(1,N)) # added by me
theSol = solve(K + lambda * ident.N, q)
log_pred <- 1 / (1 + exp(-as.vector(K %*% theSol)))
return(list(pred = log_pred, alphas = theSol))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment