class: center, middle, inverse, title-slide .title[ # Análisis de Datos Categóricos (SOC3070) ] .subtitle[ ## Inferencia en Regresión Logística ] .author[ ###
Mauricio Bucca
Profesor Asistente, Sociología UC ] .date[ ### 29 September, 2025 ] --- class: inverse, center, middle #Regresión Logística ##Inferencia --- ##Configuración -- <br> - Tenemos `\(y_{1}, \dots y_{n}\)` son `\(n\)` variables independientes con distribución `\(\text{Bernoulli}(p_{i})\)` -- - `\(\mathbb{E}(y_{i} \mid x_{i1}, \dots,x_{ik}) = \mathbb{P}(y_{i}=1 \mid x_{i1}, \dots,x_{ik}) = p_{i}\)` <br> -- donde, `$$\ln \frac{p_{i}}{1 - p_{i}} = \beta_{0} + \beta_{1} x_{i1} + \dots + \beta_{k} x_{ik}$$` --- ##Configuración <br> - Tenemos `\(y_{1}, \dots y_{n}\)` son `\(n\)` variables independientes con distribución `\(\text{Bernoulli}(p_{i})\)` - `\(\mathbb{E}(y_{i} \mid x_{i1}, \dots,x_{ik}) = \mathbb{P}(y_{i}=1 \mid x_{i1}, \dots,x_{ik}) = p_{i}\)` <br> donde, .content-box-blue[ `$$\underbrace{\ln \frac{p_{i}}{1 - p_{i}}}_{\text{Link logit}(p_{i})} = \overbrace{\beta_{0} + \beta_{1} x_{i1} + \dots + \beta_{k} x_{ik}}^{\text{Predictor lineal } \eta_{i}}$$` ] -- - .bold[Inferencia]: ¿que podemos decir sobre `\(\hat{\beta}_{0},\hat{\beta}_{1}, \dots, \hat{\beta}_{k}\)` (o cualquier producto de éstos) más allá de nuestra muestra? --- class: inverse, center, middle ## Inferencia estadística para regresión logística (y GLMs) --- ## Inferencia acerca de parámetros del modelo - Los coeficientes de un GLM son estimados via MLE. -- Un ML "estimate" `\(\hat{\theta}\)` tiene las siguientes propiedades: -- .img-right[] .pull-left[ - Es .bold[consistente]: `\(\hat{\theta} \xrightarrow{p} \theta\)`. Es decir, en la medida que `\(n \to \infty\)`, el estimador `\(\hat{\theta}\)` tiende en probabilidad a `\(\theta\)`, el valor verdadero del parámetro. ] .pull-right[ ] -- .pull-left[ - Es .bold[insesgado]: `\(\mathbb{E}(\hat{\theta}) = \theta\)`. ] .pull-right[ ] -- .pull-left[ - Distribuye .bold[asintónticamente normal]: `\(\hat{\theta} \xrightarrow{d} \mathcal{N}(\theta, \frac{\sigma_{\theta}}{\sqrt{n}})\)`. Es decir, no solo converge al valor verdadero, sino que converge rápidamente ( `\(1/\sqrt{n}\)` ). ] .pull-right[ ] -- Notar que `\(\frac{\sigma_{\theta}}{\sqrt{n}}\)` es el "standard error" (SE) de `\(\theta\)`. <style type="text/css"> .pull-right ~ * { clear: unset; } .pull-right + * { clear: both; } </style> --- ## Inferencia acerca de parámetros del modelo: intervalos de confianza Dado que `\(\hat{\theta} \sim \mathcal{N}(\theta, \frac{\sigma_{\theta}}{\sqrt{n}})\)` ... <br> -- podemos construir un intervalo de confianza de la siguiente manera: `$$(1 - \alpha) \text{ CI}_{\hat{\theta}} = \hat{\theta} \pm \Phi^{-1}(\alpha/2) \cdot SE_{\hat{\theta}}$$` <br> -- Ejemplo, un intervalo al 95% de confianza está dado por: `$$95\% \text{ CI}_{\hat{\theta}} = \hat{\theta} \pm 2 \cdot \frac{\sigma_{\theta}}{\sqrt{n}}$$` --- ## Inferencia acerca de parámetros del modelo: intervalos de confianza Retomando nuestro modelo de clases anteriores: `\(\ln \frac{p_{i}}{ 1 - p_{i}} = \beta_{0} + \beta_{1}\text{male}_{i} + \beta_{2}\text{ym}_{i}\)` -- ``` ## everaffair_d ~ factor(sex) + ym ``` ``` ## Estimate Std. Error z value Pr(>|z|) ## (Intercept) -1.71395429 0.20633183 -8.306786 9.832929e-17 ## factor(sex)male 0.22157111 0.19064190 1.162237 2.451391e-01 ## ym 0.05842959 0.01727402 3.382513 7.182590e-04 ``` -- .content-box-blue[ .bold[Calculemos un IC al 95% para efecto el de "years of marriage" sobre el logit de ser infiel:] `\(\beta_{2}\)` ] -- ``` r beta2 <- summary(logit_affairs_sex_ym)$coefficients["ym","Estimate"] se_beta2 <- summary(logit_affairs_sex_ym)$coefficients["ym","Std. Error"] ci_beta2 <- beta2 + c(-2,2)*se_beta2; ci_beta2 ``` ``` ## [1] 0.02388155 0.09297763 ``` -- ``` r confint(logit_affairs_sex_ym) ``` ``` ## Waiting for profiling to be done... ``` ``` ## 2.5 % 97.5 % ## (Intercept) -2.12990424 -1.31985336 ## factor(sex)male -0.15199429 0.59625678 ## ym 0.02479755 0.09260135 ``` --- ## Inferencia acerca de parámetros del modelo: tests ``` ## Estimate Std. Error z value Pr(>|z|) ## (Intercept) -1.71395429 0.20633183 -8.306786 9.832929e-17 ## factor(sex)male 0.22157111 0.19064190 1.162237 2.451391e-01 ## ym 0.05842959 0.01727402 3.382513 7.182590e-04 ``` -- .bold[¿Que significan los p-values en este contexto?] -- .img-right[  ] ``` ## ## ============================================= ## Dependent variable: ## --------------------------- ## everaffair_d ## --------------------------------------------- ## factor(sex)male 0.222 (0.191) ## ym 0.058*** (0.017) ## Constant -1.714*** (0.206) ## --------------------------------------------- ## Observations 601 ## Log Likelihood -331.074 ## Akaike Inf. Crit. 668.148 ## ============================================= ## Note: *p<0.1; **p<0.05; ***p<0.01 ``` --- ## Inferencia acerca de parámetros del modelo: tests ``` ## Estimate Std. Error z value Pr(>|z|) ## (Intercept) -1.71395429 0.20633183 -8.306786 9.832929e-17 ## factor(sex)male 0.22157111 0.19064190 1.162237 2.451391e-01 ## ym 0.05842959 0.01727402 3.382513 7.182590e-04 ``` -- .bold[Test de hipótesis] -- 1) `\(H_{0}:\)` Los años de matrimonio no afectan la probabilidad de ser infiel ( `\(\beta_{2}=0\)` ) -- 2) ¿Cuál es la distribución de `\(\beta_{2}\)` si la hipótesis nula es verdadera? -- .content-box-blue[ `$$\beta_{2} \mid H_{0} \sim \text{Normal}\Big(\mu_{\beta_{2}} = 0, \sigma_{\beta_{2}} = \text{SE}_{\beta_{2}}\Big)$$` ] -- 3) Calcular .bold[p-value] (2 colas) .content-box-blue[ `$$\mathbb{P}( \beta_{2} > | \hat{\beta}_{2} | \mid H_{0}) := \mathbb{P}\big(\text{Normal}(\mu_{\beta_{2}} = 0, \sigma_{\beta_{2}} = \text{SE}_{\beta_{2}}) > |\hat{\beta}_{2}| \big)$$` ] <style type="text/css"> .pull-right ~ * { clear: unset; } .pull-right + * { clear: both; } </style> --- ## Inferencia acerca de parámetros del modelo: tests ``` ## Estimate Std. Error z value Pr(>|z|) ## (Intercept) -1.71395429 0.20633183 -8.306786 9.832929e-17 ## factor(sex)male 0.22157111 0.19064190 1.162237 2.451391e-01 ## ym 0.05842959 0.01727402 3.382513 7.182590e-04 ``` <!-- --> --- ## Inferencia acerca de parámetros del modelo: ejemplo empírico -- .content-box-blue[ .bold[Calculemos ahora un IC al 95% para efecto multiplicativo de "years of marriage" sobre las odds de ser infiel:] `\(e^{\beta_{2}}\)`= 1.0601703 ] --  -- ¿Cuál es la sampling distribution de una función de nuestro estimate? --- class: inverse, center, middle ## Bootstrap Method --- .pull-left[  ] -- .pull-right[  ] --- ## Bootstrap Method .bold[Intuición:] -- - Estimamos un modelo y tenemos una cierta "cantidad de interés" (estimate) -- - No conocemos la distribución nuestro estimate a través de infinitas muestras porque sólo tenemos una muestra. -- - Tampoco tenemos conocimiento teórico sobre la distribución de nuestro estimate. -- - Podemos tomar muestras de nuestra muestra, preservando cualquier distribución desconocida subyacente. -- - Podemos observar y estudiar el comportamiento de nuestro estimate en estas muestras de nuestras muestras. --- ## Bootstrap Method .bold[Muestrando desde la muestra:] ¿Cuántas muestras podemos tomar (con reemplazo) a partir de nuestra muestra? -- .bold[Respuesta]: `\(n^n\)` <br> -- `$$\text{muestra} : \left[\begin{array}{@{}c@{}} 1 \\ 2 \\ 3 \end{array} \right]$$` <br> -- `$$\text{posibles muestras de la muesta:} \left[\begin{array}{@{}c@{}} 1 \\ 1 \\ 1 \end{array} \right] \text{ o} \left[\begin{array}{@{}c@{}} 1 \\ 1 \\ 2 \end{array} \right] \text{ o} \left[\begin{array}{@{}c@{}} 1 \\ 3 \\ 2 \end{array} \right] \text{ o} \left[\begin{array}{@{}c@{}} 3 \\ 1 \\ 2 \end{array} \right] \text{ o} \left[\begin{array}{@{}c@{}} 3 \\ 3 \\ 3 \end{array} \right] ...$$` --- ## Bootstrap Method .bold[Esquema del algoritmo] (Bootstrap no paramétrico): -- 1. Asume que la distribución empírica del los datos refleja la distribución de probabilidad de las variables de interés. -- 2. A partir de la muestra obtenén una muestra aleatoria del mismo tamaño que la muestra original (N), con reemplazo: `\((y_{b},X_{b})\)` -- 3. Regresiona `\(y_{b}\)` y `\(X_{b}\)` para obtener el estimate `\(\hat{\theta}_{b}\)` -- 4. Repite los pasos 2 y 3 un gran número de veces B. -- 5. El conjunto de B resultados obtenidos corresponde a la "Bootstrap distribution" del estimate. -- 6. Evalúa la distribución del estimate (SE,CI, etc) o de cualquier cantidad derivada de éste. --- ## Bootstrap Method: ejemplo empírico Siguiendo con `\(\ln \frac{p_{i}}{ 1 - p_{i}} = \beta_{0} + \beta_{1}\text{male}_{i} + \beta_{2}\text{ym}_{i}\)`, -- .content-box-blue[ .bold[Calculemos un IC al 95% para efecto el de "years of marriage" sobre el logit de ser infiel:] `\(\beta_{2}\)` ] -- ``` r # Escribir una función que ejecute re-sampling y la estimación bs_beta2 <- function(x) { data_b <- sample_n(affairsdata,size=nrow(affairsdata),replace=TRUE) logit_b <- glm(everaffair_d ~ factor(sex) + ym, family=binomial(link="logit"), data=data_b) beta2_b <- logit_b$coefficients[3] return(beta2_b) } # Iterar función y almacenar resultados nreps =1200 betas2_bs <- replicate(nreps,bs_beta2()); head(betas2_bs) ``` ``` ## ym ym ym ym ym ym ## 0.05347036 0.07840635 0.05628455 0.05106772 0.05973257 0.05625482 ``` --- ## Bootstrap Method: ejemplo empírico .pull-left[ ``` r se_beta2_bs <- sd(betas2_bs) se_beta2_bs ``` ``` ## [1] 0.01701065 ``` ``` r ci_beta2_bs <- quantile(betas2_bs, p=c(0.025,0.975)) ci_beta2_bs ``` ``` ## 2.5% 97.5% ## 0.02483905 0.09366330 ``` ] -- .pull-right[ <!-- --> ] --- ## Bootstrap Method: ejemplo empírico .content-box-blue[ ¿Un IC al 95% para efecto el de "years of marriage" como .bold["odds ratio"]: `\(e^{\beta_{2}}\)`? ] -- Bootstrapeando ... .img-bottom-right[  ] --- ## Bootstrap Method: ejemplo empírico .content-box-blue[ ¿Un IC al 95% para efecto el de "years of marriage" como .bold["odds ratio"]: `\(e^{\beta_{2}}\)`? ] Bootstrapeando ... ``` r # Escribir una función que ejecute re-sampling y la estimación bs_expbeta2 <- function(x) { data_b <- sample_n(affairsdata,size=nrow(affairsdata),replace=TRUE) logit_b <- glm(everaffair_d ~ factor(sex) + ym, family=binomial(link="logit"), data=data_b) expbeta2_b <- exp(logit_b$coefficients[3]) return(expbeta2_b) } # Iterar función y almacenar resultados nreps = 2000 expbetas2_bs <- replicate(nreps,bs_expbeta2()); head(expbetas2_bs) ``` ``` ## ym ym ym ym ym ym ## 1.048272 1.042646 1.062791 1.068905 1.058887 1.056007 ``` --- ## Bootstrap Method: ejemplo empírico .pull-left[ ``` r se_expbeta2_bs <- sd(expbetas2_bs) se_expbeta2_bs ``` ``` ## [1] 0.01769795 ``` ``` r ci_expbeta2_bs <- quantile(expbetas2_bs, p=c(0.025,0.975)) ci_expbeta2_bs ``` ``` ## 2.5% 97.5% ## 1.027592 1.095258 ``` ] -- .pull-right[ <!-- --> ] --- ## Bootstrap Method: ejemplo empírico .content-box-blue[ .bold[Calculemos ahora IC al 95% para el Average Marginal Effect de"years of marriage" sobre la probabilidad de ser infiel] ] -- Bootstrapeando ... .img-bottom-right[  ] --- ## Bootstrap Method: ejemplo empírico .content-box-blue[ .bold[Calculemos ahora IC al 95% para el Average Marginal Effect de"years of marriage" sobre la probabilidad de ser infiel] ] Bootstrapeando ... ``` r # Escribir una función que ejecute re-sampling y la estimación bs_ame_ym <- function(x) { data_b <- sample_n(affairsdata,size=nrow(affairsdata),replace=TRUE) logit_b <- glm(everaffair_d ~ factor(sex) + ym, family=binomial(link="logit"), data=data_b) beta2_b <- logit_b$coefficients[3] p_hat_b <- predict(logit_b, type = "response") me_ym_b <- beta2_b*p_hat_b*(1-p_hat_b) return(ame_ym_b = mean(me_ym_b)) } # Iterar función y almacenar resultados nreps =1200 ame_ym_bs <- replicate(nreps,bs_ame_ym()); head(ame_ym_bs) ``` ``` ## [1] 0.010290899 0.014071549 0.007509348 0.007126371 0.012977138 0.010265007 ``` --- ## Bootstrap Method: ejemplo empírico .pull-left[ ``` r p_hat <- predict(logit_affairs_sex_ym, type = "response") me_ym <- beta2*p_hat*(1-p_hat) ame_ym <- mean(me_ym); ame_ym ``` ``` ## [1] 0.01070277 ``` ``` r se_ame_ym_bs <- sd(ame_ym_bs) se_ame_ym_bs ``` ``` ## [1] 0.002998718 ``` ``` r ci_ame_ym_bs <- quantile(ame_ym_bs, p=c(0.025,0.975)) ci_ame_ym_bs ``` ``` ## 2.5% 97.5% ## 0.004794026 0.016362624 ``` ] -- .pull-right[ <!-- --> ] --- ## Bootstrap Method: más ... .pull-left[ <!-- --> ] -- .pull-right[ <!-- --> ] --- class: inverse, center, middle ##Hasta la próxima clase. Gracias! <br> Mauricio Bucca <br> https://mebucca.github.io/ <br> github.com/mebucca