13.2. Multiple Regression#
A real estate analyst at a mortgage lender needs to estimate what a home will sell for before it is listed. In Regression with scikit-learn you fit a four-feature model with scikit-learn, read its coefficients holding the other features fixed, and scored it on test homes. This section asks the harder questions a manager should ask of such a model. Why does one feature not suffice? What happens to a coefficient when a closely related feature joins the model? How much does the extra information help on homes the model has never seen? And is a very different kind of model, one that simply looks up similar homes, any better?
The data are the Ames, Iowa home sales from Regression with scikit-learn (2,412 real sales, 2006 to 2010).
homes = pd.read_csv(path_data + 'ames_housing.csv')
print(homes.shape)
homes.head()
(2412, 10)
| sale_price | living_area | overall_quality | year_built | garage_cars | total_rooms | full_baths | lot_area | neighborhood | year_sold | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 215000 | 1656 | 6 | 1960 | 2 | 7 | 1 | 31770 | NAmes | 2010 |
| 1 | 105000 | 896 | 5 | 1961 | 1 | 5 | 1 | 11622 | NAmes | 2010 |
| 2 | 172000 | 1329 | 6 | 1958 | 1 | 6 | 1 | 14267 | NAmes | 2010 |
| 3 | 244000 | 2110 | 7 | 1968 | 2 | 8 | 2 | 11160 | NAmes | 2010 |
| 4 | 189900 | 1629 | 5 | 1997 | 2 | 6 | 2 | 13830 | Gilbert | 2010 |
The target is sale_price, in dollars. The predictors are the four from Regression with scikit-learn (living_area, overall_quality, year_built, garage_cars) plus total_rooms (rooms above ground, not counting bathrooms).
13.2.1. One Feature Is Not Enough#
With one predictor, regression is the line from Regression Line. Here is sale price against living area, with the least squares line from scikit-learn.
line = LinearRegression().fit(homes[['living_area']], homes['sale_price'])
print('Slope: $', round(line.coef_[0], 2), 'per square foot')
print('Intercept: $', round(line.intercept_))
fig, ax = plt.subplots(figsize=(7, 4))
ax.scatter(homes['living_area'], homes['sale_price'] / 1000, s=6, alpha=0.4)
xs = np.array([400, 3800])
ax.plot(xs, (line.intercept_ + line.coef_[0] * xs) / 1000, color='red', lw=2)
ax.set_xlabel('Living area (square feet)')
ax.set_ylabel('Sale price ($1,000s)')
ax.set_title('Bigger homes sell for more, but with a wide spread')
plt.show()
Slope: $ 106.76 per square foot
Intercept: $ 17730
The line says each extra square foot goes with about $107 more in price. But the points scatter widely around it. Look at homes of roughly the same size, between 1,400 and 1,600 square feet.
same_size = homes[(homes['living_area'] >= 1400) & (homes['living_area'] <= 1600)]
print('Homes between 1,400 and 1,600 sq ft:', len(same_size))
print('Cheapest: $', same_size['sale_price'].min())
print('Median: $', int(same_size['sale_price'].median()))
print('Priciest: $', same_size['sale_price'].max())
Homes between 1,400 and 1,600 sq ft: 397
Cheapest: $ 79000
Median: $ 176000
Priciest: $ 330000
Homes of nearly the same size sold for anywhere from $79,000 to $330,000. Size alone cannot explain that. Some of the gap comes from quality, and some from age. Compare the average price of these same-size homes by quality rating.
print(same_size.groupby('overall_quality')['sale_price'].agg(['count', 'mean']).round(0))
count mean
overall_quality
1 1 81500.0
4 14 120781.0
5 86 150523.0
6 133 166482.0
7 113 198916.0
8 42 233103.0
9 8 279188.0
Among similar-sized homes, the average price climbs steadily with the quality rating. A model that also sees quality, and age, should do better than a line through size alone. That model is the multiple regression from Regression with scikit-learn, \(\hat{y} = \beta_0 + \beta_1 x_1 + \cdots + \beta_p x_p\), with the coefficients chosen by least squares.
### Exercise: Same Size, Different Prices
# 1. Keep the homes with living_area from 1,800 to 2,000 square feet (both ends included).
# 2. Print how many there are, and the cheapest and priciest sale prices.
# 3. Print how much more, on average, homes rated 8 sold for than homes rated 6,
# rounded to the nearest dollar.
# Print exactly:
# Homes: 195
# Cheapest: 97500
# Priciest: 470000
# Quality 8 minus quality 6: 80177
import pandas as pd
ex_homes = pd.read_csv(path_data + 'ames_housing.csv')
### Your code starts here.
### Your code ends here.
Homes: 195
Cheapest: 97500
Priciest: 470000
Quality 8 minus quality 6: 80177
13.2.2. Looking at the Predictors Together#
Before fitting, look at how the variables relate to each other. A correlation matrix lists the correlation \(r\) (from Correlation) for every pair of columns. In pandas it is one call to .corr().
predictors = ['living_area', 'overall_quality', 'year_built', 'garage_cars', 'total_rooms']
corr = homes[predictors + ['sale_price']].corr().round(2)
corr
| living_area | overall_quality | year_built | garage_cars | total_rooms | sale_price | |
|---|---|---|---|---|---|---|
| living_area | 1.00 | 0.55 | 0.21 | 0.48 | 0.81 | 0.73 |
| overall_quality | 0.55 | 1.00 | 0.56 | 0.57 | 0.35 | 0.79 |
| year_built | 0.21 | 0.56 | 1.00 | 0.51 | 0.08 | 0.54 |
| garage_cars | 0.48 | 0.57 | 0.51 | 1.00 | 0.35 | 0.64 |
| total_rooms | 0.81 | 0.35 | 0.08 | 0.35 | 1.00 | 0.50 |
| sale_price | 0.73 | 0.79 | 0.54 | 0.64 | 0.50 | 1.00 |
Read the last row (or column) first: it shows how each predictor relates to sale_price. Quality (0.79) and living area (0.73) have the strongest relationships with price, and total rooms the weakest (0.50).
Now read the predictors against each other. Living area and total rooms have a correlation of 0.81. That is not surprising: bigger homes have more rooms. When two predictors move together this strongly, they are called multicollinear, and the data are said to show multicollinearity (first met in Regression with scikit-learn). The scatter plots below compare this pair with a weaker one, living area and quality (r = 0.55).
fig, axes = plt.subplots(1, 2, figsize=(9, 3.8))
axes[0].scatter(homes['living_area'], homes['total_rooms'], s=6, alpha=0.4)
axes[0].set_xlabel('Living area (square feet)')
axes[0].set_ylabel('Total rooms')
axes[0].set_title('Size and rooms move together (r = 0.81)')
axes[1].scatter(homes['living_area'], homes['overall_quality'], s=6, alpha=0.4)
axes[1].set_xlabel('Living area (square feet)')
axes[1].set_ylabel('Overall quality (1-10)')
axes[1].set_title('Size and quality overlap less (r = 0.55)')
plt.tight_layout()
plt.show()
Multicollinearity does not break a model’s predictions, but it makes individual coefficients hard to read, as the next subsection shows. If two predictors carry nearly the same information, the model cannot tell which one deserves the credit.
### Exercise: Which Predictors Overlap?
# 1. Use the small made-up table of five homes below.
# 2. Compute the correlation matrix of its three numeric columns with .corr(), rounded to 2 decimals.
# 3. Print the correlation of rooms with living_area.
# 4. Print "multicollinear" if that correlation is above 0.8, otherwise "not strongly related".
# Print exactly:
# living_area rooms price
# living_area 1.00 0.97 0.99
# rooms 0.97 1.00 0.97
# price 0.99 0.97 1.00
# 0.97
# multicollinear
import pandas as pd
small = pd.DataFrame({
'living_area': [900, 1200, 1500, 1800, 2400],
'rooms': [4, 6, 6, 7, 9],
'price': [110, 150, 190, 205, 290]})
### Your code starts here.
### Your code ends here.
living_area rooms price
living_area 1.00 0.97 0.99
rooms 0.97 1.00 0.97
price 0.99 0.97 1.00
0.97
multicollinear
13.2.3. Fitting a Multiple Regression#
Fit the model with the five predictors, the four from Regression with scikit-learn plus total_rooms. For this part, fit on all the homes; the test comes in the next part.
X = homes[predictors]
y = homes['sale_price']
full_model = LinearRegression().fit(X, y)
print('Intercept: $', round(full_model.intercept_))
for name, coef in zip(predictors, full_model.coef_):
print(f'{name:16s} $ {coef:10.2f}')
Intercept: $ -778426
living_area $ 76.13
overall_quality $ 20372.04
year_built $ 372.22
garage_cars $ 12029.64
total_rooms $ -5484.25
Read each coefficient as in Regression with scikit-learn: holding the other predictors fixed. A home rated one point higher in quality, and the same in size, age, garage, and rooms, is predicted to sell for about $20,372 more, and one more garage space goes with about $12,030 more. Both are close to the four-feature model in 1301.
The coefficient on living_area is about $76 per square foot, lower than the $107 from the one-feature line. Part of what the line credited to size now goes to quality and garage, which come with larger homes.
The coefficient on total_rooms is the surprise. It is negative, about -$5,484. Does an extra room lower a home’s price? Check the relationship with price alone.
rooms_only = LinearRegression().fit(homes[['total_rooms']], y)
print('total_rooms alone: $', round(rooms_only.coef_[0]))
size_rooms = LinearRegression().fit(homes[['living_area', 'total_rooms']], y)
print('total_rooms with living_area: $', round(size_rooms.coef_[1]))
print('living_area with total_rooms: $', round(size_rooms.coef_[0], 2), 'per sq ft')
total_rooms alone: $ 22875
total_rooms with living_area: $ -12651
living_area with total_rooms: $ 139.1 per sq ft
By itself, an extra room goes with about $22,875 more in price. Add living_area and the sign flips to about -$12,651. The data have not changed; the question has. Alone, total_rooms stands in for size, because homes with more rooms are bigger. Once living_area is in the model, the question becomes: for two homes with the same square footage, what does an extra room do? Fitting the same space into more rooms means smaller rooms, and in these data such homes sold for less. The model is not saying that adding a room lowers a price; it is describing homes of equal size.
This is why multicollinearity matters to a manager. The five-predictor model predicts well, but an individual coefficient for a predictor that overlaps with another, like total_rooms, should not be read as that feature’s effect on its own. In general, a coefficient depends on which other predictors are in the model.
### Exercise: Quality With and Without Size
# 1. Use the homes DataFrame; fit LinearRegression of sale_price on overall_quality alone.
# 2. Fit a second model of sale_price on overall_quality and living_area.
# 3. Print the overall_quality coefficient from each model, rounded to the nearest dollar.
# 4. Print a sentence saying whether the coefficient is smaller with living_area in the model.
# Print exactly:
# Quality alone: 41422
# Quality with living_area: 29168
# Smaller with living_area in the model: True
import pandas as pd
from sklearn.linear_model import LinearRegression
homes = pd.read_csv(path_data + 'ames_housing.csv')
### Your code starts here.
### Your code ends here.
Quality alone: 41422
Quality with living_area: 29168
Smaller with living_area in the model: True
13.2.4. Simple vs. Multiple on Test Data#
Does the extra information help predict homes the model has not seen? As in Regression with scikit-learn, split the homes into training data (used to fit) and test data (held back to evaluate). Here 30% of the homes go to the test set, and random_state makes the split reproducible.
train, test = train_test_split(homes, test_size=0.3, random_state=13)
print('Training homes:', len(train))
print('Test homes: ', len(test))
Training homes: 1688
Test homes: 724
Fit two models on the training homes only: the one-feature line with living_area, and the five-predictor model. Then score each on the test homes with the test RMSE and \(R^2\) from Regression with scikit-learn. On test data, \(R^2\) compares the model with always predicting the average test price: that scores 0, perfect predictions score 1, and a model worse than the average can score below 0.
def test_scores(features):
model = LinearRegression().fit(train[features], train['sale_price'])
predicted = model.predict(test[features])
rmse = np.sqrt(mean_squared_error(test['sale_price'], predicted))
r2 = r2_score(test['sale_price'], predicted)
return rmse, r2
simple_rmse, simple_r2 = test_scores(['living_area'])
multi_rmse, multi_r2 = test_scores(predictors)
print('Spread (SD) of test prices: $', round(test['sale_price'].std()))
print(f'Simple (living_area): RMSE $ {simple_rmse:,.0f} R-squared {simple_r2:.3f}')
print(f'Multiple (5 predictors): RMSE $ {multi_rmse:,.0f} R-squared {multi_r2:.3f}')
Spread (SD) of test prices: $ 69586
Simple (living_area): RMSE $ 45,413 R-squared 0.574
Multiple (5 predictors): RMSE $ 31,433 R-squared 0.796
Test prices vary with a standard deviation of about $69,586. The simple line misses by about $45,413 on a typical test home and accounts for 57% of the variation in test prices (\(R^2 = 0.574\)). The multiple model misses by about $31,433 and accounts for 80% (\(R^2 = 0.796\)). Adding quality, age, garage, and rooms cut the typical error by about $14,000, and the improvement shows up on homes the model never saw. For the lender, that is the difference between a rough estimate and a usable one.
Note what \(R^2\) does not say. It is not the percent of predictions that are correct, and it says nothing about whether a feature causes higher prices. It only measures how much of the variation in prices the predictions track.
### Exercise: Predict with Quality Only
# 1. Split homes with train_test_split (test_size=0.3, random_state=13), as above.
# 2. Fit LinearRegression of sale_price on overall_quality alone, using the training homes.
# 3. Compute the test RMSE and the test R-squared; print them rounded to the nearest dollar and 3 decimals.
# 4. Print whether quality alone beats living_area alone (test RMSE 45413).
# Print exactly:
# RMSE: 44926
# R-squared: 0.583
# Beats living_area alone: True
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
homes = pd.read_csv(path_data + 'ames_housing.csv')
### Your code starts here.
### Your code ends here.
RMSE: 44926
R-squared: 0.583
Beats living_area alone: True
13.2.5. Nearest Neighbors for Regression#
A linear model assumes price changes by a fixed dollar amount per unit of each feature (linearity) and that the effects of the features simply add up (additivity). A very different idea needs no formula: to price a home, find the k nearest neighbors, the \(k\) training homes most similar to it, and predict the average of their prices. This is k-nearest neighbors regression. The same idea classifies categories in Nearest Neighbors; here the neighbors’ prices are averaged instead of voted on.
“Most similar” needs a distance, and distance depends on units. Living area ranges over thousands of square feet and quality over 1 to 10, so raw distance would be almost entirely about size. First convert each feature to standard units (from Correlation). One rule matters: compute the mean and SD from the training homes only, and reuse them to convert the test homes. Using test data in the conversion would leak information the model is not supposed to have.
knn_features = ['living_area', 'overall_quality']
train_mean = train[knn_features].mean()
train_sd = train[knn_features].std(ddof=0)
train_scaled = (train[knn_features] - train_mean) / train_sd
test_scaled = (test[knn_features] - train_mean) / train_sd
knn = KNeighborsRegressor(n_neighbors=10).fit(train_scaled, train['sale_price'])
knn_pred = knn.predict(test_scaled)
knn_rmse = np.sqrt(mean_squared_error(test['sale_price'], knn_pred))
knn_r2 = r2_score(test['sale_price'], knn_pred)
print(f'Nearest neighbors (k=10): RMSE $ {knn_rmse:,.0f} R-squared {knn_r2:.3f}')
Nearest neighbors (k=10): RMSE $ 32,731 R-squared 0.778
Compare it with linear regression. For a fair test, give the linear model the same two features, and also show the five-predictor model.
two_rmse, two_r2 = test_scores(knn_features)
print(f'Linear, 2 features: RMSE $ {two_rmse:,.0f} R-squared {two_r2:.3f}')
print(f'Nearest neighbors, k=10: RMSE $ {knn_rmse:,.0f} R-squared {knn_r2:.3f}')
print(f'Linear, 5 predictors: RMSE $ {multi_rmse:,.0f} R-squared {multi_r2:.3f}')
Linear, 2 features: RMSE $ 34,004 R-squared 0.761
Nearest neighbors, k=10: RMSE $ 32,731 R-squared 0.778
Linear, 5 predictors: RMSE $ 31,433 R-squared 0.796
On the same two features and this one split, nearest neighbors ($32,677) beats the linear model ($34,004). It can bend with the data, for example when quality adds more to price for large homes than for small ones (an interaction, where one feature’s effect depends on another), and a line cannot. But the five-predictor linear model ($31,433) beats both, because it uses information the neighbor model never saw.
So which is better? There is no single answer. Nearest neighbors tends to work well when:
relationships are curved or have interactions that a line misses,
there are plenty of training homes, and only a few features.
Linear regression tends to work better when:
there are many features, since “nearby” becomes hard to define when distance is measured in many directions at once,
a manager needs a coefficient to explain, such as “$20,000 per quality point”. Neighbors give a prediction but no such explanation,
predictions are needed far from the training data, since an average of neighbors cannot go beyond the prices it has seen.
The value \(k = 10\) was picked here without tuning it. How to choose features without peeking at the test set, using a validation set, is the subject of Choosing Features and Avoiding Overfitting; the same method chooses \(k\), as Training, Testing, and Accuracy shows.
### Exercise: A Different k
# 1. Split homes with train_test_split (test_size=0.3, random_state=13).
# 2. Standardize living_area and overall_quality using the training mean and SD (use std(ddof=0)).
# 3. Fit KNeighborsRegressor with n_neighbors=3 on the training homes and predict the test homes.
# 4. Print the test RMSE rounded to the nearest dollar, and whether it is larger than the k=10 RMSE of 32677.
# Comparing k values on the test set is only an illustration here; to choose k,
# use a validation set (1303) instead.
# Print exactly:
# k=3 RMSE: 34798
# Larger than k=10: True
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_squared_error
homes = pd.read_csv(path_data + 'ames_housing.csv')
### Your code starts here.
### Your code ends here.
k=3 RMSE: 34955
Larger than k=10: True
13.2.6. Section Practice#
A broker has the recent sales below: 12 homes with size, quality rating, year built, and sale price (made-up numbers for practice, on the same scale as the Ames data). The broker wants to price three new listings. Build a multiple regression model from the 12 sales and use it for the listings.
### Exercise: Price Three Listings
# 1. Fit LinearRegression of sale_price on living_area, overall_quality, and year_built, using the 12 sales.
# 2. Print the three coefficients, rounded to 2 decimals, labeled by predictor.
# 3. Predict the price of each listing in the listings table; print each rounded to the nearest dollar.
# 4. Print the R-squared of the model on the 12 sales, rounded to 3 decimals.
# Print exactly:
# living_area: 80.42
# overall_quality: 22723.67
# year_built: 314.25
# Listing 1: $162969
# Listing 2: $256481
# Listing 3: $109835
# R-squared: 0.972
import pandas as pd
from sklearn.linear_model import LinearRegression
sales = pd.DataFrame({
'living_area': [1100, 1350, 1500, 1620, 1800, 1250, 2100, 1400, 1950, 1700, 2400, 1000],
'overall_quality': [5, 6, 6, 7, 7, 5, 8, 5, 7, 6, 9, 4],
'year_built': [1955, 1978, 1965, 1999, 1990, 1972, 2004, 1950, 1985, 2001, 2007, 1948],
'sale_price': [105000, 148000, 142000, 198000, 196000, 126000, 265000, 118000,
215000, 184000, 335000, 84000]})
listings = pd.DataFrame({
'living_area': [1500, 2000, 1200],
'overall_quality': [6, 8, 5],
'year_built': [1980, 2005, 1960]})
### Your code starts here.
### Your code ends here.
living_area: 80.42
overall_quality: 22723.67
year_built: 314.25
Listing 1: $162969
Listing 2: $256481
Listing 3: $109835
R-squared: 0.972