Modelos - Sem15 - Logit - Probit - Logistic Regression
Modelos - Sem15 - Logit - Probit - Logistic Regression
Description
logistic fits a logistic regression model of depvar on indepvars, where depvar is a 0/1 variable (or, more
precisely, a 0/non-0 variable). Without arguments, logistic redisplays the last logistic estimates. logistic
displays estimates as odds ratios; to view coefficients, type logit after running logistic.
Syntax
logistic depvar _ indepvars _ _ if _ _ in _ _ weight _ _, options_
logistic provides an alternative and preferred way to fit maximum-likelihood logit models, the other choice
being logit.
First, let’s dispose of some confusing terminology. We use the words logit and logistic to mean the same
thing: maximum likelihood estimation. To some, one or the other of these words connotes transforming the
dependent variable and using weighted least squares to fit the model, but that is not how we use either word
here. Thus, the logit and logistic commands produce the same results.
The logistic command is generally preferred to the logit command because logistic presents the estimates in
terms of odds ratios rather than coefficients. To some people, this may seem disadvantageous, but you can
type logit without arguments after logistic to see the underlying coefficients. You should be cautious when
interpreting the odds ratio of the constant term. Usually, this odds ratio represents the baseline odds of the
model when all predictor variables are set to zero.
The odds ratios are for a one-unit change in the variable
However, you must verify that a zero value for all predictor variables in the model actually makes sense
before continuing with this interpretation.
Modelos logit
Description
logit fits a logit model for a binary response by maximum likelihood; it models the probability of a positive
outcome given a set of regressors. depvar equal to nonzero and nonmissing (typically depvar equal to one)
indicates a positive outcome, whereas depvar equal to zero indicates a negative outcome.
Many users prefer the logistic command to logit. Results are the same regardless of which you use—both are
the maximumlikelihood estimator. Several auxiliary commands that can be run after logit, probit, or logistic
estimation are described here.
logit fits maximum likelihood models with dichotomous dependent (left-hand-side) variables coded as 0/1 (or,
more precisely, coded as 0 and not-0).
For grouped data or data in binomial form, a probit model can be fit using glm with the family(binomial) and
link(logit) options.
Syntax
logit depvar _ indepvars _ _ if _ _ in _ _ weight _ _, options_
In the example, the variable foreign takes on two unique values, 0 and 1. The value 0 denotes a domestic car,
and 1 denotes a foreign car.
The model that we wish to fit is
Pr(foreign = 1) = F(βo + β1weight + β2mpg)
where F(z) = e^z /(1 + e^z) is the cumulative logistic distribution.
Modelos probit
Description
probit fits a probit model for a binary dependent variable, assuming that the probability of a positive outcome
is determined by the standard normal cumulative distribution function. probit can compute robust and cluster–
robust standard errors and adjust results for complex survey designs.
probit fits maximum likelihood models with dichotomous dependent (left-hand-side) variables coded as 0/1
(more precisely, coded as 0 and not 0).
For grouped data or data in binomial form, a probit model can be fit using glm with the family(binomial) and
link(probit) options.
Syntax
probit depvar _ indepvars _ _ if _ _ in _ _ weight _ _, options_
In the example, the foreign variable takes on two unique values, 0 and 1. The value 0 denotes a domestic car,
and 1 denotes a foreign car.
The model that we wish to fit is
Pr(foreign = 1) = Ω(βo + β1weight + β2mpg)
where Ω is the cumulative normal distribution.
Postestimation commands
Command Description
estat classification report various summary statistics, including the classification table
estat gof Pearson or Hosmer–Lemeshow goodness-of-fit test
lroc compute area under ROC curve and graph the curve
lsens graph sensitivity and specificity versus probability cutoff
Otros comandos
Command Description
contrast contrasts and ANOVA-style joint tests of estimates
estat ic Akaike’s and Schwarz’s Bayesian information criteria (AIC and BIC)
estat summarize summary statistics for the estimation sample
estat vce variance–covariance matrix of the estimators (VCE)
estat (svy) postestimation statistics for survey data
estimates cataloging estimation results
etable table of estimation results
_ forecast dynamic forecasts and simulations
_ hausman Hausman’s specification test
lincom point estimates, standard errors, testing, and inference for linear combinations
of coefficients
linktest link test for model specification
_ lrtest likelihood-ratio test
margins marginal means, predictive margins, marginal effects, and average marginal
effects
marginsplot graph the results from margins (profile plots, interaction plots, etc.)
nlcom point estimates, standard errors, testing, and inference for nonlinear combinations
of coefficients
predict probabilities, influence statistics, residuals, etc.
predictnl point estimates, standard errors, testing, and inference for generalized
predictions
Comentarios
El modelo probit modela la probabilidad (condicional) de un resultado "exitoso", a partir de la
función de distribución acumulativa de la distribución normal estándar. Básicamente, esto dice que,
condicional a los regresores, la probabilidad que la variable de resultado, Yi sea =1, sea una
determinada función de una combinación lineal de los regresores.
Normalmente nos interesa los efectos ceteris paribus de los cambios en los regresores que afectan
las características de la variable de resultado. Esta es la noción que los efectos marginales miden.
Por eso, el epicentro será medir los efectos marginales del modelo
https://stats.oarc.ucla.edu/stata/seminars/stata-logistic/
All of the variables have 200 observations, so we will not have issues with missing data. Secondly, as
expected, the mean of honors is rather low because relatively few students are admitted to honors
English. The mean of female is approximately 0.5, which means that approximately half of the
students in this sample are female. The mean of the continuous variables read, science and socst are
similar, as are the ranges for these variables.
Miremos algunas tabulaciones (está el comando table (vars) o el tab1 (vars)). El segundo es
interesante
En el modelo que se desea construir, la var honors será la variable de salida (outcome). Ella es
binaria.
Remember, values greater than 1 will be considered to be 1, which may not be what you intend. Si
fuese así será necesario optar por la regresión logística ordenada (ordered logistic regression –
oprobit o también ologit) o una regresión logística multinomial (multinomial logistic regression)
Como hay DOS valores, el modelo referenciará el valor 1 (mujer), lo que significa que la categoría 1
será comparada con la categoría 0(hombre). Mantenga esto en mente. Según los resultados de
tab1, la var honors está distribuida 75% y 25% (podría decirse que está sesgada). Se asume que la
regresión logística tiene mayor peso estadístico cuando la distribución de los dos valores es 50/50.
Ese poder decrece cuando la distribución se torna más asimétrica (lopside)
Se puede iniciar con un modelo NULO (sin var_predictoras). Debemos recordar que no todos los
estudiantes tendrán el grado con honor en inglés. Serán una proporción (éxito en términos de las
FDP discretas que conocemos). Tenemos que F(z) = e^z / (1+e^z) es la FDP logística ACUMULADA.
Apliquemos el modelo NULO:
Con logit tenemos coeficientes. Ahora bien, este coeficiente indica que: log(p/(1-p)) = -1.020141.
Se debe entender que p es la probabilidad de grado de honor en inglés (honors=1).
Acorde a la tabla para honors, tendremos que p = 53/200= 0.265. Entonces, la probabilidad
logarítmica será 0.265/(1-0.265) = 0.3605442. Pero como son probabilidades logarítmicas, entonces
el tomamos log(0.3605442)= -1.020141
Es decir, el valor del intercepto del modelo sin var_predictoras es la probabilidad logarítmica
estimada para el grado con honor en inglés para toda la población de interés.
En este caso, el comando logistics NO muestra coeficientes, sino probabilidades (odds). El valor de
0.3605442 (odds), se puede sacar de la fórmula de la probabilidad de la proporción =53/147
Ahora bien, nosotros podemos transformar el logaritmo de las probabilidades en una probabilidad,
a partir de la expresión de la FDP señalada arriba: p = e^(-1.020141) / (1+e^(-1.020141)) =
0.264999 -FD logística ACUMULADA. Revisemos el archivo Excel anexado para verlos.
Es decir, tenemos TRES conceptos para trabajar: 1_ los coeficientes; 2_ las probabilidades
logarítmicas (odds) y las razones de la probabilidad (odds ratio)
El intercepto = -1.400088 está asociado a la prob_log para el grupo de los hombres, toda vez que el
grupo referenciado son las mujeres (female=0). Retomando el archivo Excel, este coeficiente me
llevará a una prob_log= 0.2465754 y una probab_p de 0.197802
De otra parte el coeficiente para la var female (0.6513706) estará asociado a una prob_log
=1.918168 y una probab_p de 0.657319
La interpretación del coeficiente es esta, acorde a sus autores (Long and Freese, 2014): “For a unit
change in xk, we expect the log of the odds of the outcome to change bk units, holding all other
variables constant.”
En nuestro ejemplo tendríamos que por una unidad de incremento en la var_female (pasar de
hombre a mujer), el logaritmo esperado de las probabilidades de grado con honores en inglés se
incrementa en 0.65, manteniendo constante las demás variables.
Revisemos la alternativa de logit con el option or. Tendremos las Odds Ratio
Entonces, la interpretación de esta razón de probabilidad es que por una unidad incrementada en la
var female (pasar de hombre a mujer), la probabilidad de grado con honor en inglés se incrementa
en un factor de 1.918, manteniendo las otras variables constantes.
Miremos ahora un modelo no con female, sino con prog, que es una var_categórica. Obervemos
que tenemos para este caso. En este caso, el programa de referencia sería “general” (1 = general; 2
= academic; 3 = vocational)
Las frecuencias probablemente sean lo suficientemente grandes como para evitar problemas reales.
prog
academic 1.206168 .4577746 2.63 0.008 .3089465 2.10339
vocation -.3007541 .5988045 -0.50 0.615 -1.474389 .8728812
Miremos el test de Wald para la var_prog. Se hará con la ayuda del comando contrast
. contrast prog
Margins : asbalanced
df chi2 P>chi2
La probabilidad del modo completo no es igual a la probabilidad de var_prog, aunque ella sea la
única var_regresora. Sin embargo podemos de cir que la var_prog es un predictor estadísticamente
significante para var_honors. Igualmente, hay una diferencia estadísticamente significante en los
niveles “general” y “academic”
Con el comando margins se podrá mostrar (the average predicted probabilities) las probabilidades
pronosticadas promedio, para cada uno de los niveles del grupo de la var_prog
Delta-method
Margin Std. Err. z P>|z| [95% Conf. Interval]
prog
general .1555556 .0540284 2.88 0.004 .0496619 .2614493
academic .3809524 .0473917 8.04 0.000 .2880663 .4738385
vocation .12 .0459565 2.61 0.009 .0299269 .2100731
La PPP del nivel “general” es 0.155, no muy diferente de la PP del nivel “vocation”. Para el nivel
“academic” se tiene una PPP de 0.38, que es muy diferente que la “general”. Esto explica porque es
estadísticamente significativa
En este caso, el término PPP significa que, si todos los datos del dataset fueran considerados como
del nivel “general”, entonces la Prob_predicción sería de 0.156.
El coeficiente indica que por un incremento unitario en la var_read, el logaritmo esperado de las
probabilidades de la var_honors aumenta en 0.13257, manteniendo todas las demás variables
constantes.
female
female 1.08343 .4094357 2.65 0.008 .2809511 1.885909
prog
academic .5559416 .5053125 1.10 0.271 -.4344527 1.546336
vocation .0016408 .6611702 0.00 0.998 -1.294229 1.29751
Para terminar, uno puede cambiar el grupo de referencia en el análisis. Es decir, no tomar “general”
como referente, si otro. Se haría con ib2.prog (para tomar el segundo grupo, en este caso
“academic”)