El siguiente ejemplo ajusta un modelo glm con el dataset titanic. Luego crea una función que devuelve el script Qlik para calcular la probabilidad. Esta función solo sirve si todas las variables son numéricas.
Nota: Para detalles sobre regresión logística, ver nota publicada AQUI.
Conceptualmente seria así:
R Script:
# Datos y Modelo #--------------------------------------------------------------- datos_url <- "https://www.dropbox.com/s/r6panhu58ps38d2/train_titanic.csv?dl=1" datos <- read.csv(datos_url) datos <- datos[, c("Survived", "Pclass", "SibSp", "Parch")] m_glm <- glm(Survived ~.,datos, family = binomial(link="logit")) # Funcion para Print de script #--------------------------------------------------------------- glm_to_qlik <- function(m_glm, decimales, id, tbl){ xcoef = data.frame( feature = names(m_glm$coefficients), coeficientes = as.vector(round(m_glm$coefficients, decimales))) xcoef = xcoef[complete.cases(xcoef), ] for (i in seq(nrow(xcoef))){ xcoef_val = as.numeric(xcoef[i, 2]) xcoef_key = as.character(xcoef[i, 1]) if (xcoef_key == "(Intercept)"){ cat(noquote("LOAD *, exp(log_odds) / (1 + exp(log_odds)) as prob;" ), "\n") cat(noquote(paste("LOAD", id, ",")),"\n") cat(noquote(paste(xcoef_val, " + ")), "\n") } else if (i != nrow(xcoef)){ cat(noquote(paste(xcoef_key, "*", xcoef_val, "+" )), "\n") }else{ cat(noquote(paste(xcoef_key, "*", xcoef_val, "as log_odds" ) ), "\n") cat(noquote(paste("From ", tbl, "(qvd);") ), "\n") } } } # Print qlik script #--------------------------------------------------------------- glm_to_qlik(m_glm, 7, id="PassengerId", tbl="miTabla.qvd")
Referencias
1. Para calcular reg-log en Tableau
https://boraberan.wordpress.com/2016/08/11/using-your-r-models-for-in-database-scoring/
2. Para tener el scrip en SQL
https://stackoverflow.com/questions/28698395/glm-fit-logistic-regression-to-sql
No hay comentarios:
Publicar un comentario