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 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 rows, one-hot encodes ocean_proximity and builds a boolean above_median label. This page explains each step, gives a complete script that trains and evaluates the model, and fixes the parts that behave differently in current pandas and scikit-learn.


What the notebook does

Regression predicts a number. This lab turns house prices into a yes/no question instead: is this district's median_house_value above the median of the dataset? Because the cut point is the median, the two classes are almost exactly balanced, so a model that guesses at random gets about 50% accuracy. That gives you a clear baseline to compare against.

Notebook stepWhat it doesShape after
pd.read_csv('datasets/housing.csv')Loads 20,640 districts with 10 columns(20640, 10)
dropna()Removes rows where total_bedrooms is missing(20433, 10)
Drop median_house_value == 500001Removes 958 rows where the price was capped(19475, 10)
pd.get_dummies(..., columns=['ocean_proximity'])Replaces the text column with 5 indicator columns(19475, 14)
above_median = value > medianAdds the boolean label; the median here is 173,800(19475, 15)

Why the capped rows are removed: the dataset records any value above 500,000 as 500,001. Those rows do not hold their real prices, so the notebook drops them. For a median-split classifier they would all still land in the correct class, so dropping them is a cleaning choice and does not affect correctness. It matters more in the regression labs.

Prerequisites and setup

  • Python 3 with pandas, scikit-learn, matplotlib and Jupyter installed.
  • The housing.csv file (the California housing CSV with the ocean_proximity column, as used in the earlier labs), saved in a datasets/ folder next to the notebook.
  • Note: sklearn.datasets.fetch_california_housing() is a different version of this data. It has no ocean_proximity column, no missing values and prices in units of 100,000, so the notebook's code will not run against it unchanged.
python -m venv .venv
source .venv/bin/activate
pip install pandas scikit-learn matplotlib jupyter
mkdir -p datasets   # place housing.csv here
jupyter notebookCode language: PHP (php)

Complete training and evaluation script

The script below repeats the preprocessing from the example above, then does the modelling: it drops the raw price column, splits the data, sets the threshold from the training set only, scales the features and fits logistic regression. It runs as a single file or as notebook cells.

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# 1. Load and clean (same as the notebook)
housing = pd.read_csv("datasets/housing.csv")
housing = housing.dropna()
housing = housing[housing["median_house_value"] != 500001]
housing = pd.get_dummies(housing, columns=["ocean_proximity"], dtype=int)

# 2. Features and raw target. The price itself must NOT be a feature.
X = housing.drop(columns=["median_house_value"])
price = housing["median_house_value"]

X_train, X_test, price_train, price_test = train_test_split(
    X, price, test_size=0.2, random_state=42
)

# 3. Build labels using the training-set median only
threshold = price_train.median()
y_train = price_train > threshold
y_test = price_test > threshold

# 4. Scale + logistic regression in one pipeline
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)

# 5. Evaluate
y_pred = model.predict(X_test)
print("Threshold:", threshold)
print("Train accuracy:", model.score(X_train, y_train))
print("Test accuracy:", accuracy_score(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))Code language: PHP (php)
  • X = housing.drop(columns=["median_house_value"]) is the most important line. The label comes straight from this column, so leaving it in gives near-perfect accuracy that means nothing.
  • Setting threshold from price_train keeps information from the test set out of training. On this data the value will be close to the 173,800 shown in the notebook.
  • StandardScaler matters because total_rooms and population run into the tens of thousands while median_income sits around 0.5 to 15. Without scaling, the default lbfgs solver often stops before it converges and prints a ConvergenceWarning.
  • make_pipeline fits the scaler on training data only and applies the same transform at predict time. You do not have to repeat the scaling by hand.

Reading the results

Judge the test accuracy against the 50% baseline, not against 100%. If the train and test accuracy are close, the model is not overfitting. Logistic regression is a simple linear model, so this is the expected result. Exact scores depend on the split and on library versions.

  • Confusion matrix: rows are the true classes (False, True) and columns are the predicted classes. The off-diagonal cells are cheap districts predicted as expensive and expensive districts predicted as cheap.
  • Precision for True: of the districts predicted above the median, how many really were.
  • Recall for True: of the districts really above the median, how many the model found.
  • Because the classes are balanced, accuracy is a fair summary here. On imbalanced labels, check precision and recall first.
# Which features push a district above the median?
coefs = pd.Series(model[-1].coef_[0], index=X.columns).sort_values()
print(coefs)

# Probabilities instead of hard labels
proba = model.predict_proba(X_test)[:, 1]
print(proba[:5])Code language: PHP (php)

The features are standardised, so you can compare the coefficient sizes with each other. A large positive value for median_income means higher income raises the predicted probability of being above the median. predict_proba returns that probability. predict applies a fixed cut-off of 0.5, which you can change if one type of error costs more than the other.

Updates for current pandas and scikit-learn

The saved output in the notebook comes from older library versions. If you run the same cells today, you will see these differences:

  • Dummy columns are True/False, not 0/1. Since pandas 2.0, pd.get_dummies returns bool columns by default. scikit-learn accepts them, but if you want output that matches the notebook, pass dtype=int.
  • The label is easier to read written directly. (housing_data['median_house_value'] - median) > 0 works, but housing_data['median_house_value'] > median gives the same result.
  • The median should come from training data. The notebook computes the median over the whole dataset before any split. For a classroom exercise the effect is small, but taking it from price_train, as in the script above, is the correct habit.
  • Unscaled features trigger convergence warnings. Fitting LogisticRegression() on raw features with the default solver often warns that it failed to converge. Scaling, or raising max_iter, fixes this.
# Notebook cells, corrected
housing_data = pd.get_dummies(housing_data, columns=['ocean_proximity'], dtype=int)
housing_data['above_median'] = housing_data['median_house_value'] > medianCode language: PHP (php)

Common errors and fixes

ErrorCauseFix
FileNotFoundError: datasets/housing.csvThe notebook's working directory has no datasets folderPut the CSV in datasets/ next to the notebook, or use an absolute path
KeyError: "None of [Index(['ocean_proximity'])] are in the [columns]"The get_dummies cell ran twice, and the column was already replacedRestart the kernel and run the cells in order
ValueError: could not convert string to float: 'NEAR BAY'The ocean_proximity text column was never encodedRun pd.get_dummies before fitting
ValueError: Input X contains NaNdropna() was skipped; total_bedrooms has missing valuesDrop the rows, or impute with SimpleImputer inside the pipeline
ConvergenceWarning: lbfgs failed to convergeFeatures are on very different scalesAdd StandardScaler or increase max_iter
Accuracy close to 1.0median_house_value (or above_median) left in the featuresDrop both from X before training

Experiments to try next

  1. Replace the single split with cross_val_score(model, X, y, cv=5) to get a more stable accuracy estimate. This needs one global label, so build y with the full-data median for this experiment.
  2. Tune the regularisation strength with GridSearchCV over logisticregression__C values such as [0.01, 0.1, 1, 10].
  3. Add ratio features such as rooms_per_household = total_rooms / households and see whether accuracy improves.
  4. Use a ColumnTransformer to scale only the numeric columns and pass the one-hot columns through unchanged.
  5. Compare against DecisionTreeClassifier or RandomForestClassifier on the same split.

Note: The ISLAND category has only a handful of rows. A random split can leave it out of the test set, or nearly out. That is harmless here, but on small categories it is worth checking value_counts() before you trust per-category results.

Frequently asked questions

Why use logistic regression for house prices if prices are continuous?

The lab turns the price into a binary label (above or below the median), and logistic regression is a standard first model for binary classification. It shows how to reframe a regression dataset as a classification problem.

Why do I need to drop median_house_value before training?

The above_median label is computed from that column, so keeping it gives the model the answer. Accuracy would be close to perfect but would tell you nothing about real predictive power.

Why does scikit-learn say lbfgs failed to converge?

The features are on very different scales, so the optimiser runs out of iterations before it settles. Wrap the model in a pipeline with StandardScaler, or increase max_iter.

Why are my get_dummies columns True/False instead of 0/1?

pandas 2.0 changed the default dtype of pd.get_dummies to bool. Pass dtype=int if you want 0/1 integers; scikit-learn accepts either.

What accuracy should I expect?

Compare it against the 50% baseline you would get by guessing on balanced classes. A scaled logistic regression should do clearly better than that. The exact score depends on the split and the library versions.

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

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