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 step | What it does | Shape 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 == 500001 | Removes 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 > median | Adds 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,matplotliband Jupyter installed. - The
housing.csvfile (the California housing CSV with theocean_proximitycolumn, as used in the earlier labs), saved in adatasets/folder next to the notebook. - Note:
sklearn.datasets.fetch_california_housing()is a different version of this data. It has noocean_proximitycolumn, 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
thresholdfromprice_trainkeeps information from the test set out of training. On this data the value will be close to the 173,800 shown in the notebook. StandardScalermatters becausetotal_roomsandpopulationrun into the tens of thousands whilemedian_incomesits around 0.5 to 15. Without scaling, the defaultlbfgssolver often stops before it converges and prints aConvergenceWarning.make_pipelinefits 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, not0/1. Since pandas 2.0,pd.get_dummiesreturnsboolcolumns by default. scikit-learn accepts them, but if you want output that matches the notebook, passdtype=int. - The label is easier to read written directly.
(housing_data['median_house_value'] - median) > 0works, buthousing_data['median_house_value'] > mediangives 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 raisingmax_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
| Error | Cause | Fix |
|---|---|---|
FileNotFoundError: datasets/housing.csv | The notebook's working directory has no datasets folder | Put 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 replaced | Restart the kernel and run the cells in order |
ValueError: could not convert string to float: 'NEAR BAY' | The ocean_proximity text column was never encoded | Run pd.get_dummies before fitting |
ValueError: Input X contains NaN | dropna() was skipped; total_bedrooms has missing values | Drop the rows, or impute with SimpleImputer inside the pipeline |
ConvergenceWarning: lbfgs failed to converge | Features are on very different scales | Add StandardScaler or increase max_iter |
| Accuracy close to 1.0 | median_house_value (or above_median) left in the features | Drop both from X before training |
Experiments to try next
- 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 buildywith the full-data median for this experiment. - Tune the regularisation strength with
GridSearchCVoverlogisticregression__Cvalues such as[0.01, 0.1, 1, 10]. - Add ratio features such as
rooms_per_household = total_rooms / householdsand see whether accuracy improves. - Use a
ColumnTransformerto scale only the numeric columns and pass the one-hot columns through unchanged. - Compare against
DecisionTreeClassifierorRandomForestClassifieron 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
- More Machine Learning tutorials
- Lead Machine Learning Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
- Staff MLOps Engineer: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path
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.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals