0% found this document useful (0 votes)
8 views

Modelos - Sem15 - Logit - Probit - Logistic Regression

1. The document discusses logistic regression models, logit models, and probit models for binary outcome variables. 2. Logistic regression and logit models produce the same maximum likelihood estimates, while probit models assume the cumulative normal distribution. 3. It is generally preferred to use the logistic command rather than logit, as logistic presents results in terms of odds ratios rather than coefficients, though coefficients can be obtained by using logit after logistic.

Uploaded by

Emmanuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Modelos - Sem15 - Logit - Probit - Logistic Regression

1. The document discusses logistic regression models, logit models, and probit models for binary outcome variables. 2. Logistic regression and logit models produce the same maximum likelihood estimates, while probit models assume the cumulative normal distribution. 3. It is generally preferred to use the logistic command rather than logit, as logistic presents results in terms of odds ratios rather than coefficients, though coefficients can be obtained by using logit after logistic.

Uploaded by

Emmanuel
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Modelos logistics

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_

Where options include:


Model; vce(vcetype); Reporting; Maximization

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_

Where options include:


Model; vce(vcetype); Reporting; Maximization

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_

Where options include:


Model; vce(vcetype); Reporting; Maximization

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/

Tomemos la dataset hsbdemo_education.dta

We will use the hsbdemo dataset with the binary response variable honors (enrolled in an honors


English program). Other variables that will be used in example analyses will be read, which is the
score on a reading test; science, which is the score on a science test; socst, which is the score on a
social studies test; female, which indicates if the student is female (1 = female; 0 = male); and prog,
which is the type of program in which the student is enrolled (1 = general; 2 = academic; 3 =
vocational).

Miremos de manera general que hay en la dataset

--- summarize honors female read science socst

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

--- tab1 honors female prog

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)

En Stata la respuesta de una regresión logit se da en unidades de probabilidades logarítmicas. Se


puede agregar la opción or para obtener las “razones” de las probabilidades (odds rations). Se
podrá usar el comando logistic, entonces la salida será en “razones” de probabilidades, Es decir,
tendremos DOS formas de expresar los resultados, lo que hace necesario encontrar una forma de
RELACIONAR esos dos valores que se reportan.

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:

--- tab honors

--- logit honors

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.

Esto se obtiene de manera directa usando no logit, sino logistic

--- logistic honors

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.

Este asunto se podrá realizar también utilizan el comando margin


Este comando muestra los efectos marginales del último modelo corrido en Stata
--- margins

Es decir, tenemos TRES conceptos para trabajar: 1_ los coeficientes; 2_ las probabilidades
logarítmicas (odds) y las razones de la probabilidad (odds ratio)

Miremos ahora un modelo1, con una var_predictora: female

--- logit honors female

Respuesta en términos de coeficientes

--- logit honors female, or

Respuesta en términos de Odds Ration

Miremos los resultados para logit con coeficientes


------------------------------------------------------------------------------
honors | Coef. Std. Err. z P>|z| [95% Conf. Interval]
-------------+----------------------------------------------------------------
female | .6513706 .3336752 1.95 0.051 -.0026207 1.305362
_cons | -1.400088 .2631619 -5.32 0.000 -1.915875 -.8842998
------------------------------------------------------------------------------

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

Miremos como se debe leer los resultados en esta alternativa:

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

honors | Odds Ratio Std. Err. z P>|z| [95% Conf. Interval]


-------------+----------------------------------------------------------------
female | 1.918168 .6400451 1.95 0.051 .9973827 3.689024
_cons | .2465754 .0648892 -5.32 0.000 .1472129 .4130033
La interpretación original, acorde a sus autores (Long and Freese, 2014) es: “ For a unit change in xk,
the odds are expected to change by a factor of exp(b k), holding all other variables constant.”

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.

Otra cosa importante es que, al hablar de razones de probabilidades, generalmente se indica el


intervalo de confianza del 95 % asociado, en lugar del error estándar. Esto porque la razón de
probabilidades es una transformación no lineal del coeficiente logit, por lo que el intervalo de
confianza es asimétrico.

Alguna cosas adicionales a mantener presente en los modelos logit, logistic


 Utilizar la opción nolog en el modelo, acorta la respuesta, pero puede ocultar cosas
importantes cuando hay problemas en el modelo
 La regresión logística usa el procedimiento de maximum likelihood (máxima verosimilitud),
lo que requiere de muestras grandes: Long (1997) expresa que: “It is risky to use ML with
samples smaller than 100, while sample over 500 seem adequate. These values should be
raised depending on characteristics of the model and data.”
 Aquí se habla de pseudo R-cuadrado. Este R-cuadrado no es comparable con R-2 de la
regresión lineal. Es decir, no se puede interpretar como un porcentaje de variación en el
resultado que representa el modelo. Se debe usar, mejor, para comparar diferentes
modelos
 Se debe habla del p-value para todo el modelo (0.0473) y del p-value para la var_female (p
= 0.051). Recuerde que en estos modelos, el test para todo el modele es un likelihood ratio
chi-square, mientras que el test para el coeficiente es un Wald chi-square. Es raro que una
prueba sea estadísticamente significativa mientras que la otra no lo es.

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)

--- tab honors prog

Las frecuencias probablemente sean lo suficientemente grandes como para evitar problemas reales.

--- logit honors i.prog


honors Coef. Std. Err. z P>|z| [95% Conf. Interval]

prog
academic 1.206168 .4577746 2.63 0.008 .3089465 2.10339
vocation -.3007541 .5988045 -0.50 0.615 -1.474389 .8728812

_cons -1.691676 .4113064 -4.11 0.000 -2.497822 -.8855303

El modelo es estadísticamente significativo (p = 0.0003); el nivel “academic”, de la var_prog es


estadísticamente significativo diferente del nivel “general”, mientras que nivel “vocation” no lo es.

El coeficiente indica que, al estar en el programa académico en comparación con el programa


general, el logaritmo esperado de las probabilidades aumenta en 1,2, manteniendo todas las demás
variables constantes.

Miremos el test de Wald para la var_prog. Se hará con la ayuda del comando contrast

--- contrast prog

. contrast prog

Contrasts of marginal linear predictions

Margins : asbalanced

df chi2 P>chi2

prog 2 14.26 0.0008

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

--- margins 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.

Miremos con la var_read

--- logit honors read

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.

Por último, miremos un modelo con tres variables regresoras

--- logit honors read i.female i.prog

honors Coef. Std. Err. z P>|z| [95% Conf. Interval]

read .1352861 .0242218 5.59 0.000 .0878123 .18276

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

_cons -9.41691 1.481922 -6.35 0.000 -12.32142 -6.512397

Miremos el comando contrast para la var_prog y poder hablar de su significancia estadística

--- contrast prog

Se nota que no lo es.

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”)

--- logit honors read i.female ib2.prog

You might also like