Docsity

Data Analysis Logistic Regression And Newton's Method, Lecture Slide - Engineering, Slides of Advanced Data Analysis

Toggle sidebar
bg1
14. Logistic Regression and Newton’s Method
36-402, Advanced Data Analysis
15 March 2011
Reading: Faraway, Chapter 2, omitting sections 2.11 and 2.12
Contents
1 Modeling Conditional Probabilities 1
2 Logistic Regression 3
2.1 Likelihoo d Function for Logistic Regression . . . . . . . . . . . . 6
2.2 Logistic Regression with More Than Two Classes . . . . . . . . . 6
3 Newton’s Method for Numerical Optimization 7
3.1 Newton’s Method in More than One Dimension . . . . . . . . . . 9
3.2 Iteratively Re-Weighted Least Squares . . . . . . . . . . . . . . . 10
4 Generalized Linear Models and Generalized Additive Models 11
4.1 Generalized Additive Models . . . . . . . . . . . . . . . . . . . . 12
4.2 An Example (Including Model Checking) . . . . . . . . . . . . . 12
1 Modeling Conditional Probabilities
So far, we either looked at estimating the conditional expectations of continuous
variables (as in regression), or at estimating distributions. There are many
situations where however we are interested in input-output relationships, as
in regression, but the output variable is discrete rather than continuous. In
particular there are many situations where we have binary outcomes (it snows
in Pittsburgh on a given day, or it doesn’t; this squirrel carries plague, or it
doesn’t; this loan will be paid back, or it won’t; this person will get heart disease
in the next five years, or they won’t). In addition to the binary outcome, we
have some input variables, which may or may not be continuous. How could we
model and analyze such data?
We could try to come up with a rule which guesses the binary output from
the input variables. This is called classification, and is an important topic
in statistics and machine learning. However, simply guessing “yes” or “no” is
pretty crude — especially if there is no perfect rule. (Why should there be?)
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Data Analysis Logistic Regression And Newton's Method, Lecture Slide - Engineering and more Slides Advanced Data Analysis in PDF only on Docsity!

14. Logistic Regression and Newton’s Method

36-402, Advanced Data Analysis

15 March 2011

Reading: Faraway, Chapter 2, omitting sections 2.11 and 2.

Contents

1 Modeling Conditional Probabilities 1

2 Logistic Regression 3 2.1 Likelihood Function for Logistic Regression............ 6 2.2 Logistic Regression with More Than Two Classes......... 6

3 Newton’s Method for Numerical Optimization 7 3.1 Newton’s Method in More than One Dimension.......... 9 3.2 Iteratively Re-Weighted Least Squares............... 10

4 Generalized Linear Models and Generalized Additive Models 11 4.1 Generalized Additive Models.................... 12 4.2 An Example (Including Model Checking)............. 12

1 Modeling Conditional Probabilities

So far, we either looked at estimating the conditional expectations of continuous variables (as in regression), or at estimating distributions. There are many situations where however we are interested in input-output relationships, as in regression, but the output variable is discrete rather than continuous. In particular there are many situations where we have binary outcomes (it snows in Pittsburgh on a given day, or it doesn’t; this squirrel carries plague, or it doesn’t; this loan will be paid back, or it won’t; this person will get heart disease in the next five years, or they won’t). In addition to the binary outcome, we have some input variables, which may or may not be continuous. How could we model and analyze such data? We could try to come up with a rule which guesses the binary output from the input variables. This is called classification, and is an important topic in statistics and machine learning. However, simply guessing “yes” or “no” is pretty crude — especially if there is no perfect rule. (Why should there be?)

Something which takes noise into account, and doesn’t just give a binary answer, will often be useful. In short, we want probabilities — which means we need to fit a stochastic model. What would be nice, in fact, would be to have conditional distribution of the response Y , given the input variables, Pr (Y |X). This would tell us about how precise our predictions are. If our model says that there’s a 51% chance of snow and it doesn’t snow, that’s better than if it had said there was a 99% chance of snow (though even a 99% chance is not a sure thing). We have seen how to estimate conditional probabilities non-parametrically, and could do this using the kernels for discrete variables from lecture 6. While there are a lot of merits to this approach, it does involve coming up with a model for the joint distribution of outputs Y and inputs X, which can be quite time-consuming. Let’s pick one of the classes and call it “1” and the other “0”. (It doesn’t matter which is which. Then Y becomes an indicator variable, and you can convince yourself that Pr (Y = 1) = E [Y ]. Similarly, Pr (Y = 1|X = x) = E [Y |X = x]. (In a phrase, “conditional probability is the conditional expecta- tion of the indicator”.) This helps us because by this point we know all about estimating conditional expectations. The most straightforward thing for us to do at this point would be to pick out our favorite smoother and estimate the regression function for the indicator variable; this will be an estimate of the conditional probability function. There are two reasons not to just plunge ahead with that idea. One is that probabilities must be between 0 and 1, but our smoothers will not necessarily respect that, even if all the observed yi they get are either 0 or 1. The other is that we might be better off making more use of the fact that we are trying to estimate probabilities, by more explicitly modeling the probability. Assume that Pr (Y = 1|X = x) = p(x; θ), for some function p parameter- ized by θ. parameterized function θ, and further assume that observations are independent of each other. The the (conditional) likelihood function is

∏^ n

i=

Pr (Y = yi|X = xi) =

∏^ n

i=

p(xi; θ)yi^ (1 − p(xi; θ)^1 −yi^ )

Recall that in a sequence of Bernoulli trials y 1 ,... yn, where there is a con- stant probability of success p, the likelihood is

∏^ n

i=

pyi^ (1 − p)^1 −yi

As you learned in intro. stats, this likelihood is maximized when p = ˆp = n−^1

∑n i=1 yi.^ If each trial had its own success probability^ pi, this likelihood becomes (^) n ∏

i=

py i i(1 − pi)^1 −yi

Without some constraints, estimating the “inhomogeneous Bernoulli” model by maximum likelihood doesn’t work; we’d get ˆpi = 1 when yi = 1, ˆpi = 0 when

To minimize the mis-classification rate, we should predict Y = 1 when p ≥ 0 .5 and Y = 0 when p < 0 .5. This means guessing 1 whenever β 0 + x · β is non- negative, and 0 otherwise. So logistic regression gives us a linear classifier. The decision boundary separating the two predicted classes is the solution of β 0 + x · β = 0, which is a point if x is one dimensional, a line if it is two dimensional, etc. One can show (exercise!) that the distance from the decision boundary is β 0 /‖β‖ + x · β/‖β‖. So logistic regression not only says where the boundary between the classes is, but also says (via Eq. 2) that the class probabilities depend on distance from the boundary, in a particular way, and that they go towards the extremes (0 and 1) more rapidly when ‖β‖ is larger. It’s these statements about probabilities which make logistic regression more than just a linear classifier. It makes stronger, more detailed predictions, and can be fit in a different way; but those strong predictions could be wrong. Using logistic regression to predict class probabilities is a modeling choice, just like it’s a modeling choice to predict quantitative variables with linear regression. In neither case is the appropriateness of the model guaranteed by the gods, nature, mathematical necessity, etc. We begin by positing the model, to get something to work with, and we end (if we know what we’re doing) by checking whether it really does match the data, or whether it has systematic flaws. Logistic regression is one of the most commonly used tools for applied statis- tics and discrete data analysis. There are basically four reasons for this.

  1. Tradition.
  2. In addition to the heuristic approach above, the quantity log p/(1 − p) plays an important role in the analysis of contingency tables (the “log odds”). Classification is a bit like having a contingency table with two columns (classes) and infinitely many rows (values of x). With a finite contingency table, we can estimate the log-odds for each row empirically, by just taking counts in the table. With infinitely many rows, we need some sort of interpolation scheme; logistic regression is linear interpolation for the log-odds.
  3. It’s closely related to “exponential family” distributions, where the prob- ability of some vector v is proportional to exp β 0 +

∑m j=1 fj^ (v)βj^. If one of the components of v is binary, and the functions fj are all the identity function, then we get a logistic regression. Exponential families arise in many contexts in statistical theory (and in physics!), so there are lots of problems which can be turned into logistic regression.

  1. It often works surprisingly well as a classifier. But, many simple techniques often work surprisingly well as classifiers, and this doesn’t really testify to logistic regression getting the probabilities right.
  • (^) + +
  • (^) +
  • (^) +
  • (^) -

  • (^) +^ +

-1.0 -0.5 0.0 0.5 1.

-1.

-0.

0.^ 0.^

Logistic regression with b=-0.1, w=(-.2,.2)

x[,1]

x[,2] -

  • (^) + + +

+^ +

  • (^) -
  • (^) -

  • (^) -^ -

-1.0 -0.5 0.0 0.5 1.

-1.

-0.

0.^ 0.^

Logistic regression with b=-0.5, w=(-1,1)

x[,1]

x[,2]

  • (^) - - -
  • (^) -
  • -^ -
  • (^) -
  • (^) +

  • (^) -^ -

-1.0 -0.5 0.0 0.5 1.

-1.

-0.

0.^ 0.^

Logistic regression with b=-2.5, w=(-5,5)

x[,1]

x[,2] -

  • (^) - - -
  • -^ -
  • (^) -
  • (^) +

  • (^) -^ -

-1.0 -0.5 0.0 0.5 1.

-1.

-0.

0.^ 0.^

Linear classifier with b= 21 2 ,w=  −^21 , 12   

x[,1]

x[,2]

Figure 1: Effects of scaling logistic regression parameters. Values of x 1 and x 2 are the same in all plots (∼ Unif(− 1 , 1) for both coordinates), but labels were generated randomly from logistic regressions with β 0 = − 0 .1, β = (− 0. 2 , 0 .2) (top left); from β 0 = − 0 .5, β = (− 1 , 1) (top right); from β 0 = − 2 .5, β = (− 5 , 5) (bottom left); and from a perfect linear classifier with the same boundary. The large black dot is the origin.

It can be shown that when there are only two classes (say, 0 and 1), equation

10 reduces to equation 2, with β 0 = β (1) 0 −^ β

(0) 0 and^ β^ =^ β (1) (^) − β(0). (Exercise:

Show this.) In fact, no matter how many classes there are, we can always pick one of them, say c = 0, and fix its parameters at exactly zero, without any loss of generality. (Exercise: Show this.) Calculation of the likelihood now proceeds as before (only with more book- keeping), and so does maximum likelihood estimation.

3 Newton’s Method for Numerical Optimization

There are a huge number of methods for numerical optimization; we can’t cover all bases, and there is no magical method which will always work better than anything else. However, there are some methods which work very well on an awful lot of the problems which keep coming up, and it’s worth spending a moment to sketch how they work. One of the most ancient yet important of them is Newton’s method (alias “Newton-Raphson”). Let’s start with the simplest case of minimizing a function of one scalar variable, say f (β). We want to find the location of the global minimum, β∗. We suppose that f is smooth, and that β∗^ is a regular interior minimum, meaning that the derivative at β∗^ is zero and the second derivative is positive. Near the minimum we could make a Taylor expansion:

f (β) ≈ f (β∗) +

(β − β∗)^2

d^2 f dβ^2

β=β∗

(We can see here that the second derivative has to be positive to ensure that f (β) > f (β∗).) In words, f (β) is close to quadratic near the minimum. Newton’s method uses this fact, and minimizes a quadratic approximation to the function we are really interested in. (In other words, Newton’s method is to replace the problem we want to solve, with a problem which we can solve.) Guess an initial point β(0). If this is close to the minimum, we can take a second order Taylor expansion around β(0)^ and it will still be accurate:

f (β) ≈ f (β(0)) + (β − β(0))

df dw

β=β(0)

β − β(0)

) (^2) d (^2) f dw^2

β=β(0)

Now it’s easy to minimize the right-hand side of equation 12. Let’s abbreviate

the derivatives, because they get tiresome to keep writing out: (^) dwdf

β=β(0)^

f ′(β(0)), d

(^2) f dw^2

β=β(0)^

= f ′′(β(0)). We just take the derivative with respect to β,

and set it equal to zero at a point we’ll call β(1):

0 = f ′(β(0)) +

f ′′(β(0))2(β(1)^ − β(0)) (13)

β(1)^ = β(0)^ −

f ′(β(0)) f ′′(β(0))

The value β(1)^ should be a better guess at the minimum β∗^ than the initial one β(0)^ was. So if we use it to make a quadratic approximation to f , we’ll get a better approximation, and so we can iterate this procedure, minimizing one approximation and then using that to get a new approximation:

β(n+1)^ = β(n)^ −

f ′(β(n)) f ′′(β(n))

Notice that the true minimum β∗^ is a fixed point of equation 15: if we happen to land on it, we’ll stay there (since f ′(β∗) = 0). We won’t show it, but it can be proved that if β(0)^ is close enough to β∗, then β(n)^ → β∗, and that in general |β(n)^ − β∗| = O(n−^2 ), a very rapid rate of convergence. (Doubling the number of iterations we use doesn’t reduce the error by a factor of two, but by a factor of four.)

is β(n+1)^ = β(n)^ − H−^1 (β(n))∇f (β(n)) (16)

where ∇f is the gradient of f , its vector of partial derivatives [∂f /∂β 1 , ∂f /∂β 2 ,... ∂f /∂βp], and H is the Hessian of f , its matrix of second partial derivatives, Hij = ∂^2 f /∂βi∂βj. Calculating H and ∇f isn’t usually very time-consuming, but taking the inverse of H is, unless it happens to be a diagonal matrix. This leads to various quasi-Newton methods, which either approximate H by a diagonal matrix, or take a proper inverse of H only rarely (maybe just once), and then try to update an estimate of H−^1 (β(n)) as β(n)^ changes.

3.2 Iteratively Re-Weighted Least Squares

This discussion of Newton’s method is quite general, and therefore abstract. In the particular case of logistic regression, we can make everything look much more “statistical”. Logistic regression, after all, is a linear model for a transformation of the probability. Let’s call this transformation g:

g(p) ≡ log p 1 − p

So the model is g(p) = β 0 + x · β

and Y |X = x ∼ Binom(1, g−^1 (β 0 + x · β)). It seems that what we should want to do is take g(y) and regress it linearly on x. Of course, the variance of Y , according to the model, is going to chance depending on x — it will be (g−^1 (β 0 + x · β))(1 − g−^1 (β 0 + x · β)) — so we really ought to do a weighted linear regression, with weights inversely proportional to that variance. Since writing β 0 + x · β is getting annoying, let’s abbreviate it by μ (for “mean”), and let’s abbreviate that variance as V (μ). The problem is that y is either 0 or 1, so g(y) is either −∞ or +∞. We will evade this by using Taylor expansion.

g(y) ≈ g(μ) + (y − μ)g′(μ) ≡ z

The right hand side, z will be our effective response variable. To regress it, we need its variance, which by propagation of error will be (g′(μ))^2 V (μ). Notice that both the weights and z depend on the parameters of our logistic regression, through μ. So having done this once, we should really use the new parameters to update z and the weights, and do it again. Eventually, we come to a fixed point, where the parameter estimates no longer change. The treatment above is rather heuristic^3 , but it turns out to be equivalent to using Newton’s method, with the expected second derivative of the log like-

(^3) That is, mathematically incorrect.

lihood, instead of its actual value.^4 Since, with a large number of observations, the observed second derivative should be close to the expected second derivative, this is only a small approximation.

4 Generalized Linear Models and Generalized

Additive Models

Logistic regression is part of a broader family of generalized linear mod- els (GLMs), where the conditional distribution of the response falls in some parametric family, and the parameters are set by the linear predictor. Ordi- nary, least-squares regression is the case where response is Gaussian, with mean equal to the linear predictor, and constant variance. Logistic regression is the case where the response is binomial, with n equal to the number of data-points with the given x (often but not always 1), and p is given by Equation 2. Chang- ing the relationship between the parameters and the linear predictor is called changing the link function. For computational reasons, the link function is actually the function you apply to the mean response to get back the linear pre- dictor, rather than the other way around — (1) rather than (2). There are thus other forms of binomial regression besides logistic regression.^5 There is also Poisson regression (appropriate when the data are counts without any upper limit), gamma regression, etc.; we will say more about these next time. In R, any standard GLM can be fit using the (base) glm function, whose syntax is very similar to that of lm. The major wrinkle is that, of course, you need to specify the family of probability distributions to use, by the family option — family=binomial defaults to logistic regression. (See help(glm) for the gory details on how to do, say, probit regression.) All of these are fit by the same sort of numerical likelihood maximization. One caution about using maximum likelihood to fit logistic regression is that it can seem to work badly when the training data can be linearly separated. The reason is that, to make the likelihood large, p(xi) should be large when yi = 1, and p should be small when yi = 0. If β 0 , β 0 is a set of parameters which perfectly classifies the training data, then cβ 0 , cβ is too, for any c > 1, but in a logistic regression the second set of parameters will have more extreme probabilities, and so a higher likelihood. For linearly separable data, then, there is no parameter vector which maximizes the likelihood, since can always be increased by making the vector larger but keeping it pointed in the same direction. (^4) This takes a reasonable amount of algebra to show, so we’ll skip it. The key point however is the following. Take a single Bernoulli observation with success probability p. The log-likelihood is Y log p + (1 − Y ) log 1 − p. The first derivative with respect to p is Y /p − (1 − Y )/(1 − p), and the second derivative is −Y /p^2 − (1 − Y )/(1 − p)^2. Taking expectations gives − 1 /p − 1 /(1 − p) = − 1 /p(1 − p). In other words, V (p) = − 1 /E [′′]. Using weights inversely proportional to the variance thus turns out to be equivalent to dividing by the expected second derivative. (^5) My experience is that these tend to give similar error rates as classifiers, but have rather different guesses about the underlying probabilities.

probability 1 to the observed outcomes^7 , and the logarithm of 1 is zero, so D = 2`(̂β 0 , β̂). The null deviance is what’s achievable by using just a constant bias b and setting w = 0. The fitted model definitely improves on that.^8 The fitted values of the logistic regression are the class probabilities; this shows that the error rate of the logistic regression, if you force it to predict actual classes, is 32%. This sounds bad, but notice from the contour lines in the figure that lots of the probabilities are near 0.5, meaning that the classes are just genuinely hard to predict. To see how well the logistic regression assumption holds up, let’s compare this to a GAM.

gam.1 = gam(y.1~lo(x[,1])+lo(x[,2]),family="binomial") gam. Call: gam(formula = y.1 ~ lo(x[, 1]) + lo(x[, 2]), family = "binomial")

Degrees of Freedom: 49 total; 41.39957 Residual Residual Deviance: 49.

This fits a GAM to the same data, using lowess smoothing of both input vari- ables. Notice that the residual deviance is lower. That is, the GAM fits better. We expect this; the question is whether the difference is significant, or within the range of what we should expect when logistic regression is valid. To test this, we need to simulate from the logistic regression model.

simulate.from.logr = function(x, coefs) { require(faraway) # For accessible logit and inverse-logit functions n = nrow(x) linear.part = coefs[1] + x %*% coefs[-1] probs = ilogit(linear.part) # Inverse logit y = rbinom(n,size=1,prob=probs) return(y) }

Now we simulate from our fitted model, and re-fit both the logistic regression and the GAM.

delta.deviance.sim = function (x,logistic.model) { y.new = simulate.from.logr(x,logistic.model$coefficients) GLM.dev = glm(y.new ~ x[,1] + x[,2], family="binomial")$deviance

of freedom. (^7) This is not possible when there are multiple observations with the same input features, but different classes. (^8) AIC is of course the Akaike information criterion, − 2 ` + 2q, with q being the number of parameters (here, q = 3). AIC has some truly devoted adherents, especially among non- statisticians, but I have been deliberately ignoring it and will continue to do so. Claeskens and Hjort (2008) is a thorough, modern treatment of AIC and related model-selection criteria from a statistical viewpoint.

GAM.dev = gam(y.new ~ lo(x[,1]) + lo(x[,2]), family="binomial")$deviance return(GLM.dev - GAM.dev) }

Notice that in this simulation we are not generating new X~ values. The logistic regression and the GAM are both models for the response conditional on the inputs, and are agnostic about how the inputs are distributed, or even whether it’s meaningful to talk about their distribution. Finally, we repeat the simulation a bunch of times, and see where the ob- served difference in deviances falls in the sampling distribution.

delta.dev = replicate(1000,delta.deviance.sim(x,logr)) delta.dev.observed = logr$deviance - gam.1$deviance # 9. sum(delta.dev.observed > delta.dev)/ [1] 0.

In other words, the amount by which a GAM fits the data better than logistic regression is pretty near the middle of the null distribution. Since the example data really did come from a logistic regression, this is a relief.

References

Claeskens, Gerda and Nils Lid Hjort (2008). Model Selection and Model Aver- aging. Cambridge, England: Cambridge University Press.