MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Machine Learning – scikit-learn – Lab 2

This lab explores the California Housing dataset with pandas, matplotlib and seaborn. It is the exploratory step you do before training a scikit-learn regression model. The notebook above loads the Kaggle CSV, checks its shape, drops rows with missing values, summarises the numeric columns and starts plotting relationships. Below you will find setup steps, an explanation of each output, the full set of plots, and a scikit-learn pipeline that turns the exploration into a baseline model.


Set up the environment and get the dataset

The notebook reads datasets/housing.csv from a folder next to the notebook, but it never shows how to get that file. Create an isolated Python environment, install the libraries, then download the CSV from Kaggle, either through the website or with the Kaggle CLI.

python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install pandas matplotlib seaborn scikit-learn jupyterlab kaggle

# Needs a Kaggle API token in ~/.kaggle/kaggle.json
mkdir -p datasets
kaggle datasets download -d camnugent/california-housing-prices -p datasets --unzip
ls datasets
# housing.csv

jupyter labCode language: PHP (php)

Note: If you can't use Kaggle, sklearn.datasets.fetch_california_housing(as_frame=True) downloads a related version of the dataset. It is not the same file: it has 8 engineered features (such as AveRooms and AveOccup), no ocean_proximity column and no missing values, and its target MedHouseVal is measured in units of $100,000. The code on this page assumes the Kaggle CSV.

What the columns mean

Each row is one census block group in California, not one house. That explains why total_rooms and population take values in the thousands.

ColumnMeaningThings to watch
longitude, latitudeLocation of the block groupStrong geographic patterns near the coast
housing_median_ageMedian age of housesCapped at 52 (see the max in describe())
total_rooms, total_bedroomsTotals for the whole block groupDivide by households to get per-home values
population, householdsPeople and households in the blockHeavily right-skewed
median_incomeMedian household incomeScaled: 3.87 means roughly $38,700; capped near 15
median_house_valueTarget variable in USDCapped at 500,001
ocean_proximityCategorical location labelText, so it must be encoded before modelling

Reading the output of the steps above

  • housing_data.shape returns (20640, 10): 20,640 rows and 10 columns.
  • After dropna() the shape is (20433, 10), so 207 rows were removed. All of them are missing total_bedrooms. You can confirm this with housing_data.isna().sum() before dropping.
  • describe() lists only the 9 numeric columns. ocean_proximity is text, so it is left out. Use housing_data.describe(include='object') or value_counts() to summarise it.
  • The max of median_house_value is exactly 500001 and housing_median_age tops out at 52. Both values were capped when the data was collected. A model can't learn anything above these limits, so decide whether to keep or remove those rows.
  • total_rooms has a mean of about 2,636 but a max of 39,320. Large gaps like this between the 75% quartile and the max point to outliers and skewed distributions.
  • unique() on ocean_proximity returns five categories. ISLAND covers only a handful of rows (five in the full file), which matters if you stratify or split by this column.
housing_data.isna().sum()
housing_data['ocean_proximity'].value_counts()
(housing_data['median_house_value'] >= 500001).sum()   # how many capped targetsCode language: PHP (php)

Visualizing relationships

The notebook stops after its first plot of median house value. The cells below cover the views that matter most for this dataset. Run them after the cleaning cells above.

# 1. Distribution of every numeric column
housing_data.hist(bins=50, figsize=(14, 10))
plt.tight_layout()
plt.show()

# 2. Income vs house value: the strongest single predictor
fig, ax = plt.subplots(figsize=(10, 6))
sns.scatterplot(data=housing_data, x='median_income', y='median_house_value', alpha=0.2, ax=ax)
ax.set_xlabel('Median income (tens of thousands USD)')
ax.set_ylabel('Median house value')
plt.show()

# 3. House value by ocean proximity
plt.figure(figsize=(10, 6))
sns.boxplot(data=housing_data, x='ocean_proximity', y='median_house_value')
plt.show()

# 4. Geographic view: colour = value, size = population
housing_data.plot(kind='scatter', x='longitude', y='latitude', alpha=0.4,
                  s=housing_data['population'] / 100, c='median_house_value',
                  cmap='viridis', colorbar=True, figsize=(10, 7))
plt.show()

# 5. Correlation heatmap (numeric columns only)
corr = housing_data.corr(numeric_only=True)
plt.figure(figsize=(10, 8))
sns.heatmap(corr, annot=True, fmt='.2f', cmap='coolwarm')
plt.show()

corr['median_house_value'].sort_values(ascending=False)Code language: PHP (php)

Things to look for in these plots:

  • A horizontal line of points at 500,001 in the income scatter plot. These are the capped values.
  • INLAND block groups sitting much lower in the boxplot than coastal ones.
  • High-value clusters around the Bay Area and Los Angeles on the map.
  • median_income showing the highest correlation with the target in the heatmap.

Adding more useful features

Totals per block group are hard to compare because blocks differ in size. Ratios usually tell you more about a typical home, and they often correlate better with the target than the raw totals do.

housing_data['rooms_per_household'] = housing_data['total_rooms'] / housing_data['households']
housing_data['bedrooms_per_room'] = housing_data['total_bedrooms'] / housing_data['total_rooms']
housing_data['population_per_household'] = housing_data['population'] / housing_data['households']

housing_data.corr(numeric_only=True)['median_house_value'].sort_values(ascending=False)Code language: PHP (php)

From exploration to a scikit-learn baseline

Exploration should tell you what preprocessing the model needs. For this dataset that means filling in missing bedrooms, scaling the numeric columns and one-hot encoding ocean_proximity. A Pipeline keeps those steps together, and because it is fitted only on the training split, test data can't leak into the preprocessing. This version imputes missing values instead of dropping rows, so it starts from the raw CSV.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score

df = pd.read_csv('datasets/housing.csv')
X = df.drop(columns='median_house_value')
y = df['median_house_value']

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

num_cols = X.select_dtypes(include='number').columns.tolist()
cat_cols = ['ocean_proximity']

preprocess = ColumnTransformer([
    ('num', Pipeline([
        ('impute', SimpleImputer(strategy='median')),
        ('scale', StandardScaler()),
    ]), num_cols),
    ('cat', OneHotEncoder(handle_unknown='ignore'), cat_cols),
])

model = Pipeline([('prep', preprocess), ('reg', LinearRegression())])
model.fit(X_train, y_train)

pred = model.predict(X_test)
print('MAE:', round(mean_absolute_error(y_test, pred)))
print('R2 :', round(r2_score(y_test, pred), 3))Code language: JavaScript (javascript)

A plain linear model leaves a large error on this data because the relationships are non-linear and the target is capped. Treat the scores as a baseline. To improve on it, swap LinearRegression for RandomForestRegressor or HistGradientBoostingRegressor and add the ratio features from the previous section.

Common errors and fixes

ErrorCauseFix
FileNotFoundError: datasets/housing.csvThe CSV isn't in a datasets folder next to the notebookDownload it as shown above, or pass an absolute path to read_csv
ValueError: could not convert string to float: 'NEAR BAY' on corr()Recent pandas versions no longer skip text columns silentlyUse corr(numeric_only=True)
Same error when calling model.fitocean_proximity was passed to the model as raw textEncode it with OneHotEncoder in a ColumnTransformer
Input X contains NaNtotal_bedrooms has missing valuesUse SimpleImputer or drop rows before fitting
No plot appears when running as a scriptOutside Jupyter, figures aren't displayed automaticallyCall plt.show() after each figure

Corrections to the original notebook

  • Run order: the execution counts jump around (24, 13–19, 51, 48), so the cells were run out of order. Use *Kernel → Restart and Run All* to check that the notebook works from top to bottom.
  • Missing download step: the notebook reads datasets/housing.csv but never explains how to get it. Use the Kaggle download commands above.
  • Reproducibility: housing_data.sample(5) returns different rows on every run. Use housing_data.sample(5, random_state=42) to get the same output each time.
  • Silent data loss: dropna() removes 207 rows without showing which column caused it. Inspect isna().sum() first. For modelling, prefer imputation inside a pipeline so you keep every row.

Frequently asked questions

Why does the California Housing dataset have missing values?

The Kaggle CSV has 207 rows with an empty total_bedrooms value. The scikit-learn version from fetch_california_housing has no missing values because it uses different, pre-computed features.

Why is median_house_value capped at 500,001?

Values above that level were capped when the data was collected, so the maximum shows up as exactly 500,001. Many tutorials remove these rows or flag them, because a model can't learn prices above the cap.

What is the difference between the Kaggle and scikit-learn California Housing datasets?

The Kaggle CSV has 10 raw columns, including totals and the text column ocean_proximity. The scikit-learn version has 8 per-household averages, no categorical column, and a target expressed in $100,000 units.

How do I use ocean_proximity in a scikit-learn model?

Encode it with OneHotEncoder inside a ColumnTransformer. This creates one binary column per category, and handle_unknown='ignore' keeps prediction from failing when a category was missing from the training split.

Which feature best predicts house value in this dataset?

median_income has the strongest correlation with median_house_value. Location features, meaning latitude, longitude and ocean proximity, add a lot of extra predictive power.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Machine Learning – scikit-learn – Lab 4

This lab uses scikit-learn's LogisticRegression to classify California housing districts as above or below the median house value. The notebook above loads housing.csv, drops missing and capped…

Read More

Machine Learning – scikit-learn – Lab 1

This lab shows how to load and explore the datasets that ship with scikit-learn: the Breast Cancer Wisconsin classification set, a housing regression set and the 20…

Read More

Machine Learning – scikit-learn – Lab 3

This lab uses scikit-learn's LinearRegression to predict median_house_value from the California housing dataset (housing.csv). It covers cleaning missing and capped values, one-hot encoding ocean_proximity, splitting the data,…

Read More

Databricks: Hello world AI Code

The example above is a minimal end-to-end machine learning workflow on Databricks: it trains a scikit-learn logistic regression model on the Iris dataset, tracks the run with…

Read More

Associate Data Scientist: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The **Associate Data Scientist** is an early-career individual contributor in the **Scientist** role family within **Data & Analytics**, responsible for turning data into measurable product, operational, and customer outcomes through analysis, experimentation, and applied machine learning. The role blends statistical thinking, coding, and business context to support decision-making and to build data science assets (models, features, metrics, and insights) that can be productionized with partner teams.

Read More

Top 10 SVM (Support Vector Machine) Tools in 2026: Features, Pros, Cons & Comparison

Introduction Support Vector Machine (SVM) tools are powerful machine learning algorithms used for classification, regression, and outlier detection. In 2026, SVM continues to be one of the…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x