AI/ML

Linear and Logistic Regression Explained with Python and scikit-learn Ep02

KaveeshaGNov 29, 2026 • 14 min read
Linear and Logistic Regression Explained with Python and scikit-learn Ep02
Part 2 of 18

Machine Learning: From 0 to Machine

“One predicts a number, one predicts a probability – and they are built from the same three ideas.”

In Ep01 we trained a house-price model in four lines: LinearRegression(), fit, predict, done. It worked, but it was a black box. In this post we open it up, build the same model by hand in NumPy, then make one small change that turns it into a classifier.

Those two models, linear regression and logistic regression, are the first two of the nine supervised algorithms in Module 2. They are worth learning properly because almost everything later in the series reuses their ideas: a model with learnable weights, a cost that measures how wrong it is, and gradient descent to make it less wrong. Neural networks in Ep06 are, quite literally, many logistic regressions stacked together.

Linear regression: the core idea

Linear regression predicts a continuous number by drawing the best straight line (or flat surface) through your data. Back to houses: if bigger houses cost more, there is some line that captures “price goes up by roughly this much per square foot”.

With one feature, the model is the line you met in school:

ŷ = w · x + b
  • x is the feature (house size), ŷ (“y-hat”) is the prediction.
  • w is the weight or slope: how much ŷ changes when x goes up by one.
  • b is the bias or intercept: the prediction when x is zero.

With several features (size, bedrooms, distance to Colombo) it becomes multivariate linear regression, one weight per feature:

ŷ = w₁x₁ + w₂x₂ + … + wₙxₙ + b

Training means finding the values of w and b that make the predictions as close as possible to the real prices. To do that, we first need a number that says how far off we are.

Measuring wrongness: the cost function

For each house, the error (or residual) is the gap between the prediction and the real price, ŷ − y. Some errors are positive, some negative, so we square them (which also punishes big misses more) and average them. That gives the mean squared error (MSE) cost function:

J(w, b) = 1/(2m) · Σ (ŷᵢ − yᵢ)²

Here m is the number of training examples. The ½ is a convenience that cancels out when we take the derivative; it doesn’t change where the minimum is. A perfect line has J = 0, and every possible pair of (w, b) has some cost. Our job is to find the pair with the smallest one.

Gradient descent: walking downhill

Picture the cost J as a landscape. For linear regression with MSE it is a smooth bowl, and the best (w, b) sits at the bottom. Gradient descent finds it the way you would walk down a hill in thick fog: feel which way the ground slopes, take a step downhill, repeat.

The slope is given by the partial derivatives of the cost:

∂J/∂w = 1/m · Σ (ŷᵢ − yᵢ) · xᵢ
∂J/∂b = 1/m · Σ (ŷᵢ − yᵢ)

and each step updates both parameters at the same time:

w := w − α · ∂J/∂w
b := b − α · ∂J/∂b

The learning rate α controls the step size, and it is the setting you will tune most often:

  • Too small, and training crawls; thousands of steps to get anywhere.
  • Too large, and each step jumps past the bottom, the cost goes up, and training diverges.
  • Just right, and the cost drops quickly at first, then settles.

A simple health check: print the cost every few hundred steps. If it ever increases, lower α.

Step 1: Build linear regression from scratch

Let’s do exactly that with the six houses from Ep01, sizes in thousands of square feet so the numbers stay small:

import numpy as np

# Same houses as Ep01: size in '000 sq ft, price in Rs. millions
x = np.array([0.8, 1.0, 1.2, 1.5, 1.8, 2.2])
y = np.array([18, 22, 26, 32, 38, 46])

w, b = 0.0, 0.0          # start with a flat line at zero
alpha = 0.1              # learning rate
m = len(x)

for step in range(5001):
    y_hat = w * x + b                    # predictions
    error = y_hat - y
    cost = (error ** 2).mean() / 2       # J(w, b) = 1/(2m) * sum of squared errors
    dw = (error * x).mean()              # dJ/dw
    db = error.mean()                    # dJ/db
    w -= alpha * dw                      # step downhill
    b -= alpha * db
    if step in (0, 10, 100, 1000, 5000):
        print(f"step {step:>4}: cost={cost:8.4f}  w={w:6.3f}  b={b:6.3f}")

Output:

step    0: cost=505.6667  w= 4.753  b= 3.033
step   10: cost=  2.9398  w=15.074  b= 9.024
step  100: cost=  0.7311  w=17.550  b= 5.740
step 1000: cost=  0.0000  w=19.996  b= 2.006
step 5000: cost=  0.0000  w=20.000  b= 2.000

What’s actually happening here

The cost starts at 505 because a flat line at zero is terrible, then collapses within ten steps and creeps to zero. The model lands on w = 20, b = 2: price = 20 × size + 2. With size in thousands of square feet, that is Rs. 20,000 per square foot plus Rs. 2 million, exactly the 0.02 and 2.0 that scikit-learn found in Ep01. Same answer, but now you know where it came from.

Try alpha = 1.0 and run it again. The cost explodes to huge numbers within a few steps: that’s the “too large” panel in the diagram, happening in your terminal.

scikit-learn’s LinearRegression doesn’t actually loop like this. For linear regression there is a direct formula, the normal equation θ = (XᵀX)⁻¹Xᵀy, which solves for the best weights in one shot. Gradient descent matters because it also works when no such formula exists, which is the case for logistic regression and every neural network.

Step 2: Multivariate regression with scikit-learn

Real prices depend on more than size. Here we generate 200 houses whose price follows a known pattern plus random noise, then check whether the model can recover that pattern from the data alone:

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, r2_score

rng = np.random.default_rng(42)
n = 200
size = rng.uniform(600, 3000, n)          # square feet
bedrooms = rng.integers(1, 6, n)
distance = rng.uniform(1, 30, n)          # km to Colombo city centre
# the "true" pattern plus noise (prices in Rs. millions)
price = 0.018 * size + 2.5 * bedrooms - 0.6 * distance + 10 + rng.normal(0, 3, n)

X = np.column_stack([size, bedrooms, distance])
X_train, X_test, y_train, y_test = train_test_split(X, price, test_size=0.2, random_state=42)

model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)

print("coefficients:", model.coef_.round(3), "intercept:", round(model.intercept_, 2))
print("MAE:", round(mean_absolute_error(y_test, pred), 2))
print("R2 :", round(r2_score(y_test, pred), 3))

Output:

coefficients: [ 0.018  2.491 -0.591] intercept: 10.1
MAE: 2.58
R2 : 0.929

What’s actually happening here

The model never saw the formula we used to make the data, yet it recovered it almost exactly: Rs. 18,000 per square foot, about Rs. 2.5 million per bedroom, and Rs. 0.6 million less for every kilometre from the city. That last coefficient is negative, which is the model telling you distance lowers the price. Reading coefficients like this is the biggest strength of linear regression: it is fully explainable.

We also held back 20% of the houses with train_test_split and scored the model only on those:

  • MAE (mean absolute error) of 2.58 means predictions are off by about Rs. 2.6 million on average, close to the noise we added (a standard deviation of 3).
  • R² (coefficient of determination) of 0.929 means the model explains about 93% of the variation in price. 1.0 would be perfect; 0 means no better than always guessing the average.

From numbers to probabilities: logistic regression

Now change the question. Instead of “how much will this house sell for?” ask “will this email be spam?”, “is this tumour malignant?”, “will this student pass?”. The answer is a class, not a number.

Why not use linear regression and call anything above 0.5 a “yes”? Because a straight line is unbounded: it happily predicts 1.7 or −0.4, which mean nothing as probabilities, and a single extreme example can tilt the whole line and move the 0.5 cut-off. We need an output that always stays between 0 and 1.

Logistic regression keeps the same linear score, z = w·x + b, and passes it through the sigmoid (logistic) function:

σ(z) = 1 / (1 + e⁻ᶻ)

The sigmoid squashes any number into the range 0 to 1: σ(−4) = 0.018, σ(0) = 0.5, σ(4) = 0.982. The output is read as P(y = 1 | x), the probability that this example belongs to the positive class. By default we predict class 1 when that probability is at least 0.5, which happens exactly when z ≥ 0. So the line w·x + b = 0 becomes the decision boundary: everything on one side is class 0, everything on the other is class 1.

Despite the name, logistic regression is a classification algorithm. The “regression” refers to the linear score inside it.

Why logistic regression needs a different cost

If you plug the sigmoid into the MSE cost, the cost landscape stops being a clean bowl; it gets flat regions and local dips where gradient descent can get stuck. So logistic regression uses log loss (binary cross-entropy) instead:

J = −1/m · Σ [ yᵢ · log(ŷᵢ) + (1 − yᵢ) · log(1 − ŷᵢ) ]

It looks heavier than it is. For a positive example (y = 1) only the first term survives, so the cost is −log(ŷ): predict 0.9 and the cost is 0.105; predict 0.1 and it is 2.303. Being confidently wrong is punished hard, which is exactly the behaviour we want. The function is convex, so gradient descent reliably finds the bottom, and the update rule ends up looking the same as linear regression’s, just with the sigmoid inside ŷ:

w := w − α · 1/m · Σ (σ(w·xᵢ + b) − yᵢ) · xᵢ

Step 3: Logistic regression with scikit-learn

scikit-learn ships a real medical dataset, so no download is needed: 569 breast tumours, 30 measurements each (radius, texture, smoothness and so on), labelled malignant (0) or benign (1).

from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

X, y = load_breast_cancer(return_X_y=True)     # 569 tumours, 30 features, 0 = malignant, 1 = benign
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)

model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)

print("accuracy:", round(accuracy_score(y_test, model.predict(X_test)), 3))
print("P(benign) for first 3 test tumours:", model.predict_proba(X_test[:3])[:, 1].round(3))
print("predicted classes:", model.predict(X_test[:3]), " actual:", y_test[:3])

Output:

accuracy: 0.982
P(benign) for first 3 test tumours: [0.    1.    0.006]
predicted classes: [0 1 0]  actual: [0 1 0]

What’s actually happening here

Three details matter more than the 98.2% accuracy:

  • StandardScaler rescales every feature to mean 0 and standard deviation 1 before training. Tumour area is in the hundreds while smoothness is around 0.1; without scaling, gradient descent zig-zags and converges slowly. Wrapping both steps in make_pipeline guarantees the scaler is fitted on training data only, so no information leaks from the test set.
  • stratify=y keeps the same malignant-to-benign ratio in both splits, so the test set is representative.
  • predict_proba gives the probability behind each decision, not just the label. For the third tumour the model gives P(benign) = 0.006, so it is very confident the tumour is malignant. In medicine you might lower the threshold from 0.5 so borderline cases get flagged for a doctor, trading a few false alarms for fewer missed cancers.

Accuracy alone can be dangerously misleading, especially when one class is rare. We will cover precision, recall, F1 and the confusion matrix properly in Ep06.

Linear vs logistic, side by side

  • Linear regression predicts a number. Model ŷ = w·x + b, cost MSE, judged with MAE, RMSE and R². Use it for prices, demand, temperatures, salaries.
  • Logistic regression predicts a probability, then a class. Model ŷ = σ(w·x + b), cost log loss, judged with accuracy, precision, recall and F1. Use it for spam detection, churn, credit default, diagnosis, pass or fail.

Both train with gradient descent, both produce weights you can read and explain, and both are fast enough to be the first baseline you try on any tabular problem. For more than two classes, LogisticRegression handles it automatically by switching to the softmax version, which outputs one probability per class.

Common first-regression mistakes

  • Using linear regression for a yes/no target. It will run without complaint and give you nonsense probabilities. If the answer is a category, use a classifier.
  • Forgetting to scale features before gradient descent, or fitting the scaler on the whole dataset instead of the training set (that’s data leakage).
  • Learning rate too high. If the cost goes up or turns into nan, divide α by 10.
  • Extrapolating. A model trained on houses from 600 to 3,000 sq ft has no idea what a 20,000 sq ft mansion costs. Linear models will still answer, confidently.
  • Reading coefficients from unscaled, correlated features. If size and number of rooms rise together, their weights can swap around between runs. Check correlations before telling anyone “bedrooms add Rs. 2.5M”.
  • Trusting the default 0.5 threshold. It is a choice, not a law. Pick it based on which mistake is more expensive.

The honest limitations

Both models assume the relationship is linear in the features. If price rises steeply only above a certain size, or a disease risk appears only when two symptoms occur together, a straight line or flat boundary will miss it unless you engineer features by hand (x², x₁·x₂) – which is exactly the gap that decision trees, SVM kernels and neural networks fill later in this module.

They are also sensitive to outliers (squared errors let one wild point drag the line) and to highly correlated features. And they will overfit if you give them hundreds of features and few examples; the fix, regularization (adding a penalty λΣw² to the cost), is built into scikit-learn’s LogisticRegression by default and gets its own section in Ep06.


Where to go next

In Ep03 we leave straight lines behind. Decision trees split data with a series of yes/no questions you can read like a flowchart, and random forests combine hundreds of them into one of the most reliable models for tabular data. We will also calculate entropy and information gain by hand, so you can see exactly why a tree picks one question over another.


This post is part of the CeyTech series Machine Learning: From 0 to Machine – deep tech, no fluff. Change the learning rate, add a fourth feature to the house data, or try lowering the tumour threshold to 0.3, and tell me what moved.




Share this story:

Comments (...)

You must be signed in to join the discussion.

Loading comments...