The best line, and the line turned into a probability
Linear regression looks for the line that passes closest to your data, and logistic regression takes that same line and turns it into a probability between 0 and 1. They are the two models worth starting from for a practical reason: they are fast, you interpret them by reading the weights, and they serve as a baseline. If a complicated model does not beat a regression by much, the complication is not needed. Here you build them by hand before using the library, because understanding where the optimization breaks saves you half the problems of real projects. If you have not yet read the map of the paradigms, start from the introduction to the series.
Linear regression: weights, error and least squares
With a single variable the model is y = wx + b: w is the slope, that is by how much y grows for every unit of x, and b is the intercept, the predicted value when x is zero. With more variables you add more w·x terms. An everyday example: the price of a house as a function of square meters, where w is the marginal price of one more meter. To decide which line is "the best" you need a cost function that measures the error; the classic choice is the Mean Squared Error, the mean of the squared differences between prediction and true value. The square makes an error of 10 weigh a hundred times an error of 1, so the model tolerates many small errors but fears large ones, and this is also why it is sensitive to outliers. The Mean Absolute Error, which uses the absolute value, is less sensitive but less convenient to optimize, because it is not differentiable at zero.
For linear regression a closed-form solution exists, ordinary least squares (OLS, the method described in the scikit-learn guide): the slope is the covariance between x and y divided by the variance of x, and the intercept makes the line pass through the point of the means. The listing implements it in three lines and compares it with np.polyfit. Then it repeats the calculation changing a single price, that of the largest house, to show how much an outlier weighs. The six house ads are invented: they serve to keep the calculations verifiable by hand.
import numpy as np
# House area (m2) and price (thousands of euros): six listings invented for the example
X = np.array([50, 70, 80, 100, 120, 150], dtype=float)
y = np.array([150, 200, 220, 280, 330, 400], dtype=float)
def minimi_quadrati(X, y):
dx = X - X.mean()
w = np.sum(dx * (y - y.mean())) / np.sum(dx ** 2) # slope
b = y.mean() - w * X.mean() # intercept
return w, b
w, b = minimi_quadrati(X, y)
mse = np.mean((y - (w * X + b)) ** 2)
print(f"w = {w:.3f} b = {b:.3f} MSE = {mse:.2f}")
print(f"estimated price for 90 m2: {w * 90 + b:.0f}k euro")
print("check with np.polyfit:", np.polyfit(X, y, 1).round(3))
# Same dataset, but the last house (150 m2) is on sale at 250k instead of 400k
y_anomalo = y.copy()
y_anomalo[-1] = 250
w2, b2 = minimi_quadrati(X, y_anomalo)
print(f"with a single outlier price: w = {w2:.3f} b = {b2:.3f}")
# Output:
# w = 2.534 b = 22.570 MSE = 10.52
# estimated price for 90 m2: 251k euro
# check with np.polyfit: [ 2.534 22.57 ]
# with a single outlier price: w = 1.275 b = 117.226
The first two lines of the output give w = 2.534: each additional square meter adds about 2.5 thousand euros, and a 90 m² house is worth 251k according to the model. The MSE of 10.52 says that the prices are off on average by about 3.2k (the square root), a small error because the data are almost aligned. The check line confirms that np.polyfit finds the same coefficients. Now the last line: I changed a single price out of six, from 400k to 250k, and the slope was halved, from 2.534 to 1.275. A single anomalous observation rewrote the model, and it is the reason why before trusting a regression you look at the data, and why in the presence of outliers more robust cost functions are considered.
Gradient descent: finding the weights when there is no formula
Least squares works because linear regression is a lucky case. For almost all other models, neural networks included, the weights are not computed in closed form and are searched by successive approximations: gradient descent. Imagine being in a foggy valley wanting to go down: you cannot see the bottom, but you feel in which direction the ground drops most steeply, and you take a step that way. The "ground" is the cost function, the "step" is the learning rate, and the slope is computed with the partial derivatives of the MSE with respect to w and b. The learning rate is the parameter on which everything depends: too large and the steps jump over the bottom and the error grows, too small and the descent never arrives.
In the listing the function records the MSE at every epoch and is launched in three ways on the same six house ads. First with learning rate 0.0001, the value many guides use for this example, then with 0.00005, finally with the area standardized, that is with the mean subtracted and divided by the standard deviation, and with a learning rate of 0.1. np.errstate serves to silence the overflow warnings of the first case, the one that blows up.
import numpy as np
X = np.array([50, 70, 80, 100, 120, 150], dtype=float)
y = np.array([150, 200, 220, 280, 330, 400], dtype=float)
def gradient_descent(X, y, learning_rate, epochs):
w, b, n = 0.0, 0.0, len(X)
storia = []
for _ in range(epochs):
errore = y - (w * X + b)
storia.append(np.mean(errore ** 2)) # MSE before the update
dw = (-2 / n) * np.sum(X * errore) # derivative of the MSE with respect to w
db = (-2 / n) * np.sum(errore) # derivative of the MSE with respect to b
w -= learning_rate * dw
b -= learning_rate * db
return w, b, storia
with np.errstate(all="ignore"):
for lr in (0.0001, 0.00005):
w, b, mse = gradient_descent(X, y, lr, 1000)
print(f"lr={lr}: MSE at epoch 0, 10, 999 = {mse[0]:.4g}, {mse[10]:.4g}, {mse[999]:.4g}")
# Same regression with the standardized area: mean 0, standard deviation 1
Xs = (X - X.mean()) / X.std()
w, b, mse = gradient_descent(Xs, y, 0.1, 200)
print(f"standardized area, lr=0.1: final MSE = {mse[-1]:.2f}")
print(f"slope per m2: {w / X.std():.3f} intercept: {b - w * X.mean() / X.std():.3f}")
# Output:
# lr=0.0001: MSE at epoch 0, 10, 999 = 7.637e+04, 1.215e+05, 1.117e+25
# lr=5e-05: MSE at epoch 0, 10, 999 = 7.637e+04, 65.35, 64.19
# standardized area, lr=0.1: final MSE = 10.52
# slope per m2: 2.534 intercept: 22.570
Read the output line by line. With 0.0001 the MSE rises, from about 76,370 to 121,500 after ten epochs and to 10^25 at the end: each step overshoots the bottom of the valley and lands higher on the other side, and this is divergence. With 0.00005 the method converges, but at epoch 999 the MSE is still 64.19 against the minimum of 10.52 computed earlier: the slope settles quickly and the intercept barely moves, because the two derivatives have different orders of magnitude (x reaches 150, the constant term is always 1). In the last line standardization solves both problems: with a learning rate two thousand times larger the MSE reaches 10.52, identical to least squares, and converting the coefficients back to the original units you find 2.534 and 22.570. It is the concrete reason why variables are scaled even when the model does not use distances.
Logistic regression: from the line to the probability
Despite the name, logistic regression classifies. It computes the same linear combination z = w·x + b and passes it through the sigmoid function, σ(z) = 1 / (1 + e^-z), which squeezes any number into an interval between 0 and 1: a very negative z gives a probability close to 0, z = 0 gives exactly 0.5, a very positive z gives a probability close to 1. A threshold is then chosen, usually 0.5, to decide the class. The cost function is no longer the MSE but the log loss (binary cross-entropy), which strongly punishes confident and wrong predictions: saying "99% probability" on a case that turns out to be of the other class costs far more than saying "60%".
The listing uses the Wisconsin breast cancer dataset included in scikit-learn: 569 samples, 30 measurements, two classes. Beware of a detail that the dataset documentation reports and that is easily lost: class 0 is malignant (212 cases) and class 1 is benign (357 cases). When precision_score and recall_score compute the metrics, they do so for class 1 by default, so here "positive" means "benign": in a clinical context it is the less critical class to miss. I put the scaler in a Pipeline for the reasons seen above; the sigmoid line checks by hand that the model's probabilities are exactly σ(z).
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, log_loss, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
print("class 0:", np.sum(y == 0), "class 1:", np.sum(y == 1))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
modello = make_pipeline(StandardScaler(), LogisticRegression())
modello.fit(X_train, y_train)
pred = modello.predict(X_test)
proba = modello.predict_proba(X_test)[:, 1]
print(f"accuracy {accuracy_score(y_test, pred):.3f} precision {precision_score(y_test, pred):.3f} recall {recall_score(y_test, pred):.3f}")
print(f"log loss {log_loss(y_test, proba):.3f}")
def sigmoide(z):
return 1 / (1 + np.exp(-z))
z = modello.decision_function(X_test) # the linear score w*x + b
print("sigmoid(z) equal to predict_proba:", np.allclose(sigmoide(z), proba))
print("first 5 probabilities of class 1:", proba[:5].round(3), "true classes:", y_test[:5])
# Output:
# class 0: 212 class 1: 357
# accuracy 0.974 precision 0.972 recall 0.986
# log loss 0.060
# sigmoid(z) equal to predict_proba: True
# first 5 probabilities of class 1: [0.886 0. 0.003 0.999 1. ] true classes: [1 0 0 1 1]
The accuracy of 0.974 is the fraction of samples classified correctly, but it is the comparison between precision (0.972) and recall (0.986) that says something more: out of 100 samples labeled by the model as benign, about 97 really are, and out of 100 really benign samples it finds about 99. The log loss of 0.060 is the value of the cost function on the test set: the lower it is, the more the probabilities are both right and confident. The np.allclose check shows that predict_proba is the sigmoid of the decision_function score, nothing more. The first five probabilities, set next to the true classes, show the typical behavior: four cases are almost certain (0.000, 0.003, 0.999, 1.000), one is more uncertain (0.886) and, fortunately, that one is right too. On the same dataset without StandardScaler the optimizer, with the default settings, ends with a convergence warning, and raising max_iter to 10000 the test accuracy drops to 0.956: scaling is not just a computational convenience, it changes the result.
The decision boundary, in numbers
The decision boundary is the locus of points where the probability is 0.5, that is z = 0. With two variables it is a line, with three a plane, with thirty a hyperplane: you can draw it only in the first case, but you can always compute it. The listing retrains the model with just two columns, mean radius and mean texture, and solves w₁·r + w₂·t + b = 0 for the radius at a fixed texture, converting the result from standardized units to the original ones. The last line proves that the point found really has probability 0.5.
import numpy as np
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
dati = load_breast_cancer()
colonne = [list(dati.feature_names).index(n) for n in ("mean radius", "mean texture")]
X, y = dati.data[:, colonne], dati.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
modello = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
scaler, logit = modello[0], modello[1]
(w1, w2), b = logit.coef_[0], logit.intercept_[0]
print(f"accuracy with 2 variables: {modello.score(X_test, y_test):.3f}")
print(f"weights (on standardized data): {w1:.2f} {w2:.2f} bias {b:.2f}")
# On the boundary z = w1*r' + w2*t' + b = 0, with r' and t' standardized. I solve for the radius, at a fixed texture.
texture = 25.0
t_std = (texture - scaler.mean_[1]) / scaler.scale_[1]
r_std = -(w2 * t_std + b) / w1
raggio = r_std * scaler.scale_[0] + scaler.mean_[0]
print(f"at texture {texture} the boundary sits at radius {raggio:.2f}")
print("probability of class 1 at that point:", modello.predict_proba([[raggio, texture]])[0, 1].round(3))
# Output:
# accuracy with 2 variables: 0.904
# weights (on standardized data): -3.11 -0.89 bias 0.72
# at texture 25.0 the boundary sits at radius 13.55
# probability of class 1 at that point: 0.5
With just two variables the accuracy drops to 0.904, against 0.974 with all thirty: the other columns carry information. The weight of mean radius is -3.11 and that of mean texture is -0.89, both negative: increasing the radius or the texture lowers the probability of "benign", and the radius counts about three and a half times more, and the comparison between the two weights makes sense only because the variables were standardized. At texture 25 the boundary passes at radius 13.55: below that value the model says "benign", above it "malignant". The point found has probability 0.5, as expected from the definition.
Regression in practice: R², RMSE and the comparison with the baseline
For regression the main metrics are the MSE, its root (RMSE), which comes back in the units of the target, the MAE and the R² coefficient. R² compares your model with the most naive one, which always predicts the mean: it is 1 if you predict perfectly, 0 if you do as well as the mean, and it can become negative if you do worse. As in the previous article it is best to always put the baseline alongside. The listing uses the scikit-learn diabetes dataset (442 patients, 10 variables; the target is a numerical measure of disease progression one year after the initial visit) because it is included in the library and requires no download.
from sklearn.datasets import load_diabetes
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
dati = load_diabetes()
X_train, X_test, y_train, y_test = train_test_split(dati.data, dati.target, test_size=0.2, random_state=42)
for nome, modello in (("target mean", DummyRegressor()), ("linear regression", LinearRegression())):
modello.fit(X_train, y_train)
pred = modello.predict(X_test)
mse = mean_squared_error(y_test, pred)
print(f"{nome:20s} MSE {mse:8.1f} RMSE {mse ** 0.5:5.1f} MAE {mean_absolute_error(y_test, pred):5.1f} R2 {r2_score(y_test, pred):6.3f}")
# Output:
# target mean MSE 5361.5 RMSE 73.2 MAE 64.0 R2 -0.012
# linear regression MSE 2900.2 RMSE 53.9 MAE 42.8 R2 0.453
The first row is the baseline: always predicting the mean gives R² = -0.012, practically zero as expected (slightly negative because the mean is computed on the train set, not on the test set). Linear regression brings the MSE from 5361 to 2900 and the typical error (RMSE) from 73 to 54, with R² = 0.453: it explains less than half of the variability. It is an honest and modest result, and it must be read for what it is: the data contain more noise than a line can capture. The comparison between RMSE (53.9) and MAE (42.8) also signals some large errors: if all errors were equal the two measures would coincide. The classification metrics, precision, recall, F1, ROC-AUC, have their own article: Evaluation Metrics.
When linear and logistic are not enough
Both models assume that the signal is a sum of independent contributions: if the price of a house depends on the area in combination with the floor space, you need to build by hand a variable that combines them, as you will see in Feature Engineering, or move to models that combine them by themselves such as decision trees. With many correlated variables or few examples the weights become unstable, and a penalty is added to the cost function: it is the regularization of article 8.
What you can do now
You can compute a least-squares line by hand and understand how much a single outlier moves it. You can recognize when gradient descent diverges (the error rises) and when it converges poorly (the error drops only slightly), and you know that standardizing the variables is often the fix. You can read the weights of a logistic regression, compute its decision boundary and tell which class is called "positive". Next step: decision trees and random forest, where the boundary is no longer a line.
The gradient descent of this article returns, applied to trees, in the gradient boosting written by hand.
Frequently asked questions
Is logistic regression a regression algorithm?
No: despite the name it is a classifier. It computes a linear combination of the variables and turns it into a probability with the sigmoid; the class is decided by comparing the probability with a threshold, usually 0.5.
Why can gradient descent diverge?
Because with a learning rate that is too large each step overshoots the minimum and lands higher on the other side, so the error grows at every epoch. It is fixed by reducing the learning rate or by standardizing the variables.
What does a negative R² mean?
That the model predicts worse than the plain mean of the target. It can happen on the test set if the model fits the train set too closely or if the variables carry no information.
How I checked the listings: I ran each one on its own on 2026-11-21 with Python 3.14.4, NumPy 2.3.5 and scikit-learn 1.8.0, and the decimal figures quoted in the text match the ones produced. With other library versions the last digits may change.
Sources
- scikit-learn User Guide: Linear Models - ordinary least squares, logistic regression and regularization, consulted on 2026-11-12
- scikit-learn API: LogisticRegression - parameters, max_iter and the lbfgs solver, consulted on 2026-11-12
- scikit-learn User Guide: Metrics and scoring - definitions of MSE, MAE, R2, log loss and of the default positive class, consulted on 2026-11-12
- scikit-learn: Toy datasets - the composition of diabetes (one-year target) and Wisconsin breast cancer (212 malignant, 357 benign), consulted on 2026-11-12
- Hastie, Tibshirani and Friedman, The Elements of Statistical Learning - theoretical treatment of linear and logistic regression, consulted on 2026-11-12
Commenti
Caricamento commenti...
Sign in to comment