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 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, training the model and reading its coefficients. Below the notebook you will find a version that runs on current scikit-learn, because the original normalize=True argument has been removed from the library.


What the notebook does, step by step

The notebook above is a standard supervised regression workflow. Each cell moves the data one step closer to something a linear model can learn from. The table maps the main cells to their purpose and the results shown in the notebook.

CellPurposeResult in the notebook
pd.read_csv('datasets/housing.csv')Load the raw data10 columns, one of them text (ocean_proximity)
dropna()Remove rows with missing values (only total_bedrooms has gaps)Shape becomes (20433, 10)
Drop rows where median_house_value == 500001Remove 958 rows whose target was capped at the top valueShape becomes (19475, 10)
pd.get_dummies(..., columns=['ocean_proximity'])Turn the text category into one 0/1 column per valueShape becomes (19475, 14)
train_test_split(X, Y, test_size=0.2)Hold back 20% of rows for testing15580 train rows, 3895 test rows
LinearRegression(...).fit()Fit the modelTraining R² of about 0.61
pd.Series(linear_model.coef_, predictors)Show how much each feature moves the predictionmedian_income is the strongest positive numeric feature

Note: The capped rows matter. The dataset clips house values at 500,001, so those rows do not show the real price. Leaving them in pulls a straight-line fit toward an artificial ceiling.

Prerequisites and setup

You need Python 3, Jupyter, pandas, matplotlib and scikit-learn. The notebook expects the California housing CSV (the version with the ocean_proximity column) in a datasets folder next to the notebook.

python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install pandas matplotlib scikit-learn jupyter

# expected layout
# lab3/
#   03-LinearRegressionForPricePrediction.ipynb
#   datasets/
#     housing.csv

jupyter notebookCode language: PHP (php)

Check which scikit-learn version you have before you run the training cell, because that cell decides whether the original code works:

python -c "import sklearn; print(sklearn.__version__)"Code language: JavaScript (javascript)

Fixing the LinearRegression call for current scikit-learn

The training cell calls LinearRegression(normalize=True, fit_intercept=False). scikit-learn deprecated the normalize parameter in version 1.0 and removed it in 1.2. On any current install this cell fails with:

TypeError: LinearRegression.__init__() got an unexpected keyword argument 'normalize'Code language: JavaScript (javascript)

Removing the argument does not change the results. Older versions documented that normalize was ignored when fit_intercept=False, so it never did anything in this notebook. Scaling also has no effect on the predictions or R² of ordinary least squares. It only changes the size of the coefficients. If you want scaled features, for example to compare coefficients, use StandardScaler in a pipeline:

from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# Minimal fix: same behaviour as the original notebook
linear_model = LinearRegression(fit_intercept=False).fit(x_train, y_train)

# Preferred: explicit scaling plus a normal intercept
linear_model = make_pipeline(StandardScaler(), LinearRegression()).fit(x_train, y_train)Code language: PHP (php)

Why fit_intercept=False still worked: get_dummies creates one column for every ocean_proximity value, and in every row exactly one of them is 1. Together those five columns act as an intercept, so the model learns one baseline per region. That is why the dummy coefficients are all around -2,000,000: each one is that region's intercept. A clearer approach is pd.get_dummies(..., drop_first=True) with the default fit_intercept=True. It drops one category as the reference level and avoids perfectly collinear columns.

Complete working version of the lab

This script runs end to end on current pandas and scikit-learn. It follows the same steps as the notebook, adds a fixed random_state so the results can be repeated, and evaluates the model on the test set with several metrics.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error

# 1. Load and clean
housing = pd.read_csv('datasets/housing.csv')
housing = housing.dropna()
housing = housing[housing['median_house_value'] != 500001]

# 2. One-hot encode; drop_first keeps one category as the baseline
housing = pd.get_dummies(housing, columns=['ocean_proximity'],
                         drop_first=True, dtype=int)

# 3. Features and target
X = housing.drop('median_house_value', axis=1)
y = housing['median_house_value']

x_train, x_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42)

# 4. Train
model = LinearRegression().fit(x_train, y_train)

# 5. Evaluate on data the model has not seen
y_pred = model.predict(x_test)
print('Train R2 :', round(model.score(x_train, y_train), 4))
print('Test  R2 :', round(r2_score(y_test, y_pred), 4))
print('MAE      :', round(mean_absolute_error(y_test, y_pred)))
print('RMSE     :', round(np.sqrt(mean_squared_error(y_test, y_pred))))

# 6. Coefficients
print(pd.Series(model.coef_, X.columns).sort_values())

# 7. Actual vs predicted
plt.figure(figsize=(6, 6))
plt.scatter(y_test, y_pred, s=5, alpha=0.4)
plt.plot([y.min(), y.max()], [y.min(), y.max()], 'r--')
plt.xlabel('Actual median_house_value')
plt.ylabel('Predicted median_house_value')
plt.title('Linear regression: actual vs predicted')
plt.show()Code language: PHP (php)

Expect the train and test R² to be close to each other and near the notebook's 0.61. The exact numbers depend on the split. When train and test scores are similar, the model is not overfitting. Its limit is bias: a straight line cannot capture all of the relationship.

Note: In pandas 2.x, get_dummies returns True/False columns by default instead of the 1/0 shown in the notebook output. scikit-learn accepts either. Passing dtype=int makes the output match the notebook.

Reading the coefficients and scores

  • R² (score) is the share of the variance in house value that the model explains. 1.0 is perfect. 0 is no better than always predicting the mean.
  • MAE is the average absolute error in dollars, which is easy to explain to non-specialists. RMSE penalises large misses more heavily.
  • Coefficients give the change in predicted value for a one-unit increase in a feature when all other features stay the same. In the notebook, each extra unit of median_income (measured in tens of thousands of dollars) adds roughly 38,000 to the prediction.
  • Coefficients on raw features cannot be compared with each other, because the features use different units. total_rooms and latitude are on very different scales. Standardise the features first if you want to rank them by importance.
  • total_rooms, total_bedrooms, households and population are strongly correlated. Their individual coefficients can flip sign or look odd even when the predictions are fine. That is multicollinearity, not a bug.

Common errors and fixes

ErrorCauseFix
TypeError: ... unexpected keyword argument 'normalize'scikit-learn 1.2 or laterRemove normalize=True. Use StandardScaler if you need scaling
FileNotFoundError: datasets/housing.csvThe notebook was started from a different directory, or the CSV is missingPut the file in datasets/ next to the notebook, or use an absolute path
ValueError: could not convert string to float: 'NEAR BAY'ocean_proximity was not encoded before fittingRun the get_dummies cell before you split the data
ValueError: Input X contains NaNdropna() was skippedDrop or impute missing total_bedrooms values, for example with SimpleImputer
Different scores on every runtrain_test_split has no random_statePass random_state=42 or any other fixed integer

Next steps to improve the model

  • Add ratio features such as rooms_per_household, bedrooms_per_room and population_per_household. They usually carry more signal than the raw totals.
  • Predict np.log1p(median_house_value) and convert predictions back with np.expm1. Prices are right-skewed, and a log target often fits a linear model better.
  • Use cross_val_score(model, X, y, cv=5, scoring='r2') instead of a single split to get a more stable estimate.
  • Try Ridge or Lasso to handle the correlated count features, then compare with a tree-based model such as RandomForestRegressor.
  • Wrap the encoding and the model in a Pipeline with ColumnTransformer. New data then goes through exactly the same preprocessing at prediction time.

Frequently asked questions

Why does LinearRegression(normalize=True) raise an error?

scikit-learn deprecated normalize in 1.0 and removed it in 1.2. Delete the argument, and put a StandardScaler before the model in a pipeline if you want scaled features.

Why are the ocean_proximity coefficients around -2,000,000?

The model was fitted with fit_intercept=False and a dummy column for every category, so each dummy coefficient acts as that region's intercept. Use drop_first=True with a normal intercept to get coefficients relative to a baseline category.

Is a training R² of 0.61 good for this dataset?

It is a typical result for plain linear regression on California housing data. Feature engineering, a log-transformed target or non-linear models such as random forests usually do better.

Why remove rows where median_house_value equals 500001?

The dataset caps values at 500,001, so those rows do not show the true price. Removing them stops the model from learning an artificial ceiling.

Do I need to scale features for linear regression?

For ordinary least squares, scaling does not change predictions or R². It only matters if you want to compare coefficients directly or you switch to regularised models such as Ridge and Lasso.

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 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…

Read More

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

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