13.4.3. Homework#
Use this assignment to practice the chapter’s concepts and coding skills in runnable Python code.
Sign in from the account menu before you start working on the assignment.
Write and run your code directly in the coding cells.
Multiple submissions are allowed. The highest score is kept.
1. Reading a Coefficient
In a regression of house price (in dollars) on square feet, rooms, and age, the coefficient on square feet is 120. Holding rooms and age fixed, each additional square foot is associated with a $120 higher predicted price.
2. Correlated Predictors
When two predictors are strongly correlated with each other, such as square feet and rooms, their individual coefficients are hard to interpret as each feature’s own effect.
3. Training Error
An analyst judges a pricing model by its RMSE on the same houses used to fit it. That RMSE is the best estimate of how far off the model’s quotes for new listings will be.
4. More Predictors
An analyst adds 30 more predictors to a pricing model, and its training RMSE falls. So its predictions for new listings cannot be worse than before.
5. R-squared
A regression has an R-squared of 0.8 on the test set. Its predictions account for 80% of the variation in test-set prices.
### 6. Cross-Validating Two Pricing Models
# A broker asks whether agents should also record year built and lot size.
# Compare two models with 5-fold cross-validation on the 40 sales below:
# Model A: living_area and overall_quality
# Model B: living_area, overall_quality, year_built, and lot_area
# 1. For each model, run cross_val_score(LinearRegression(), X, homes['price'], cv=5,
# scoring='neg_root_mean_squared_error') and take the average RMSE
# (the scores are negative RMSEs), rounded to 1 decimal.
# 2. Print each average RMSE and the model with the lower one.
# Print exactly:
# Model A: 5-fold RMSE 40.2
# Model B: 5-fold RMSE 25.0
# Chosen: B
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
# Data: 40 real home sales from Ames, Iowa (Ames Housing data, De Cock 2011),
# drawn at random from the book's ames_housing.csv; prices in $1,000s.
homes = pd.DataFrame({
"living_area": [1006, 1776, 1404, 3279, 1088, 1425, 1720, 1053, 2127, 1224, 944, 1795, 900, 914, 1955, 1694, 1138, 1437, 972, 1570,
1094, 887, 1664, 1405, 800, 864, 2288, 864, 1215, 971, 1226, 2054, 1304, 2134, 1464, 1416, 1560, 1316, 1796, 1135],
"overall_quality": [5, 7, 7, 8, 8, 7, 7, 5, 7, 6, 3, 5, 5, 4, 5, 7, 6, 5, 5, 6,
6, 5, 6, 7, 2, 5, 7, 4, 6, 5, 8, 6, 5, 6, 5, 6, 6, 6, 6, 7],
"year_built": [1959, 2002, 1999, 2003, 1986, 1998, 2004, 1959, 1991, 1948, 1952, 1954, 1967, 1961, 1958, 1997, 1960, 1976, 1955, 1958,
1953, 1984, 2000, 2003, 1936, 1955, 1977, 1920, 1940, 1969, 1980, 2000, 1977, 1916, 1963, 1968, 1912, 1926, 1998, 1936],
"lot_area": [9000, 14006, 2160, 53504, 3696, 8685, 8244, 10007, 13125, 8064, 10206, 12150, 7838, 17199, 9000, 8314, 15312, 10768, 10895, 13200,
10452, 10447, 8121, 3136, 6120, 8172, 13774, 9000, 7000, 9920, 3874, 12224, 2665, 11888, 12886, 11700, 12900, 8969, 9531, 7200],
"price": [80.0, 192.5, 170.0, 538.0, 170.0, 193.0, 183.5, 145.5, 238.0, 132.0, 82.0, 131.5, 123.0, 128.0, 165.5, 200.0, 148.0, 218.0, 122.5, 166.8,
155.0, 124.5, 172.4, 171.8, 60.0, 115.0, 230.0, 65.0, 141.0, 128.5, 190.0, 244.0, 104.5, 214.5, 175.0, 179.9, 159.9, 145.0, 211.0, 155.0], # $1,000s
})
### Your code starts here.
### Your code ends here.
### 7. How Sure Is the Coefficient?
# The broker wants to tell sellers how much more newer houses sell for.
# Use the 40 sales below (the same as Question 6).
# 1. Fit LinearRegression of price on living_area, overall_quality, and year_built,
# and keep the year_built coefficient (in $1,000s per year).
# 2. Bootstrap 200 times: resample with homes.sample(40, replace=True, random_state=i)
# for i = 0, ..., 199, refit, and keep the year_built coefficient.
# 3. Compute the 95% interval with np.percentile(..., [2.5, 97.5], method='nearest').
# 4. Print the estimate and interval, rounded to 2 decimals, and whether the whole
# interval is above 0.
# Print exactly:
# Estimate: 0.29
# 95% interval: -0.08 to 0.61
# Clearly positive: False
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
# Data: 40 real home sales from Ames, Iowa (Ames Housing data, De Cock 2011),
# drawn at random from the book's ames_housing.csv; prices in $1,000s.
homes = pd.DataFrame({
"living_area": [1006, 1776, 1404, 3279, 1088, 1425, 1720, 1053, 2127, 1224, 944, 1795, 900, 914, 1955, 1694, 1138, 1437, 972, 1570,
1094, 887, 1664, 1405, 800, 864, 2288, 864, 1215, 971, 1226, 2054, 1304, 2134, 1464, 1416, 1560, 1316, 1796, 1135],
"overall_quality": [5, 7, 7, 8, 8, 7, 7, 5, 7, 6, 3, 5, 5, 4, 5, 7, 6, 5, 5, 6,
6, 5, 6, 7, 2, 5, 7, 4, 6, 5, 8, 6, 5, 6, 5, 6, 6, 6, 6, 7],
"year_built": [1959, 2002, 1999, 2003, 1986, 1998, 2004, 1959, 1991, 1948, 1952, 1954, 1967, 1961, 1958, 1997, 1960, 1976, 1955, 1958,
1953, 1984, 2000, 2003, 1936, 1955, 1977, 1920, 1940, 1969, 1980, 2000, 1977, 1916, 1963, 1968, 1912, 1926, 1998, 1936],
"lot_area": [9000, 14006, 2160, 53504, 3696, 8685, 8244, 10007, 13125, 8064, 10206, 12150, 7838, 17199, 9000, 8314, 15312, 10768, 10895, 13200,
10452, 10447, 8121, 3136, 6120, 8172, 13774, 9000, 7000, 9920, 3874, 12224, 2665, 11888, 12886, 11700, 12900, 8969, 9531, 7200],
"price": [80.0, 192.5, 170.0, 538.0, 170.0, 193.0, 183.5, 145.5, 238.0, 132.0, 82.0, 131.5, 123.0, 128.0, 165.5, 200.0, 148.0, 218.0, 122.5, 166.8,
155.0, 124.5, 172.4, 171.8, 60.0, 115.0, 230.0, 65.0, 141.0, 128.5, 190.0, 244.0, 104.5, 214.5, 175.0, 179.9, 159.9, 145.0, 211.0, 155.0], # $1,000s
})
### Your code starts here.
### Your code ends here.
### 8. Nearest-Neighbor Regression
# The data below are made up for practice.
# Predict a house's price from the 3 most similar houses. Both features are
# already in standard units.
# 1. Compute the distance from new_house to each house (or use
# KNeighborsRegressor(n_neighbors=3) from sklearn.neighbors).
# 2. Predict the price as the average price of the 3 nearest houses,
# rounded to 1 decimal.
# Print exactly:
# Predicted price: 298.3
import numpy as np
import pandas as pd
houses = pd.DataFrame({
"size_su": [-1.2, -0.5, 0.0, 0.4, 0.9, 1.5, -0.8, 0.2],
"age_su": [0.8, -0.3, 0.5, -1.0, 0.2, -0.6, 1.2, -0.2],
"price": [210, 265, 280, 330, 350, 410, 230, 300],
})
new_house = np.array([0.3, -0.4])
### Your code starts here.
### Your code ends here.
### 9. Checking Two Predictors
# The data below are made up for practice.
# 1. Compute the correlation between square feet and number of bathrooms,
# rounded to 2 decimals.
# 2. Flag the pair if the absolute correlation is above 0.8.
# Print exactly:
# Correlation: 0.83
# Multicollinearity flag: True
import numpy as np
import pandas as pd
houses = pd.DataFrame({
"sqft": [1200, 1500, 1700, 1900, 2200, 2600, 3000],
"bathrooms": [1, 2, 2, 2, 3, 2, 4],
})
### Your code starts here.
### Your code ends here.
### 10. Recommending a Model
# Four pricing models were compared with 5-fold cross-validation (RMSE in $1,000s).
# The numbers are illustrative, based loosely on the Ames results in Section 13.3.
# Agents must explain every coefficient to sellers, so the broker requires:
# - at most 5 features, and
# - every coefficient's 95% interval excludes 0 (low > 0 or high < 0).
# 1. Find the models that meet both requirements (D's 35 intervals are not listed).
# 2. Among them, recommend the model with the lowest cross-validated RMSE.
# 3. Print the qualifying models, the recommendation, and its test RMSE (used once).
# Print exactly:
# Qualifying models: A, B
# Recommended: B
# Test RMSE: 34.0
import numpy as np
import pandas as pd
models = pd.DataFrame({
"features": [2, 3, 5, 35],
"cv_rmse": [36.0, 33.2, 31.0, 29.8],
"test_rmse": [36.5, 34.0, 31.8, 30.1],
}, index=["A", "B", "C", "D"])
# 95% bootstrap intervals for each coefficient of models A, B, and C (in dollars)
intervals = pd.DataFrame({
"model": ["A", "A", "B", "B", "B", "C", "C", "C", "C", "C"],
"feature": ["living_area", "overall_quality",
"living_area", "overall_quality", "year_built",
"living_area", "overall_quality", "year_built", "garage_cars", "full_baths"],
"low": [78, 21500, 55, 20100, 230, 50, 18800, 150, 3100, -2100],
"high": [102, 30400, 75, 28300, 570, 71, 27000, 520, 15800, 6800],
})
### Your code starts here.
### Your code ends here.