Sub topic 3
Looking at the Data Before Modeling
This chapter covers exploratory data analysis (EDA) on the California housing data. It assumes you can use pandas DataFrames (selecting columns, describe, groupby), can run Python with numpy, pandas, matplotlib and scikit-learn installed, and know what features and a target are. You have already loaded the data into a DataFrame called df. Here you inspect it before choosing any model.
Why look first
EDA means checking the shape, types, ranges and relationships in your data before you fit anything. It is cheap, and it catches problems that no model will fix for you. Common examples are missing values, impossible values, a capped target, and features on very different scales.
EDA also drives later choices. What you see here decides whether you need scaling (the pipeline chapter), which models are plausible, and which metric suits the target.
One rule applies from the start. You are about to set aside a test set in a later chapter. Looking at the whole dataset for sanity checks is fine. Deciding feature transformations or model settings from patterns you saw in the test rows is a mild form of leakage. Keep your EDA descriptive. When you reach the split chapter, remember what you have already seen.
Load and check the basics
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
df = housing.frame
print(df.shape)
print(df.dtypes)
print(df.isna().sum())You should see 20,640 rows and 9 columns: eight features and the target MedHouseVal. All columns are float64. The missing-value count is zero in every column. This dataset is already clean, so you will not need an imputer here. On real data, a non-zero count is the first thing to resolve.
Each row describes one census block group, which is a small geographic area with a few hundred to a few thousand people. A row is not a single house. This matters for interpretation. AveRooms is the average number of rooms per household in that block group, and MedHouseVal is the median house value in that block group.
| Column | Meaning |
|---|---|
| `MedInc` | Median household income in the block group, in tens of thousands of dollars |
| `HouseAge` | Median age of houses, in years |
| `AveRooms` | Average rooms per household |
| `AveBedrms` | Average bedrooms per household |
| `Population` | People living in the block group |
| `AveOccup` | Average household members |
| `Latitude`, `Longitude` | Location of the block group |
| `MedHouseVal` | Target: median house value, in units of $100,000 |
Summary statistics
print(df.describe().T)Transposing with .T puts one feature per row, which is easier to read with nine columns. Read the min, 50% and max columns together for each feature.
Look for these things:
- Different scales.
Populationruns into the thousands whileMedIncis a single or double digit. Linear models with regularization are sensitive to this, and tree-based models are not. That is why the scaler appears in the Ridge pipeline later. - Extreme maxima.
AveRooms,AveBedrmsandAveOccuphave maxima far above their medians. A block group with an average of over 100 rooms per household is not a typical home. It is probably a small area with vacation homes or hotels, or a data quirk. - The target's range.
MedHouseValruns from about 0.15 to 5.0. Since the unit is $100,000, that is roughly $15,000 to $500,000.
The capped target
The maximum of exactly 5.0 is suspicious. Count how many rows sit at it:
at_cap = (df["MedHouseVal"] >= 5.0).sum()
print(at_cap, f"{at_cap / len(df):.1%}")A few hundred block groups, a little over 4% of the data, share the same top value. The source data was censored, meaning any value above $500,000 was recorded as $500,000. The true prices for those rows are higher and unknown.
This has two consequences:
- Models cannot learn to predict values above the cap, because they never see them. Predictions for expensive areas will be biased low.
- Error metrics for those rows are measured against a wrong "truth".
You do not need to fix this now. Some practitioners drop capped rows, but that changes the question the model answers, so it should be a deliberate choice. The point of EDA is to know about the cap so you can explain odd results later.
Distributions
Plot a histogram of every column:
import matplotlib.pyplot as plt
df.hist(bins=50, figsize=(12, 8))
plt.tight_layout()
plt.show()What to look for in each panel:
MedIncandMedHouseValare right-skewed. Most values are low, with a long tail of high ones.MedHouseValshows a spike at the right edge. That is the cap.HouseAgealso has a spike at its maximum, 52 years. It is likely capped too.AveRooms,AveBedrms,PopulationandAveOccuplook squashed against the left side. The few extreme values stretch the x-axis so far that the bulk of the data is hard to see.
A heavily skewed feature is not an error. Linear models can be helped by transforms such as a logarithm, and tree-based models do not care. Note the skew now, and decide later whether it matters for the model you pick.
To see the bulk of an outlier-heavy feature, look at percentiles rather than the maximum:
print(df["AveOccup"].quantile([0.01, 0.5, 0.99, 0.999]))The 99th percentile is a small number, while the maximum is in the hundreds. A handful of rows cause the stretched axis, not the whole column.
Relationships with the target
Correlation measures how strongly two columns move together, from -1 to 1. Sort the features by their correlation with the target:
corr = df.corr()["MedHouseVal"].drop("MedHouseVal")
print(corr.sort_values(ascending=False))MedInc has the strongest positive correlation, at about 0.69. Richer neighborhoods have higher house values, which matches intuition. AveRooms is weakly positive, Latitude is weakly negative, and Population is near zero.
Read these numbers with care:
- Pearson correlation, the default in
df.corr(), only captures straight-line relationships. A feature with a strong curved relationship can show a correlation near zero. - A near-zero correlation does not mean a feature is useless.
LatitudeandLongitudelook weak on their own, but together they say where a block group is, and location matters a great deal for housing. AveRoomsandAveBedrmsare correlated with each other. This is multicollinearity, which can make linear model coefficients unstable. Ridge regularization, covered later, helps with that.
Plot the location
Latitude and longitude can be drawn as a scatter plot, which gives you a rough map of California:
df.plot(
kind="scatter",
x="Longitude",
y="Latitude",
c="MedHouseVal",
cmap="viridis",
alpha=0.3,
s=8,
figsize=(8, 6),
)
plt.show()The shape of the coast appears. The expensive areas, in brighter colors, cluster around the Bay Area and the Los Angeles coast, and the inland areas are cheaper. No single straight-line effect describes this. A model needs to combine latitude and longitude to capture it. That is one reason a non-linear model such as gradient boosting is expected to beat a linear one on this data.
What the EDA tells us
The diagram shows how each finding feeds a later decision.
Common mistakes
- Treating rows as houses. Each row is a block group. A prediction is for a typical house in an area, not for one particular home.
- Dropping outliers automatically. An extreme
AveRoomsvalue may be a data error or a real unusual area. Decide with a reason, and do it after the split, using only the training data. - Computing statistics on everything and reusing them. Means, medians and scaling parameters calculated on the full dataset carry information from the test rows into training. Looking is fine. Fitting is not.
- Trusting correlation alone. It misses curved relationships and interactions, as the latitude and longitude example shows.
Exercises
Exercise
The target MedHouseVal has its highest value at exactly 5.0, and several hundred rows share it. What does this tell you, and how could it affect your results?
Show answer
The target was censored: any block group with a median value above $500,000 was recorded as 5.0 (units of $100,000). The true values for these rows are higher and unknown. A model never sees prices above the cap, so it tends to underpredict expensive areas. Error metrics for those rows are measured against an inaccurate target.
Exercise
Latitude has a weak correlation with MedHouseVal, and Longitude is similar. A colleague says to drop both. What would you answer, and what check supports it?
Show answer
Pearson correlation only measures straight-line relationships for each column alone. Location affects price in a curved, combined way, with high values near the Bay Area and Los Angeles coast. The scatter plot of longitude against latitude, colored by MedHouseVal, shows this clearly. Keep both features, and a non-linear model can use them together.