Questions and answers
Addenda.
These notes answer questions about the ft_linear_regression project. A teammate or an evaluator can ask these questions. Each answer is short. The text follows the ASD-STE100 writing rules.
ft_linear_regression · solo · validated 14 Oct 2026
1. Foundations
Read this section first. It gives the basic ideas. The other sections use them. The dataset has 24 rows: km and price.
What is the model? What do θ0 and θ1 mean?
The model is a straight line. The program uses it to estimate the price of a car from its mileage.
price = θ0 + θ1 × km- θ0 is the intercept. It is the estimated price, in euros, of a car with 0 km.
- θ1 is the slope. It is the change of the price, in euros, for each additional km.
The trained values are θ0 = 8499.60 € and θ1 = −0.02145 €/km. Each additional 1000 km decreases the estimated price by about 21.45 €. The slope is negative because a car with more km is cheaper.
The model has two parameters. Training finds the two values that make the line fit the 24 data points best.
What are training, error and cost?
Training finds the values of θ0 and θ1 from the data. Prediction uses these values to estimate a price. train.py does the training. predict.py does the prediction. The two programs share only the file theta.csv.
The error of one point is the estimate minus the real price. It is positive when the estimate is too high.
The cost is one number for the complete line. It is half of the mean squared error:
J(θ0, θ1) = 1/(2m) Σ (θ0 + θ1·xᵢ − yᵢ)²The cost is 0 for a perfect fit. A small cost means a good fit. Training makes the cost smaller.
What is gradient descent, in simple words?
Think of the cost as a bowl. The position in the bowl is the pair (θ0, θ1). The height is the cost. The program starts at θ0 = 0 and θ1 = 0. Each step does these actions:
- Find the direction in which the cost increases the fastest. This direction is the gradient.
- Move a small distance in the opposite direction. The learning rate sets this distance.
- Do the steps again.
This is batch gradient descent. Each step uses all m points. The program stops after a fixed number of iterations. It does not test if the cost is small enough.
The cost of a linear regression is a convex bowl. It has only one minimum. For this reason, each start value gives the same result, if the learning rate is not too large. Zero is the simplest start value.
What are the limits of the model?
- Straight line only. If the real relation is curved, the line cannot follow it.
- One feature only. The model uses km. It does not use the age, the make or the condition of the car.
- Small data. The dataset has 24 points. The km values are from 22 899 to 240 000. Estimates outside this range are not reliable.
- Impossible prices. The line gives a price of 0 € at about 396 271 km. After this value the estimate is negative. A negative price has no meaning.
- Correlation is not cause. The km value does not alone cause the price. The age of the car is related to both.
- No test data. The program measures the error on the same points that it used for training. The result shows how well the line fits the known points. It does not show how well the line predicts new cars.
How can I show that the result is correct?
Use the closed form of the simple linear regression. It gives the exact least-squares answer in one calculation:
θ1 = Σ (xᵢ − x̄)(yᵢ − ȳ) / Σ (xᵢ − x̄)² θ0 = ȳ − θ1·x̄For data.csv, the closed form gives θ0 = 8499.599649933 and θ1 = −0.0214489635917. Gradient descent with the default values gives the same numbers to more than 12 digits.
Other values to check on the training data:
- The cost at the minimum is about 222 823.
- The RMSE is about 667.57 €.
- R² is 0.733. The correlation between km and price is −0.856, and 0.856² = 0.733.
The closed form is an independent method. If it gives the same thetas as gradient descent, the training is correct.
ft_linear_regression · solo · validated 14 Oct 2026
2. Scaling, error measures and R²
About train.py (fit_line) and precision.py.
Are mu and sigma in fit_line arbitrary?
No. The program calculates them from the data. The method is standardisation. It is also named z-score scaling or feature scaling.
μ = (1/m) Σ xᵢ σ = √( (1/m) Σ (xᵢ − μ)² ) x′ᵢ = (xᵢ − μ) / σThe scaled mileages have a mean of 0 and a standard deviation of 1.
Why. The mileages are about 10⁵. The prices are 10³ to 10⁴. The gradient of θ1 contains the raw mileage as a factor. For this reason, it is much larger than the gradient of θ0. The program uses one learning rate for both. A rate that is large enough for θ0 makes θ1 diverge (overflow, nan). A rate that is small enough for θ1 makes θ0 very slow. After scaling, the two gradients have a similar size. Then a rate of 0.1 reaches the minimum in 1000 iterations. The value 0.1 is an empirical choice.
Back to raw km. Training fits y ≈ θ0′ + θ1′·(x − μ)/σ. When you expand this equation, you get:
θ1 = θ1′ / σ θ0 = θ0′ − θ1′·μ/σThe saved thetas are then the θ0 + θ1 × km of the subject. predict.py does not need μ or σ. If σ is 0, infinite or nan, the program raises a TrainingError.
This is standard feature scaling. The formulas of the subject do not change. They run on scaled data. At the end, the program converts the thetas back to raw km.
Is a standard deviation of 1 arbitrary? Why divide by m and not by m − 1?
Deviation of 1. This is the convention of the z-score. It is not a rule. Other methods also work, for example min-max scaling to [0, 1] or division by the maximum value. The feature must have a size of about 1. The z-score also centres the data (μ = 0). This makes θ0 and θ1 independent of each other, and θ0 goes to the mean price. Libraries do the same (StandardScaler).
m or m − 1. When you divide by m, the result is the population deviation σ. When you divide by m − 1 (Bessel's correction), the result is the sample deviation s = σ·√(m/(m−1)). You use s to estimate an unknown population variance. Here the difference is small:
- For m = 24, the factor is √(24/23) ≈ 1.021. This is about 2 %.
- σ is only a scale factor. It is not an estimate. A different factor changes the scaled values by a constant. The conversion θ1 = θ1′/σ cancels this constant. The final thetas in raw km stay the same, within the precision of the convergence.
- With m, the scaled values have a variance of exactly 1. This gives an optimal learning rate of exactly 1 (see section 3).
- With m = 1, σ is 0 and the program stops with a
TrainingError. With m − 1, the division itself fails first, with aZeroDivisionError.
I divide by m because I normalise. I do not estimate a variance. The choice does not change the final thetas.
Can each theta have its own learning rate, instead of scaling?
Yes. You can use one learning rate for each parameter (α₀ and α₁). This solves the scale problem. On raw km, the curvature is about 1 along θ0. It is about mean(km²), or 10¹⁰, along θ1. So α₁ ≈ 10⁻¹⁰ and α₀ ≈ 1. AdaGrad and Adam use this idea.
This does not solve the coupling problem. Raw km are not centred (the mean is about 10⁵). When θ1 changes, the complete line moves. Then θ0 must compensate. This coupling is in the off-diagonal term of the Hessian. A rate for each parameter cannot change it. The valley of the cost stays long and narrow. The descent moves from side to side.
| Scale | θ0/θ1 coupling | |
|---|---|---|
| One α for each theta | solved | not solved |
| Centre only (x − μ) | not solved | solved |
| Centre and scale (z-score) | solved | solved |
This method also does not follow the subject, which uses one learning rate. The values 10⁻¹⁰ and 1 are valid only for this dataset. The z-score needs no tuning.
A rate for each theta solves the scale. It does not solve the correlation between θ0 and θ1 that uncentred km cause. The z-score solves both.
Why does precision.py use squared errors and not absolute values?
The sum of squares (residual_sum) gives the MSE, the RMSE and R². The absolute value gives the MAE. The program prints all of them.
R² is by definition a ratio of sums of squares. Squares are also the standard for regression, for three reasons:
- Training minimises this value.
compute_costis the MSE (divided by 2). It is consistent to measure with the criterion that you optimise. - x² has a derivative at all points. |x| has no derivative at 0. The gradient of the subject comes from x².
- Large errors have more weight. An error of 1000 € counts 100 times as much as an error of 100 €. With absolute values, it counts 10 times. The result is that the metric is more sensitive to outliers.
The MAE is in euros. You can read it directly: on average, the model is wrong by X €. The RMSE is also in euros. It is always larger than or equal to the MAE. A large difference between them shows that a few errors are large.
I use squares because R² is a ratio of sums of squares, and because gradient descent minimises this criterion. The MAE uses absolute values and gives an error in euros.
What if residual_sum and total_sum used absolute values?
The result is 1 − Σ|error| / Σ|price − mean|. This is 1 minus the MAE divided by the mean absolute deviation. It is 1 for a perfect model. It is 0 for a model that predicts the mean. But it is not an R²:
- No variance is explained. The equation SS_tot = SS_explained + SS_res is the Pythagorean theorem. It is true only with squares, for a least-squares line with an intercept.
- The result can be negative. In squares, the least-squares line is always at least as good as the mean. The program did not optimise the line for absolute values. With outliers, the Σ|error| of the line can be larger than that of the mean. Then the score is negative.
- The baseline is wrong. The mean minimises the sum of squares. The median minimises the sum of absolute values.
- You cannot compare the result with scikit-learn or with the R² of another student.
This score is correct only if the model is also trained on the L1 norm (LAD regression). The gradient of the subject is the MSE gradient. If you measure an L2 model with L1, you mix two criteria.
Is R² a variance?
No. R² is a ratio of variances. It is a proportion and has no unit. When you divide the top and the bottom by m, you get:
R² = 1 − MSE / Var(price)Var(price) is the mean squared error of a model that always predicts the mean. MSE is the mean squared error of the trained model. R² shows by how much the model decreases this error.
- R² = 1: MSE = 0. The line goes through all points.
- R² = 0: the model is not better than the mean.
- R² = 0.733 (the value for
data.csv): the mileage explains 73.3 % of the variance of the prices.
For a linear regression with an intercept, measured on the training data, R² is also the square of the Pearson correlation between km and price (0.856² = 0.733). R² is not an error in euros. For an error in euros, use the RMSE or the MAE. A good R² can hide an error of several hundred euros when the prices vary a lot.
R² compares the error of my model with the error of the simplest model, which always predicts the mean. It is 1 minus the MSE divided by the variance of the prices.
Do outliers make R² very large? Can I remove them before training?
R² does not become very large. Its maximum is 1. An outlier usually decreases R², because its squared error adds to SS_res. A point that is extreme in km and in price, but close to the line, can increase R². It increases SS_tot, but not SS_res. An outlier also pulls the least-squares line. For this reason, it changes the thetas and not only the metric.
Detection methods: the IQR rule, a z-score above 3, large residuals after a first fit, and Cook's distance.
Why I do not remove them here.
- A better R² is not a more precise model. When you remove the points that are far from the line, the score increases by construction. The argument is circular.
- The reason must not depend on the line. A proven entry error (negative km, a price of 0 €) is a valid reason. A point outside the domain of the model is also a valid reason.
- The subject gives
data.csvand expects training on it. With 24 rows, each point has a large weight. Removed rows can look like manipulation of the score. - An outlier can contain information.
Two honest alternatives: keep all the data and state that R² is sensitive to outliers (the MAE is more robust, and a gap between the MAE and the RMSE shows outliers); or calculate the metrics with and without the outliers as a sensitivity study, and do not change what the program delivers.
ft_linear_regression · solo · validated 14 Oct 2026
3. Gradient descent, learning rate and the command line
About train.py: gradient_descent_step, fit_line and parse_arguments. The numbers come from runs of the program on data.csv with scaled mileages.
How does the program set the number of iterations and the learning rate? What is the "error rate"?
The program does not calculate them. DEFAULT_LEARNING_RATE = 0.1 and DEFAULT_ITERATIONS = 1000 are values that I set by hand. The user can change them with --learning-rate and --iterations. The "error rate" is the cost: half of the mean squared error, from compute_cost. The program prints it every iterations // 10 steps. A cost that decreases shows that the training works.
On scaled data, each step multiplies the distance to the optimum by |1 − α|. With α = 0.1, this factor is 0.9 for each step. The value 0.9¹⁰⁰⁰ is much smaller than the float precision. For this reason, 1000 iterations is more than enough. At the minimum the cost is about 223 000. It does not reach 0, because the points are not on a line.
The values are empirical. I look at the cost curve. It must decrease smoothly and become flat. The program also refuses to save the thetas if the final cost is not lower than the initial cost.
Why this gradient descent formula and not another method?
The subject gives the formulas. They are the partial derivatives of the cost:
∂J/∂θ0 = (1/m) Σ errorᵢ ∂J/∂θ1 = (1/m) Σ errorᵢ · xᵢThe derivative points uphill. For this reason, each step is θ ← θ − α·∂J. The 2 of the square cancels the 2 of 1/(2m). Both temporary values use the old thetas. The program applies them together. If you update θ0 first, the θ1 gradient is wrong.
| Method | Comment |
|---|---|
| Normal equation θ = (XᵀX)⁻¹Xᵀy | Exact in one step. It is good for 2 parameters, but the subject asks for gradient descent. Use it to check the result. |
| θ1 = cov(x, y) / var(x) | Closed form of the simple regression. It is the simplest check of the final thetas. |
| Stochastic or mini-batch | Useful only for very large datasets. Here m = 24. |
| Momentum, Adam | For neural networks. Too complex for a convex bowl with 2 parameters. |
The cost is convex. For this reason, plain gradient descent always reaches the one minimum, if α is not too large.
Which learning rates can I show? What is the optimal rate?
Measured values, after 100 iterations:
| --learning-rate | Result |
|---|---|
| 0.001 | The cost goes from 20.9 M to 17.1 M. Much too slow. |
| 0.01 | The cost is 3.0 M. The descent is not finished. |
| 0.1 (default) | The cost is 223 k. The descent is finished. |
| 1.0 | The descent is finished in 1 step. This is the optimum. |
| 1.9 | The descent is finished, but it moves from side to side. The speed is the same as for 0.1. |
| 2.0 | The cost does not change. The thetas jump between two points. |
| 2.1 | The descent diverges (cost 4·10¹⁵). The program stops with an error. |
For a demonstration, use 0.001 (too slow), 0.1 (good) and 2.1 (diverges).
Why 1.0 is optimal. The curvature of J is its Hessian. For standardised data, the Hessian is the identity matrix: ∂²J/∂θ0² = 1, ∂²J/∂θ1² = mean(x′²) = 1, and the cross term mean(x′) = 0. For a quadratic with curvature λ, the fastest stable rate is 1/λ = 1. Each rate of 2/λ = 2 or more diverges. The factor for each step is |1 − α|. For this reason, 0.1 and 1.9 have the same speed. This result is exact because the program divides by m when it calculates σ.
On raw km, the curvature along θ1 is about 10¹⁰. The rate must then be about 10⁻¹⁰. This is the main reason for scaling.
In practice you do not know the curvature in advance. Try powers of 10 and look at the cost. Keep the largest rate for which the cost still decreases smoothly.
1.0 is optimal for this standardised dataset. I keep 0.1. It is fast enough and it is far from the divergence limit of 2.
What other scaling methods exist? Why the z-score? How does the program convert the two thetas back?
Training runs on x′ = (x − μ)/σ. The line is then y = θ0′ + θ1′·x′. The last lines of fit_line convert the thetas back to raw km. This is exact algebra. It is not an approximation:
| Scaling | x′ | Back to raw km |
|---|---|---|
| Z-score (used) | (x − μ)/σ | θ1 = θ1′/σ, θ0 = θ0′ − θ1′·μ/σ |
| Min-max | (x − min)/(max − min) | θ1 = θ1′/(max−min), θ0 = θ0′ − θ1′·min/(max−min) |
| Mean normalisation | (x − μ)/(max − min) | same form, with max − min instead of σ |
| Division by the maximum | x / max | θ1 = θ1′/max, θ0 = θ0′ |
All these methods give a feature of size 1. I use the z-score for two reasons. It centres the data, which makes θ0 and θ1 independent of each other. It also makes the Hessian exactly the identity matrix. Then the optimal rate is exactly 1 and the two thetas reach the minimum together. For the details on the independence, see the first question of section 2.
What are the key=value pairs (kwargs) in parse_arguments? Why does the program use them?
train.py has no literal **kwargs. The key=value pairs are keyword arguments of parser.add_argument(...). They are nargs, type, default and help. In Python, a call can give the name of an argument instead of its position. argparse defines add_argument(*name_or_flags, **kwargs). It accepts many optional settings. Each call gives only the settings that it needs.
| Keyword | Function here |
|---|---|
"dataset" (no --) | Positional argument. |
nargs="?" | Optional: zero or one value. |
type=Path, float, int | Converts the text. Rejects bad input (--iterations abc gives an error). |
default= | The value that the program uses when the user gives none. |
help= | The text that python train.py -h shows. |
This is the standard way to make a command line. These commands all work: train.py, train.py other.csv and train.py --learning-rate 0.5 --iterations 200. The program checks the types automatically. It makes the help text automatically. The program checks the meaning with parser.error: the rate must be above 0 and the iterations must be 1 or more. parser.error shows the usage and stops with exit code 2.