Linear Regression: Statistical Models and Hypothesis Testing - PDF

Summary

This document introduces linear regression, a fundamental statistical tool for analyzing relationships between variables. It covers essential concepts like the linear regression model, model selection, and hypothesis testing. The text also touches base on how to work with this in R.

Full Transcript

15. Linear regression The goal in this chapter is to introduce linear regression, the standard tool that statisticians rely on when analysing the relationship between interval scale predictors and interval scale outcomes. Stripped to its bare essentials, linear regression models are basically a sli...

15. Linear regression The goal in this chapter is to introduce linear regression, the standard tool that statisticians rely on when analysing the relationship between interval scale predictors and interval scale outcomes. Stripped to its bare essentials, linear regression models are basically a slightly fancier version of the Pearson correlation (Section 5.7) though as we’ll see, regression models are much more powerful tools. 15.1 What is a linear regression model? Since the basic ideas in regression are closely tied to correlation, we’ll return to the parenthood.Rdata file that we were using to illustrate how correlations work. Recall that, in this data set, we were trying to find out why Dan is so very grumpy all the time, and our working hypothesis was that I’m not getting enough sleep. We drew some scatterplots to help us examine the relationship between the amount of sleep I get, and my grumpiness the following day. The actual scatterplot that we draw is the one shown in Figure 15.1, and as we saw previously this corresponds to a correlation of r “ ´.90, but what we find ourselves secretly imagining is something that looks closer to Figure 15.2a. That is, we mentally draw a straight line through the middle of the data. In statistics, this line that we’re drawing is called a regression line. Notice that – since we’re not idiots – the regression line goes through the middle of the data. We don’t find ourselves imagining anything like the rather silly plot shown in Figure 15.2b. This is not highly surprising: the line that I’ve drawn in Figure 15.2b doesn’t “fit” the data very well, so it doesn’t make a lot of sense to propose it as a way of summarising the data, right? This is a very simple observation to make, but it turns out to be very powerful when we start trying to wrap just a little bit of maths around it. To do so, let’s start with a refresher of some high school maths. The formula for a straight line is usually written like this: y “ mx ` c Or, at least, that’s what it was when I went to high school all those years ago. The two variables are x and y, and we have two coefficients, m and c. The coefficient m represents the slope of the line, and the coefficient c represents the y-intercept of the line. Digging further back into our decaying memories of high school (sorry, for some of us high school was a long time ago), we remember that the intercept is interpreted as “the value of y that you get when x “ 0”. Similarly, a slope of m means that if you increase the x-value by 1 unit, then the y-value goes up by m units; a negative slope means that the y-value would go down rather than up. Ah yes, it’s all coming back to me now. Now that we’ve remembered that, it should come as no surprise to discover that we use the exact same formula to describe a regression line. If Y is the outcome variable (the DV) and X is the predictor - 457 - 90 80 My grumpiness (0−100) 70 60 50 40 5 6 7 8 9 My sleep (hours) Figure 15.1: Scatterplot showing grumpiness as a function of hours slept........................................................................................................ variable (the IV), then the formula that describes our regression is written like this: Ŷi “ b1 Xi ` b0 Hm. Looks like the same formula, but there’s some extra frilly bits in this version. Let’s make sure we understand them. Firstly, notice that I’ve written Xi and Yi rather than just plain old X and Y. This is because we want to remember that we’re dealing with actual data. In this equation, Xi is the value of predictor variable for the ith observation (i.e., the number of hours of sleep that I got on day i of my little study), and Yi is the corresponding value of the outcome variable (i.e., my grumpiness on that day). And although I haven’t said so explicitly in the equation, what we’re assuming is that this formula works for all observations in the data set (i.e., for all i). Secondly, notice that I wrote Ŷi and not Yi. This is because we want to make the distinction between the actual data Yi , and the estimate Ŷi (i.e., the prediction that our regression line is making). Thirdly, I changed the letters used to describe the coefficients from m and c to b1 and b0. That’s just the way that statisticians like to refer to the coefficients in a regression model. I’ve no idea why they chose b, but that’s what they did. In any case b0 always refers to the intercept term, and b1 refers to the slope. Excellent, excellent. Next, I can’t help but notice that – regardless of whether we’re talking about the good regression line or the bad one – the data don’t fall perfectly on the line. Or, to say it another way, the data Yi are not identical to the predictions of the regression model Ŷi. Since statisticians love to attach letters, names and numbers to everything, let’s refer to the di↵erence between the model prediction and that actual data point as a residual, and we’ll refer to it as ✏i.1 Written using mathematics, the residuals are defined as: ✏i “ Yi ´ Ŷi which in turn means that we can write down the complete linear regression model as: Y i “ b 1 X i ` b0 ` ✏ i 1 The ✏ symbol is the Greek letter epsilon. It’s traditional to use ✏i or ei to denote a residual. - 458 - The Best Fitting Regression Line Not The Best Fitting Regression Line! 90 90 80 80 My grumpiness (0−100) My grumpiness (0−100) 70 70 60 60 50 50 40 40 5 6 7 8 9 5 6 7 8 9 My sleep (hours) My sleep (hours) (a) (b) Figure 15.2: Panel a shows the sleep-grumpiness scatterplot from Figure 15.1 with the best fitting regres- sion line drawn over the top. Not surprisingly, the line goes through the middle of the data. In contrast, panel b shows the same data, but with a very poor choice of regression line drawn over the top........................................................................................................ 15.2 Estimating a linear regression model Okay, now let’s redraw our pictures, but this time I’ll add some lines to show the size of the residual for all observations. When the regression line is good, our residuals (the lengths of the solid black lines) all look pretty small, as shown in Figure 15.3a, but when the regression line is a bad one, the residuals are a lot larger, as you can see from looking at Figure 15.3b. Hm. Maybe what we “want” in a regression model is small residuals. Yes, that does seem to make sense. In fact, I think I’ll go so far as to say that the “best fitting” regression line is the one that has the smallest residuals. Or, better yet, since statisticians seem to like to take squares of everything why not say that... The estimated regression coefficients, b̂0 and ∞ b̂1 are those that∞ minimise the sum of the squared residuals, which we could either write as i pYi ´ Ŷi q2 or as i ✏i 2. Yes, yes that sounds even better. And since I’ve indented it like that, it probably means that this is the right answer. And since this is the right answer, it’s probably worth making a note of the fact that our regression coefficients are estimates (we’re trying to guess the parameters that describe a population!), which is why I’ve added the little hats, so that we get b̂0 and b̂1 rather than b0 and b1. Finally, I should also note that – since there’s actually more than one way to estimate a regression model – the more technical name for this estimation process is ordinary least squares (OLS) regression. At this point, we now have a concrete definition for what counts as our “best” choice of regression coefficients, b̂0 and b̂1. The natural question to ask next is, if our optimal regression coefficients are those that minimise the sum squared residuals, how do we find these wonderful numbers? The actual answer - 459 - Regression Line Close to the Data Regression Line Distant from the Data 90 90 80 80 My grumpiness (0−100) My grumpiness (0−100) 70 70 60 60 50 50 40 40 5 6 7 8 9 5 6 7 8 9 My sleep (hours) My sleep (hours) (a) (b) Figure 15.3: A depiction of the residuals associated with the best fitting regression line (panel a), and the residuals associated with a poor regression line (panel b). The residuals are much smaller for the good regression line. Again, this is no surprise given that the good line is the one that goes right through the middle of the data........................................................................................................ to this question is complicated, and it doesn’t help you understand the logic of regression.2 As a result, this time I’m going to let you o↵ the hook. Instead of showing you how to do it the long and tedious way first, and then “revealing” the wonderful shortcut that R provides you with, let’s cut straight to the chase... and use the lm() function (short for “linear model”) to do all the heavy lifting. 15.2.1 Using the function The lm() function is a fairly complicated one: if you type ?lm, the help files will reveal that there are a lot of arguments that you can specify, and most of them won’t make a lot of sense to you. At this stage however, there’s really only two of them that you care about, and as it turns out you’ve seen them before: formula. A formula that specifies the regression model. For the simple linear regression models that we’ve talked about so far, in which you have a single predictor variable as well as an intercept term, this formula is of the form outcome ~ predictor. However, more complicated formulas are allowed, and we’ll discuss them later. 2 Or at least, I’m assuming that it doesn’t help most people. But on the o↵ chance that someone reading this is a proper kung fu master of linear algebra (and to be fair, I always have a few of these people in my intro stats class), it will help you to know that the solution to the estimation problem turns out to be b̂ “ pX1 Xq´1 X1 y, where b̂ is a vector containing the estimated regression coefficients, X is the “design matrix” that contains the predictor variables (plus an additional column containing all ones; strictly X is a matrix of the regressors, but I haven’t discussed the distinction yet), and y is a vector containing the outcome variable. For everyone else, this isn’t exactly helpful, and can be downright scary. However, since quite a few things in linear regression can be written in linear algebra terms, you’ll see a bunch of footnotes like this one in this chapter. If you can follow the maths in them, great. If not, ignore it. - 460 - data. The data frame containing the variables. As we saw with aov() in Chapter 14, the output of the lm() function is a fairly complicated object, with quite a lot of technical information buried under the hood. Because this technical information is used by other functions, it’s generally a good idea to create a variable that stores the results of your regression. With this in mind, to run my linear regression, the command I want to use is this: > regression.1 print( regression.1 ) Call: lm(formula = dan.grump ~ dan.sleep, data = parenthood) Coefficients: (Intercept) dan.sleep 125.956 -8.937 This looks promising. There’s two separate pieces of information here. Firstly, R is politely reminding us what the command was that we used to specify the model in the first place, which can be helpful. More importantly from our perspective, however, is the second part, in which R gives us the intercept b̂0 “ 125.96 and the slope b̂1 “ ´8.94. In other words, the best-fitting regression line that I plotted in Figure 15.2 has this formula: Ŷi “ ´8.94 Xi ` 125.96 15.2.2 Interpreting the estimated model The most important thing to be able to understand is how to interpret these coefficients. Let’s start with b̂1 , the slope. If we remember the definition of the slope, a regression coefficient of b̂1 “ ´8.94 means that if I increase Xi by 1, then I’m decreasing Yi by 8.94. That is, each additional hour of sleep that I gain will improve my mood, reducing my grumpiness by 8.94 grumpiness points. What about the intercept? Well, since b̂0 corresponds to “the expected value of Yi when Xi equals 0”, it’s pretty straightforward. It implies that if I get zero hours of sleep (Xi “ 0) then my grumpiness will go o↵ the scale, to an insane value of (Yi “ 125.96). Best to be avoided, I think. 15.3 Multiple linear regression The simple linear regression model that we’ve discussed up to this point assumes that there’s a single predictor variable that you’re interested in, in this case dan.sleep. In fact, up to this point, every statistical tool that we’ve talked about has assumed that your analysis uses one predictor variable and one outcome variable. However, in many (perhaps most) research projects you actually have multiple predictors that you want to examine. If so, it would be nice to be able to extend the linear regression - 461 - framework to be able to include multiple predictors. Perhaps some kind of multiple regression model would be in order? Multiple regression is conceptually very simple. All we do is add more terms to our regression equation. Let’s suppose that we’ve got two variables that we’re interested in; perhaps we want to use both dan.sleep and baby.sleep to predict the dan.grump variable. As before, we let Yi refer to my grumpiness on the i-th day. But now we have two X variables: the first corresponding to the amount of sleep I got and the second corresponding to the amount of sleep my son got. So we’ll let Xi1 refer to the hours I slept on the i-th day, and Xi2 refers to the hours that the baby slept on that day. If so, then we can write our regression model like this: Yi “ b2 Xi2 ` b1 Xi1 ` b0 ` ✏i As before, ✏i is the residual associated with the i-th observation, ✏i “ Yi ´ Ŷi. In this model, we now have three coefficients that need to be estimated: b0 is the intercept, b1 is the coefficient associated with my sleep, and b2 is the coefficient associated with my son’s sleep. However, although the number of coefficients that need to be estimated has changed, the basic idea of how the estimation works is unchanged: our estimated coefficients b̂0 , b̂1 and b̂2 are those that minimise the sum squared residuals. 15.3.1 Doing it in R Multiple regression in R is no di↵erent to simple regression: all we have to do is specify a more complicated formula when using the lm() function. For example, if we want to use both dan.sleep and baby.sleep as predictors in our attempt to explain why I’m so grumpy, then the formula we need is this: dan.grump ~ dan.sleep + baby.sleep Notice that, just like last time, I haven’t explicitly included any reference to the intercept term in this formula; only the two predictor variables and the outcome. By default, the lm() function assumes that the model should include an intercept (though you can get rid of it if you want). In any case, I can create a new regression model – which I’ll call regression.2 – using the following command: > regression.2 print( regression.2 ) Call: lm(formula = dan.grump ~ dan.sleep + baby.sleep, data = parenthood) Coefficients: (Intercept) dan.sleep baby.sleep 125.96557 -8.95025 0.01052 The coefficient associated with dan.sleep is quite large, suggesting that every hour of sleep I lose makes me a lot grumpier. However, the coefficient for baby.sleep is very small, suggesting that it doesn’t really matter how much sleep my son gets; not really. What matters as far as my grumpiness goes is how much sleep I get. To get a sense of what this multiple regression model looks like, Figure 15.4 shows a 3D plot that plots all three variables, along with the regression model itself. - 462 - Figure 15.4: A 3D visualisation of a multiple regression model. There are two predictors in the model, dan.sleep and baby.sleep; the outcome variable is dan.grump. Together, these three variables form a 3D space: each observation (blue dots) is a point in this space. In much the same way that a simple linear regression model forms a line in 2D space, this multiple regression model forms a plane in 3D space. When we estimate the regression coefficients, what we’re trying to do is find a plane that is as close to all the blue dots as possible. (This plot was drawn using the scatter3d() function in the car package, and it looked much nicer before it got butchered by the image conversion process that I used to get it into the book pdf) - 463 - 15.3.2 Formula for the general case The equation that I gave above shows you what a multiple regression model looks like when you include two predictors. Not surprisingly, then, if you want more than two predictors all you have to do is add more X terms and more b coefficients. In other words, if you have K predictor variables in the model then the regression equation looks like this: ˜ ¸ ÿ K Yi “ bk Xik ` b0 ` ✏i k“1 15.4 Quantifying the fit of the regression model So we now know how to estimate the coefficients of a linear regression model. The problem is, we don’t yet know if this regression model is any good. For example, the regression.1 model claims that every hour of sleep will improve my mood by quite a lot, but it might just be rubbish. Remember, the regression model only produces a prediction Ŷi about what my mood is like: my actual mood is Yi. If these two are very close, then the regression model has done a good job. If they are very di↵erent, then it has done a bad job. 15.4.1 The R2 value Once again, let’s wrap a little bit of mathematics around this. Firstly, we’ve got the sum of the squared residuals: ÿ SSres “ pYi ´ Ŷi q2 i which we would hope to be pretty small. Specifically, what we’d like is for it to be very small in comparison to the total variability in the outcome variable, ÿ SStot “ pYi ´ Ȳ q2 i While we’re here, let’s calculate these values in R. Firstly, in order to make my R commands look a bit more similar to the mathematical equations, I’ll create variables X and Y: > X Y Y.pred SS.resid print( SS.resid ) 1838.722 - 464 - Wonderful. A big number that doesn’t mean very much. Still, let’s forge boldly onwards anyway, and calculate the total sum of squares as well. That’s also pretty simple: > SS.tot print( SS.tot ) 9998.59 Hm. Well, it’s a much bigger number than the last one, so this does suggest that our regression model was making good predictions. But it’s not very interpretable. Perhaps we can fix this. What we’d like to do is to convert these two fairly meaningless numbers into one number. A nice, interpretable number, which for no particular reason we’ll call R2. What we would like is for the value of R2 to be equal to 1 if the regression model makes no errors in predicting the data. In other words, if it turns out that the residual errors are zero – that is, if SSres “ 0 – then we expect R2 “ 1. Similarly, if the model is completely useless, we would like R2 to be equal to 0. What do I mean by “useless”? Tempting as it is demand that the regression model move out of the house, cut its hair and get a real job, I’m probably going to have to pick a more practical definition: in this case, all I mean is that the residual sum of squares is no smaller than the total sum of squares, SSres “ SStot. Wait, why don’t we do exactly that? The formula that provides us with out R2 value is pretty simple to write down, SSres R2 “ 1 ´ SStot and equally simple to calculate in R: > R.squared print( R.squared ) 0.8161018 The R2 value, sometimes called the coefficient of determination3 has a simple interpretation: it is the proportion of the variance in the outcome variable that can be accounted for by the predictor. So in this case, the fact that we have obtained R2 “.816 means that the predictor (my.sleep) explains 81.6% of the variance in the outcome (my.grump). Naturally, you don’t actually need to type in all these commands yourself if you want to obtain the R2 value for your regression model. As we’ll see later on in Section 15.5.3, all you need to do is use the summary() function. However, let’s put that to one side for the moment. There’s another property of R2 that I want to point out. 15.4.2 The relationship between regression and correlation At this point we can revisit my earlier claim that regression, in this very simple form that I’ve discussed so far, is basically the same thing as a correlation. Previously, we used the symbol r to denote a Pearson correlation. Might there be some relationship between the value of the correlation coefficient r and the R2 value from linear regression? Of course there is: the squared correlation r2 is identical to the R2 value for a linear regression with only a single predictor. To illustrate this, here’s the squared correlation: > r print( r^2 ) # print the squared correlation 0.8161027 Yep, same number. In other words, running a Pearson correlation is more or less equivalent to running a linear regression model that uses only one predictor variable. 3 And by “sometimes” I mean “almost never”. In practice everyone just calls it “R-squared”. - 465 - 15.4.3 The adjusted R2 value One final thing to point out before moving on. It’s quite common for people to report a slightly di↵erent measure of model performance, known as “adjusted R2 ”. The motivation behind calculating the adjusted R2 value is the observation that adding more predictors into the model will always call the R2 value to increase (or at least not decrease). The adjusted R2 value introduces a slight change to the calculation, as follows. For a regression model with K predictors, fit to a data set containing N observations, the adjusted R2 is: ˆ ˙ SSres N ´1 adj. R2 “ 1 ´ ˆ SStot N ´K ´1 This adjustment is an attempt to take the degrees of freedom into account. The big advantage of the adjusted R2 value is that when you add more predictors to the model, the adjusted R2 value will only increase if the new variables improve the model performance more than you’d expect by chance. The big disadvantage is that the adjusted R2 value can’t be interpreted in the elegant way that R2 can. R2 has a simple interpretation as the proportion of variance in the outcome variable that is explained by the regression model; to my knowledge, no equivalent interpretation exists for adjusted R2. An obvious question then, is whether you should report R2 or adjusted R2. This is probably a matter of personal preference. If you care more about interpretability, then R2 is better. If you care more about correcting for bias, then adjusted R2 is probably better. Speaking just for myself, I prefer R2 : my feeling is that it’s more important to be able to interpret your measure of model performance. Besides, as we’ll see in Section 15.5, if you’re worried that the improvement in R2 that you get by adding a predictor is just due to chance and not because it’s a better model, well, we’ve got hypothesis tests for that. 15.5 Hypothesis tests for regression models So far we’ve talked about what a regression model is, how the coefficients of a regression model are estimated, and how we quantify the performance of the model (the last of these, incidentally, is basically our measure of e↵ect size). The next thing we need to talk about is hypothesis tests. There are two di↵erent (but related) kinds of hypothesis tests that we need to talk about: those in which we test whether the regression model as a whole is performing significantly better than a null model; and those in which we test whether a particular regression coefficient is significantly di↵erent from zero. At this point, you’re probably groaning internally, thinking that I’m going to introduce a whole new collection of tests. You’re probably sick of hypothesis tests by now, and don’t want to learn any new ones. Me too. I’m so sick of hypothesis tests that I’m going to shamelessly reuse the F -test from Chapter 14 and the t-test from Chapter 13. In fact, all I’m going to do in this section is show you how those tests are imported wholesale into the regression framework. 15.5.1 Testing the model as a whole Okay, suppose you’ve estimated your regression model. The first hypothesis test you might want to try is one in which the null hypothesis that there is no relationship between the predictors and the outcome, and the alternative hypothesis is that the data are distributed in exactly the way that the regression model predicts. Formally, our “null model” corresponds to the fairly trivial “regression” model in which we include 0 predictors, and only include the intercept term b0 H0 : Y i “ b0 ` ✏ i - 466 - If our regression model has K predictors, the “alternative model” is described using the usual formula for a multiple regression model: ˜ ¸ ÿ K H1 : Y i “ bk Xik ` b0 ` ✏i k“1 How can we test these two hypotheses against each other? The trick is to understand that just like we did with ANOVA, it’s possible to divide up the total variance SStot into the sum of the residual variance SSres and the regression model variance SSmod. I’ll skip over the technicalities, since we covered most of them in the ANOVA chapter, and just note that: SSmod “ SStot ´ SSres And, just like we did with the ANOVA, we can convert the sums of squares in to mean squares by dividing by the degrees of freedom. SSmod MSmod “ dfmod SSres MSres “ dfres So, how many degrees of freedom do we have? As you might expect, the df associated with the model is closely tied to the number of predictors that we’ve included. In fact, it turns out that dfmod “ K. For the residuals, the total degrees of freedom is dfres “ N ´ K ´ 1. Now that we’ve got our mean square values, you’re probably going to be entirely unsurprised (possibly even bored) to discover that we can calculate an F -statistic like this: MSmod F “ MSres and the degrees of freedom associated with this are K and N ´ K ´ 1. This F statistic has exactly the same interpretation as the one we introduced in Chapter 14. Large F values indicate that the null hypothesis is performing poorly in comparison to the alternative hypothesis. And since we already did some tedious “do it the long way” calculations back then, I won’t waste your time repeating them. In a moment I’ll show you how to do the test in R the easy way, but first, let’s have a look at the tests for the individual regression coefficients. 15.5.2 Tests for individual coefficients The F -test that we’ve just introduced is useful for checking that the model as a whole is performing better than chance. This is important: if your regression model doesn’t produce a significant result for the F -test then you probably don’t have a very good regression model (or, quite possibly, you don’t have very good data). However, while failing this test is a pretty strong indicator that the model has problems, passing the test (i.e., rejecting the null) doesn’t imply that the model is good! Why is that, you might be wondering? The answer to that can be found by looking at the coefficients for the regression.2 model: > print( regression.2 ) Call: lm(formula = dan.grump ~ dan.sleep + baby.sleep, data = parenthood) Coefficients: (Intercept) dan.sleep baby.sleep 125.96557 -8.95025 0.01052 - 467 - I can’t help but notice that the estimated regression coefficient for the baby.sleep variable is tiny (0.01), relative to the value that we get for dan.sleep (-8.95). Given that these two variables are absolutely on the same scale (they’re both measured in “hours slept”), I find this suspicious. In fact, I’m beginning to suspect that it’s really only the amount of sleep that I get that matters in order to predict my grumpiness. Once again, we can reuse a hypothesis test that we discussed earlier, this time the t-test. The test that we’re interested has a null hypothesis that the true regression coefficient is zero (b “ 0), which is to be tested against the alternative hypothesis that it isn’t (b ‰ 0). That is: H0 : b“0 H1 : b‰0 How can we test this? Well, if the central limit theorem is kind to us, we might be able to guess that the sampling distribution of b̂, the estimated regression coefficient, is a normal distribution with mean centred on b. What that would mean is that if the null hypothesis were true, then the sampling distribution of b̂ has mean zero and unknown standard deviation. Assuming that we can come up with a good estimate for the standard error of the regression coefficient, sepb̂q, then we’re in luck. That’s exactly the situation for which we introduced the one-sample t way back in Chapter 13. So let’s define a t-statistic like this, b̂ t“ sepb̂q I’ll skip over the reasons why, but our degrees of freedom in this case are df “ N ´ K ´ 1. Irritatingly, the estimate of the standard error of the regression coefficient, sepb̂q, is not as easy to calculate as the standard error of the mean that we used for the simpler t-tests in Chapter 13. In fact, the formula is somewhat ugly, and not terribly helpful to look at.4 For our purposes it’s sufficient to point out that the standard error of the estimated regression coefficient depends on both the predictor and outcome variables, and is somewhat sensitive to violations of the homogeneity of variance assumption (discussed shortly). In any case, this t-statistic can be interpreted in the same way as the t-statistics that we discussed in Chapter 13. Assuming that you have a two-sided alternative (i.e., you don’t really care if b ° 0 or b † 0), then it’s the extreme values of t (i.e., a lot less than zero or a lot greater than zero) that suggest that you should reject the null hypothesis. 15.5.3 Running the hypothesis tests in R To compute all of the quantities that we have talked about so far, all you need to do is ask for a summary() of your regression model. Since I’ve been using regression.2 as my example, let’s do that: > summary( regression.2 ) The output that this command produces is pretty dense, but we’ve already discussed everything of interest in it, so what I’ll do is go through it line by line. The first line reminds us of what the actual regression model is: Call: lm(formula = dan.grump ~ dan.sleep + baby.sleep, data = parenthood) 4 For advanced readers only. The vector of residuals is ✏ “ y ´ Xb̂. For K predictors plus the intercept, the estimated residual variance is ˆ 2 “ ✏1 ✏{pN ´ K ´ 1q. The estimated covariance matrix of the coefficients is ˆ 2 pX1 Xq´1 , the main diagonal of which is sepb̂q, our estimated standard errors. - 468 - You can see why this is handy, since it was a little while back when we actually created the regression.2 model, and so it’s nice to be reminded of what it was we were doing. The next part provides a quick summary of the residuals (i.e., the ✏i values), Residuals: Min 1Q Median 3Q Max -11.0345 -2.2198 -0.4016 2.6775 11.7496 which can be convenient as a quick and dirty check that the model is okay. Remember, we did assume that these residuals were normally distributed, with mean 0. In particular it’s worth quickly checking to see if the median is close to zero, and to see if the first quartile is about the same size as the third quartile. If they look badly o↵, there’s a good chance that the assumptions of regression are violated. These ones look pretty nice to me, so let’s move on to the interesting stu↵. The next part of the R output looks at the coefficients of the regression model: Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 125.96557 3.04095 41.423 |t|) (Intercept) 125.9563 3.0161 41.76 library(lsr) > correlate(parenthood, test=TRUE) CORRELATIONS ============ - correlation type: pearson - correlations shown only when both variables are numeric dan.sleep baby.sleep dan.grump day dan.sleep. 0.628*** -0.903*** -0.098 baby.sleep 0.628***. -0.566*** -0.010 dan.grump -0.903*** -0.566***. 0.076 day -0.098 -0.010 0.076. --- Signif. codes:. = p <.1, * = p residuals( object = regression.2 ) One drawback to using ordinary residuals is that they’re always on a di↵erent scale, depending on what the outcome variable is and how good the regression model is. That is, Unless you’ve decided to run a regression model without an intercept term, the ordinary residuals will have mean 0; but the variance is di↵erent for every regression. In a lot of contexts, especially where you’re only interested in the pattern of the residuals and not their actual values, it’s convenient to estimate the standardised residuals, which are normalised in such a way as to have standard deviation 1. The way we calculate these is to divide the ordinary residual by an estimate of the (population) standard deviation of these residuals. For technical reasons, mumble mumble, the formula for this is: ✏i ✏1i “ ? ˆ 1 ´ hi where ˆ in this context is the estimated population standard deviation of the ordinary residuals, and hi is the “hat value” of the ith observation. I haven’t explained hat values to you yet (but have no fear,8 it’s coming shortly), so this won’t make a lot of sense. For now, it’s enough to interpret the standardised residuals as if we’d converted the ordinary residuals to z-scores. In fact, that is more or less the truth, it’s just that we’re being a bit fancier. To get the standardised residuals, the command you want is this: > rstandard( model = regression.2 ) Note that this function uses a di↵erent name for the input argument, but it’s still just a linear regression object that the function wants to take as its input here. The third kind of residuals are Studentised residuals (also called “jackknifed residuals”) and they’re even fancier than standardised residuals. Again, the idea is to take the ordinary residual and divide it by some quantity in order to estimate some standardised notion of the residual, but the formula for doing the calculations this time is subtly di↵erent: ✏ ✏˚i “ ?i ˆp´iq 1 ´ hi Notice that our estimate of the standard deviation here is written ˆp´iq. What this corresponds to is the estimate of the residual standard deviation that you would have obtained, if you just deleted the ith observation from the data set. This sounds like the sort of thing that would be a nightmare to calculate, since it seems to be saying that you have to run N new regression models (even a modern computer might grumble a bit at that, especially if you’ve got a large data set). Fortunately, some terribly clever person has shown that this standard deviation estimate is actually given by the following equation: d N ´ K ´ 1 ´ ✏1i 2 ˆp´iq “ ˆ N ´K ´2 Isn’t that a pip? Anyway, the command that you would use if you wanted to pull out the Studentised residuals for our regression model is 8 Or have no hope, as the case may be. - 476 - Outlier Outcome Predictor Figure 15.5: An illustration of outliers. The dotted lines plot the regression line that would have been estimated without the anomalous observation included, and the corresponding residual (i.e., the Studen- tised residual). The solid line shows the regression line with the anomalous observation included. The outlier has an unusual value on the outcome (y axis location) but not the predictor (x axis location), and lies a long way from the regression line........................................................................................................ > rstudent( model = regression.2 ) Before moving on, I should point out that you don’t often need to manually extract these residuals yourself, even though they are at the heart of almost all regression diagnostics. That is, the residuals(), rstandard() and rstudent() functions are all useful to know about, but most of the time the various functions that run the diagnostics will take care of these calculations for you. Even so, it’s always nice to know how to actually get hold of these things yourself in case you ever need to do something non-standard. 15.9.2 Three kinds of anomalous data One danger that you can run into with linear regression models is that your analysis might be dispro- portionately sensitive to a smallish number of “unusual” or “anomalous” observations. I discussed this idea previously in Section 6.5.2 in the context of discussing the outliers that get automatically identified by the boxplot() function, but this time we need to be much more precise. In the context of linear regres- sion, there are three conceptually distinct ways in which an observation might be called “anomalous”. All three are interesting, but they have rather di↵erent implications for your analysis. The first kind of unusual observation is an outlier. The definition of an outlier (in this context) is an observation that is very di↵erent from what the regression model predicts. An example is shown in Figure 15.5. In practice, we operationalise this concept by saying that an outlier is an observation that - 477 - High leverage Outcome Predictor Figure 15.6: An illustration of high leverage points. The anomalous observation in this case is unusual both in terms of the predictor (x axis) and the outcome (y axis), but this unusualness is highly con- sistent with the pattern of correlations that exists among the other observations; as a consequence, the observation falls very close to the regression line and does not distort it........................................................................................................ has a very large Studentised residual, ✏˚i. Outliers are interesting: a big outlier might correspond to junk data – e.g., the variables might have been entered incorrectly, or some other defect may be detectable. Note that you shouldn’t throw an observation away just because it’s an outlier. But the fact that it’s an outlier is often a cue to look more closely at that case, and try to find out why it’s so di↵erent. The second way in which an observation can be unusual is if it has high leverage: this happens when the observation is very di↵erent from all the other observations. This doesn’t necessarily have to correspond to a large residual: if the observation happens to be unusual on all variables in precisely the same way, it can actually lie very close to the regression line. An example of this is shown in Figure 15.6. The leverage of an observation is operationalised in terms of its hat value, usually written hi. The formula for the hat value is rather complicated9 but its interpretation is not: hi is a measure of the extent to which the i-th observation is “in control” of where the regression line ends up going. You can extract the hat values using the following command: > hatvalues( model = regression.2 ) In general, if an observation lies far away from the other ones in terms of the predictor variables, it will have a large hat value (as a rough guide, high leverage is when the hat value is more than 2-3 times the 9 Again, for the linear algebra fanatics: the “hat matrix” is defined to be that matrix H that converts the vector of observed values y into a vector of fitted values ŷ, such that ŷ “ Hy. The name comes from the fact that this is the matrix that “puts a hat on y”. The hat value of the i-th observation is the i-th diagonal element of this matrix (so technically I should be writing it as hii rather than hi ). Oh, and in case you care, here’s how it’s calculated: H “ XpX1 Xq´1 X1. Pretty, isn’t it? - 478 - Outcome High influence Predictor Figure 15.7: An illustration of high influence points. In this case, the anomalous observation is highly unusual on the predictor variable (x axis), and falls a long way from the regression line. As a consequence, the regression line is highly distorted, even though (in this case) the anomalous observation is entirely typical in terms of the outcome variable (y axis)........................................................................................................ average; and note that the sum of the hat values is constrained to be equal to K ` 1). High leverage points are also worth looking at in more detail, but they’re much less likely to be a cause for concern unless they are also outliers. This brings us to our third measure of unusualness, the influence of an observation. A high influence observation is an outlier that has high leverage. That is, it is an observation that is very di↵erent to all the other ones in some respect, and also lies a long way from the regression line. This is illustrated in Figure 15.7. Notice the contrast to the previous two figures: outliers don’t move the regression line much, and neither do high leverage points. But something that is an outlier and has high leverage... that has a big e↵ect on the regression line. That’s why we call these points high influence; and it’s why they’re the biggest worry. We operationalise influence in terms of a measure known as Cook’s distance, ✏˚i 2 hi Di “ ˆ K ` 1 1 ´ hi Notice that this is a multiplication of something that measures the outlier-ness of the observation (the bit on the left), and something that measures the leverage of the observation (the bit on the right). In other words, in order to have a large Cook’s distance, an observation must be a fairly substantial outlier and have high leverage. In a stunning turn of events, you can obtain these values using the following command: > cooks.distance( model = regression.2 ) - 479 - As a rough guide, Cook’s distance greater than 1 is often considered large (that’s what I typically use as a quick and dirty rule), though a quick scan of the internet and a few papers suggests that 4{N has also been suggested as a possible rule of thumb. As hinted above, you don’t usually need to make use of these functions, since you can have R au- tomatically draw the critical plots.10 For the regression.2 model, these are the plots showing Cook’s distance (Figure 15.8) and the more detailed breakdown showing the scatter plot of the Studentised residual against leverage (Figure 15.9). To draw these, we can use the plot() function. When the main argument x to this function is a linear model object, it will draw one of six di↵erent plots, each of which is quite useful for doing regression diagnostics. You specify which one you want using the which argument (a number between 1 and 6). If you don’t do this then R will draw all six. The two plots of interest to us in this context are generated using the following commands: > plot(x = regression.2, which = 4) # Figure 15.8 > plot(x = regression.2, which = 5) # Figure 15.9 An obvious question to ask next is, if you do have large values of Cook’s distance, what should you do? As always, there’s no hard and fast rules. Probably the first thing to do is to try running the regression with that point excluded and see what happens to the model performance and to the regression coefficients. If they really are substantially di↵erent, it’s time to start digging into your data set and your notes that you no doubt were scribbling as your ran your study; try to figure out why the point is so di↵erent. If you start to become convinced that this one data point is badly distorting your results, you might consider excluding it, but that’s less than ideal unless you have a solid explanation for why this particular case is qualitatively di↵erent from the others and therefore deserves to be handled separately.11 To give an example, let’s delete the observation from day 64, the observation with the largest Cook’s distance for the regression.2 model. We can do this using the subset argument: > lm( formula = dan.grump ~ dan.sleep + baby.sleep, # same formula + data = parenthood, # same data frame... + subset = -64 #...but observation 64 is deleted + ) Call: lm(formula = dan.grump ~ dan.sleep + baby.sleep, data = parenthood, subset = -64) Coefficients: (Intercept) dan.sleep baby.sleep 126.3553 -8.8283 -0.1319 As you can see, those regression coefficients have barely changed in comparison to the values we got earlier. In other words, we really don’t have any problem as far as anomalous data are concerned. 15.9.3 Checking the normality of the residuals Like many of the statistical tools we’ve discussed in this book, regression models rely on a normality assumption. In this case, we assume that the residuals are normally distributed. The tools for testing this aren’t fundamentally di↵erent to those that we discussed earlier in Section 13.9. Firstly, I firmly 10 Though special mention should be made of the influenceIndexPlot() and influencePlot() functions in the car package. These produce somewhat more detailed pictures than the default plots that I’ve shown here. There’s also an outlierTest() function that tests to see if any of the Studentised residuals are significantly larger than would be expected by chance. 11 An alternative is to run a “robust regression”; I’ll discuss robust regression in a later version of this book. - 480 - Cook’s distance 0.00 0.02 0.04 0.06 0.08 0.10 0.12 64 Cook’s distance 85 27 0 20 40 60 80 100 Obs. number lm(dan.grump ~ dan.sleep + baby.sleep) Figure 15.8: Cook’s distance for every observation. This is one of the standard regression plots produced by the plot() function when the input is a linear regression object. It is obtained by setting which=4........................................................................................................ Residuals vs Leverage 3 85 2 27 Standardized residuals 1 0 −1 −2 64 Cook’s distance −3 0.00 0.02 0.04 0.06 0.08 Leverage lm(dan.grump ~ dan.sleep + baby.sleep) Figure 15.9: Residuals versus leverage. This is one of the standard regression plots produced by the plot() function when the input is a linear regression object. It is obtained by setting which=5........................................................................................................ - 481 - 12 10 8 Frequency 6 4 2 0 −10 −5 0 5 10 Value of residual Figure 15.10: A histogram of the (ordinary) residuals in the regression.2 model. These residuals look very close to being normally distributed, much moreso than is typically seen with real data. This shouldn’t surprise you... they aren’t real data, and they aren’t real residuals!....................................................................................................... - 482 - Normal Q−Q 3 78 2 Standardized residuals 1 0 −1 −2 81 36 −2 −1 0 1 2 Theoretical Quantiles lm(dan.grump ~ dan.sleep + baby.sleep) Figure 15.11: Plot of the theoretical quantiles according to the model, against the quantiles of the standardised residuals. This is one of the standard regression plots produced by the plot() function when the input is a linear regression object. It is obtained by setting which=2........................................................................................................ believe that it never hurts to draw an old fashioned histogram. The command I use might be something like this: > hist( x = residuals( regression.2 ), # data are the residuals + xlab = "Value of residual", # x-axis label + main = "", # no title + breaks = 20 # lots of breaks + ) The resulting plot is shown in Figure 15.10, and as you can see the plot looks pretty damn close to normal, almost unnaturally so. I could also run a Shapiro-Wilk test to check, using the shapiro.test() function; the W value of.99, at this sample size, is non-significant (p “.84), again suggesting that the normality assumption isn’t in any danger here. As a third measure, we might also want to draw a QQ-plot using the qqnorm() function. The QQ plot is an excellent one to draw, and so you might not be surprised to discover that it’s one of the regression plots that we can produce using the plot() function: > plot( x = regression.2, which = 2 ) # Figure 15.11 The output is shown in Figure 15.11, showing the standardised residuals plotted as a function of their theoretical quantiles according to the regression model. The fact that the output appends the model specification to the picture is nice. - 483 - 90 80 Observed Values 70 60 50 40 50 60 70 80 Fitted Values Figure 15.12: Plot of the fitted values against the observed values of the outcome variable. A straight line is what we’re hoping to see here. This looks pretty good, suggesting that there’s nothing grossly wrong, but there could be hidden subtle issues........................................................................................................ 15.9.4 Checking the linearity of the relationship The third thing we might want to test is the linearity of the relationships between the predictors and the outcomes. There’s a few di↵erent things that you might want to do in order to check this. Firstly, it never hurts to just plot the relationship between the fitted values Ŷi and the observed values Yi for the outcome variable, as illustrated in Figure 15.12. To draw this we could use the fitted.values() function to extract the Ŷi values in much the same way that we used the residuals() function to extract the ✏i values. So the commands to draw this figure might look like this: > yhat.2 plot( x = yhat.2, + y = parenthood$dan.grump, + xlab = "Fitted Values", + ylab = "Observed Values" + ) One of the reasons I like to draw these plots is that they give you a kind of “big picture view”. If this plot looks approximately linear, then we’re probably not doing too badly (though that’s not to say that there aren’t problems). However, if you can see big departures from linearity here, then it strongly suggests that you need to make some changes. In any case, in order to get a more detailed picture it’s often more informative to look at the relation- ship between the fitted values and the residuals themselves. Again, we could draw this plot using low - 484 - Residuals vs Fitted 78 10 5 Residuals 0 −5 −10 81 36 50 60 70 80 Fitted values lm(dan.grump ~ dan.sleep + baby.sleep) Figure 15.13: Plot of the fitted values against the residuals for regression.2, with a line showing the relationship between the two. If this is horizontal and straight, then we can feel reasonably confident that the “average residual” for all “fitted values” is more or less the same. This is one of the standard regression plots produced by the plot() function when the input is a linear regression object. It is obtained by setting which=1........................................................................................................ level commands, but there’s an easier way. Just plot() the regression model, and select which = 1: > plot(x = regression.2, which = 1) # Figure 15.13 The output is shown in Figure 15.13. As you can see, not only does it draw the scatterplot showing the fitted value against the residuals, it also plots a line through the data that shows the relationship between the two. Ideally, this should be a straight, perfectly horizontal line. There’s some hint of curvature here, but it’s not clear whether or not we be concerned. A somewhat more advanced version of the same plot is produced by the residualPlots() function in the car package. This function not only draws plots comparing the fitted values to the residuals, it does so for each individual predictor. The command is > residualPlots( model = regression.2 ) # Figure 15.14 and the resulting plots are shown in Figure 15.14. Note that this function also reports the results of a bunch of curvature tests. For a predictor variable X in some regression model, this test is equivalent to adding a new predictor to the model corresponding to X 2 , and running the t-test on the b coefficient associated with this new predictor. If it comes up significant, it implies that there is some nonlinear relationship between the variable and the residuals. For what it’s worth, here’s what you get for the regression.2 model: - 485 - 10 10 Pearson residuals Pearson residuals 5 5 0 0 −10 −10 5 6 7 8 9 4 6 8 10 12 dan.sleep baby.sleep 10 Pearson residuals 5 0 −10 50 60 70 80 Fitted values Figure 15.14: Plot of the fitted values against the residuals for regression.2, along with similar plots for the two predictors individually. This plot is produced by the residualPlots() function in the car package. Note that it refers to the residuals as “Pearson residuals”, but in this context these are the same as ordinary residuals........................................................................................................ Test stat Pr(>|t|) dan.sleep 2.160 0.033 baby.sleep -0.545 0.587 Tukey test 2.162 0.031 The third line here is the Tukey test, which is basically the same test, except that instead of squaring one of the predictors and adding it to the model, you square the fitted-value. In any case, the fact that the curvature tests have come up significant is hinting that the curvature that we can see in Figures 15.13 and 15.14 is genuine;12 although it still bears remembering that the pattern in Figure 15.12 is pretty damn straight: in other words the deviations from linearity are pretty small, and probably not worth worrying about. 12 And, if you take the time to check the residualPlots() for regression.1, it’s pretty clear that this isn’t some wacky dis- tortion being caused by the fact that baby.sleep is a useless predictor variable. It’s an actual nonlinearity in the relationship between dan.sleep and dan.grump. - 486 - In a lot of cases, the solution to this problem (and many others) is to transform one or more of the variables. We discussed the basics of variable transformation in Sections 7.2 and 7.3, but I do want to make special note of one additional possibility that I didn’t mention earlier: the Box-Cox transform. The Box-Cox function is a fairly simple one, but it’s very widely used x ´1 f px, q “ for all values of except “ 0. When “ 0 we just take the natural logarithm (i.e., lnpxq). You can calculate it using the boxCox() function in the car package. Better yet, if what you’re trying to do is convert a data to normal, or as normal as possible, there’s the powerTransform() function in the car package that can estimate the best value of. Variable transformation is another topic that deserves a fairly detailed treatment, but (again) due to deadline constraints, it will have to wait until a future version of this book. 15.9.5 Checking the homogeneity of variance The regression models that we’ve talked about all make a homogeneity of variance assumption: the variance of the residuals is assumed to be constant. The “default” plot that R provides to help a with doing this (which = 3 when using plot()) shows a plot of the square root of the size of the residual |✏i |, as a function of the fitted value Ŷi. We can produce the plot using the following command, > plot(x = regression.2, which = 3) and the resulting plot is shown in Figure 15.15. Note that this plot actually uses the standardised residuals (i.e., converted to z scores) rather than the raw ones, but it’s immaterial from our point of view. What we’re looking to see here is a straight, horizontal line running through the middle of the plot. A slightly more formal approach is to run hypothesis tests. The car package provides a function called ncvTest() (non-constant variance test) that can be used for this purpose (Cook & Weisberg, 1983). I won’t explain the details of how it works, other than to say that the idea is that what you do is run a regression to see if there is a relationship between the squared residuals ✏i and the fitted values Ŷi , or possibly to run a regression using all of the original predictors instead of just Ŷi.13 Using the default settings, the ncvTest() looks for a relationship between Ŷi and the variance of the residuals, making it a straightforward analogue of Figure 15.15. So if we run it for our model, > ncvTest( regression.2 ) Non-constant Variance Score Test Variance formula: ~ fitted.values Chisquare = 0.09317511 Df = 1 p = 0.7601788 We see that our original impression was right: there’s no violations of homogeneity of variance in this data. It’s a bit beyond the scope of this chapter to talk too much about how to deal with violations of homogeneity of variance, but I’ll give you a quick sense of what you need to consider. The main thing to worry about, if homogeneity of variance is violated, is that the standard error estimates associated with the regression coefficients are no longer entirely reliable, and so your t tests for the coefficients aren’t quite right either. A simple fix to the problem is to make use of a “heteroscedasticity corrected covariance matrix” when estimating the standard errors. These are often called sandwich estimators, for reasons 13 Note that the underlying mechanics of the test aren’t the same as the ones I’ve described for regressions; the goodness of fit is assessed using what’s known as a score-test not an F -test, and the test statistic is (approximately) 2 distributed if there’s no relationship - 487 - Scale−Location 78 81 36 1.5 Standardized residuals 1.0 0.5 0.0 50 60 70 80 Fitted values lm(dan.grump ~ dan.sleep + baby.sleep) Figure 15.15: Plot of the fitted values (model predictions) against the square root of the abs standardised residuals. This plot is used to diagnose violations of homogeneity of variance. If the variance is really constant, then the line through the middle should be horizontal and flat. This is one of the standard regression plots produced by the plot() function when the input is a linear regression object. It is obtained by setting which=3........................................................................................................ that only make sense if you understand the maths at a low level14 You don’t need to understand what this means (not for an introductory class), but it might help to note that there’s a hccm() function in the car() package that does it. Better yet, you don’t even need to use it. You can use the coeftest() function in the lmtest package, but you need the car package loaded: > coeftest( regression.2, vcov= hccm ) t test of coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 125.965566 3.247285 38.7910 cor( parenthood ) dan.sleep baby.sleep dan.grump day dan.sleep 1.00000000 0.62794934 -0.90338404 -0.09840768 baby.sleep 0.62794934 1.00000000 -0.56596373 -0.01043394 dan.grump -0.90338404 -0.56596373 1.00000000 0.07647926 day -0.09840768 -0.01043394 0.07647926 1.00000000 We have some fairly large correlations between some of our predictor variables! When we run the regression model and look at the VIF values, we see that the collinearity is causing a lot of uncertainty about the coefficients. First, run the regression... > regression.3 vif( regression.3 ) baby.sleep dan.sleep dan.grump 1.651064 6.102337 5.437903 Yep, that’s some mighty fine collinearity you’ve got there. - 489 - 15.10 Model selection One fairly major problem that remains is the problem of “model selection”. That is, if we have a data set that contains several variables, which ones should we include as predictors, and which ones should we not include? In other words, we have a problem of variable selection. In general, model selection is a complex business, but it’s made somewhat simpler if we restrict ourselves to the problem of choosing a subset of the variables that ought to be included in the model. Nevertheless, I’m not going to try covering even this reduced topic in a lot of detail. Instead, I’ll talk about two broad principles that you need to think about; and then discuss one concrete tool that R provides to help you select a subset of variables to include in your model. Firstly, the two principles: It’s nice to have an actual substantive basis for your choices. That is, in a lot of situations you the researcher have good reasons to pick out a smallish number of possible regression models that are of theoretical interest; these models will have a sensible interpretation in the context of your field. Never discount the importance of this. Statistics serves the scientific process, not the other way around. To the extent that your choices rely on statistical inference, there is a trade o↵ between simplicity and goodness of fit. As you add more predictors to the model, you make it more complex; each predictor adds a new free parameter (i.e., a new regression coefficient), and each new parameter increases the model’s capacity to “absorb” random variations. So the goodness of fit (e.g., R2 ) continues to rise as you add more predictors no matter what. If you want your model to be able to generalise well to new observations, you need to avoid throwing in too many variables. This latter principle is often referred to as Ockham’s razor, and is often summarised in terms of the following pithy saying: do not multiply entities beyond necessity. In this context, it means: don’t chuck in a bunch of largely irrelevant predictors just to boost your R2. Hm. Yeah, the original was better. In any case, what we need is an actual mathematical criterion that will implement the qualitative principle behind Ockham’s razor in the context of selecting a regression model. As it turns out there are several possibilities. The one that I’ll talk about is the Akaike information criterion (AIC; Akaike, 1974) simply because it’s the default one used in the R function step(). In the context of a linear regression model (and ignoring terms that don’t depend on the model in any way!), the AIC for a model that has K predictor variables plus an intercept is:15 SSres AIC “ ` 2K ˆ2 The smaller the AIC value, the better the model performance is. If we ignore the low level details, it’s fairly obvious what the AIC does: on the left we have a term that increases as the model predictions get worse; on the right we have a term that increases as the model complexity increases. The best model is the one that fits the data well (low residuals; left hand side) using as few predictors as possible (low K; right hand side). In short, this is a simple implementation of Ockham’s razor. 15 Note, however, that the step() function computes the full version of AIC, including the irrelevant constants that I’ve dropped here. As a consequence this equation won’t correctly describe the AIC values that you see in the outputs here. However, if you calculate the AIC values using my formula for two di↵erent regression models and take the di↵erence between them, this will be the same as the di↵erences between AIC values that step() reports. In practice, this is all you care about: the actual value of an AIC statistic isn’t very informative, but the di↵erences between two AIC values are useful, since these provide a measure of the extent to which one model outperforms another. - 490 - 15.10.1 Backward elimination Okay, let’s have a look at the step() function at work. In this example I’ll keep it simple and use only the basic backward elimination approach. That is, start with the complete regression model, including all possible predictors. Then, at each “step” we try all possible ways of removing one of the variables, and whichever of these is best (in terms of lowest AIC value) is accepted. This becomes our new regression model; and we then try all possible deletions from the new model, again choosing the option with lowest AIC. This process continues until we end up with a model that has a lower AIC value than any of the other possible models that you could produce by deleting one of its predictors. Let’s see this in action. First, I need to define the model from which the process starts. > full.model step( object = full.model, # start at the full model + direction = "backward" # allow it remove predictors but not add them + ) although in practice I didn’t need to specify direction because "backward" is the default. The output is somewhat lengthy, so I’ll go through it slowly. Firstly, the output reports the AIC value for the current best model: Start: AIC=299.08 dan.grump ~ dan.sleep + baby.sleep + day That’s our starting point. Since small AIC values are good, we want to see if we can get a value smaller than 299.08 by deleting one of those three predictors. So what R does is try all three possibilities, calculate the AIC values for each one, and then print out a short table with the results: Df Sum of Sq RSS AIC - baby.sleep 1 0.1 1837.2 297.08 - day 1 1.6 1838.7 297.16 1837.1 299.08 - dan.sleep 1 4909.0 6746.1 427.15 To read this table, it helps to note that the text in the left hand column is telling you what change R made to the regression model. So the line that reads is the actual model we started with, and you can see on the right hand side that this still corresponds to an AIC value of 299.08 (obviously). The other three rows in the table correspond to the other three models that it looked at: it tried removing the baby.sleep variable, which is indicated by - baby.sleep, and this produced an AIC value of 297.08. That was the best of the three moves, so it’s at the top of the table. So, this move is accepted, and now we start again. There are two predictors left in the model, dan.sleep and day, so it tries deleting those: Step: AIC=297.08 dan.grump ~ dan.sleep + day Df Sum of Sq RSS AIC - day 1 1.6 1838.7 295.17 1837.2 297.08 - dan.sleep 1 8103.0 9940.1 463.92 - 491 - Okay, so what we can see is that removing the day variable lowers the AIC value from 297.08 to 295.17. So R decides to keep that change too, and moves on: Step: AIC=295.17 dan.grump ~ dan.sleep Df Sum of Sq RSS AIC 1838.7 295.17 - dan.sleep 1 8159.9 9998.6 462.50 This time around, there’s no further deletions that can actually improve the AIC value. So the step() function stops, and prints out the result of the best regression model it could find: Call: lm(formula = dan.grump ~ dan.sleep, data = parenthood) Coefficients: (Intercept) dan.sleep 125.956 -8.937 which is (perhaps not all that surprisingly) the regression.1 model that we started with at the beginning of the chapter. 15.10.2 Forward selection As an alternative, you can also try forward selection. This time around we start with the smallest possible model as our start point, and only consider the possible additions to the model. However, there’s one complication: you also need to tell step() what the largest possible model you’re willing to entertain is, using the scope argument. The simplest usage is like this: > null.model step( object = null.model, # start with null.model + direction = "forward", # only consider "addition" moves + scope = dan.grump ~ dan.sleep + baby.sleep + day # largest model allowed + ) If I do this, the output takes on a similar form, but now it only considers addition (+) moves rather than deletion (-) moves: Start: AIC=462.5 dan.grump ~ 1 Df Sum of Sq RSS AIC + dan.sleep 1 8159.9 1838.7 295.17 + baby.sleep 1 3202.7 6795.9 425.89 9998.6 462.50 + day 1 58.5 9940.1 463.92 Step: AIC=295.17 dan.grump ~ dan.sleep Df Sum of Sq RSS AIC 1838.7 295.17 - 492 - + day 1 1.55760 1837.2 297.08 + baby.sleep 1 0.02858 1838.7 297.16 Call: lm(formula = dan.grump ~ dan.sleep, data = parenthood) Coefficients: (Intercept) dan.sleep 125.956 -8.937 As you can see, it’s found the same model. In general though, forward and backward selection don’t always have to end up in the same place. 15.10.3 A caveat Automated variable selection methods are seductive things, especially when they’re bundled up in (fairly) simple functions like step(). They provide an element of objectivity to your model selection, and that’s kind of nice. Unfortunately, they’re sometimes used as an excuse for thoughtlessness. No longer do you have to think carefully about which predictors to add to the model and what the theoretical basis for their inclusion might be... everything is solved by the magic of AIC. And if we start throwing around phrases like Ockham’s razor, well, it sounds like everything is wrapped up in a nice neat little package that no-one can argue with. Or, perhaps not. Firstly, there’s very little agreement on what counts as an appropriate model selection criterion. When I was taught backward elimination as an undergraduate, we used F -tests to do it, because that was the default method used by the software. The default in the step() function is AIC, and since this is an introductory text that’s the only method I’ve described, but the AIC is hardly the Word of the Gods of Statistics. It’s an approximation, derived under certain assumptions, and it’s guaranteed to work only for large samples when those assumptions are met. Alter those assumptions and you get a di↵erent criterion, like the BIC for instance. Take a di↵erent approach again and you get the NML criterion. Decide that you’re a Bayesian and you get model selection based on posterior odds ratios. Then there are a bunch of regression specific tools that I haven’t mentioned. And so on. All of these di↵erent methods have strengths and weaknesses, and some are easier to calculate than others (AIC is probably the easiest of the lot, which might account for its popularity). Almost all of them produce the same answers when the answer is “obvious” but there’s a fair amount of disagreement when the model selection problem becomes hard. What does this mean in practice? Well, you could go and spend several years teaching yourself the theory of model selection, learning all the ins and outs of it; so that you could finally decide on what you personally think the right thing to do is. Speaking as someone who actually did that, I wouldn’t recommend it: you’ll probably come out the other side even more confused than when you started. A better strategy is to show a bit of common sense... if you’re staring at the results of a step() procedure, and the model that makes sense is close to having the smallest AIC, but is narrowly defeated by a model that doesn’t make any sense... trust your instincts. Statistical model selection is an inexact tool, and as I said at the beginning, interpretability matters. 15.10.4 Comparing two regression models An alternative to using automated model selection procedures is for the researcher to explicitly select two or more regression models to compare to each other. You can do this in a few di↵erent ways, depending on what research question you’re trying to answer. Suppose we want to know whether or not the amount of sleep that my son got has any relationship to my grumpiness, over and above what we - 493 - might expect from the amount of sleep that I got. We also want to make sure that the day on which we took the measurement has no influence on the relationship. That is, we’re interested in the relationship between baby.sleep and dan.grump, and from that perspective dan.sleep and day are nuisance variable or covariates that we want to control for. In this situation, what we would like to know is whether dan.grump ~ dan.sleep + day + baby.sleep (which I’ll call Model 1, or M1) is a better regression model for these data than dan.grump ~ dan.sleep + day (which I’ll call Model 0, or M0). There are two di↵erent ways we can compare these two models, one based on a model selection criterion like AIC, and the other based on an explicit hypothesis test. I’ll show you the AIC based approach first because it’s simpler, and follows naturally from the step() function that we saw in the last section. The first thing I need to do is actually run the regressions: > M0 M1 AIC( M0, M1 ) df AIC M0 4 582.8681 M1 5 584.8646 Since Model 0 has the smaller AIC value, it is judged to be the better model for these data. A somewhat di↵erent approach to the problem comes out of the hypothesis testing framework. Sup- pose you have two regression models, where one of them (Model 0) contains a subset of the predictors from the other one (Model 1). That is, Model 1 contains all of the predictors included in Model 0, plus one or more additional predictors. When this happens we say that Model 0 is nested within Model 1, or possibly that Model 0 is a submodel of Model 1. Regardless of the terminology what this means is that we can think of Model 0 as a null hypothesis and Model 1 as an alternative hypothesis. And in fact we can construct an F test for this in a fairly straightforward fashion. We can fit both models to the data p0q p1q and obtain a residual sum of squares for both models. I’ll denote these as SSres and SSres respectively. The superscripting here just indicates which model we’re talking about. Then our F statistic is pSSp0q p1q res ´ SSres q{k F “ pSSp1q res q{pN ´ p ´ 1q where N is the number of observations, p is the number of predictors in the full model (not including the intercept), and k is the di↵erence in the number of parameters between the two models.17 The degrees of freedom here are k and N ´ p ´ 1. Note that it’s often more convenient to think about the di↵erence 16 While I’m on this topic I should point out that there is also a function called BIC() which computes the Bayesian information criterion (BIC) for the models. So you could type BIC(M0,M1) and get a very similar output. In fact, while I’m not particularly impressed with either AIC or BIC as model selection methods, if you do find yourself using one of these two, the empirical evidence suggests that BIC is the better criterion of the two. In most simulation studies that I’ve seen, BIC does a much better job of selecting the correct model. 17 It’s worth noting in passing that this same F statistic can be used to test a much broader range of hypotheses than those that I’m mentioning here. Very briefly: notice that the nested model M0 corresponds to the full model M1 when we constrain some of the regression coefficients to zero. It is sometimes useful to construct submodels by placing other kinds of constraints on the regression coefficients. For instance, maybe two di↵erent coefficients might have to sum to zero, or something like that. You can construct hypothesis tests for those kind of constraints too, but it is somewhat more complicated and the sampling distribution for F can end up being something known as the non-central F distribution, which is waaaaay beyond the scope of this book! All I want to do is alert you to this possibility. - 494 - between those two SS values as a sum of squares in its own right. That is: SS “ SSp0q p1q res ´ SSres The reason why this his helpful is that we can express SS a measure of the extent to which the two models make di↵erent predictions about the the outcome variable. Specifically: ÿ´ p1q p0q ¯2 SS “ ŷi ´ ŷi i p0q p1q where ŷi is the fitted value for yi according to model M0 and ŷi is the is the fitted value for yi according to model M1. Okay, so that’s the hypothesis test that we use to compare two regression models to one another. Now, how do we do it in R? The answer is to use the anova() function. All we have to do is input the two models that we want to compare (null model first): > anova( M0, M1 ) Analysis of Variance Table Model 1: dan.grump ~ dan.sleep + day Model 2: dan.grump ~ dan.sleep + day + baby.sleep Res.Df RSS Df Sum of Sq F Pr(>F) 1 97 1837.2 2 96 1837.1 1 0.063688 0.0033 0.9541 Note that, just like we saw with the output from the step() function, R has used the acronym RSS to refer to the residual sum of squares from each model. That is, RSS in this output corresponds to SSres in the formula above. Since we have p °.05 we retain the null hypothesis (M0). This approach to regression, in which we add all of our covariates into a null model, and then add the variables of interest into an alternative model, and then compare the two models in hypothesis testing framework, is often referred to as hierarchical regression. 15.11 Summary Basic ideas in linear regression and how regression models are estimated (Sections 15.1 and 15.2). Multiple linear regression (Section 15.3). Measuring the overall performance of a regression model using R2 (Section 15.4) Hypothesis tests for regression models (Section 15.5) Calculating confidence intervals for regression coefficients, and standardised coefficients (Section 15.7) The assumptions of regression (Section 15.8) and how to check them (Section 15.9) Selecting a regression model (Section 15.10) - 495 -

Use Quizgecko on...
Browser
Browser