Chapter page 13 / 387 Linear regression with a single predictor
English

7  Linear regression with a single predictor

Linear regression is a very powerful statistical technique. Many people have some familiarity with regression models just from reading the news, where straight lines are overlaid on scatterplots. Linear models can be used for prediction or to describe the relationship between two numerical variables, assuming there is a linear relationship between them.

7.1 Fitting a line, residuals, and correlation

When considering linear regression, it’s helpful to think deeply about the line fitting process. In this section, we define the form of a linear model, explore criteria for what makes a good fit, and introduce a new statistic called correlation.

7.1.1 Fitting a line to data

Figure 7.1 shows two variables whose relationship can be modeled perfectly with a straight line. The equation for the line is \(y = 5 + 64.96 x.\) Consider what a perfect linear relationship means: we know the exact value of \(y\) just by knowing the value of \(x.\) A perfect linear relationship is unrealistic in almost any natural process. For example, if we took family income \((x),\) this value would provide some useful information about how much financial support a college may offer a prospective student \((y.)\) However, the prediction would be far from perfect, since other factors play a role in financial support beyond a family’s finances.

A scatterplot showing a perfect linear relationship between number of stocks to purchase on the x-axis and total cost of the share purchase on the y-axis.
Figure 7.1: Requests from twelve separate buyers were simultaneously placed with a trading company to purchase Target Corporation stock (ticker TGT, December 28th, 2018), and the total cost of the shares was reported. Because the cost is computed using a linear formula, the linear fit is perfect.

Linear regression is the statistical method for fitting a line to data where the relationship between two variables, \(x\) and \(y,\) can be modeled by a straight line with some error:

\[ y = b_0 + b_1 \ x + e \]

The values \(b_0\) and \(b_1\) represent the model’s intercept and slope, respectively, and the error is represented by \(e.\) These values are calculated based on the data, i.e., they are sample statistics. If the observed data is a random sample from a target population that we are interested in making inferences about, these values are considered to be point estimates for the population parameters \(\beta_0\) and \(\beta_1.\) We will discuss how to make inferences about parameters of a linear model based on sample statistics in Chapter 24.

The Greek letter \(\beta\) is pronounced beta, listen to the pronunciation here.

When we use \(x\) to predict \(y,\) we usually call \(x\) the predictor variable and we call \(y\) the outcome. We also often drop the \(e\) term when writing down the model since our main focus is often on the prediction of the average outcome.

It is rare for all of the data to fall perfectly on a straight line. Instead, it’s more common for data to appear as a cloud of points, such as those examples shown in Figure 7.2. In each case, the data fall around a straight line, even if none of the observations fall exactly on the line. The first plot shows a relatively strong downward linear trend, where the remaining variability in the data around the line is minor relative to the strength of the relationship between \(x\) and \(y.\) The second plot shows an upward trend that, while evident, is not as strong as the first. The last plot shows a very weak downward trend in the data, so slight we can hardly notice it. In each of these examples, we will have some uncertainty regarding our estimates of the model parameters, \(\beta_0\) and \(\beta_1.\) For instance, we might wonder, should we move the line up or down a little, or should we tilt it more or less? As we move forward in this chapter, we will learn about criteria for line-fitting, and we will also learn about the uncertainty associated with estimates of model parameters.

Three scatterplots with fabricated data. The first panel shows a strong negative linear relationship. The second panel shows a moderate positive linear relationship. The last panel shows no relationship between the x and y variables.
Figure 7.2: Three datasets where a linear model may be useful even though the data do not all fall exactly on the line.

There are also cases where fitting a straight line to the data, even if there is a clear relationship between the variables, is not helpful. One such case is shown in Figure 7.3 where there is a very clear relationship between the variables even though the trend is not linear. We discuss nonlinear trends in this chapter and the next, but details of fitting nonlinear models are saved for a later course.

A scatterplot showing a perfect quadratic relationship between angle of incline on the x-axis and distance traveled on the y-axis. The line of best fit is superimposed as a perfectly horizontal line. That is to say, the variables are clearly related, but they do not have a linear relationship.
Figure 7.3: The best fitting line for these data is flat, which is not a useful way to describe the non-linear relationship. These data are from a physics experiment.

7.1.2 Using linear regression to predict possum head lengths

Brushtail possums are marsupials that live in Australia, and a photo of one is shown in Figure 7.4. Researchers captured 104 of these animals and took body measurements before releasing the animals back into the wild. We consider two of these measurements: the total length of each possum, from head to tail, and the length of each possum’s head.

Photograph of a common brushtail possum of Australia.
Figure 7.4: The common brushtail possum of Australia. Photo by Greg Schecter, flic.kr/p/9BAFbR, CC BY 2.0 license.

The possum data can be found in the openintro R package.

Figure 7.5 shows a scatterplot for the head length (mm) and total length (cm) of the possums. Each point represents a single possum from the data. The head and total length variables are associated: possums with an above average total length also tend to have above average head lengths. While the relationship is not perfectly linear, it could be helpful to partially explain the connection between these variables with a straight line.

A scatterplot with total length on the x-axis and head length on the y-axis. The variables show a moderately strong positive linear relationship. A single observation is circled in red with coordinates of approximately 84cm of total length and 87mm of head length.
Figure 7.5: A scatterplot showing head length against total length for 104 brushtail possums. A point representing a possum with head length 86.7 mm and total length 84 cm is highlighted.

We want to describe the relationship between head and total length of possums with a line. In this example, we will use the total length as the predictor variable, \(x,\) to predict a possum’s head length, \(y.\) We could fit the linear relationship by eye, as in Figure 7.6.

A scatterplot with total length on the x-axis and head length on the y-axis. The variables show a moderately strong positive linear relationship. A least squares line is superimposed.
Figure 7.6: A reasonable linear model was fit to represent the relationship between head length and total length.

The equation for this line is

\[ \hat{y} = 41 + 0.59x \]

A “hat” on \(y\) is used to signify that this is an estimate. We can use this line to discuss properties of possums. For instance, the equation predicts a possum with a total length of 80 cm will have a head length of

\[ \hat{y} = 41 + 0.59 \times 80 = 88.2 \]

The estimate may be viewed as an average: the equation predicts that possums with a total length of 80 cm will have an average head length of 88.2 mm. Absent further information about an 80 cm possum, the prediction for head length that uses the average is a reasonable estimate.

There may be other variables that could help us predict the head length of a possum besides its length. Perhaps the relationship would be a little different for male possums than female possums, or perhaps it would differ for possums from one region of Australia versus another region. Figure 7.7 (a) shows the relationship between total length and head length of brushtail possums, taking into consideration their sex. Male possums (represented by blue triangles) seem to be larger in terms of total length and head length than female possums (represented by red circles). Figure 7.7 (b) shows the same relationship, taking into consideration their age. It’s harder to tell if age changes the relationship between total length and head length for these possums.

Two scatterplots, both with total length on the x-axis and head length on the y-axis. The top plot colors the points by sex where the female possums seem slightly longer with slightly smaller head lengths. The bottom plot is colored by age with no obvious trends between age and lengths.
(a) By sex
Two scatterplots, both with total length on the x-axis and head length on the y-axis. The top plot colors the points by sex where the female possums seem slightly longer with slightly smaller head lengths. The bottom plot is colored by age with no obvious trends between age and lengths.
(b) By age
Figure 7.7: Relationship between total length and head length of brushtail possums, taking into consideration their sex or age.

In Chapter 8, we’ll learn about how we can include more than one predictor in our model. Before we get there, we first need to better understand how to best build a linear model with one predictor.

7.1.3 Residuals

Residuals are the leftover variation in the data after accounting for the model fit:

\[ \text{Data} = \text{Fit} + \text{Residual} \]

Each observation will have a residual, and three of the residuals for the linear model we fit for the possum data are shown in Figure 7.8. If an observation is above the regression line, then its residual, the vertical distance from the observation to the line, is positive. Observations below the line have negative residuals. One goal in picking the right linear model is for residuals to be as small as possible.

Figure 7.8 is almost a replica of Figure 7.6, with three points from the data highlighted. The observation marked by a red circle has a small, negative residual of about -1; the observation marked by a gray diamond has a large positive residual of about +7; and the observation marked by a pink triangle has a moderate negative residual of about -4. The size of a residual is usually discussed in terms of its absolute value. For example, the residual for the observation marked by a pink triangle is larger than that of the observation marked by a red circle because \(|-4|\) is larger than \(|-1|.\)

A scatterplot with total length on the x-axis and head length on the y-axis. A least squares line is superimposed onto the scatterplot. Three individual observations are circled to indicate their vertical distance from the least square line.
Figure 7.8: A reasonable linear model was fit to represent the relationship between head length and total length, with three points highlighted.

Residual: Difference between observed and expected.

The residual of the \(i^{th}\) observation \((x_i, y_i)\) is the difference of the observed outcome \((y_i)\) and the outcome we would predict based on the model fit \((\hat{y}_i):\)

\[ e_i = y_i - \hat{y}_i \]

We typically identify \(\hat{y}_i\) by plugging \(x_i\) into the model.

The linear fit shown in Figure 7.8 is given as \(\hat{y} = 41 + 0.59x.\) Based on this line, compute the residual of the observation \((76.0, 85.1).\) This observation is marked by a red circle in Figure 7.8. Check it against the earlier visual estimate, -1.


We first compute the predicted value of the observation marked by a red circle based on the model: \(\hat{y} = 41+0.59x = 41+0.59\times 76.0 = 85.84\). Next we compute the difference of the actual head length and the predicted head length: \(e = y - \hat{y} = 85.1 - 85.84 = -0.74\). The model’s error is \(e = -0.74\) mm, which is very close to the visual estimate of -1 mm. The negative residual indicates that the linear model overpredicted head length for this possum.

If a model underestimates an observation, will the residual be positive or negative? What about if it overestimates the observation?1

Compute the residuals for the observation marked by a blue diamond, \((85.0, 98.6),\) and the observation marked by a pink triangle, \((95.5, 94.0),\) in the figure using the linear relationship \(\hat{y} = 41 + 0.59x.\)2

Residuals are helpful in evaluating how well a linear model fits a dataset. We often display them in a scatterplot such as the one shown in Figure 7.9 for the regression line in Figure 7.8. The residuals are plotted with their predicted outcome variable value as the horizontal coordinate, and the vertical coordinate as the residual. For instance, the point \((85.0, 98.6)\) (marked by the blue diamond) had a predicted value of 91.4 mm and had a residual of 7.45 mm, so in the residual plot it is placed at \((91.4, 7.45).\) Creating a residual plot is sort of like tipping the scatterplot over so the regression line is horizontal, as indicated by the dashed line.

A residual plot based on @fig-scattHeadLTotalLLine-highlighted displaying predicted values on the x-axis and residual values on the y-axis. The same three points that were circled in @fig-scattHeadLTotalLLine-highlighted are still circled, demonstrating the vertical distance from the least squares line is the residual.
Figure 7.9: Residual plot for the model predicting head length from total length for brushtail possums.

One purpose of residual plots is to identify characteristics or patterns still apparent in the data after fitting a model. The figure below shows three scatterplots with linear models in the first row and residual plots in the second row. Can you identify any patterns in the residuals?

A grid of 2 by 3 scatterplots with fabricated data. The top row of plots contains original x-y data plots with a least squares regression line. The bottom row of plots is a series of residual plot with predicted value on the x-axis and residual on the y-axis. The first column of plots gives an example of points that are well described by a linear model. The second column of plots gives an example where the correct model seems to be quadratic insead of linear. The third column of points gives an example where there is no visual relationship between x and y.


Dataset 1: the residuals show no obvious patterns. The residuals are scattered randomly around 0, represented by the dashed line.

Dataset 2: The second dataset shows a pattern in the residuals. There is some curvature in the scatterplot, which is more obvious in the residual plot. We should not use a straight line to model these data. Instead, a more advanced technique should be used to model the curved relationship, such as the variable transformations discussed in Section 5.7.

Dataset 3: The last plot shows very little upwards trend, and the residuals also show no obvious patterns. It is reasonable to try to fit a linear model to the data. However, it is unclear whether there is evidence that the slope parameter is different from zero. The point estimate of the slope parameter is not zero, but we might wonder if this could just be due to chance. We will address this scenario in Chapter 24.

7.1.4 Describing linear relationships with correlation

We’ve seen plots with strong linear relationships and others with very weak linear relationships. It would be useful if we could quantify the strength of these linear relationships with a statistic.

Correlation: strength of a linear relationship.

Correlation which always takes values between -1 and 1, describes the strength and direction of the linear relationship between two variables. We denote the correlation by \(r.\)

The correlation value has no units and will not be affected by a linear change in the units (e.g., going from inches to centimeters).

We can compute the correlation using a formula, just as we did with the sample mean and standard deviation. The formula for correlation, however, is rather complex3, and like with other statistics, we generally perform the calculations on a computer or calculator.

\[ r = \frac{1}{n-1} \sum_{i=1}^{n} \frac{x_i-\bar{x}}{s_x}\frac{y_i-\bar{y}}{s_y} \]

where \(\bar{x},\) \(\bar{y},\) \(s_x,\) and \(s_y\) are the sample means and standard deviations for each variable.

Figure 7.10 shows eight plots and their corresponding correlations. Only when the relationship is perfectly linear is the correlation either -1 or +1. If the relationship is strong and positive, the correlation will be near +1. If it is strong and negative, it will be near -1. If there is no apparent linear relationship between the variables, then the correlation will be near zero.

Eight scatterplots on fabricated data. The first seven plots show linear trends with correlations ranging from -1 to +1. The eighth plot shows a quadratic relationship whih produces a correlation of -0.28.
Figure 7.10: Sample scatterplots and their correlations. The first row shows variables with a positive relationship, represented by the trend up and to the right. The second row shows variables with a negative trend, where a large value in one variable is associated with a lower value in the other.

The correlation is intended to quantify the strength of a linear trend. Nonlinear trends, even when strong, sometimes produce correlations that do not reflect the strength of the relationship; see three such examples in Figure 7.11.

Three scatterplots on fabricated data which demonstrate strong patterns between the x and y variables. The first plot shows a quadratic trend with a correlation of -0.23. The second plot shows a cyclic trend (like a sin wave) with a correlation of 0.31. The third plot shows a distinct relationship that is not obviously functional and has a correlation of 0.5.
Figure 7.11: Sample scatterplots and their correlations. In each case, there is a strong relationship between the variables. However, because the relationship is not linear, the correlation is relatively weak.

No straight line is a good fit for any of the datasets represented in Figure 7.11. Try drawing nonlinear curves on each plot. Once you create a curve for each, describe what is important in your fit.4

The plot below displays the relationships between various crop yields in countries. In the plots, each point represents a different country. The x and y variables represent the proportion of total yield in the last 50 years which is due to that crop type. If a country did not produce a particular crop, it has been removed from the plot (so different plots may have different numbers of dots, each corresponding to one country).

Order the six scatterplots from strongest negative to strongest positive linear relationship.

From a real dataset, we display scatterplots of the relationship between percent of crop which is each of the following -- bananas, potatoes, cassava, soybeans, maize, cocoa, barley, peas, and wheat for each country. For example, potatoes and bananas are negatively correlated and bananas and cocoa do not seem correlated at all.


The order of most negative correlation to most positive correlation is:

\[ A \rightarrow D \rightarrow B \rightarrow C \rightarrow E \rightarrow F \]

  • Plot A - bananas vs. potatoes: -0.45
  • Plot B - cassava vs. soybeans: 0.19
  • Plot C - cassava vs. maize: 0.41
  • Plot D - cocoa vs. bananas: 0.01
  • Plot E - peas vs. barley: 0.71
  • Plot F - wheat vs. barley: 0.86

One important aspect of the correlation is that it’s unitless. That is, unlike a measurement of the slope of a line (see the next section) which provides an increase in the y-coordinate for a one unit increase in the x-coordinate (in units of the x and y variable), there are no units associated with the correlation of x and y. Figure 7.12 shows the relationship between weights and heights of 507 physically active individuals. In Figure 7.12 (a), weight is measured in kilograms (kg) and height in centimeters (cm). In Figure 7.12 (b), weight has been converted to pounds (lbs) and height to inches (in). The correlation coefficient (\(r = 0.72\)) is also noted on both plots. We can see that the shape of the relationship has not changed, and neither has the correlation coefficient. The only visual change to the plot is the axis labeling of the points.

Two scatterplots, both displaying the relationship between weights and heights of 507 physically healthy adults. In the first plot height is measured in cm and weight is measured in kg. In the second plot height is measured in inches and weight is measured in pounds. The images look identical, except for the axes tick marks.
(a) The units are kilograms and centimeters.
Two scatterplots, both displaying the relationship between weights and heights of 507 physically healthy adults. In the first plot height is measured in cm and weight is measured in kg. In the second plot height is measured in inches and weight is measured in pounds. The images look identical, except for the axes tick marks.
(b) The units are pounds and inches.
Figure 7.12: Two scatterplots, both displaying the relationship between weights and heights of 507 physically healthy adults and the correlation coefficient, \(r = 0.72\).

7.2 Least squares regression

Fitting linear models by eye is open to criticism since it is based on an individual’s preference. In this section, we use least squares regression as a more rigorous approach to fitting a line to a scatterplot.

7.2.1 Gift aid for first-year at Elmhurst College

This section considers a dataset on family income and gift aid data from a random sample of fifty students in the first-year class of Elmhurst College in Illinois. Gift aid is financial aid that does not need to be paid back, as opposed to a loan. A scatterplot of these data is shown in Figure 7.13 along with a linear fit. The line follows a negative trend in the data; students who have higher family incomes tended to have lower gift aid from the university.

Is the correlation positive or negative in Figure 7.13?5

Scatterplot with family income on the x-axis and gift aid on the y-axis. The relationship is moderate negative and linear.
Figure 7.13: Gift aid and family income for a random sample of 50 first-year students from Elmhurst College.

7.2.2 An objective measure for finding the best line

We begin by thinking about what we mean by the “best” line. Mathematically, we want a line that has small residuals. But beyond the mathematical reasons, hopefully it also makes sense intuitively that whatever line we fit, the residuals should be small (i.e., the points should be close to the line). The first option that may come to mind is to minimize the sum of the residual magnitudes:

\[ |e_1| + |e_2| + \dots + |e_n| \]

which we could accomplish with a computer program. The resulting dashed line shown in Figure 7.14 demonstrates this fit can be quite reasonable.

Scatterplot with family income on the x-axis and gift aid on the y-axis. The relationship is moderate negative and linear. Two lines are superimposed on the scatterplot. One line is fit to the data by minimizing the sum of squared residuals, i.e., the least squares line. The other line is fit to the data by minimizing the sum of the absolute values of the residuals.
Figure 7.14: Gift aid and family income for a random sample of 50 first-year Elmhurst College students. The dashed line is the line that minimizes the sum of the absolute value of residuals, the solid line is the line that minimizes the sum of squared residuals, i.e., the least squares line.

However, a more common practice is to choose the line that minimizes the sum of the squared residuals:

\[ e_{1}^2 + e_{2}^2 + \dots + e_{n}^2 \]

The line that minimizes this least squares criterion is represented as the solid line in Figure 7.14 and is commonly called the least squares line. The following are four possible reasons to choose the least squares option instead of trying to minimize the sum of residual magnitudes without any squaring:

  1. It is the most commonly used method.
  2. Computing the least squares line is widely supported in statistical software.
  3. In many applications, a residual twice as large as another residual is more than twice as bad. For example, being off by 4 is usually more than twice as bad as being off by 2. Squaring the residuals accounts for this discrepancy.
  4. The analyses which link the model to inference about a population are most straightforward when the line is fit through least squares.

The first two reasons are largely for tradition and convenience; the third and fourth reasons explain why the least squares criterion is typically most helpful when working with real data.6

7.2.3 Finding and interpreting the least squares line

For the Elmhurst data, we could write the equation of the least squares regression line as

\[ \widehat{\texttt{aid}} = \beta_0 + \beta_{1}\times \texttt{family\_income} \]

Here the equation is set up to predict gift aid based on a student’s family income, which would be useful to students considering Elmhurst. These two values, \(\beta_0\) and \(\beta_1,\) are the parameters of the regression line.

The parameters are estimated using the observed data. In practice, this estimation is done using a computer in the same way that other estimates, like a sample mean, can be estimated using a computer or calculator.

The dataset where these data are stored is called elmhurst. The first 5 rows of this dataset are given in Table 7.1.

Table 7.1: First five rows of the elmhurst dataset.
family_income gift_aid price_paid
92.92 21.7 14.28
0.25 27.5 8.53
53.09 27.8 14.25
50.20 27.2 8.78
137.61 18.0 24.00

We can see that family income is recorded in a variable called family_income and gift aid from university is recorded in a variable called gift_aid. For now, we won’t worry about the price_paid variable. We should also note that these data are from the 2011-2012 academic year, and all monetary amounts are given in $1,000s, i.e., the family income of the first student in the data shown in Table 7.1 is $92,920 and they received a gift aid of $21,700. (The data source states that all numbers have been rounded to the nearest whole dollar.)

Statistical software is usually used to compute the least squares line and the typical output generated as a result of fitting regression models looks like the one shown in Table 7.2. For now we will focus on the first column of the output, which lists \({b}_0\) and \({b}_1.\) In Chapter 24 we will dive deeper into the remaining columns which give us information on how accurate and precise these values of intercept and slope that are calculated from a sample of 50 students are in estimating the population parameters of intercept and slope for all students.

Table 7.2: Summary of least squares fit for the Elmhurst data.
term estimate std.error statistic p.value
(Intercept) 24.32 1.29 18.83 <0.0001
family_income -0.04 0.01 -3.98 2e-04

The model output tells us that the intercept is approximately 24.319 and the slope on family_income is approximately -0.043.

But what do these values mean? Interpreting parameters in a regression model is often one of the most important steps in the analysis.

The intercept and slope estimates for the Elmhurst data are \(b_0\) = 24.319 and \(b_1\) = -0.043. What do these numbers really mean?


Interpreting the slope parameter is helpful in almost any application. For each additional $1,000 of family income, we would expect a student to receive a net difference of 1,000 \(\times\) (-0.0431) = -$43.10 in aid on average, i.e., $43.10 less. Note that a higher family income corresponds to less aid because the coefficient of family income is negative in the model. We must be cautious in this interpretation: while there is a real association, we cannot interpret a causal connection between the variables because these data are observational. That is, increasing a particular student’s family income may not cause the student’s aid to drop. (Although it would be reasonable to contact the college and ask if the relationship is causal, i.e., if Elmhurst College’s aid decisions are partially based on students’ family income.)

The estimated intercept \(b_0\) = 24.319 describes the average aid if a student’s family had no income, $24,319. The meaning of the intercept is relevant to this application since the family income for some students at Elmhurst is $0. In other applications, the intercept may have little or no practical value if there are no observations where \(x\) is near zero.

Interpreting parameters estimated by least squares.

The slope describes the estimated difference in the predicted average outcome of \(y\) if the predictor variable \(x\) happened to be one unit larger. The intercept describes the average outcome of \(y\) if \(x = 0\) and the linear model is valid all the way to \(x = 0\) (values of \(x = 0\) are not observed or relevant in many applications).

If you would like to learn more about using R to fit linear models, see Section 10.2 for the interactive R tutorials. An alternative way of calculating the values of intercept and slope of a least squares line is manual calculations using formulas. While manual calculations are not commonly used by practicing statisticians and data scientists, it is useful to work through the first time you’re learning about the least squares line and modeling in general. Calculating the values by hand leverages two properties of the least squares line:

  1. The slope of the least squares line can be estimated by

\[ b_1 = \frac{s_y}{s_x} r \]

where \(r\) is the correlation between the two variables, and \(s_x\) and \(s_y\) are the sample standard deviations of the predictor and outcome, respectively.

  1. If \(\bar{x}\) is the sample mean of the predictor variable and \(\bar{y}\) is the sample mean of the outcome variable, then the point \((\bar{x}, \bar{y})\) falls on the least squares line.

Table 7.3 shows the sample means for the family income and gift aid as $101,780 and $19,940, respectively. We could plot the point \((102, 19.9)\) on Figure 7.13 to verify it falls on the least squares line (the solid line).

Table 7.3: Summary statistics for family income and gift aid.
Family income, x
Gift aid, y
mean sd mean sd r
102 63.2 19.9 5.46 -0.499

Next, we find the point estimates \(b_0\) and \(b_1\) of the parameters \(\beta_0\) and \(\beta_1.\)

Using the summary statistics in Table 7.3, compute the slope for the regression line of gift aid against family income.


Compute the slope using the summary statistics from Table 7.3:

\[ b_1 = \frac{s_y}{s_x} r = \frac{5.46}{63.2}(-0.499) = -0.0431 \]

You might recall the form of a line from math class, which we can use to find the model fit, including the estimate of \(b_0.\) Given the slope of a line and a point on the line, \((x_0, y_0),\) the equation for the line can be written as

\[ y - y_0 = slope\times (x - x_0) \]

Identifying the least squares line from summary statistics.

To identify the least squares line from summary statistics:

  • Estimate the slope parameter, \(b_1 = (s_y / s_x) r.\)
  • Note that the point \((\bar{x}, \bar{y})\) is on the least squares line, use \(x_0 = \bar{x}\) and \(y_0 = \bar{y}\) with the point-slope equation: \(y - \bar{y} = b_1 (x - \bar{x}).\)
  • Simplify the equation, we get \(y = \bar{y} - b_1 \bar{x} + b_1 x,\) which reveals that \(b_0 = \bar{y} - b_1 \bar{x}.\)

Using the point (102, 19.9) from the sample means and the slope estimate \(b_1 = -0.0431,\) find the least-squares line for predicting aid based on family income.


Apply the point-slope equation using \((102, 19.9)\) and the slope \(b_1 = -0.0431\):

\[ \begin{aligned} y - y_0 &= b_1 (x - x_0) \\ y - 19.9 &= -0.0431 (x - 102) \end{aligned} \]

Expanding the right side and then adding 19.9 to each side, the equation simplifies:

\[ \widehat{\texttt{aid}} = 24.3 - 0.0431 \times \texttt{family\_income} \]

Here we have replaced \(y\) with \(\widehat{\texttt{aid}}\) and \(x\) with \(\texttt{family\_income}\) to put the equation in context. The final least squares equation should always include a “hat” on the variable being predicted, whether it is a generic \(``y"\) or a named variable like \(``aid"\).

Suppose a high school senior is considering Elmhurst College. Can they simply use the linear equation that we have estimated to calculate her financial aid from the university?


She may use it as an estimate, though some qualifiers on this approach are important. First, all data come from one first-year class, and the way aid is determined by the university may change from year to year. Second, the equation will provide an imperfect estimate. While the linear equation is good at modeling the trend in the data, no individual student’s aid will be perfectly predicted (as can be seen from the individual data points around the line).

7.2.4 Extrapolation is treacherous

Linear models can be used to approximate the relationship between two variables. However, like any model, they have real limitations. Linear regression is simply a modeling framework. The truth is almost always much more complex than a simple line. For example, we do not know how the data outside of our limited window will behave.

Use the model \(\widehat{\texttt{aid}} = 24.3 - 0.0431 \times \texttt{family\_income}\) to estimate the aid of another first-year student whose family had income of $1 million.


We want to calculate the aid for a family with $1 million income. Note that in our model this will be represented as 1,000 since the data are in $1,000s.

\[ 24.3 - 0.0431 \times 1000 = -18.8 \]

The model predicts this student will have -$18,800 in aid (!). However, Elmhurst College does not offer negative aid where they select some students to pay extra on top of tuition to attend.

Applying a model estimate to values outside of the realm of the original data is called extrapolation. Generally, a linear model is only an approximation of the real relationship between two variables. If we extrapolate, we are making an unreliable bet that the approximate linear relationship will be valid in places where it has not been analyzed.

7.2.5 Describing the strength of a fit

We evaluated the strength of the linear relationship between two variables earlier using the correlation, \(r.\) However, it is more common to explain the strength of a linear fit using \(R^2,\) called R-squared. If provided with a linear model, we might like to describe how closely the data cluster around the linear fit.

The \(R^2\) of a linear model describes the amount of variation in the outcome variable that is explained by the least squares line. For example, consider the Elmhurst data, shown in Figure 7.13). The variance of the outcome variable, aid received, is about \(s_{aid}^2 \approx 29.8\) million (calculated from the data, some of which is shown in Table 7.1). However, if we apply our least squares line, then this model reduces our uncertainty in predicting aid using a student’s family income. The variability in the residuals describes how much variation remains after using the model: \(s_{_{RES}}^2 \approx 22.4\) million. In short, there was a reduction of

\[ \frac{s_{aid}^2 - s_{_{RES}}^2}{s_{aid}^2} = \frac{29800 - 22400}{29800} = \frac{7500}{29800} \approx 0.25, \]

or about 25%, of the outcome variable’s variation by using information about family income for predicting aid using a linear model. It turns out that \(R^2\) corresponds exactly to the squared value of the correlation:

\[ r = -0.499 \rightarrow R^2 = 0.25 \]

If a linear model has a very strong negative relationship with a correlation of -0.97, how much of the variation in the outcome is explained by the predictor?7

\(R^2\) is also called the coefficient of determination.

Coefficient of determination: proportion of variability in the outcome variable explained by the model.

Since \(r\) is always between -1 and 1, \(R^2\) will always be between 0 and 1. This statistic is called the coefficient of determination, and it measures the proportion of variation in the outcome variable, \(y,\) that can be explained by the linear model with predictor \(x.\)

More generally, \(R^2\) can be calculated as a ratio of a measure of variability around the line divided by a measure of total variability.

Sums of squares to measure variability in \(y.\)

We can measure the variability in the \(y\) values by how far they tend to fall from their mean, \(\bar{y}.\) We define this value as the total sum of squares, calculated using the formula below, where \(y_i\) represents each \(y\) value in the sample, and \(\bar{y}\) represents the mean of the \(y\) values in the sample.

\[ SST = (y_1 - \bar{y})^2 + (y_2 - \bar{y})^2 + \cdots + (y_n - \bar{y})^2. \]

Left-over variability in the \(y\) values if we know \(x\) can be measured by the sum of squared errors, or sum of squared residuals, calculated using the formula below, where \(\hat{y}_i\) represents the predicted value of \(y_i\) based on the least squares regression.8,

\[ \begin{aligned} SSE &= (y_1 - \hat{y}_1)^2 + (y_2 - \hat{y}_2)^2 + \cdots + (y_n - \hat{y}_n)^2\\ &= e_{1}^2 + e_{2}^2 + \dots + e_{n}^2 \end{aligned} \]

The coefficient of determination can then be calculated as

\[ R^2 = \frac{SST - SSE}{SST} = 1 - \frac{SSE}{SST} \]

Among 50 students in the elmhurst dataset, the total variability in gift aid is \(SST = 1461\).9 The sum of squared residuals is \(SSE = 1098.\) Find \(R^2.\)


Since we know \(SSE\) and \(SST,\) we can calculate \(R^2\) as

\[ R^2 = 1 - \frac{SSE}{SST} = 1 - \frac{1098}{1461} = 0.25, \]

the same value we found when we squared the correlation: \(R^2 = (-0.499)^2 = 0.25.\)

7.2.6 Categorical predictors with two levels

Categorical variables are also useful in predicting outcomes. Here we consider a categorical predictor with two levels (recall that a level is the same as a category). We’ll consider Ebay auctions for a video game, Mario Kart for the Nintendo Wii, where both the total price of the auction and the condition of the game were recorded. Here we want to predict total price based on game condition, which takes values used and new.

The mariokart data can be found in the openintro R package.

A plot of the auction data is shown in Figure 7.15. Note that the original dataset contains some Mario Kart games being sold at prices above $100 but for this analysis we have limited our focus to the 141 Mario Kart games that were sold below $100.

Scatterplot of Mario Kart data with condion (used or new) on the x-axis and total price on the y-axis. Despite the x-axis being categorical, a least squares line is fit to the data with the value of used set to 0 and the value of new set to 1.
Figure 7.15: Total auction prices for the video game Mario Kart, divided into used (\(x = 0\)) and new (\(x = 1\)) condition games. The least squares regression line is also shown.

To incorporate the game condition variable into a regression equation, we must convert the categories into a numerical form. We will do so using an indicator variable called condnew, which takes value 1 when the game is new and 0 when the game is used. Using this indicator variable, the linear model may be written as

\[ \widehat{\texttt{price}} = b_0 + b_1 \times \texttt{condnew} \]

The parameter estimates are given in Table 7.4.

Table 7.4: Least squares regression summary for the final auction price against the condition of the game.
term estimate std.error statistic p.value
(Intercept) 42.9 0.81 52.67 <0.0001
condnew 10.9 1.26 8.66 <0.0001

Using values from Table 7.4, the model equation can be summarized as

\[ \widehat{\texttt{price}} = 42.87 + 10.9 \times \texttt{condnew} \]

Interpret the two parameters estimated in the model for the price of Mario Kart in eBay auctions.


The intercept is the estimated price when condnew has a value 0, i.e., when the game is in used condition. That is, the average selling price of a used version of the game is $42.9. The slope indicates that, on average, new games sell for about $10.9 more than used games.

Interpreting model estimates for categorical predictors.

The estimated intercept is the value of the outcome variable for the first category (i.e., the category corresponding to an indicator value of 0). The estimated slope is the average change in the outcome variable between the two categories.

Note that, fundamentally, the intercept and slope interpretations do not change when modeling categorical variables with two levels. However, when the predictor variable is binary, the coefficient estimates (\(b_0\) and \(b_1\)) are directly interpretable with respect to the dataset at hand.

We’ll elaborate further on modeling categorical predictors in Chapter 8, where we examine the influence of many predictor variables simultaneously using multiple regression.

7.3 Outliers in linear regression

In this section, we discuss when outliers are important and influential. Outliers in a regression model with one predictor and one outcome are observations that fall far from the cloud of points. These points are especially important because they can have a strong influence on the least squares line. Note that there are times when observations are outlying in the \(x\) direction, the \(y\) direction, or both. However, being outlying in a univariate sense (either \(x\) or \(y\) or both) is not outlying from the bivariate model. If the points are in-line with the bivariate model, they will not influence the least squares regression line (even if the observations are outlying in the \(x\) or \(y\) or both directions!).

There are three plots shown in Figure 7.16 (a) along with the corresponding least squares line and residual plots. For each scatterplot and residual plot pair, identify the outliers and note how they influence the least squares line. Recall that an outlier is any point that does not appear to belong with the vast majority of the other points.


A: There is one outlier far from the other points (in the \(y\) direction and it is an outlier of the bivariate model), though it only appears to slightly influence the line.

B: There is one outlier on the right (in the \(x\) and \(y\) direction although it is not an outlier of the bivariate model), though it is quite close to the least squares line, which suggests it wasn’t very influential.

C: There is one point far away from the cloud (in the \(x\) and \(y\) direction and an outlier of the bivariate model), and this outlier appears to pull the least squares line up on the right; examine how the line around the primary cloud does not appear to fit very well.

There are three plots shown in Figure 7.16 (b) along with the least squares line and residual plots. As you did in previous exercise, for each scatterplot and residual plot pair, identify the outliers and note how they influence the least squares line. Recall that an outlier is any point that does not appear to belong with the vast majority of the other points. A point can be outlying in the \(x\) direction, in the \(y\) direction, or in relation to the bivariate model.


D: There is a primary cloud and then a small secondary cloud of four outliers (with respect to both \(x\) and the bivariate model). The secondary cloud appears to be influencing the line somewhat strongly, making the least square line fit poorly almost everywhere. There might be an interesting explanation for the dual clouds, which is something that could be investigated.

E: There is no obvious trend in the main cloud of points and the outlier on the right (with respect to both \(x\) and \(y\)) appears to largely (and problematically) control the slope of the least squares line. The point creates a bivariate model when seemingly there is none.

F: There is one outlier far from the cloud (with respect to both \(x\) and \(y\)). However, it falls quite close to the least squares line and does not appear to be very influential (it is not outlying with respect to the bivariate model).

A grid of 2 by 3 scatterplots with fabricated data, all of which contain at least one outlying observation. The top row of plots contains original x-y data plots with a least squares regression line. The bottom row of plots is a series of residual plot with predicted value on the x-axis and residual on the y-axis. The first column of plots gives an example of an outlier in the bivariate model which does not impact the least squares regression line. The second column gives an example of a point which is outlying in both the x and y directions but it is not a model outlier. The third column gives an example of a point that pulls the regression line toward it, impacting the least squares line. The fourth column of plots gives an example of a small cloud of points that drags the regression line toward it. The fifth column gives an example of a point which is outlying enough in both the x and y direction that it changes a model which has no linearity into what seems like a strong positive relationship. The sixth column gives an example of a point that is far in both the x and y directions but is in-line with the regression model and has very little impact on the least squares regression line.
(a) Plots A, B, and C
A grid of 2 by 3 scatterplots with fabricated data, all of which contain at least one outlying observation. The top row of plots contains original x-y data plots with a least squares regression line. The bottom row of plots is a series of residual plot with predicted value on the x-axis and residual on the y-axis. The first column of plots gives an example of an outlier in the bivariate model which does not impact the least squares regression line. The second column gives an example of a point which is outlying in both the x and y directions but it is not a model outlier. The third column gives an example of a point that pulls the regression line toward it, impacting the least squares line. The fourth column of plots gives an example of a small cloud of points that drags the regression line toward it. The fifth column gives an example of a point which is outlying enough in both the x and y direction that it changes a model which has no linearity into what seems like a strong positive relationship. The sixth column gives an example of a point that is far in both the x and y directions but is in-line with the regression model and has very little impact on the least squares regression line.
(b) Plots D, E, and F
Figure 7.16: Plots of six datasets, each with a least squares line and corresponding residual plot. Each dataset has at least one outlier.

Examine the residual plots in Figure 7.16 (a) and Figure 7.16 (b). In Plots C, D, and E, you will probably find that there are a few observations which are both away from the remaining points along the x-axis and not in the trajectory of the trend in the rest of the data. In these cases, the outliers influenced the slope of the least squares lines. In Plot E, the bulk of the data show no clear trend, but if we fit a line to these data, we impose a trend where there isn’t really one.

A good practice for dealing with outlying observations is to produce two analyses: one with and one without the outlying observations. Presenting both analyses to a client and discussing the role of the outlying observations should lead you to a more holistic understanding of the appropriate model for the data.

Leverage.

Points that fall horizontally away from the center of the cloud tend to pull harder on the line, so we call them points with high leverage or leverage points.

Points that fall horizontally far from the line are points of high leverage; these points can strongly influence the slope of the least squares line. If one of these high leverage points does appear to actually invoke its influence on the slope of the line – as in Plots C, D, and E of Figure 7.16 (a) and Figure 7.16 (b) – then we call it an influential point. Usually we can say a point is influential if, had we fitted the line without it, the influential point would have been unusually far from the least squares line.

Types of outliers.

A point (or a group of points) that stands out from the rest of the data is called an outlier. Outliers that fall horizontally away from the center of the cloud of points are called leverage points. Outliers that influence on the slope of the line are called influential points.

It is tempting to remove outliers. Don’t do this without a very good reason. Models that ignore exceptional (and interesting) cases often perform poorly. For instance, if a financial firm ignored the largest market swings – the “outliers” – they would soon go bankrupt by making poorly thought-out investments.

7.4 Chapter review

7.4.1 Summary

Throughout this chapter, the nuances of the linear model have been described. You have learned how to create a linear model with explanatory variables that are numerical (e.g., total possum length) and those that are categorical (e.g., whether a video game was new). The residuals in a linear model are an important metric used to understand how well a model fits; high leverage points, influential points, and other types of outliers can impact the fit of a model. Correlation is a measure of the strength and direction of the linear relationship of two variables, without specifying which variable is the explanatory and which is the outcome. Future chapters will focus on generalizing the linear model from the sample of data to claims about the population of interest.

7.4.2 Terms

The terms introduced in this chapter are presented in Table 7.5. If you’re not sure what some of these terms mean, we recommend you go back in the text and review their definitions. You should be able to easily spot them as bolded text.

Table 7.5: Terms introduced in this chapter.
coefficient of determination least squares line regression sum of squares
correlation leverage point residuals
extrapolation outcome sum of squared error
high leverage outlier total sum of squares
indicator variable predictor
influential point R-squared

7.5 Exercises

Answers to odd-numbered exercises can be found in Appendix A.7.

  1. Visualizing residuals. The scatterplots shown below each have a superimposed regression line. If we were to construct a residual plot (residuals versus \(x\)) for each, describe in words what those plots would look like.

  1. Trends in residuals. Shown below are two plots of residuals remaining after fitting a linear model to two different sets of data. For each plot, describe important features and determine if a linear model would be appropriate for these data. Explain your reasoning.

  1. Identify relationships, I. For each of the six plots, identify the strength of the relationship (e.g., weak, moderate, or strong) in the data and whether fitting a linear model would be reasonable.

  1. Identify relationships, II. For each of the six plots, identify the strength of the relationship (e.g., weak, moderate, or strong) in the data and whether fitting a linear model would be reasonable.

  1. Midterms and final. The two scatterplots below show the relationship between the overall course average and two midterm exams (Exam 1 and Exam 2) recorded for 233 students during several years for a statistics course at a university.10

    1. Based on these graphs, which of the two exams has the strongest correlation with the course grade? Explain.

    2. Can you think of a reason why the correlation between the exam you chose in part (a) and the course grade is higher?

  1. Meat consumption and life expectancy. In data collected for You et al. (2022), total meat intake is associated with life expectancy (at birth) in 175 countries. Meat intake is measured in kg per capita per year (averaged over 2011 to 2013). Additionally, the authors collected data on carbohydrate crops (e.g., cereals, root, sugar, etc.) in kg per capita per year (averaged over 2011 and 2013). The scatterplot on the left shows the life expectancy at birth plotted against the per capita meat consumption. The scatterplot on the right shows the amount of carbohydrate consumption plotted against the per capita meat consumption.

    1. Describe the relationship between meat consumption and life expectancy.

    2. Describe the relationship between meat consumption and carbohydrate consumption.

    3. Which plot shows a stronger correlation? Explain your reasoning.

    4. Data on consumption were originally collected in kilograms. How would the plots above and the correlation values change if the consumption variables were converted to pounds?

  1. Match the correlation, I. Match each correlation to the corresponding scatterplot.11

    1. \(r = -0.7\)

    2. \(r = 0.45\)

    3. \(r = 0.06\)

    4. \(r = 0.92\)

  1. Match the correlation, II. Match each correlation to the corresponding scatterplot.12

    1. \(r = 0.49\)

    2. \(r = -0.48\)

    3. \(r = -0.03\)

    4. \(r = -0.85\)

  1. Body measurements, correlation. Researchers studying anthropometry collected body and skeletal diameter measurements, as well as age, weight, height and sex for 507 physically active individuals. The scatterplot below shows the relationship between height and shoulder girth (circumference of shoulders measured over deltoid muscles), both measured in centimeters.13 (Heinz et al. 2003)

    1. Describe the relationship between shoulder girth and height.

    2. How would the relationship change if shoulder girth was measured in inches while the units of height remained in centimeters?

  1. Compare correlations. Eduardo and Rosie are both collecting data on number of rainy days in a year and the total rainfall for the year. Eduardo records rainfall in inches and Rosie in centimeters. How will their correlation coefficients compare?
  1. The Coast Starlight, correlation. The Coast Starlight Amtrak train runs from Seattle to Los Angeles. The scatterplot below displays the distance between each stop (in miles) and the amount of time it takes to travel from one stop to another (in minutes).14

    1. Describe the relationship between distance and travel time.

    2. How would the relationship change if travel time was instead measured in hours, and distance was instead measured in kilometers?

    3. Correlation between travel time (in miles) and distance (in minutes) is \(r = 0.636\). What is the correlation between travel time (in kilometers) and distance (in hours)?

  1. Crawling babies, correlation. A study conducted at the University of Denver investigated whether babies take longer to learn to crawl in cold months, when they are often bundled in clothes that restrict their movement, than in warmer months. Infants born during the study year were split into twelve groups, one for each birth month. We consider the average crawling age of babies in each group against the average temperature when the babies are six months old (that’s when babies often begin trying to crawl). Temperature is measured in degrees Fahrenheit (F) and age is measured in weeks.15 (Benson 1993)

    1. Describe the relationship between temperature and crawling age.

    2. How would the relationship change if temperature was measured in degrees Celsius (C) and age was measured in months?

    3. The correlation between temperature in F and age in weeks was \(r=-0.70\). If we converted the temperature to C and age to months, what would the correlation be?

  1. Meat and carbohydrate consumption. What would be the correlation between the per capita meat consumption and per capita carbohydrate consumption if, for each country, people always consumed

    1. 3 kg more of meat than of carbohydrates each year?

    2. 2 kg less of meat than of carbohydrates each year?

    3. half as much meat as carbohydrates each year?

  1. Graduate degrees and salaries. What would be the correlation between the annual salaries of people with and without a graduate degree at a company if, for a certain type of position, someone with a graduate degree always made

    1. $5,000 more than those without a graduate degree?

    2. 25% more than those without a graduate degree?

    3. 15% less than those without a graduate degree?

  1. Units of regression. Consider a regression predicting the number of calories (cal) from width (cm) for a sample of square shaped chocolate brownies. What are the units of the correlation coefficient, the intercept, and the slope?
  1. Which is higher? Determine if (I) or (II) is higher or if they are equal: “For a regression line, the uncertainty associated with the slope estimate, \(b_1\), is higher when (I) there is a lot of scatter around the regression line or (II) there is very little scatter around the regression line.” Explain your reasoning.
  1. Over-under, I. Suppose we fit a regression line to predict the shelf life of an apple based on its weight. For a particular apple, we predict the shelf life to be 4.6 days. The apple’s residual is -0.6 days. Did we over or under estimate the shelf-life of the apple? Explain your reasoning.
  1. Over-under, II. Suppose we fit a regression line to predict the number of incidents of skin cancer per 1,000 people from the number of sunny days in a year. For a particular year, we predict the incidence of skin cancer to be 1.5 per 1,000 people, and the residual for this year is 0.5. Did we over or under estimate the incidence of skin cancer? Explain your reasoning.
  1. Starbucks, calories, and protein. The scatterplot below shows the relationship between the number of calories and amount of protein (in grams) Starbucks food menu items contain. Since Starbucks only lists the number of calories on the display items, we might be interested in predicting the amount of protein a menu item has based on its calorie content.16

    1. Describe the relationship between number of calories and amount of protein (in grams) that Starbucks food menu items contain.

    2. In this scenario, what are the predictor and outcome variables?

    3. Why might we want to fit a regression line to these data?

    4. What does the residuals vs. predicted plot tell us about the variability in prediction errors based on this model for items with lower vs. higher predicted protein?

  1. Starbucks, calories, and carbs. The scatterplot below shows the relationship between the number of calories and amount of carbohydrates (in grams) Starbucks food menu items contain. Since Starbucks only lists the number of calories on the display items, we might be interested in predicting the amount of carbs a menu item has based on its calorie content.17

    1. Describe the relationship between number of calories and amount of carbohydrates (in grams) that Starbucks food menu items contain.

    2. In this scenario, what are the predictor and outcome variables?

    3. Why might we want to fit a regression line to these data?

    4. What does the residuals vs. predicted plot tell us about the variability in prediction errors based on this model for items with lower vs. higher predicted carbs?

  1. The Coast Starlight, regression. The Coast Starlight Amtrak train runs from Seattle to Los Angeles. The scatterplot below displays the distance between each stop (in miles) and the amount of time it takes to travel from one stop to another (in minutes). The mean travel time from one stop to the next on the Coast Starlight is 129 mins, with a standard deviation of 113 minutes. The mean distance traveled from one stop to the next is 108 miles with a standard deviation of 99 miles. The correlation between travel time and distance is 0.636.18

    1. Write the equation of the regression line for predicting travel time.

    2. Interpret the slope and the intercept in this context.

    3. Calculate \(R^2\) of the regression line for predicting travel time from distance traveled for the Coast Starlight, and interpret \(R^2\) in the context of the application.

    4. The distance between Santa Barbara and Los Angeles is 103 miles. Use the model to estimate the time it takes for the Starlight to travel between these two cities.

    5. It takes the Coast Starlight about 168 mins to travel from Santa Barbara to Los Angeles. Calculate the residual and explain the meaning of this residual value.

    6. Suppose Amtrak is considering adding a stop to the Coast Starlight 500 miles away from Los Angeles. Would it be appropriate to use this linear model to predict the travel time from Los Angeles to this point?

  1. Body measurements, regression. Researchers studying anthropometry collected body and skeletal diameter measurements, as well as age, weight, height and sex for 507 physically active individuals. The scatterplot below shows the relationship between height and shoulder girth (circumference of shoulders measured over deltoid muscles), both measured in centimeters. The mean shoulder girth is 107.20 cm with a standard deviation of 10.37 cm. The mean height is 171.14 cm with a standard deviation of 9.41 cm. The correlation between height and shoulder girth is 0.67.19 (Heinz et al. 2003)

    1. Write the equation of the regression line for predicting height.

    2. Interpret the slope and the intercept in this context.

    3. Calculate \(R^2\) of the regression line for predicting height from shoulder girth, and interpret it in the context of the application.

    4. A randomly selected student from your class has a shoulder girth of 100 cm. Predict the height of this student using the model.

    5. The student from part (d) is 160 cm tall. Calculate the residual, and explain what this residual means.

    6. A one year old has a shoulder girth of 56 cm. Would it be appropriate to use this linear model to predict the height of this child?

  1. Poverty and unemployment. The following scatterplot shows the relationship between percent of population below the poverty level (poverty) from unemployment rate among those ages 20-64 (unemployment_rate) in counties in the US, as provided by data from the 2019 American Community Survey. The regression output for the model for predicting poverty from unemployment_rate is also provided.20

    term estimate std.error statistic p.value
    (Intercept) 4.60 0.349 13.2 <0.0001
    unemployment_rate 2.05 0.062 33.1 <0.0001

     

    1. Write out the linear model.

    2. Interpret the intercept.

    3. Interpret the slope.

    4. The \(R^2\) of this model is 46%.
      Interpret this value.

    5. Calculate the correlation coefficient.

  1. Cat weights. The following regression output is for predicting the heart weight (Hwt, in g) of cats from their body weight (Bwt, in kg). The coefficients are estimated using a dataset of 144 domestic cats.21

    term estimate std.error statistic p.value
    (Intercept) -0.357 0.692 -0.515 0.6072
    Bwt 4.034 0.250 16.119 <0.0001

     

    1. Write out the linear model.

    2. Interpret the intercept.

    3. Interpret the slope.

    4. The \(R^2\) of this model is 65%.
      Interpret \(R^2\).

    5. Calculate the correlation coefficient.

  2. Outliers, I. Identify the outliers in the scatterplots shown below, and determine what type of outliers they are. Explain your reasoning.

  3. Outliers, II. Identify the outliers in the scatterplots shown below and determine what type of outliers they are. Explain your reasoning.

  4. Urban homeowners, outliers. The scatterplot below shows the percent of families who own their home vs. the percent of the population living in urban areas. There are 52 observations, each corresponding to a state in the US. Puerto Rico and District of Columbia are also included.22

     

    1. Describe the relationship between the percent of families who own their home and the percent of the population living in urban areas.

    2. The outlier at the bottom right corner is District of Columbia, where 100% of the population is considered urban. What type of an outlier is this observation?

     

  1. Crawling babies, outliers. A study conducted at the University of Denver investigated whether babies take longer to learn to crawl in cold months, when they are often bundled in clothes that restrict their movement, than in warmer months. The plot below shows the relationship between average crawling age of babies born in each month and the average temperature in the month when the babies are six months old. The plot reveals a potential outlying month when the average temperature is about 53F and average crawling age is about 28.5 weeks. Does this point have high leverage? Is it an influential point?23 (Benson 1993)

  1. True / False. Determine if the following statements are true or false. If false, explain why.

    1. A correlation coefficient of -0.90 indicates a stronger linear relationship than a correlation of 0.5.

    2. Correlation is a measure of the association between any two variables.

  1. Cherry trees. The scatterplots below show the relationship between height, diameter, and volume of timber in 31 felled black cherry trees. The diameter of the tree is measured 4.5 feet above the ground.24

    1. Describe the relationship between volume and height of these trees.

    2. Describe the relationship between volume and diameter of these trees.

    3. Suppose you have height and diameter measurements for another black cherry tree. Which of these variables would be preferable to use to predict the volume of timber in this tree using a simple linear regression model? Explain your reasoning.

  1. Match the correlation, III. Match each correlation to the corresponding scatterplot.25

    1. r = 0.69

    2. r = 0.09

    3. r = -0.91

    4. r = 0.97

  1. Helmets and lunches. The scatterplot shows the relationship between socioeconomic status measured as the percentage of children in a neighborhood receiving reduced-fee lunches at school (lunch) and the percentage of bike riders in the neighborhood wearing helmets (helmet). The average percentage of children receiving reduced-fee lunches is 30.833% with a standard deviation of 26.724% and the average percentage of bike riders wearing helmets is 30.883% with a standard deviation of 16.948%.

    1. If the \(R^2\) for the least-squares regression line for these data is 72%, what is the correlation between lunch and helmet?

    2. Calculate the slope and intercept for the least-squares regression line for these data.

    3. Interpret the intercept of the least-squares regression line in the context of the application.

    4. Interpret the slope of the least-squares regression line in the context of the application.

    5. What would the value of the residual be for a neighborhood where 40% of the children receive reduced-fee lunches and 40% of the bike riders wear helmets? Interpret the meaning of this residual in the context of the application.


  1. If a model underestimates an observation, then the model estimate is below the actual. The residual, which is the actual observation value minus the model estimate, must then be positive. The opposite is true when the model overestimates the observation: the residual is negative.↩︎

  2. Gray diamond: \(\hat{y} = 41+0.59x = 41+0.59\times 85.0 = 91.15 \rightarrow e = y - \hat{y} = 98.6-91.15=7.45.\) This is close to the earlier estimate of 7. pink triangle: \(\hat{y} = 41+0.59x = 97.3 \rightarrow e = -3.3.\) This is also close to the estimate of -4.↩︎

  3. Formally, we can compute the correlation for observations \((x_1, y_1),\) \((x_2, y_2),\) …, \((x_n, y_n)\) using the formula↩︎

  4. We’ll leave it to you to draw the lines. In general, the lines you draw should be close to most points and reflect overall trends in the data.↩︎

  5. Larger family incomes are associated with lower amounts of aid, so the correlation will be negative. Using a computer, the correlation can be computed: -0.499.↩︎

  6. There are applications where the sum of residual magnitudes may be more useful, and there are plenty of other criteria we might consider. However, this book only applies the least squares criterion.↩︎

  7. About \(R^2 = (-0.97)^2 = 0.94\) or 94% of the variation in the outcome variable is explained by the linear model.↩︎

  8. The difference \(SST - SSE\) is called the regression sum of squares, \(SSR,\) and can also be calculated as \(SSR = (\hat{y}_1 - \bar{y})^2 + (\hat{y}_2 - \bar{y})^2 + \cdots + (\hat{y}_n - \bar{y})^2.\) \(SSR\) represents the variation in \(y\) that was accounted for in our model.↩︎

  9. \(SST\) can be calculated by finding the sample variance of the outcome variable, \(s^2\) and multiplying by \(n-1.\)↩︎

  10. The exam_grades data used in this exercise can be found in the openintro R package.↩︎

  11. The corr_match data used in this exercise can be found in the openintro R package.↩︎

  12. The corr_match data used in this exercise can be found in the openintro R package.↩︎

  13. The bdims data used in this exercise can be found in the openintro R package.↩︎

  14. The coast_starlight data used in this exercise can be found in the openintro R package.↩︎

  15. The babies_crawl data used in this exercise can be found in the openintro R package.↩︎

  16. The starbucks data used in this exercise can be found in the openintro R package.↩︎

  17. The starbucks data used in this exercise can be found in the openintro R package.↩︎

  18. The coast_starlight data used in this exercise can be found in the openintro R package.↩︎

  19. The bdims data used in this exercise can be found in the openintro R package.↩︎

  20. The county_2019 data used in this exercise can be found in the usdata R package.↩︎

  21. The cats data used in this exercise can be found in the MASS R package.↩︎

  22. The urban_owner data used in this exercise can be found in the usdata R package.↩︎

  23. The babies_crawl data used in this exercise can be found in the openintro R package.↩︎

  24. The trees data used in this exercise can be found in the datasets R package.↩︎

  25. The corr_match data used in this exercise can be found in the openintro R package.↩︎

中文

7  含单个预测变量的线性回归

线性回归是一种非常强大的统计技术。许多人仅通过阅读新闻就对回归模型有一定的了解,新闻中常在散点图上叠加直线。线性模型可用于预测或描述两个数值变量之间的关系,前提是它们之间存在线性关系。

7.1 拟合直线、残差与相关性

在考虑线性回归时,深入思考直线拟合的过程是很有帮助的。在本节中,我们将定义线性模型的形式,探讨判断拟合好坏的标准,并引入一个称为 相关系数.

7.1.1 对数据进行直线拟合

图 7.1 展示了两个变量,它们之间的关系可以用一条直线完美地建模。该直线的方程为 \(y = 5 + 64.96 x.\) 思考一下完美的线性关系意味着什么:只需知道 \(y\) 的值,我们就能知道 \(x.\) 的精确值。 \((x),\) 在几乎任何自然过程中,完美的线性关系都是不现实的。例如,如果我们获取家庭收入 \((y.)\) 这个数值将提供一些有用的信息,说明大学可能会为潜在学生提供多少经济资助

A scatterplot showing a perfect linear relationship between number of stocks to purchase on the x-axis and total cost of the share purchase on the y-axis.
然而,预测结果远非完美,因为除了家庭财务状况之外,其他因素也在经济资助中发挥作用。

图 7.1:同时向一家贸易公司发出十二个不同买家的请求,购买塔吉特公司(Target Corporation)的股票(股票代码 TGT,2018 年 12 月 28 日),并报告股票的总成本。由于成本是使用线性公式计算的,因此线性拟合是完美的。 \(x\)\(y,\) 线性回归是一种对数据拟合直线的统计方法,其中两个变量之间的关系

\[ y = b_0 + b_1 \ x + e \]

可以用一条带有一定误差的直线来建模: \(b_0\)\(b_1\) 数值 \(e.\) 分别代表模型的截距和斜率,误差用 \(\beta_0\)\(\beta_1.\) 表示。这些值是根据数据计算得出的,即它们是样本统计量。如果观测数据是来自我们想要进行推断的目标总体的随机样本,那么这些值被视为总体参数 第24章.

希腊字母 \(\beta\) 读作 的点估计。我们将在讨论如何基于样本统计量对线性模型的参数进行推断。,发音请听 这里.

当我们使用 \(x\) 来预测 \(y,\) 时,我们通常把 \(x\)predictor 称为变量,并把 \(y\)结果变量项,因为我们的主要关注点通常是对平均结果的预测。 \(e\) 所有数据都完美地落在一条直线上是很罕见的。更常见的情况是数据呈现为一个

点云 ,例如中所示的那些例子。在每种情况下,数据都围绕一条直线分布,即使没有任何观测值恰好落在直线上。第一幅图显示了一个相对较强的向下线性趋势,数据围绕直线的剩余变异性相对于 图 7.2之间关系的强度而言较小。第二幅图显示了一个上升趋势,虽然明显,但不如第一个强。最后一幅图显示了数据中非常微弱的下降趋势,微弱到我们几乎察觉不到。在每一个这样的例子中,我们对模型参数 \(x\)\(y.\) 的估计都会存在一些不确定性。例如,我们可能会想,是否应该把直线稍微上移或下移,或者是否应该把它的倾斜度调大或调小一些?随着本章的推进,我们将学习拟合直线的准则,还将学习与模型参数估计相关的不确定性。 \(\beta_0\)\(\beta_1.\) 图 7.2:三个数据集,即使数据并非全部恰好落在直线上,线性模型也可能是有用的。

Three scatterplots with fabricated data. The first panel shows a strong negative linear relationship. The second panel shows a moderate positive linear relationship. The last panel shows no relationship between the x and y variables.
也有一些情况,即使变量之间存在明显的关系,用直线拟合数据也没有帮助。其中一个例子如

所示,其中变量之间存在非常明显的关系,尽管趋势不是线性的。我们在本章和下一章讨论非线性趋势,但拟合非线性模型的细节留待后续课程讲解。 图 7.3 图 7.3:这些数据的最佳拟合直线是水平的,这不是描述该非线性关系的有用方式。这些数据来自一个物理实验。

A scatterplot showing a perfect quadratic relationship between angle of incline on the x-axis and distance traveled on the y-axis. The line of best fit is superimposed as a perfectly horizontal line. That is to say, the variables are clearly related, but they do not have a linear relationship.
图 7.3:这些数据的最佳拟合线是平的,这不是描述这种非线性关系的有效方式。这些数据来自一项物理实验。

7.1.2 使用线性回归预测负鼠头长

刷尾负鼠是一种生活在澳大利亚的有袋类动物,其照片见 图 7.4。研究人员捕获了104只这种动物,在将它们放归野外之前对其进行了身体测量。我们考虑其中两项测量:每只负鼠从头到尾的总长度,以及每只负鼠的头长。

Photograph of a common brushtail possum of Australia.
图 7.4:澳大利亚的普通刷尾负鼠。照片由 Greg Schecter 拍摄, flic.kr/p/9BAFbR,CC BY 2.0 许可。

possum 数据可以在 openintro R 包中找到。

图 7.5 展示了负鼠头长(毫米)与总长(厘米)的散点图。每个点代表数据中的一只负鼠。头长与总长这两个变量是相关联的:总长高于平均值的负鼠,其头长往往也高于平均值。虽然这种关系并非完全线性,但用一条直线来部分解释这些变量之间的联系可能会有所帮助。

A scatterplot with total length on the x-axis and head length on the y-axis. The variables show a moderately strong positive linear relationship. A single observation is circled in red with coordinates of approximately 84cm of total length and 87mm of head length.
图 7.5:104只刷尾负鼠的头长与总长的散点图。图中突出显示了一只头长为86.7毫米、总长为84厘米的负鼠所对应的点。

我们想用一条直线来描述负鼠头长与总长之间的关系。在本例中,我们将总长作为预测变量, \(x,\) 来预测负鼠的头长, \(y.\) 我们可以像 图 7.6.

A scatterplot with total length on the x-axis and head length on the y-axis. The variables show a moderately strong positive linear relationship. A least squares line is superimposed.
中那样凭肉眼拟合线性关系。

图 7.6:拟合了一个合理的线性模型来表示头长与总长之间的关系。

\[ \hat{y} = 41 + 0.59x \]

这条直线的方程为 \(y\) 上的“帽子”符号表示这是一个估计值。我们可以用这条直线来讨论负鼠的特性。例如,该方程预测总长为80厘米的负鼠的头长为

\[ \hat{y} = 41 + 0.59 \times 80 = 88.2 \]

这个估计值可以被视为一个平均值:该方程预测总长为80厘米的负鼠的平均头长为88.2毫米。在没有关于一只80厘米负鼠的更多信息的情况下,使用平均值进行的头长预测是一个合理的估计。

除了袋鼠的体长之外,可能还有其他变量可以帮助我们预测其头长。雄性袋鼠与雌性袋鼠之间的关系可能略有不同,或者来自澳大利亚不同地区的袋鼠之间的关系也可能有所不同。 图 7.7 (a) 展示了在考虑性别的情况下,帚尾袋鼠的总体长与头长之间的关系。雄性袋鼠(用蓝色三角形表示)在总体长和头长方面似乎都比雌性袋鼠(用红色圆圈表示)更大。 图 7.7 (b) 展示了在考虑年龄的情况下的相同关系。很难判断年龄是否会改变这些袋鼠的总体长与头长之间的关系。

Two scatterplots, both with total length on the x-axis and head length on the y-axis. The top plot colors the points by sex where the female possums seem slightly longer with slightly smaller head lengths. The bottom plot is colored by age with no obvious trends between age and lengths.
(a) 按性别
Two scatterplots, both with total length on the x-axis and head length on the y-axis. The top plot colors the points by sex where the female possums seem slightly longer with slightly smaller head lengths. The bottom plot is colored by age with no obvious trends between age and lengths.
(b) 按年龄
图 7.7:在考虑性别或年龄的情况下,帚尾袋鼠的总体长与头长之间的关系。

第 8 章中,我们将学习如何在模型中包含多个预测变量。在此之前,我们首先需要更好地理解如何用单个预测变量构建最佳的线性模型。

7.1.3 残差

残差 是指数据在考虑模型拟合后剩余的变异:

\[ \text{Data} = \text{Fit} + \text{Residual} \]

每个观测值都会有一个残差,我们为袋鼠数据拟合的线性模型的三个残差显示在 图 7.8中。如果观测值位于回归线上方,则其残差(即观测值到直线的垂直距离)为正。位于直线下方的观测值具有负残差。选择合适线性模型的一个目标是使残差尽可能小。

图 7.8 几乎是 图 7.6的复制品,只是突出显示了数据中的三个点。用红色圆圈标记的观测值具有约为 -1 的小负残差;用灰色菱形标记的观测值具有约为 +7 的大正残差;用粉色三角形标记的观测值具有约为 -4 的中等负残差。残差的大小通常用其绝对值来讨论。例如,用粉色三角形标记的观测值的残差大于用红色圆圈标记的观测值的残差,因为 \(|-4|\) 大于 \(|-1|.\)

A scatterplot with total length on the x-axis and head length on the y-axis. A least squares line is superimposed onto the scatterplot. Three individual observations are circled to indicate their vertical distance from the least square line.
图7.8:拟合了一个合理的线性模型来表示头长与总长之间的关系,其中三个点被突出显示。

残差:观测值与期望值之间的差异。

的残差是观测结果 \(i^{th}\) 观测值 \((x_i, y_i)\) 与我们基于模型拟合预测的结果 \((y_i)\) 之间的差。 \((\hat{y}_i):\)

\[ e_i = y_i - \hat{y}_i \]

我们通常通过将 \(\hat{y}_i\) 代入模型来确定 \(x_i\)

中所示的线性拟合为 图 7.8 根据这条直线,计算观测值 \(\hat{y} = 41 + 0.59x.\) 的残差。该观测值在 \((76.0, 85.1).\) 中用红色圆圈标出。请将其与之前的视觉估计值 -1 进行核对。 图 7.8我们首先根据模型计算用红色圆圈标出的观测值的预测值:


首先根据模型计算红色圆圈所标观测值的预测值:\(\hat{y} = 41+0.59x = 41+0.59\times 76.0 = 85.84\)。然后计算实际头长与预测头长之差:\(e = y - \hat{y} = 85.1 - 85.84 = -0.74\)。模型误差为 \(e = -0.74\) 毫米,非常接近目测估计的 -1 毫米。负残差表示线性模型高估了这只负鼠的头长。

如果模型低估了某个观测值,残差是正还是负?如果高估了该观测值呢?1

计算图中由蓝色菱形标记的观测值 \((85.0, 98.6),\) 以及由粉色三角形标记的观测值 \((95.5, 94.0),\) 的残差,使用线性关系 \(\hat{y} = 41 + 0.59x.\)2

残差有助于评估线性模型对数据集的拟合程度。我们通常将它们显示在散点图中,例如 图 7.9 中针对 图 7.8中回归线所示的图。残差图中,横坐标为预测的结果变量值,纵坐标为残差。例如,点 \((85.0, 98.6)\) (由蓝色菱形标记)的预测值为 91.4 毫米,残差为 7.45 毫米,因此在残差图中它被绘制在 \((91.4, 7.45).\) 创建残差图有点像把散点图翻转过来,使回归线呈水平状态,如虚线所示。

A residual plot based on @fig-scattHeadLTotalLLine-highlighted displaying predicted values on the x-axis and residual values on the y-axis. The same three points that were circled in @fig-scattHeadLTotalLLine-highlighted are still circled, demonstrating the vertical distance from the least squares line is the residual.
图 7.9:根据总长预测帚尾袋貂头长的模型的残差图。

残差图的一个用途是识别在拟合模型后数据中仍然存在的特征或模式。下图显示了三个散点图,第一行为带线性模型的散点图,第二行为残差图。你能识别出残差中的任何模式吗?

A grid of 2 by 3 scatterplots with fabricated data. The top row of plots contains original x-y data plots with a least squares regression line. The bottom row of plots is a series of residual plot with predicted value on the x-axis and residual on the y-axis. The first column of plots gives an example of points that are well described by a linear model. The second column of plots gives an example where the correct model seems to be quadratic insead of linear. The third column of points gives an example where there is no visual relationship between x and y.


数据集 1:残差没有明显的模式。残差随机地分布在 0 附近,由虚线表示。

数据集 2:第二个数据集的残差呈现出某种模式。散点图中存在一些弯曲,这在残差图中更为明显。我们不应使用直线来建模这些数据。相反,应使用更高级的技术来建模这种曲线关系,例如 第 5.7 节.

数据集3:最后一幅图显示出很小的上升趋势,残差也没有明显的模式。尝试对数据拟合线性模型是合理的。然而,尚不清楚是否有证据表明斜率参数不同于零。斜率参数的点估计不为零,但我们可能会怀疑这是否只是偶然所致。我们将在 第24章.

7.1.4 用相关系数描述线性关系

我们已经见过线性关系很强的图,也见过线性关系很弱的图。如果我们能用一个统计量来量化这些线性关系的强度,那将非常有用。

相关系数:线性关系的强度。

相关系数 的取值总是在 -1 和 1 之间,它描述两个变量之间线性关系的强度和方向。我们用 \(r.\)

相关系数没有单位,并且不会受单位线性变化的影响(例如,从英寸换算为厘米)。

我们可以像计算样本均值和标准差那样,用公式来计算相关系数。然而,相关系数的公式相当复杂3,与其他统计量一样,我们通常在计算机或计算器上进行计算。

\[ r = \frac{1}{n-1} \sum_{i=1}^{n} \frac{x_i-\bar{x}}{s_x}\frac{y_i-\bar{y}}{s_y} \]

其中 \(\bar{x},\) \(\bar{y},\) \(s_x,\)\(s_y\) 是每个变量的样本均值和标准差。

图 7.10 展示了八幅图及其对应的相关系数。只有当关系是完全线性时,相关系数才为 -1 或 +1。如果关系强且为正,相关系数将接近 +1。如果关系强且为负,它将接近 -1。如果变量之间没有明显的线性关系,相关系数将接近零。

Eight scatterplots on fabricated data. The first seven plots show linear trends with correlations ranging from -1 to +1. The eighth plot shows a quadratic relationship whih produces a correlation of -0.28.
图 7.10:样本散点图及其相关系数。第一行显示呈正相关的变量,其趋势向右上方延伸。第二行显示呈负趋势的变量,即一个变量取较大值时,另一个变量取较小值。

相关系数旨在量化线性趋势的强度。非线性趋势即使很强,有时产生的相关系数也不能反映关系的强度;参见 图 7.11.

Three scatterplots on fabricated data which demonstrate strong patterns between the x and y variables. The first plot shows a quadratic trend with a correlation of -0.23. The second plot shows a cyclic trend (like a sin wave) with a correlation of 0.31. The third plot shows a distinct relationship that is not obviously functional and has a correlation of 0.5.
中的三个此类示例。

图 7.11:样本散点图及其相关系数。在每种情况下,变量之间都存在很强的关系。然而,由于该关系不是线性的,相关系数相对较弱。 图 7.11对于所展示的任何数据集,都没有一条直线能很好地拟合。请尝试在每幅图上画出非线性曲线。一旦为每幅图画出曲线,请描述你的拟合中哪些方面是重要的。4

下图展示了各国各种作物产量之间的关系。在图中,每个点代表一个不同的国家。x 和 y 变量表示过去 50 年中该作物类型占总产量的比例。如果某个国家没有生产某种特定作物,则该国家已从图中移除(因此不同的图可能包含不同数量的点,每个点对应一个国家)。

将六幅散点图按从最强负线性关系到最强正线性关系的顺序排列。

From a real dataset, we display scatterplots of the relationship between percent of crop which is each of the following -- bananas, potatoes, cassava, soybeans, maize, cocoa, barley, peas, and wheat for each country. For example, potatoes and bananas are negatively correlated and bananas and cocoa do not seem correlated at all.


从最负相关到最正相关的顺序为:

\[ A \rightarrow D \rightarrow B \rightarrow C \rightarrow E \rightarrow F \]

  • 图 A - 香蕉 vs. 土豆:-0.45
  • 图 B - 木薯 vs. 大豆:0.19
  • 图 C - 木薯 vs. 玉米:0.41
  • 图 D - 可可 vs. 香蕉:0.01
  • 图 E - 豌豆 vs. 大麦:0.71
  • 图 F - 小麦 vs. 大麦:0.86

相关系数的一个重要特性是它 没有单位。也就是说,与直线斜率的度量(见下一节)不同——斜率表示 x 坐标每增加一个单位时 y 坐标的增加量(以 x 和 y 变量的单位计)——x 和 y 的相关性没有任何单位。 图 7.12 展示了 507 名经常进行体力活动个体的体重与身高之间的关系。在 图 7.12 (a)中,体重以千克(kg)为单位,身高以厘米(cm)为单位。在 图 7.12 (b), 体重已换算为磅(lbs),身高已换算为英寸(in)。两个图上都标注了相关系数(\(r = 0.72\))。可以看到,关系的形状没有改变,相关系数也没有改变。图上唯一的视觉变化是坐标轴的 标注

Two scatterplots, both displaying the relationship between weights and heights of 507 physically healthy adults. In the first plot height is measured in cm and weight is measured in kg. In the second plot height is measured in inches and weight is measured in pounds. The images look identical, except for the axes tick marks.
(a) 单位是千克和厘米。
Two scatterplots, both displaying the relationship between weights and heights of 507 physically healthy adults. In the first plot height is measured in cm and weight is measured in kg. In the second plot height is measured in inches and weight is measured in pounds. The images look identical, except for the axes tick marks.
(b) 单位是磅和英寸。
图 7.12:两张散点图,均显示了507名身体健康的成年人的体重与身高之间的关系以及相关系数, \(r = 0.72\).

7.2 最小二乘回归

通过肉眼拟合线性模型容易受到批评,因为它基于个人的偏好。在本节中,我们使用 最小二乘回归 作为一种更严谨的方法来对散点图拟合直线。

7.2.1 埃尔姆赫斯特学院一年级学生的助学金

本节考虑一个关于家庭收入和助学金的数据集,该数据来自伊利诺伊州埃尔姆赫斯特学院一年级班级中50名学生的随机样本。助学金(gift aid)是无需偿还的经济资助,与贷款不同。这些数据的散点图如 图 7.13 所示,并附有线性拟合。该直线呈现负趋势;家庭收入较高的学生往往从学校获得的助学金较少。

中的相关系数是正还是负? 图 7.13?5

Scatterplot with family income on the x-axis and gift aid on the y-axis. The relationship is moderate negative and linear.
图 7.13:埃尔姆赫斯特学院50名一年级学生的随机样本的助学金与家庭收入。

7.2.2 寻找最佳直线的客观度量

我们首先思考“最佳”直线意味着什么。从数学上讲,我们希望找到一条残差很小的直线。但除了数学上的原因之外,从直观上看,无论我们拟合哪条直线,残差都应该很小(即数据点应该靠近直线),这也是合理的。首先想到的方法可能是使残差绝对值之和最小:

\[ |e_1| + |e_2| + \dots + |e_n| \]

我们可以用计算机程序来实现这一点。图中所示的虚线表明这种拟合可以相当合理。 图 7.14 图 7.14:Elmhurst College 50 名一年级新生随机样本的助学金与家庭收入。虚线是使残差绝对值之和最小的直线,实线是使残差平方和最小的直线,即最小二乘直线。

Scatterplot with family income on the x-axis and gift aid on the y-axis. The relationship is moderate negative and linear. Two lines are superimposed on the scatterplot. One line is fit to the data by minimizing the sum of squared residuals, i.e., the least squares line. The other line is fit to the data by minimizing the sum of the absolute values of the residuals.
然而,更常见的做法是选择使残差平方和最小的直线:

使这一最小二乘准则最小的直线在图中用实线表示,通常称为

\[ e_{1}^2 + e_{2}^2 + \dots + e_{n}^2 \]

最小二乘直线 图 7.14 。以下是不对残差平方、仅尝试使残差绝对值之和最小,而选择最小二乘法的四个可能原因: 最小二乘直线统计软件广泛支持最小二乘直线的计算。

  1. 在许多应用中,一个残差若是另一个残差的两倍大,其影响往往不止两倍坏。例如,偏差为 4 通常比偏差为 2 的两倍还要糟糕。对残差取平方可以解释这种差异。
  2. 当直线通过最小二乘法拟合时,将模型与关于总体的推断联系起来的分析最为直接。
  3. 前两个原因主要是出于传统和便利;第三和第四个原因解释了为什么在处理真实数据时,最小二乘准则通常最有帮助。
  4. 求出并解释最小二乘直线

寻找并解释最小二乘直线6

7.2.3 寻找并解释最小二乘直线

对于 Elmhurst 数据,我们可以将最小二乘回归线的方程写为

\[ \widehat{\texttt{aid}} = \beta_0 + \beta_{1}\times \texttt{family\_income} \]

这里方程的设定是基于学生家庭收入来预测助学金,这对考虑就读 Elmhurst 的学生很有用。这两个值, \(\beta_0\)\(\beta_1,\) 是回归线的参数。

参数是利用观测数据来估计的。在实际操作中,这种估计是使用计算机完成的,就像样本均值等其他估计值可以用计算机或计算器来估计一样。

存储这些数据的数据集称为 elmhurst。该数据集的前 5 行见 表 7.1.

表 7.1: elmhurst 数据集的最后五行。
family_income 的前五行 gift_aid
92.92 21.7 14.28
0.25 27.5 8.53
53.09 27.8 14.25
50.20 27.2 8.78
137.61 18.0 24.00

price_paid family_income 我们可以看到,家庭收入记录在名为 gift_aid的变量中,而大学的助学金记录在名为 price_paid 的变量中。目前,我们先不关注 表 7.1 变量。我们还应注意,这些数据来自 2011-2012 学年,所有金额均以 1,000 美元为单位,即

中所示数据里第一位学生的家庭收入为 92,920 美元,其获得的助学金为 21,700 美元。(数据来源指出所有数字均已四舍五入到最接近的整美元。) 表 7.2统计软件通常用于计算最小二乘直线,拟合回归模型所生成的典型输出类似于所示的内容。目前我们将关注输出的第一列,其中列出了 \({b}_0\)\({b}_1.\)第24章 我们将深入探讨其余的列,这些列告诉我们,基于50名学生样本计算出的截距和斜率值,在估计总体的截距和斜率参数时有多准确和精确。 所有 名学生。

表 7.2:Elmhurst 数据的最小二乘拟合摘要。
term 估计 的线性模型摘要 统计量 std.error
p.value 24.32 1.29 18.83 <0.0001
family_income -0.04 0.01 -3.98 2e-04

模型输出告诉我们,截距约为 24.319, family_income 的斜率约为 -0.043。

但这些值意味着什么?解释回归模型中的参数往往是分析中最重要的步骤之一。

Elmhurst 数据的截距和斜率估计值为 \(b_0\) = 24.319 和 \(b_1\) = -0.043。这些数字究竟意味着什么?


解释斜率参数在几乎任何应用中都很有用。家庭收入每增加 1,000 美元,我们预计学生获得的资助平均净差异为 1,000 \(\times\) (-0.0431) = -$43.10,即 $43.10 更不。请注意,由于模型中家庭收入的系数为负,较高的家庭收入对应较少的资助。在这种解释中我们必须谨慎:虽然存在真实的关联,但由于这些数据是观察性的,我们不能将其解释为变量之间的因果关系。也就是说,提高某个特定学生的家庭收入未必会导致该学生的资助减少。(不过,联系该学院询问这种关系是否为因果关系是合理的,即 Elmhurst 学院的资助决定是否部分基于学生的家庭收入。)

估计的截距 \(b_0\) = 24.319 描述了学生家庭没有收入时的平均资助额,即 $24,319。截距的含义在此应用中是相关的,因为 Elmhurst 有些学生的家庭收入为 $0。在其他应用中,如果没有 \(x\) 接近零的观测值,截距可能几乎没有或完全没有实际价值。

解释由最小二乘法估计的参数。

斜率描述的是当预测变量 \(y\) 恰好增大一个单位时, \(x\) 的预测平均结果估计值的差异。截距描述的是当 \(y\) 时, \(x = 0\) 而且 的平均结果,前提是线性模型一直有效到 \(x = 0\) (在许多应用中, \(x = 0\) 的取值并未被观测到或并不相关)。

如果你想进一步了解如何使用 R 拟合线性模型,请参见 第 10.2 节 的交互式 R 教程。计算最小二乘直线的截距和斜率值的另一种方法是使用公式进行手工计算。虽然实际工作中的统计学家和数据科学家并不常用手工计算,但在初次学习最小二乘直线和一般建模时,动手演算一遍是很有帮助的。手工计算利用了最小二乘直线的两个性质:

  1. 最小二乘直线的斜率可以通过下式估计:

\[ b_1 = \frac{s_y}{s_x} r \]

其中 \(r\) 是两个变量之间的相关系数,而 \(s_x\)\(s_y\) 分别是预测变量和结果变量的样本标准差。

  1. 如果 \(\bar{x}\) 是预测变量的样本均值, \(\bar{y}\) 是结果变量的样本均值,那么点 \((\bar{x}, \bar{y})\) 位于最小二乘直线上。

表 7.3 给出了家庭收入和助学金的样本均值,分别为 $101,780 和 $19,940。我们可以绘制点 \((102, 19.9)\)图 7.13 来验证它落在最小二乘直线(实线)上。

表 7.3:家庭收入和助学金的汇总统计量。
家庭收入,x
助学金,y
mean sd mean sd r
102 63.2 19.9 5.46 -0.499

接下来,我们求参数 \(b_0\)\(b_1\) 的点估计 \(\beta_0\)\(\beta_1.\)

时,我们对置信区间公式稍作修改。 表 7.3,计算助学金对家庭收入的回归直线的斜率。


使用 表 7.3:

\[ b_1 = \frac{s_y}{s_x} r = \frac{5.46}{63.2}(-0.499) = -0.0431 \]

中的汇总统计量计算斜率。 \(b_0.\) 你可能还记得数学课上学过的直线形式,我们可以用它来求模型拟合,包括 \((x_0, y_0),\) 的估计值。

\[ y - y_0 = slope\times (x - x_0) \]

给定直线的斜率和直线上的一个点,直线的方程可以写成:。

根据汇总统计量确定最小二乘直线:

  • 估计斜率参数, \(b_1 = (s_y / s_x) r.\)
  • 注意点 \((\bar{x}, \bar{y})\) 位于最小二乘直线上,使用 \(x_0 = \bar{x}\)\(y_0 = \bar{y}\) 点斜式方程: \(y - \bar{y} = b_1 (x - \bar{x}).\)
  • 化简方程,我们得到 \(y = \bar{y} - b_1 \bar{x} + b_1 x,\) 这表明 \(b_0 = \bar{y} - b_1 \bar{x}.\)

使用样本均值点 (102, 19.9) 和斜率估计值 \(b_1 = -0.0431,\) 根据家庭收入预测资助金额,求出最小二乘直线。


使用 \((102, 19.9)\) 和斜率 \(b_1 = -0.0431\):

\[ \begin{aligned} y - y_0 &= b_1 (x - x_0) \\ y - 19.9 &= -0.0431 (x - 102) \end{aligned} \]

应用点斜式方程

\[ \widehat{\texttt{aid}} = 24.3 - 0.0431 \times \texttt{family\_income} \]

将右边展开,然后在两边加上 19.9,方程化简为: \(y\)\(\widehat{\texttt{aid}}\)\(x\)\(\texttt{family\_income}\) 这里我们用 \(``y"\) 替换,使方程符合具体情境。最终的最小二乘方程应始终在被预测的变量上加上“帽子”符号,无论是通用的 \(``aid"\).

还是像这样的命名变量:


她可以用它作为估计值,不过这种方法有一些重要的限制条件。首先,所有数据都来自同一个一年级班级,而大学确定助学金的方式可能逐年变化。其次,该方程只能提供一个不完美的估计。虽然线性方程能很好地拟合数据中的趋势,但没有任何单个学生的助学金会被完全准确地预测出来(从直线周围各个数据点的分布可以看出这一点)。

7.2.4 外推是危险的

线性模型可以用来近似两个变量之间的关系。然而,与任何模型一样,它们存在实际的局限性。线性回归仅仅是一种建模框架,而真实情况几乎总是比一条简单的直线复杂得多。例如,我们并不知道在有限数据窗口之外的数据会如何表现。

使用该模型 \(\widehat{\texttt{aid}} = 24.3 - 0.0431 \times \texttt{family\_income}\) 来估计另一位家庭收入为100万美元的一年级学生的助学金。


我们想计算收入为100万美元的家庭的助学金。注意,在我们的模型中,由于数据以千美元为单位,这个数值应表示为1,000。

\[ 24.3 - 0.0431 \times 1000 = -18.8 \]

该模型预测这名学生将获得 -18,800 美元的助学金(!)。然而,Elmhurst College 并不提供 负助学金 ,即挑选某些学生在学费之外额外支付费用来入学。

将模型估计应用于原始数据范围之外的值称为 外推。一般来说,线性模型只是两个变量之间真实关系的一种近似。如果我们进行外推,就是在进行一个不可靠的赌注,即假设这种近似的线性关系在尚未分析的地方仍然有效。

7.2.5 描述拟合的强度

我们之前使用相关系数 \(r.\) 评估了两个变量之间线性关系的强度。然而,更常见的做法是使用 \(R^2,\) ,称为 R方。如果给定一个线性模型,我们可能想要描述数据围绕线性拟合的聚集紧密程度。

\(R^2\) (线性模型的)描述了结果变量中被最小二乘直线所解释的变异量。例如,考虑Elmhurst数据,如 图 7.13)所示。结果变量(获得的资助)的方差约为 \(s_{aid}^2 \approx 29.8\) 百万(由数据计算得出,部分数据如 表 7.1)所示。然而,如果我们应用最小二乘直线,该模型会降低我们利用学生家庭收入预测资助时的不确定性。残差的变异性描述了使用模型后剩余的变异量: \(s_{_{RES}}^2 \approx 22.4\) 百万。简而言之,利用家庭收入信息通过线性模型预测资助,结果变量的变异减少了

\[ \frac{s_{aid}^2 - s_{_{RES}}^2}{s_{aid}^2} = \frac{29800 - 22400}{29800} = \frac{7500}{29800} \approx 0.25, \]

,约25%。事实证明, \(R^2\) 恰好等于相关系数的平方:

\[ r = -0.499 \rightarrow R^2 = 0.25 \]

如果一个线性模型具有非常强的负相关关系,相关系数为-0.97,那么结果变量中有多少变异被预测变量解释?7

\(R^2\) 也称为 决定系数.

决定系数:模型所解释的结果变量变异的比例。

由于 \(r\) 总是在-1和1之间, \(R^2\) 则总是在0和1之间。这个统计量被称为 决定系数, 它衡量结果变量 \(y,\) 的变异中可以由带有预测变量的线性模型解释的比例。 \(x.\)

更一般地, \(R^2\) 可以用围绕直线的变异度量除以总变异度量所得的比值来计算。

用于衡量 \(y.\)

中变异的平方和 \(y\) 我们可以通过 \(\bar{y}.\) 值偏离其均值 总平方和我们将该值定义为 \(y_i\) 总平方和 \(y\) ,使用下面的公式计算,其中 \(\bar{y}\) 表示样本中的每个 \(y\) 值,

\[ SST = (y_1 - \bar{y})^2 + (y_2 - \bar{y})^2 + \cdots + (y_n - \bar{y})^2. \]

表示样本中 \(y\) 值的均值。 \(x\) 可以通过 误差平方和(即残差平方和)来度量,其计算公式如下,其中 \(\hat{y}_i\) 表示基于最小二乘回归得到的 \(y_i\) 的预测值。8,

\[ \begin{aligned} SSE &= (y_1 - \hat{y}_1)^2 + (y_2 - \hat{y}_2)^2 + \cdots + (y_n - \hat{y}_n)^2\\ &= e_{1}^2 + e_{2}^2 + \dots + e_{n}^2 \end{aligned} \]

然后可以按如下方式计算决定系数

\[ R^2 = \frac{SST - SSE}{SST} = 1 - \frac{SSE}{SST} \]

elmhurst 数据集的 50 名学生中,助学金的总变异为 \(SST = 1461\).9 残差平方和为 \(SSE = 1098.\)\(R^2.\)


由于我们已知 \(SSE\)\(SST,\) 我们可以计算出 \(R^2\)

\[ R^2 = 1 - \frac{SSE}{SST} = 1 - \frac{1098}{1461} = 0.25, \]

这与我们对相关系数平方后得到的值相同: \(R^2 = (-0.499)^2 = 0.25.\)

7.2.6 具有两个水平的分类预测变量

分类变量同样可用于预测结果。这里我们考虑一个具有两个水平的分类预测变量(回想一下, 水平类别)。我们将考虑一款电子游戏的 eBay 拍卖, 马力卡丁车 (任天堂 Wii 游戏),其中记录了拍卖的总价和游戏的状态。这里我们希望根据游戏状态来预测总价,游戏状态取值为 usednew.

mariokart 数据可以在 openintro R 包中找到。

拍卖数据的图示见 图 7.15。注意,原始数据集中包含一些售价高于 $100 的马里奥赛车(Mario Kart)游戏,但在本分析中,我们仅关注售价低于 $100 的 141 个马里奥赛车游戏。

Scatterplot of Mario Kart data with condion (used or new) on the x-axis and total price on the y-axis. Despite the x-axis being categorical, a least squares line is fit to the data with the value of used set to 0 and the value of new set to 1.
图 7.15:电子游戏马里奥赛车拍卖的总价,分为二手(\(x = 0\))和全新(\(x = 1\))两种状态。图中还显示了最小二乘回归线。

要将游戏状态变量纳入回归方程,我们必须将这些类别转换为数值形式。我们将使用一个 指示变量 ,称为 condnew,当游戏为全新时取值为 1,为二手时取值为 0。使用这个指示变量,线性模型可以写为

\[ \widehat{\texttt{price}} = b_0 + b_1 \times \texttt{condnew} \]

参数估计值见 表 7.4.

表 7.4:最终拍卖价格与游戏状态的最小二乘回归摘要。
term 估计 的线性模型摘要 统计量 std.error
p.value 42.9 0.81 52.67 <0.0001
condnew 10.9 1.26 8.66 <0.0001

使用来自 表 7.4, 模型方程可以总结为

\[ \widehat{\texttt{price}} = 42.87 + 10.9 \times \texttt{condnew} \]

解释在 eBay 拍卖中为马里奥赛车价格所估计的模型中的两个参数。


截距是当 condnew 取值为 0 时(即游戏为二手状态时)的估计价格。也就是说,二手版本游戏的平均售价为 $42.9。斜率表明,平均而言新游戏的售价比二手游戏高约 $10.9。

解释分类预测变量的模型估计值。

估计的截距是第一个类别(即指示变量取值为 0 的类别)对应的结果变量的值。估计的斜率是两个类别之间结果变量的平均变化。

请注意,从根本上说,在建模具有两个水平的分类变量时,截距和斜率的解释并不会改变。然而,当预测变量为二元变量时,系数估计值(\(b_0\)\(b_1\))可以直接针对当前数据集进行解释。

我们将在 第 8 章中进一步详细讨论分类预测变量的建模,届时我们将使用多元回归同时考察多个预测变量的影响。

7.3 线性回归中的离群点

在本节中,我们讨论离群点何时重要且具有影响力。在含有一个预测变量和一个结果变量的回归模型中,离群点是远离点云的观测值。这些点尤其重要,因为它们可能对最小二乘直线产生很强的影响。请注意,有时观测值可能在 \(x\) 方向、 \(y\) 方向,或两个方向上都是离群的。然而,在单变量意义上离群( \(x\)\(y\) 或两者)并不意味着在双变量模型中离群。如果这些点与双变量模型保持一致,它们将不会影响最小二乘回归直线(即使这些观测值在 \(x\)\(y\) 或两个方向上都是离群的!)。

图中显示了三幅图,见 图 7.16 (a) ,并附有相应的最小二乘直线和残差图。对于每一对散点图和残差图,找出离群点并说明它们如何影响最小二乘直线。回顾一下,离群点是指任何看起来不属于其他绝大多数点的点。


A: 有一个离群点远离其他点(在 \(y\) 方向上,并且它是二元模型的离群点),不过它似乎只是轻微地影响了直线。

B: 右侧有一个离群点(在 \(x\)\(y\) 方向上是离群点,尽管它不是二元模型的离群点),不过它非常接近最小二乘直线,这表明它的影响并不大。

C: 有一个点远离点云(在 \(x\)\(y\) 方向上,并且是二元模型的离群点),这个离群点似乎把最小二乘直线的右端向上拉了;观察一下直线在主点云附近的部分,可以发现拟合效果并不太好。

图中显示了三幅图,见 图 7.16 (b) ,并附有最小二乘直线和残差图。与上一题一样,对于每一对散点图和残差图,找出离群点并说明它们如何影响最小二乘直线。回顾一下,离群点是指任何看起来不属于其他绝大多数点的点。一个点可以在 \(x\) 方向上是离群的,在 \(y\) 方向上是离群的,或者相对于二元模型是离群的。


D: 有一个主点云,然后有一个由四个离群点组成的小的次级点云(相对于 \(x\) 和二元模型都是离群点)。次级点云似乎对直线有较强的影响,使得最小二乘直线几乎在所有地方都拟合得很差。这种双点云现象可能有一个有趣的解释,值得进一步研究。

E: 主点云没有明显趋势,而右侧的离群点(相对于 \(x\)\(y\))似乎在很大程度上(且有问题地)控制了最小二乘直线的斜率。这个点在看似没有关系的地方制造了一个双变量模型。

F: 有一个离群点远离点云(相对于 \(x\)\(y\))。然而,它相当接近最小二乘直线,看起来影响不大(相对于双变量模型它不是离群的)。

A grid of 2 by 3 scatterplots with fabricated data, all of which contain at least one outlying observation. The top row of plots contains original x-y data plots with a least squares regression line. The bottom row of plots is a series of residual plot with predicted value on the x-axis and residual on the y-axis. The first column of plots gives an example of an outlier in the bivariate model which does not impact the least squares regression line. The second column gives an example of a point which is outlying in both the x and y directions but it is not a model outlier. The third column gives an example of a point that pulls the regression line toward it, impacting the least squares line. The fourth column of plots gives an example of a small cloud of points that drags the regression line toward it. The fifth column gives an example of a point which is outlying enough in both the x and y direction that it changes a model which has no linearity into what seems like a strong positive relationship. The sixth column gives an example of a point that is far in both the x and y directions but is in-line with the regression model and has very little impact on the least squares regression line.
(a) 图 A、B 和 C
A grid of 2 by 3 scatterplots with fabricated data, all of which contain at least one outlying observation. The top row of plots contains original x-y data plots with a least squares regression line. The bottom row of plots is a series of residual plot with predicted value on the x-axis and residual on the y-axis. The first column of plots gives an example of an outlier in the bivariate model which does not impact the least squares regression line. The second column gives an example of a point which is outlying in both the x and y directions but it is not a model outlier. The third column gives an example of a point that pulls the regression line toward it, impacting the least squares line. The fourth column of plots gives an example of a small cloud of points that drags the regression line toward it. The fifth column gives an example of a point which is outlying enough in both the x and y direction that it changes a model which has no linearity into what seems like a strong positive relationship. The sixth column gives an example of a point that is far in both the x and y directions but is in-line with the regression model and has very little impact on the least squares regression line.
(b) 图 D、E 和 F
图 7.16:六个数据集的散点图,每个都带有最小二乘直线和相应的残差图。每个数据集至少有一个离群点。

检查 图 7.16 (a)图 7.16 (b)中的残差图。在图 C、D 和 E 中,你可能会发现有几个观测值既在 x 轴方向上远离其余的点,又不在其余数据趋势的轨迹上。在这些情况下,离群点影响了最小二乘直线的斜率。在图 E 中,大部分数据没有显示明显的趋势,但如果我们对这些数据拟合一条直线,就会在实际上没有趋势的地方强加一个趋势。

处理离群观测值的一个好做法是进行两次分析:一次包含离群观测值,一次不包含。向客户展示这两种分析并讨论离群观测值的作用,应能让你更全面地理解适合该数据的模型。

杠杆。

在水平方向上远离点云中心的点往往对直线的拉力更大,因此我们称它们为具有 高杠杆杠杆点.

在水平方向上远离直线的点称为高杠杆点;这些点会强烈影响最小二乘直线的斜率。如果这些高杠杆点中的某一个确实对直线的斜率产生了实际影响——如 图 7.16 (a)图 7.16 (b) 中的图 C、D 和 E 所示——那么我们称之为 强影响点。通常,如果去掉某个点后重新拟合直线,而该点距离最小二乘直线异常遥远,我们就可以说这个点是强影响点。

离群点的类型。

从其余数据中凸显出来的一个点(或一组点)称为离群点。在水平方向上远离点云中心的离群点称为杠杆点。对直线斜率有影响的离群点称为强影响点。

人们很容易想删除离群点。没有充分的理由不要这样做。忽略特殊(且有趣)情形的模型往往表现不佳。例如,如果一家金融公司忽略了最大的市场波动——即“离群点”——那么由于做出欠考虑的投资,他们很快就会破产。

7.4 本章复习

7.4.1 小结

在本章中,我们介绍了线性模型的各种细节。你已经学会了如何使用数值型解释变量(例如,负鼠总体长)和分类型解释变量(例如,电子游戏是否为新品)来构建线性模型。线性模型中的残差是衡量模型拟合优度的重要指标;高杠杆点、强影响点以及其他类型的离群点都会影响模型的拟合。相关系数衡量两个变量之间线性关系的强度和方向,但不指明哪个变量是解释变量、哪个是结果变量。后续章节将重点讨论如何将线性模型从数据样本推广到关于目标总体的推断。

7.4.2 术语

本章中介绍的术语列于 表 7.5。如果您不确定其中一些术语的含义,我们建议您回到正文中复习它们的定义。您应该能够很容易地发现它们是 粗体文本.

表 7.5:本章介绍的术语。
决定系数 最小二乘直线 回归平方和
相关系数 杠杆点 残差
外推 结果变量 误差平方和
高杠杆 离群值 总平方和
指示变量 predictor
强影响点 R方

7.5 练习

奇数编号习题的答案见 附录 A.7.

  1. 残差的可视化。 下面显示的每个散点图都叠加了一条回归线。如果要为每个图构建残差图(残差与 \(x\)的关系图),请用文字描述这些图的样子。

  1. 残差的趋势。 下面显示的是对两组不同数据拟合线性模型后所得残差的两幅图。对于每个图,描述其重要特征,并判断线性模型是否适用于这些数据。请解释你的理由。

  1. 识别关系,I。 针对下面六幅图中的每一幅,判断数据中关系的强度(例如,弱、中等或强),以及拟合线性模型是否合理。

  1. 识别相关关系,II。 针对下面六幅图中的每一幅,判断数据中关系的强度(例如,弱、中等或强),以及拟合线性模型是否合理。

  1. 期中考试与期末考试。 下面两幅散点图展示了某大学统计学课程在数年间记录的233名学生的课程总平均成绩与两次期中考试(考试1和考试2)之间的关系。10

    1. 根据这些图,哪一次考试与课程成绩的相关性最强?请解释。

    2. 你能想出一个理由,解释为什么你在(a)部分选择的考试与课程成绩之间的相关性更高吗?

  1. 肉类消费与预期寿命。 在为 You et al. (2022),总肉类摄入量与175个国家(地区)的预期寿命(出生时)相关。肉类摄入量以每人每年公斤数衡量(2011年至2013年的平均值)。此外,作者还收集了碳水化合物作物(例如谷物、块根、糖类等)的数据,以每人每年公斤数衡量(2011年和2013年的平均值)。左边的散点图显示出生时预期寿命与人均肉类消费量的关系。右边的散点图显示碳水化合物消费量与人均肉类消费量的关系。

    1. 描述肉类消费与预期寿命之间的关系。

    2. 描述肉类消费量与碳水化合物消费量之间的关系。

    3. 哪幅图显示的相关性更强?请解释你的理由。

    4. 消费数据最初以公斤为单位收集。如果将消费变量换算成磅,上面的图和相关系数会如何变化?

  1. 匹配相关系数,I。 将每个相关系数与对应的散点图进行匹配。11

    1. \(r = -0.7\)

    2. \(r = 0.45\)

    3. \(r = 0.06\)

    4. \(r = 0.92\)

  1. 匹配相关系数,II。 将每个相关系数与对应的散点图进行匹配。12

    1. \(r = 0.49\)

    2. \(r = -0.48\)

    3. \(r = -0.03\)

    4. \(r = -0.85\)

  1. 身体测量,相关性。 研究人体测量学的研究人员收集了507名经常进行体力活动个体的身体和骨骼直径测量数据,以及年龄、体重、身高和性别。下面的散点图显示了身高与肩围(在三角肌上方测量的肩部周长)之间的关系,两者均以厘米为单位测量。13 (Heinz 等人,2003)

    1. 描述肩围与身高之间的关系。

    2. 如果肩围以英寸测量而身高单位仍为厘米,这种关系会如何变化?

  1. 比较相关系数。 Eduardo 和 Rosie 都在收集一年中下雨天数和全年总降雨量的数据。Eduardo 以英寸记录降雨量,Rosie 以厘米记录。他们的相关系数相比会如何?
  1. 海岸星光号列车,相关性。 海岸星光号 Amtrak 列车从西雅图开往洛杉矶。下面的散点图显示了每两站之间的距离(以英里为单位)与从一站到另一站所需的时间(以分钟为单位)。14

    1. 描述距离与旅行时间之间的关系。

    2. 如果旅行时间改以小时测量,距离改以千米测量,这种关系会如何变化?

    3. 旅行时间(以英里为单位)与距离(以分钟为单位)之间的相关系数为 \(r = 0.636\)。旅行时间(以千米为单位)与距离(以小时为单位)之间的相关系数是多少?

  1. 爬行的婴儿,相关性。 丹佛大学进行的一项研究调查了婴儿在寒冷月份(此时他们常被包裹在限制活动的衣服里)学习爬行是否比在较暖月份花费更长时间。研究当年出生的婴儿被分为十二组,每个出生月份一组。我们考察每组婴儿的平均爬行年龄与婴儿六个月大时的平均温度(这是婴儿通常开始尝试爬行的时候)之间的关系。温度以华氏度(F)测量,年龄以周测量。15 (Benson 1993)

    1. 描述温度与爬行年龄之间的关系。

    2. 如果温度以摄氏度(C)测量,年龄以月测量,这种关系会如何变化?

    3. 华氏温度与周龄之间的相关系数为 \(r=-0.70\). 如果我们把温度转换为摄氏度、年龄转换为月,相关系数会是多少?

  1. 肉类和碳水化合物消费。 如果每个国家的人总是比碳水化合物多消费一定量的肉类,那么人均肉类消费与人均碳水化合物消费之间的相关系数会是多少?

    1. 每年比碳水化合物多消费 3 公斤肉类?

    2. 每年比碳水化合物少消费 2 公斤肉类?

    3. 每年消费的肉类是碳水化合物的一半?

  1. 研究生学历与薪资。 如果对于某类职位,拥有研究生学历的人的年薪总是比没有研究生学历的人高或低一定数额,那么在一家公司里,有研究生学历与没有研究生学历的人的年薪之间的相关系数会是多少?

    1. 比没有研究生学历的人多 5,000 美元?

    2. 比没有研究生学历的人多 25%?

    3. 比没有研究生学历的人少 15%?

  1. 回归的单位。 考虑一个基于方形巧克力布朗尼样本、用宽度(cm)预测热量(cal)的回归。相关系数、截距和斜率的单位分别是什么?
  1. 哪个更高? 判断 (I) 还是 (II) 更高,或者两者相等:“对于一条回归线,斜率估计值的不确定度, \(b_1\)在 (I) 回归线周围散点很多时更高,还是在 (II) 回归线周围散点很少时更高。”请解释你的理由。
  1. 高估还是低估,I。 假设我们拟合了一条回归线,根据苹果的重量来预测其保质期。对于某个苹果,我们预测其保质期为4.6天。该苹果的残差为-0.6天。我们是高估还是低估了这个苹果的保质期?请解释你的理由。
  1. 高估还是低估,II。 假设我们拟合了一条回归线,根据一年中晴天的数量来预测每1,000人中皮肤癌的发病数。对于某一年,我们预测皮肤癌的发病率为每1,000人1.5例,而该年的残差为0.5。我们是高估还是低估了皮肤癌的发病率?请解释你的理由。
  1. 星巴克、卡路里和蛋白质。 下面的散点图显示了星巴克食品菜单中各食品所含卡路里数量与蛋白质含量(以克为单位)之间的关系。由于星巴克在展示商品时只列出卡路里数量,我们可能想根据卡路里含量来预测某菜单食品的蛋白质含量。16

    1. 描述星巴克食品菜单中各食品所含卡路里数量与蛋白质含量(以克为单位)之间的关系。

    2. 在这个情境中,预测变量和结果变量分别是什么?

    3. 为什么我们可能想对这些数据拟合一条回归线?

    4. 残差与预测值图告诉我们,基于该模型,对于预测蛋白质含量较低与较高的食品,预测误差的变异性有何不同?

  1. 星巴克、卡路里和碳水化合物。 下面的散点图显示了星巴克食品菜单中各食品所含卡路里数量与碳水化合物含量(以克为单位)之间的关系。由于星巴克在展示商品时只列出卡路里数量,我们可能想根据卡路里含量来预测某菜单食品的碳水化合物含量。17

    1. 描述星巴克食品菜单中各食品所含卡路里数量与碳水化合物含量(以克为单位)之间的关系。

    2. 在这个情境中,预测变量和结果变量分别是什么?

    3. 为什么我们可能想对这些数据拟合一条回归线?

    4. 残差与预测值图告诉我们,基于该模型,对于预测碳水化合物含量较低与较高的食品,预测误差的变异性有何不同?

  1. 海岸星光号列车,回归。 Coast Starlight 号 Amtrak(美铁)列车从西雅图开往洛杉矶。下面的散点图显示了每两站之间的距离(单位:英里)与从一站到另一站所需的时间(单位:分钟)之间的关系。Coast Starlight 号列车从一站到下一站的平均旅行时间为 129 分钟,标准差为 113 分钟。从一站到下一站的平均行驶距离为 108 英里,标准差为 99 英里。旅行时间与距离之间的相关系数为 0.636。18

    1. 写出用于预测旅行时间的回归直线方程。

    2. 在此情境下解释斜率和截距的含义。

    3. 计算 \(R^2\) (用于根据行驶距离预测旅行时间的回归直线的决定系数),并在该应用情境下解释 \(R^2\) 的含义。

    4. 圣巴巴拉与洛杉矶之间的距离为 103 英里。使用该模型估计 Starlight 号列车在这两个城市之间行驶所需的时间。

    5. Coast Starlight 号列车从圣巴巴拉到洛杉矶实际需要约 168 分钟。计算残差并解释该残差值的含义。

    6. 假设 Amtrak 正考虑在距洛杉矶 500 英里处为 Coast Starlight 号列车增设一站。使用这个线性模型来预测从洛杉矶到该点的旅行时间是否合适?

  1. 身体测量与回归。 研究人体测量学的研究人员收集了 507 名经常进行体力活动的人的身体和骨骼直径测量数据,以及年龄、体重、身高和性别。下面的散点图显示了身高与肩围(在三角肌上方测量的肩部周长)之间的关系,两者均以厘米为单位测量。平均肩围为 107.20 厘米,标准差为 10.37 厘米。平均身高为 171.14 厘米,标准差为 9.41 厘米。身高与肩围之间的相关系数为 0.67。19 (Heinz 等人,2003)

    1. 写出用于预测身高的回归直线方程。

    2. 在此情境下解释斜率和截距的含义。

    3. 计算 \(R^2\) (用于根据肩围预测身高的回归直线的决定系数),并在该应用情境下解释其含义。

    4. 从你的班级中随机选出一名学生,其肩围为 100 厘米。使用该模型预测这名学生的身高。

    5. 第 (d) 部分中的学生身高为 160 厘米。计算残差,并解释这个残差的含义。

    6. 一个一岁的孩子肩围为 56 厘米。使用这个线性模型来预测该儿童的身高是否合适?

  1. 贫困与失业。 下面的散点图显示了美国各县贫困线以下人口百分比(poverty)与 20-64 岁人群失业率(unemployment_rate)之间的关系,数据来自 2019 年美国社区调查。用于预测 poverty 表 25.6:用 unemployment_rate 的模型的回归输出也已给出。20

    term 估计 的线性模型摘要 统计量 std.error
    p.value 4.60 0.349 13.2 <0.0001
    unemployment_rate 2.05 0.062 33.1 <0.0001

     

    1. 写出该线性模型。

    2. 解释截距。

    3. 解释斜率。

    4. \(R^2\) 该模型的 R² 为 46%。
      解释这个数值。

    5. 计算相关系数。

  1. 猫的体重。 下面的回归输出用于根据猫的体重(Hwt,单位为克)预测其心脏重量(Bwt,单位为 kg)。这些系数是使用包含 144 只家猫的数据集估计得到的。21

    term 估计 的线性模型摘要 统计量 std.error
    p.value -0.357 0.692 -0.515 0.6072
    Bwt 4.034 0.250 16.119 <0.0001

     

    1. 写出该线性模型。

    2. 解释截距。

    3. 解释斜率。

    4. \(R^2\) 该模型的 为 65%。
      解释 \(R^2\).

    5. 计算相关系数。

  2. 离群点,I。 找出下面散点图中的离群点,并确定它们属于哪种类型的离群点。解释你的理由。

  3. 离群点,II。 找出下面散点图中的离群点,并确定它们属于哪种类型的离群点。解释你的理由。

  4. 城市房主,离群点。 下面的散点图显示了拥有住房的家庭百分比与居住在城市地区的人口百分比之间的关系。共有 52 个观测值,每个观测值对应美国的一个州。波多黎各和哥伦比亚特区也包括在内。22

     

    1. 描述拥有住房的家庭百分比与居住在城市地区的人口百分比之间的关系。

    2. 右下角的离群点是哥伦比亚特区,那里 100% 的人口被视为城市人口。这个观测值属于哪种类型的离群点?

     

  1. 爬行的婴儿,离群点。 丹佛大学开展的一项研究调查了婴儿在寒冷月份(此时他们常被裹在限制活动的衣服里)学会爬行所需的时间是否比在较暖和的月份更长。下图显示了各月出生的婴儿的平均爬行年龄与婴儿六个月大时当月平均温度之间的关系。该图揭示了一个潜在的异常月份,其平均温度约为53华氏度,平均爬行年龄约为28.5周。这个点是否具有高杠杆值?它是否是一个有影响的点?23 (Benson 1993)

  1. 当备择假设为真且可辨别性水平为 (i) 0.05 或 (ii) 0.10 时,犯第二类错误的概率。 判断以下陈述是真是假。如果是假的,请解释原因。

    1. 相关系数为-0.90表示比相关系数0.5更强的线性关系。

    2. 相关是衡量任意两个变量之间关联性的度量。

  1. 黑樱桃树。 下面的散点图显示了31棵被砍伐的黑樱桃树的树高、直径和木材体积之间的关系。树的直径是在离地面4.5英尺处测量的。24

    1. 描述这些树的体积与高度之间的关系。

    2. 描述这些树的体积与直径之间的关系。

    3. 假设你有另一棵黑樱桃树的树高和直径测量数据。若要使用简单线性回归模型来预测这棵树的木材体积,使用哪个变量更为合适?请解释你的理由。

  1. 匹配相关系数,III。 将每个相关系数与对应的散点图进行匹配。25

    1. r = 0.69

    2. r = 0.09

    3. r = -0.91

    4. r = 0.97

  1. 头盔与午餐。 散点图显示了社会经济地位(以社区内享受学校减费午餐的儿童百分比(lunch)衡量)与社区内佩戴头盔的骑行者百分比(helmet)之间的关系。享受减费午餐的儿童百分比平均为30.833%,标准差为26.724%;佩戴头盔的骑行者百分比平均为30.883%,标准差为16.948%。

    1. 如果这些数据的最小二乘回归线的 \(R^2\) 为 72%,那么 lunchhelmet?

    2. 之间的相关系数是多少?

    3. 计算这些数据的最小二乘回归线的斜率和截距。

    4. 结合实际应用背景解释最小二乘回归线的截距。

    5. 结合实际应用背景解释最小二乘回归线的斜率。


  1. https://doi.org/10.1016/0163-6383(93)80029-8↩︎

  2. 如果模型低估了某个观测值,则模型估计值低于实际值。残差(实际观测值减去模型估计值)此时必为正。当模型高估观测值时则相反:残差为负。灰色菱形: \(\hat{y} = 41+0.59x = 41+0.59\times 85.0 = 91.15 \rightarrow e = y - \hat{y} = 98.6-91.15=7.45.\) 这接近于之前对 7 的估计。粉红三角形: \(\hat{y} = 41+0.59x = 97.3 \rightarrow e = -3.3.\) 这也接近于对 -4 的估计。↩︎

  3. 形式上,我们可以对观测值计算相关系数 \((x_1, y_1),\) \((x_2, y_2),\) …, \((x_n, y_n)\) ,使用公式↩︎

  4. 我们留给你来画这些线。一般来说,你画的线应该接近大多数点,并反映数据的整体趋势。↩︎

  5. 较高的家庭收入对应较低的资助金额,因此相关系数为负。使用计算机可以计算出相关系数:-0.499。↩︎

  6. 在某些应用中,残差绝对值之和可能更有用,而且我们还可以考虑许多其他标准。不过,本书只使用最小二乘标准。↩︎

  7. 大约 \(R^2 = (-0.97)^2 = 0.94\) 或 94% 的结果变量的变异可以由该线性模型解释。↩︎

  8. 差异 \(SST - SSE\) 被称为 回归平方和, \(SSR,\) ,也可以计算为 \(SSR = (\hat{y}_1 - \bar{y})^2 + (\hat{y}_2 - \bar{y})^2 + \cdots + (\hat{y}_n - \bar{y})^2.\) \(SSR\) 表示 \(y\) 中被我们的模型所解释的变异。↩︎

  9. \(SST\) 可以通过求结果变量的样本方差 \(s^2\) 并乘以 \(n-1.\)↩︎

  10. exam_grades 本练习中使用的数据可在 openintro R 包中找到。↩︎

  11. corr_match 本练习中使用的数据可在 openintro R 包中找到。↩︎

  12. corr_match 本练习中使用的数据可在 openintro R 包中找到。↩︎

  13. bdims 本练习中使用的数据可在 openintro R 包中找到。↩︎

  14. coast_starlight 本练习中使用的数据可在 openintro R 包中找到。↩︎

  15. babies_crawl 本练习中使用的数据可在 openintro R 包中找到。↩︎

  16. starbucks 本练习中使用的数据可在 openintro R 包中找到。↩︎

  17. starbucks 本练习中使用的数据可在 openintro R 包中找到。↩︎

  18. coast_starlight 本练习中使用的数据可在 openintro R 包中找到。↩︎

  19. bdims 本练习中使用的数据可在 openintro R 包中找到。↩︎

  20. county_2019 本练习中使用的数据可在 usdata R 包中找到。↩︎

  21. cats 本练习中使用的数据可在 MASS R 包中找到。↩︎

  22. urban_owner 本练习中使用的数据可在 usdata R 包中找到。↩︎

  23. babies_crawl 本练习中使用的数据可在 openintro R 包中找到。↩︎

  24. trees 本练习中使用的数据可在 datasets R 包中找到。↩︎

  25. corr_match 本练习中使用的数据可在 openintro R 包中找到。↩︎