Sub topic 2
Loading the California housing data
This chapter loads the dataset the rest of the project uses and checks that it arrived intact. It assumes you can read basic Python and pandas (DataFrames, column selection, describe) and that numpy, pandas, matplotlib and scikit-learn are installed. The previous chapter framed the task as regression. Here you get the data into memory and learn what each column means.
What the dataset contains
The California housing dataset comes from the 1990 US census. Each row is a block group, the smallest geographic unit for which the census publishes data. A block group typically holds 600 to 3,000 people, so a row describes a neighborhood, not a single house.
There are 20,640 rows. Each has eight numeric features and one target.
| 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 number of rooms per household |
| `AveBedrms` | Average number of bedrooms per household |
| `Population` | Number of people living in the block group |
| `AveOccup` | Average number of household members |
| `Latitude` | Block group latitude |
| `Longitude` | Block group longitude |
| `MedHouseVal` | Target: median house value, in units of $100,000 |
A MedHouseVal of 2.5 means a median house value of $250,000. When you read an error metric later, remember this unit. A mean absolute error of 0.5 means about $50,000.
Fetching the data
scikit-learn ships small datasets inside the package, with functions named load_*. Larger datasets are downloaded on demand by functions named fetch_*. California housing is one of the downloaded ones.
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
df = housing.frame
print(df.shape)
print(df.head())
print(df.describe())With as_frame=True, the function returns a Bunch. A Bunch is a dictionary-like object whose keys you can also read as attributes. housing.frame is a single DataFrame that holds the features and the target together. The target is the last column, MedHouseVal.
df.shape should print (20640, 9): eight features plus the target.
What the Bunch holds
Print the keys to see what else came back.
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
print(list(housing.keys()))
print(type(housing.data), housing.data.shape)
print(type(housing.target), housing.target.shape)
print(housing.feature_names)
print(housing.target_names)The main entries are:
data: a DataFrame of the eight features, shape(20640, 8).target: a Series with the house values, shape(20640,).frame:dataandtargetjoined into one DataFrame. It exists only whenas_frame=True.feature_namesandtarget_names: lists of column names.DESCR: a text description of the dataset. Runprint(housing.DESCR)to read it.
The later chapters split df into X (all columns except MedHouseVal) and y (the MedHouseVal column). You can get the same pair directly with return_X_y.
from sklearn.datasets import fetch_california_housing
X, y = fetch_california_housing(as_frame=True, return_X_y=True)
print(X.shape, y.shape)This chapter keeps the full frame because the next chapter explores features and target together.
Where the download goes
The first call downloads an archive over the network and stores it on disk. By default the cache is a folder named scikit_learn_data in your home directory. Later calls read from that cache and need no network access.
The diagram below shows the decision the function makes on each call.
Three parameters control this behavior:
data_home: the cache folder. Set it to keep the data inside your project, for exampledata_home="data".download_if_missing: the default isTrue. If you set it toFalseand the file is not cached, the call raises anOSErrorinstead of downloading.return_X_y: described above.
On a machine that cannot reach the internet, pre-populate the cache once on a connected machine and copy the folder across. Then point data_home at the copy.
Checking the data after loading
Do not assume the data is clean because a library supplied it. A few checks cost almost nothing and catch real problems, such as a partial download or a changed schema.
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
df = housing.frame
print(df.dtypes)
print("Missing values per column:")
print(df.isna().sum())
print("Duplicate rows:", df.duplicated().sum())
assert df.shape == (20640, 9), "Unexpected shape"
assert list(df.columns[:-1]) == housing.feature_names
assert df.columns[-1] == "MedHouseVal"You should see eight float64 columns for the features, plus MedHouseVal, all float64 too. There are no missing values, so this project needs no imputation step. The check for duplicates may report a small number or zero. Two block groups can have identical values by coincidence, and they do not matter here.
The assert lines make the code fail loudly if the data is not what the later chapters expect. Failing here with a clear message is better than getting a confusing error three chapters later.
Reading the summary statistics
df.describe() prints the count, mean, standard deviation, minimum, quartiles and maximum for every column. Read it with these points in mind.
- The count is 20640 for every column. That confirms there are no missing values.
- The columns are on very different scales.
Populationranges up to about 35,000.MedIncstays below about 15, and the latitude values run from about 32 to 42. Models that are sensitive to scale, such as Ridge regression, need scaling. A later chapter handles this inside a pipeline. - Some features have extreme maximums.
AveRoomsreaches about 142 andAveOccupexceeds 1,000. A block group with a thousand people per household is not a normal neighborhood. These are probably places with few households, such as dormitories or resorts, and they distort the averages. The exploration chapter looks at them properly. - The target is capped. The maximum of
MedHouseValis 5.00001, which is about $500,000. The census recorded higher values as that ceiling. Many rows sit exactly at the cap, so the model cannot learn that some neighborhoods cost more. This is a property of the data, not a bug. It also puts a limit on how well any model can do.
Treat these observations as notes for later. Do not clean anything yet. Any decision that uses statistics from the data, such as clipping outliers at a percentile, must be made after the train/test split. Otherwise information from the test rows influences training.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `URLError` or a connection timeout on the first call | No network access, or a proxy blocks the download | Connect and retry, or copy a cache folder to the machine and set `data_home` |
| `OSError` mentioning the data is not found | `download_if_missing=False` and the cache is empty | Remove that argument or fill the cache |
| `AttributeError` or `KeyError` on `housing.frame` | The call used `as_frame=False`, which returns numpy arrays and has no `frame` | Pass `as_frame=True` |
| `ImportError` when `as_frame=True` | pandas is not installed | Install pandas |
| A corrupt-file error after an interrupted download | The cached file is partial | Delete the `scikit_learn_data` folder (or your `data_home` folder) and fetch again |
A frequent mistake is to read the target in the wrong unit. A median value printed as 3.2 is $320,000, not $3.20. Another is to forget that housing.data and housing.frame are different objects. frame contains the target. If you build X from frame and forget to drop MedHouseVal, the model sees the answer as a feature, and you get suspiciously perfect scores. The next chapters return to this kind of mistake under the name data leakage.
What to carry forward
By now you have a DataFrame df of shape (20640, 9), no missing values, and a clear idea of the units and quirks in each column. The next chapter looks at the distributions and relationships in this DataFrame using plots. Keep df in your session or rerun the loading code at the top of each script. The cache means the later runs are fast.
Exercise
You load the data with fetchcaliforniahousing(as_frame=True) and find that housing.frame.shape is (20640, 9) while housing.data.shape is (20640, 8). Why do the two differ, and what is the danger of training a model on housing.frame without further changes?
Show answer
housing.frame contains the eight feature columns plus the target column MedHouseVal, so it has nine columns. housing.data holds only the eight features. If you train on housing.frame without dropping MedHouseVal, the target is included among the features, so the model can read the answer directly. It will report almost perfect scores that do not reflect real predictive ability. Build X by dropping MedHouseVal (or use housing.data) and keep y as the target.
Exercise
The describe() output shows that the maximum of MedHouseVal is 5.00001. What does this tell you about the data, and how might it affect your model's predictions for the most expensive neighborhoods?
Show answer
The target is capped at about $500,000, because the census recorded any higher value as that ceiling. Many rows share this top value, and the true prices there are unknown and higher. A model trained on this data cannot learn to predict values above the cap, and it will tend to underestimate the most expensive neighborhoods. This also limits the best error any model can reach.