Sub topic 3
Looking at the Data Before Modeling
This chapter assumes you can use pandas DataFrames, select columns, and call describe(). You also need matplotlib and a loaded copy of the California housing data from the previous chapter. The goal is to spot problems that will affect modeling decisions later. It is not to produce polished charts.
Why look first
Models accept almost any numbers without complaint. Bad inputs only show up later as poor scores that are hard to trace. A few minutes of inspection tells you which columns need scaling, which are skewed, and whether the target has quirks. These findings feed directly into the preprocessing and metric choices in later chapters.
Run this on the full frame to start.
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
df = housing.frame
print(df.shape)
print(df.isna().sum().sum(), "missing values")
print(df.describe().T[["min", "mean", "50%", "max"]])What to check
Read the describe() output with these questions in mind:
- Missing values. This dataset has none, so no imputation is needed. Real data usually does.
- Scale differences.
Populationruns into the thousands, whileAveRoomsis a single digit. Ridge regression is sensitive to this, so scaling will matter. - Mean versus median. A mean far above the 50% value means a long right tail. Compare them for
AveRooms,AveOccup, andPopulation. - Extreme maxima.
AveRoomsandAveOccuphave maxima far above their medians. These are likely odd districts, such as areas with many vacation homes or very few households.
Looking at the target
The target MedHouseVal is in units of $100,000. Plot its distribution and count the rows at the top value.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
df["MedHouseVal"].hist(bins=50, ax=axes[0])
axes[0].set_title("Median house value")
df.plot.scatter(x="MedInc", y="MedHouseVal", alpha=0.1, ax=axes[1])
axes[1].set_title("Income vs. value")
plt.tight_layout()
plt.show()
print((df["MedHouseVal"] >= 5.0).sum(), "rows at the cap")The histogram shows a spike at 5.0, which is $500,000. The source data capped values at that level, so many expensive districts all carry the same number. A model cannot learn the true price of those districts, and it will tend to underpredict them. Keep this in mind when you interpret errors later.
The scatter plot shows that higher income tends to go with higher value, with a wide spread. The same plot also shows the cap as a flat horizontal line of points.
Correlations as a rough guide
Correlation with the target gives a quick ranking of which features carry linear signal.
print(df.corr()["MedHouseVal"].sort_values(ascending=False))MedInc should stand out. Treat these numbers as a hint only. Correlation misses non-linear relationships, and Latitude and Longitude matter in ways a single coefficient cannot show.
What the findings change
Exercise
The target column has a spike at 5.0. Why does that matter for a model, and why should you not simply delete those rows from the full dataset before splitting?
Show answer
The cap hides the true price of those districts, so the model sees the same value for houses that differ widely and will tend to underpredict them. Deleting rows changes what the model is asked to predict, so new data with expensive districts would be handled poorly. Doing it on the full dataset before splitting also lets a decision based on all the data, including the test rows, shape the training set. Note the cap and move on, or decide on any removal after the split.