Mathew K Analytics

Lesson 64 · Pandas Full Course

Predict House Prices with Pandas and scikit-learn (End-to-End Project) | Pandas Course #64

In this lesson you'll be able to: Explore a prediction target and spot capped values Engineer ratio features that make districts comparable Turn text…

📓 Full notebook

Download .ipynb

Pandas 64: Hands-on Project - Predicting House Prices#

In this lesson you'll be able to:

  • Explore a prediction target and spot capped values
  • Engineer ratio features that make districts comparable
  • Turn text categories into model-ready numbers
  • Split, fill and fit without leaking test data
  • Judge a model against a baseline, and find where it fails Dataset: California housing, 20,640 districts (data/pandas/housing.csv)

Warm-up: summarise by group#

Lesson 63 compared groups with totals and shares. Same skills, new data.

import pandas as pd
df = pd.read_csv("data/pandas/housing.csv")
print(df.shape)
df[["median_income", "median_house_value", "ocean_proximity"]].head(3)
(20640, 10)
median_income median_house_value ocean_proximity
0 8.3252 452600.0 NEAR BAY
1 8.3014 358500.0 NEAR BAY
2 7.2574 352100.0 NEAR BAY
target = "median_house_value"
loc = df.groupby("ocean_proximity")[target].agg(["size", "median"])
loc["share"] = loc["size"] / loc["size"].sum()
loc.sort_values("median").round(2)
size median share
ocean_proximity
INLAND 6551 108500.0 0.32
<1H OCEAN 9136 214850.0 0.44
NEAR OCEAN 2658 229450.0 0.13
NEAR BAY 2290 233800.0 0.11
ISLAND 5 414700.0 0.00

Understand the target before predicting it#

Problem: a model can only be as good as the numbers it learns from.

cols = ["median_income", "housing_median_age", target]
df[cols].describe().round(2)
median_income housing_median_age median_house_value
count 20640.00 20640.00 20640.00
mean 3.87 28.64 206855.82
std 1.90 12.59 115395.62
min 0.50 1.00 14999.00
25% 2.56 18.00 119600.00
50% 3.53 29.00 179700.00
75% 4.74 37.00 264725.00
max 15.00 52.00 500001.00

Quick check: which house value appears most often?

df[target].value_counts().head(3)
median_house_value
500001.0    965
137500.0    122
162500.0    117
Name: count, dtype: int64
import matplotlib.pyplot as plt
ax = df[target].plot(kind="hist", bins=50, figsize=(7, 4))
ax.set_title("Median house value per district")
ax.set_xlabel("Median house value (dollars)")
ax.set_ylabel("Number of districts")
plt.show()
No description has been provided for this image
capped = df[target] >= 500001
print(capped.sum())
df = df[~capped].copy()
print(len(df))
965
19675
old = df["housing_median_age"] == 52
print(old.sum())
print(round(df.loc[old, target].median()))
1103
234600

Engineer features that describe a typical home#

Problem: totals grow with district size, not with how nice homes are.

df["rooms_per_house"] = df["total_rooms"] / df["households"]
df["bedroom_ratio"] = df["total_bedrooms"] / df["total_rooms"]
df["people_per_house"] = df["population"] / df["households"]
new = ["rooms_per_house", "bedroom_ratio", "people_per_house"]
df[new].describe().round(2)
rooms_per_house bedroom_ratio people_per_house
count 19675.00 19475.00 19675.00
mean 5.36 0.21 3.10
std 2.29 0.06 10.63
min 0.85 0.10 0.69
25% 4.41 0.18 2.45
50% 5.18 0.20 2.84
75% 5.97 0.24 3.30
max 132.53 1.00 1243.33
show = ["people_per_house", "population", "households", target]
df.nlargest(3, "people_per_house")[show].round(1)
people_per_house population households median_house_value
19006 1243.3 7460.0 6.0 137500.0
3364 599.7 4198.0 7.0 67500.0
16669 502.5 6532.0 13.0 350000.0

Common mistake: asking for correlations with a text column present

df.corr()[target]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[11], line 1
----> 1 df.corr()[target]

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\frame.py:13135, in DataFrame.corr(self, method, min_periods, numeric_only)
  13133 cols = data.columns
  13134 idx = cols.copy()
> 13135 mat = data.to_numpy(dtype=float, na_value=np.nan, copy=False)
  13137 if method == "pearson":
  13138     correl = libalgos.nancorr(mat, minp=min_periods)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\frame.py:2081, in DataFrame.to_numpy(self, dtype, copy, na_value)
   2079 if dtype is not None:
   2080     dtype = np.dtype(dtype)
-> 2081 result = self._mgr.as_array(dtype=dtype, copy=copy, na_value=na_value)
   2082 if result.dtype is not dtype:
   2083     result = np.asarray(result, dtype=dtype)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\internals\managers.py:1885, in BlockManager.as_array(self, dtype, copy, na_value)
   1883         arr.flags.writeable = False
   1884 else:
-> 1885     arr = self._interleave(dtype=dtype, na_value=na_value)
   1886     # The underlying data was copied within _interleave, so no need
   1887     # to further copy if copy=True or setting na_value
   1889 if na_value is lib.no_default:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\internals\managers.py:1938, in BlockManager._interleave(self, dtype, na_value)
   1932 rl = blk.mgr_locs
   1933 if blk.is_extension:
   1934     # Avoid implicit conversion of extension blocks to object
   1935 
   1936     # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no
   1937     # attribute "to_numpy"
-> 1938     arr = blk.values.to_numpy(  # type: ignore[union-attr]
   1939         dtype=dtype,
   1940         na_value=na_value,
   1941     )
   1942 else:
   1943     arr = blk.get_values(dtype)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\arrays\arrow\array.py:1803, in ArrowExtensionArray.to_numpy(self, dtype, copy, na_value)
   1801 result = data._pa_array.to_numpy()
   1802 if dtype is not None:
-> 1803     result = result.astype(dtype, copy=False)
   1804 if copy:
   1805     result = result.copy()

ValueError: could not convert string to float: 'NEAR BAY'
corr = df.corr(numeric_only=True)[target]
corr.drop(target).sort_values().round(3)
bedroom_ratio        -0.216
latitude             -0.148
longitude            -0.047
people_per_house     -0.021
population            0.012
housing_median_age    0.068
total_bedrooms        0.075
households            0.095
rooms_per_house       0.110
total_rooms           0.143
median_income         0.643
Name: median_house_value, dtype: float64
sample = df.sample(2000, random_state=42)
ax = sample.plot(kind="scatter", x="median_income", y=target,
                 alpha=0.3, figsize=(7, 4))
ax.set_title("Richer districts have pricier homes")
ax.set_xlabel("Median income (tens of thousands of dollars)")
ax.set_ylabel("Median house value (dollars)")
plt.show()
No description has been provided for this image

Your turn#

Cut median_income into 5 equal-width bands and find the median value in each.

bands = pd.cut(df["median_income"], bins=5)
by_band = df.groupby(bands, observed=True)[target]
by_band.agg(["size", "median"]).round(0)
size median
median_income
(0.485, 3.4] 9620 126650.0
(3.4, 6.3] 8816 213200.0
(6.3, 9.2] 1171 344200.0
(9.2, 12.1] 59 426000.0
(12.1, 15.0] 9 400000.0

Turn location text into numbers#

Problem: models do arithmetic, and you can't multiply a word.

Common mistake: giving a model a text column

from sklearn.linear_model import LinearRegression
LinearRegression().fit(df[["median_income", "ocean_proximity"]],
                       df[target])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_24828\3468875733.py in ?()
      1 from sklearn.linear_model import LinearRegression
----> 2 LinearRegression().fit(df[["median_income", "ocean_proximity"]],
      3                        df[target])

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\base.py in ?(estimator, *args, **kwargs)
   1399                     )
   1400                 ),
   1401                 callback_management_context(estimator),
   1402             ):
-> 1403                 return fit_method(estimator, *args, **kwargs)

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\linear_model\_base.py in ?(self, X, y, sample_weight)
    677         n_jobs_ = self.n_jobs
    678 
    679         accept_sparse = False if self.positive else ["csr", "csc", "coo"]
    680 
--> 681         X, y = validate_data(
    682             self,
    683             X,
    684             y,

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py in ?(_estimator, X, y, reset, validate_separately, skip_check_array, **check_params)
   3054             if "estimator" not in check_y_params:
   3055                 check_y_params = {**default_check_params, **check_y_params}
   3056             y = check_array(y, input_name="y", **check_y_params)
   3057         else:
-> 3058             X, y = check_X_y(X, y, **check_params)
   3059         out = X, y
   3060 
   3061     if not no_val_X and check_params.get("ensure_2d", True):

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py in ?(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, ensure_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
   1326         raise ValueError(
   1327             f"{estimator_name} requires y to be passed, but the target y is None"
   1328         )
   1329 
-> 1330     X = check_array(
   1331         X,
   1332         accept_sparse=accept_sparse,
   1333         accept_large_sparse=accept_large_sparse,

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py in ?(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, ensure_all_finite, ensure_non_negative, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name)
   1035                         )
   1036                     array = xp.astype(array, dtype, copy=False)
   1037                 else:
   1038                     array = _asarray_with_order(array, order=order, dtype=dtype, xp=xp)
-> 1039             except ComplexWarning as complex_warning:
   1040                 raise ValueError(
   1041                     "Complex data not supported\n{}\n".format(array)
   1042                 ) from complex_warning

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\_array_api.py in ?(array, dtype, order, copy, xp, device)
    979         # Use NumPy API to support order
    980         if copy is True:
    981             array = numpy.array(array, order=order, dtype=dtype)
    982         else:
--> 983             array = numpy.asarray(array, order=order, dtype=dtype)
    984 
    985         # At this point array is a NumPy ndarray. We convert it to an array
    986         # container that is consistent with the input's namespace.

~\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\generic.py in ?(self, dtype, copy)
   2023             )
   2024         values = self._values
   2025         if copy is None:
   2026             # Note: branch avoids `copy=None` for NumPy 1.x support
-> 2027             arr = np.asarray(values, dtype=dtype)
   2028         else:
   2029             arr = np.array(values, dtype=dtype, copy=copy)
   2030 

ValueError: could not convert string to float: 'NEAR BAY'
dummies = pd.get_dummies(df["ocean_proximity"], dtype=int)
dummies.head(3)
<1H OCEAN INLAND ISLAND NEAR BAY NEAR OCEAN
0 0 0 0 1 0
1 0 0 0 1 0
2 0 0 0 1 0

Quick check: how many districts are in each new column?

dummies.sum()
<1H OCEAN     8604
INLAND        6524
ISLAND           5
NEAR BAY      2096
NEAR OCEAN    2446
dtype: int64
cols = ["median_income", target]
df.groupby("ocean_proximity")[cols].median().round(2)
median_income median_house_value
ocean_proximity
<1H OCEAN 3.76 207650.0
INLAND 2.98 108300.0
ISLAND 2.74 414700.0
NEAR BAY 3.69 219850.0
NEAR OCEAN 3.52 218250.0
features = ["median_income", "housing_median_age", "latitude",
            "longitude"] + new
X = pd.concat([df[features], dummies], axis=1)
y = df[target]
print(X.shape)
(19675, 12)
X.dtypes.value_counts()
float64    7
int64      5
Name: count, dtype: int64

Split before you fill: train and test sets#

Problem: a model must be tested on districts it has never seen.

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)
(15740, 12) (3935, 12)
print(round(y_train.mean()), round(y_test.mean()))
192191 193625
print(round(X_train["INLAND"].mean(), 3))
print(round(X_test["INLAND"].mean(), 3))
0.332
0.332

Common mistake: fitting with missing values

model = LinearRegression().fit(X_train, y_train)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[24], line 1
----> 1 model = LinearRegression().fit(X_train, y_train)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\base.py:1403, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
   1393     estimator._validate_params()
   1395 with (
   1396     config_context(
   1397         skip_parameter_validation=(
   (...)
   1401     callback_management_context(estimator),
   1402 ):
-> 1403     return fit_method(estimator, *args, **kwargs)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\linear_model\_base.py:681, in LinearRegression.fit(self, X, y, sample_weight)
    677 n_jobs_ = self.n_jobs
    679 accept_sparse = False if self.positive else ["csr", "csc", "coo"]
--> 681 X, y = validate_data(
    682     self,
    683     X,
    684     y,
    685     accept_sparse=accept_sparse,
    686     y_numeric=True,
    687     multi_output=True,
    688     force_writeable=True,
    689 )
    691 has_sw = sample_weight is not None
    692 if has_sw:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py:3058, in validate_data(_estimator, X, y, reset, validate_separately, skip_check_array, **check_params)
   3056         y = check_array(y, input_name="y", **check_y_params)
   3057     else:
-> 3058         X, y = check_X_y(X, y, **check_params)
   3059     out = X, y
   3061 if not no_val_X and check_params.get("ensure_2d", True):

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py:1330, in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, ensure_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator)
   1325         estimator_name = _check_estimator_name(estimator)
   1326     raise ValueError(
   1327         f"{estimator_name} requires y to be passed, but the target y is None"
   1328     )
-> 1330 X = check_array(
   1331     X,
   1332     accept_sparse=accept_sparse,
   1333     accept_large_sparse=accept_large_sparse,
   1334     dtype=dtype,
   1335     order=order,
   1336     copy=copy,
   1337     force_writeable=force_writeable,
   1338     ensure_all_finite=ensure_all_finite,
   1339     ensure_2d=ensure_2d,
   1340     allow_nd=allow_nd,
   1341     ensure_min_samples=ensure_min_samples,
   1342     ensure_min_features=ensure_min_features,
   1343     estimator=estimator,
   1344     input_name="X",
   1345 )
   1347 y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric, estimator=estimator)
   1349 check_consistent_length(X, y)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py:1090, in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, ensure_all_finite, ensure_non_negative, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name)
   1084     raise ValueError(
   1085         f"Found array with dim {array.ndim},"
   1086         f" while dim <= 2 is required{context}."
   1087     )
   1089 if ensure_all_finite:
-> 1090     _assert_all_finite(
   1091         array,
   1092         input_name=input_name,
   1093         estimator_name=estimator_name,
   1094         allow_nan=ensure_all_finite == "allow-nan",
   1095     )
   1097 if copy:
   1098     if _is_numpy_namespace(xp):
   1099         # only make a copy if `array` and `array_orig` may share memory`

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py:137, in _assert_all_finite(X, allow_nan, msg_dtype, estimator_name, input_name)
    134 if first_pass_isfinite:
    135     return
--> 137 _assert_all_finite_element_wise(
    138     X,
    139     xp=xp,
    140     allow_nan=allow_nan,
    141     msg_dtype=msg_dtype,
    142     estimator_name=estimator_name,
    143     input_name=input_name,
    144 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py:186, in _assert_all_finite_element_wise(X, xp, allow_nan, msg_dtype, estimator_name, input_name)
    169 if estimator_name and input_name == "X" and has_nan_error:
    170     # Improve the error message on how to handle missing values in
    171     # scikit-learn.
    172     msg_err += (
    173         f"\n{estimator_name} does not accept missing values"
    174         " encoded as NaN natively. For supervised learning, you might want"
   (...)
    184         "#estimators-that-handle-nan-values"
    185     )
--> 186 raise ValueError(msg_err)

ValueError: Input X contains NaN.
LinearRegression does not accept missing values encoded as NaN natively. For supervised learning, you might want to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor which accept missing values encoded as NaNs natively. Alternatively, it is possible to preprocess the data, for instance by using an imputer transformer in a pipeline or drop samples with missing values. See https://scikit-learn.org/stable/modules/impute.html You can find a list of all estimators that handle NaN values at the following page: https://scikit-learn.org/stable/modules/impute.html#estimators-that-handle-nan-values
ratio_med = X_train["bedroom_ratio"].median()
X_train = X_train.fillna({"bedroom_ratio": ratio_med})
X_test = X_test.fillna({"bedroom_ratio": ratio_med})
print(X_train.isna().sum().sum(), X_test.isna().sum().sum())
0 0

Quick check: why use the training median, not the whole dataset's?

all_med = df["bedroom_ratio"].median()
print(round(ratio_med, 4), round(all_med, 4))
0.2049 0.2046

Fit a model and judge it fairly#

Problem: an error number means nothing without a baseline to beat.

from sklearn.metrics import mean_absolute_error
guess = pd.Series(y_train.median(), index=y_test.index)
base_mae = mean_absolute_error(y_test, guess)
print(f"Baseline error: {base_mae:,.0f}")
Baseline error: 78,582
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
lin_mae = mean_absolute_error(y_test, pred)
print(f"Linear error:   {lin_mae:,.0f}")
Linear error:   47,286

Quick check: is that error big compared with a typical home?

print(round(lin_mae / y_test.median(), 3))
0.275
weights = pd.Series(model.coef_, index=X_train.columns)
weights[["median_income", "housing_median_age", "INLAND"]].round(0)
median_income         41680.0
housing_median_age      750.0
INLAND               -67389.0
dtype: float64
res = pd.DataFrame({"actual": y_test, "predicted": pred})
res["error"] = res["predicted"] - res["actual"]
res.head().round(0)
actual predicted error
15065 104200.0 136920.0 32720.0
14534 171200.0 220585.0 49385.0
13570 97300.0 165164.0 67864.0
2607 102700.0 183242.0 80542.0
12750 116500.0 100924.0 -15576.0
ax = res.plot(kind="scatter", x="actual", y="predicted",
               alpha=0.2, figsize=(6, 5))
ax.plot([0, 500000], [0, 500000], color="red")
ax.set_title("Linear model: predicted vs actual value")
ax.set_xlabel("Actual value (dollars)")
ax.set_ylabel("Predicted value (dollars)")
plt.show()
No description has been provided for this image

Your turn#

Fit a RandomForestRegressor (100 trees, random_state=42). Does it beat the line?

from sklearn.ensemble import RandomForestRegressor
forest = RandomForestRegressor(n_estimators=100, random_state=42)
forest.fit(X_train, y_train)
res["forest"] = forest.predict(X_test)
forest_mae = mean_absolute_error(y_test, res["forest"])
print(f"Forest error:   {forest_mae:,.0f}")
Forest error:   30,450
from sklearn.metrics import r2_score
print(round(r2_score(y_test, pred), 3))
print(round(r2_score(y_test, res["forest"]), 3))
0.594
0.789
imp = pd.Series(forest.feature_importances_, index=X_train.columns)
imp.nlargest(5).round(3)
median_income       0.425
INLAND              0.159
people_per_house    0.125
longitude           0.083
latitude            0.077
dtype: float64

Common mistake: predicting with different columns than you fitted

forest.predict(X_test[["median_income", "latitude", "longitude"]])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[36], line 1
----> 1 forest.predict(X_test[["median_income", "latitude", "longitude"]])

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\ensemble\_forest.py:1065, in ForestRegressor.predict(self, X)
   1063 check_is_fitted(self)
   1064 # Check data
-> 1065 X = self._validate_X_predict(X)
   1067 # Assign chunk of trees to jobs
   1068 n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\ensemble\_forest.py:615, in BaseForest._validate_X_predict(self, X)
    612 else:
    613     ensure_all_finite = True
--> 615 X = validate_data(
    616     self,
    617     X,
    618     dtype=np.float32,
    619     accept_sparse="csr",
    620     reset=False,
    621     ensure_all_finite=ensure_all_finite,
    622 )
    623 if issparse(X) and (X.indices.dtype != np.intc or X.indptr.dtype != np.intc):
    624     raise ValueError("No support for np.int64 index based sparse matrices")

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py:3016, in validate_data(_estimator, X, y, reset, validate_separately, skip_check_array, **check_params)
   2932 def validate_data(
   2933     _estimator,
   2934     /,
   (...)
   2940     **check_params,
   2941 ):
   2942     """Validate input data and set or check feature names and counts of the input.
   2943 
   2944     This helper function should be used in an estimator that requires input
   (...)
   3014         validated.
   3015     """
-> 3016     _check_feature_names(_estimator, X, reset=reset)
   3017     tags = get_tags(_estimator)
   3018     if y is None and tags.target_tags.required:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\sklearn\utils\validation.py:2868, in _check_feature_names(estimator, X, reset)
   2865 if not missing_names and not unexpected_names:
   2866     message += "Feature names must be in the same order as they were in fit.\n"
-> 2868 raise ValueError(message)

ValueError: The feature names should match those that were passed during fit.
Feature names seen at fit time, yet now missing:
- <1H OCEAN
- INLAND
- ISLAND
- NEAR BAY
- NEAR OCEAN
- ...
one = X_test.iloc[[0]]
print(round(forest.predict(one)[0]))
print(round(y_test.iloc[0]))
124283
104200

Mini-project: where does the model go wrong?#

Plan: attach location to each error, group, then summarise.

res["miss"] = (res["forest"] - res["actual"]).abs()
res["bias"] = res["forest"] - res["actual"]
res["place"] = df.loc[res.index, "ocean_proximity"]
res[["actual", "forest", "miss", "place"]].head(3).round(0)
actual forest miss place
15065 104200.0 124283.0 20083.0 <1H OCEAN
14534 171200.0 166321.0 4879.0 <1H OCEAN
13570 97300.0 153342.0 56042.0 INLAND
by_place = res.groupby("place")[["actual", "miss", "bias"]].mean()
by_place["miss_pct"] = by_place["miss"] / by_place["actual"]
by_place.sort_values("miss_pct").round(2)
actual miss bias miss_pct
place
<1H OCEAN 224742.02 32302.07 895.25 0.14
NEAR OCEAN 227081.84 35981.21 -3795.17 0.16
NEAR BAY 245933.42 41246.09 -7595.67 0.17
ISLAND 287500.00 52298.00 52298.00 0.18
INLAND 123700.38 22643.05 1333.91 0.18
ax = by_place["miss_pct"].sort_values().plot(kind="barh",
                                             figsize=(7, 4))
ax.set_title("Forest miss as a share of district value")
ax.set_xlabel("Average miss / average value")
ax.set_ylabel("Location")
plt.show()
No description has been provided for this image
top = res["actual"] >= 400000
print(round(res.loc[top, "bias"].mean()))
print(round(res.loc[~top, "bias"].mean()))
-91975
4015
import os
os.makedirs("output/pandas", exist_ok=True)
path = "output/pandas/l64_predictions.csv"
res.round(0).to_csv(path)
print(pd.read_csv(path, index_col=0).shape)
(3935, 7)
gain = 1 - forest_mae / base_mae
print(f"Forest misses by {forest_mae:,.0f} on average,")
print(f"{gain:.0%} smaller than guessing the median.")
Forest misses by 30,450 on average,
61% smaller than guessing the median.

Recap#

  • Look at the target first: capped values distort a model
  • Ratios beat raw totals for comparing districts
  • get_dummies turns text categories into 0/1 columns
  • Split first, then fill gaps using training data only
  • Always compare a model's error with a simple baseline

Challenges#

  1. Add income_per_person as a feature. Does the forest improve?
  2. Group the forest's misses by housing_median_age bands.
  3. Refit without latitude and longitude. How much worse is it?

What's next#

Lesson 65: Capstone Project - Sales Analytics with Pandas One real retail dataset, taken from raw file to finished insights.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.