Machine learning fundamentals
UAT 306 Artificial Intelligence for UAS
Lesson
By the end of this module you will be able to
- Write logistic regression and train it with gradient descent from scratch
- Explain the cross-entropy loss and the role of the learning rate
- Use k-fold cross-validation to choose model complexity
- Distinguish underfitting from overfitting using training and validation error
- Fit a linear regression to drone flight data, evaluate it with RMSE and R², and state its valid range
Why this matters
Libraries such as scikit-learn and PyTorch let you train a model in a few lines, but without understanding what happens inside, you cannot fix a model that will not learn, or one that learns too much to work on new data. The textbooks by Géron and Prince explain this in detail. This module writes everything in NumPy to see the real mechanism.
Logistic regression
Logistic regression predicts a class probability with the sigmoid of a weighted sum of features. Training finds the weights that minimise cross-entropy, which heavily penalises confident wrong predictions. Gradient descent moves the weights against the gradient one step at a time; the step size is the learning rate . Too small and learning is slow; too large and it jumps over the minimum.
Example 1 Separating cracks from stains with two features
Two hypothetical features from image patches: the length-to-width ratio of the mark and its edge strength (200 simulated examples).
import numpy as np
rng = np.random.default_rng(5)
n = 200
elong = np.r_[rng.normal(2, 0.8, n // 2), rng.normal(4, 0.8, n // 2)] # length-to-width ratio
edge = np.r_[rng.normal(1, 0.6, n // 2), rng.normal(2.5, 0.6, n // 2)] # edge strength
y = np.r_[np.zeros(n // 2), np.ones(n // 2)] # 1 = crack
X = np.c_[np.ones(n), (elong - elong.mean()) / elong.std(), (edge - edge.mean()) / edge.std()]
w, lr = np.zeros(3), 0.5
for it in range(1, 501):
p = 1 / (1 + np.exp(-X @ w))
w -= lr * X.T @ (p - y) / n
if it in (1, 10, 100, 500):
loss = -np.mean(y * np.log(p + 1e-12) + (1 - y) * np.log(1 - p + 1e-12))
print(f"iteration {it:>3}: loss {loss:.3f}, accuracy {((p > 0.5) == y).mean():.3f}")
print("weights (bias, elongation, edge):", np.round(w, 2))
iteration 1: loss 0.693, accuracy 0.500
iteration 10: loss 0.241, accuracy 0.980
iteration 100: loss 0.102, accuracy 0.980
iteration 500: loss 0.083, accuracy 0.980
weights (bias, elongation, edge): [0.09 4.25 3.11]
The loss falls quickly at first and then slows. Both feature weights are positive, meaning long, narrow marks with sharp edges tend to be cracks. Standardising the features (subtracting the mean and dividing by the standard deviation) before training makes gradient descent converge faster.
A rate of 0.5 is not the only one that works. The code below trains again with five rates and computes the ceiling on the learning rate from the curvature of the loss around its minimum. Near the minimum the loss is almost a parabola, so each gradient-descent step multiplies the weight error by , where is the largest curvature (the largest eigenvalue of the Hessian matrix ). Convergence needs , that is . Above this ceiling every step overshoots the minimum by more than the last one.
def train(lr, iters=500):
w, hist = np.zeros(3), []
for _ in range(iters):
p = 1 / (1 + np.exp(-np.clip(X @ w, -30, 30)))
hist.append(-np.mean(y * np.log(p + 1e-12) + (1 - y) * np.log(1 - p + 1e-12)))
w -= lr * X.T @ (p - y) / n
return w, np.array(hist)
w5, _ = train(5) # converged weights, near the minimum
p = 1 / (1 + np.exp(-X @ w5))
lam = np.linalg.eigvalsh(X.T @ (X * (p * (1 - p))[:, None]) / n).max() # largest curvature
print(f"curvature {lam:.4f}, stable only if lr < 2/curvature = {2 / lam:.0f}")
for lr in (0.01, 0.5, 5, 100, 300):
_, h = train(lr)
print(f"lr {lr:>6}: loss at 10 {h[9]:.3f}, at 499 {h[498]:.3f}, at 500 {h[499]:.3f}, worst after 50 {h[50:].max():.3f}")
curvature 0.0236, stable only if lr < 2/curvature = 85
lr 0.01: loss at 10 0.665, at 499 0.237, at 500 0.237, worst after 50 0.560
lr 0.5: loss at 10 0.241, at 499 0.083, at 500 0.083, worst after 50 0.121
lr 5: loss at 10 0.096, at 499 0.080, at 500 0.080, worst after 50 0.082
lr 100: loss at 10 0.308, at 499 0.092, at 500 0.094, worst after 50 0.177
lr 300: loss at 10 0.364, at 499 0.129, at 500 0.119, worst after 50 4.904
The ceiling is about 85. A rate of 5 is far below it, so it converges, and even faster than 0.5. A rate of 100 is above the ceiling: the loss alternates between 0.092 and 0.094 on every iteration and never reaches 0.080. A rate of 300 is far above it, and the loss shoots up to 4.9, several times its starting value of 0.693.
Overfitting and cross-validation
A model that is too complex memorises noise in the training set, so its training error is low but its error on new data is high: overfitting. A model that is too simple is wrong on both: underfitting. k-fold cross-validation splits the data into parts, trains times leaving one part out for validation each time, and averages the results. It chooses complexity without touching the test set (scikit-learn cross-validation documentation).
Example 2 Choosing a polynomial degree with 5-fold
A hypothetical relationship between crack depth and distance from the beam edge, 30 points (simulated data).
import numpy as np
rng = np.random.default_rng(2)
x = np.linspace(0, 1, 30)
y = 5 * x + 2 * np.sin(5 * x) + rng.normal(0, 0.6, 30)
folds = np.array_split(rng.permutation(30), 5)
for degree in (1, 3, 9):
tr_err, va_err = [], []
for f in folds:
tr = np.setdiff1d(np.arange(30), f)
c = np.polyfit(x[tr], y[tr], degree)
tr_err.append(np.sqrt(np.mean((np.polyval(c, x[tr]) - y[tr]) ** 2)))
va_err.append(np.sqrt(np.mean((np.polyval(c, x[f]) - y[f]) ** 2)))
print(f"degree {degree}: train RMSE {np.mean(tr_err):.2f}, validation RMSE {np.mean(va_err):.2f}")
degree 1: train RMSE 1.09, validation RMSE 1.22
degree 3: train RMSE 0.55, validation RMSE 0.61
degree 9: train RMSE 0.46, validation RMSE 0.74
Degree 1 is wrong on both training and validation data: underfitting. Degree 9 has the lowest training error but a higher validation error: overfitting. A middle degree gives the lowest validation error. The same principle applies to neural networks: watch the validation loss, not the training loss.
Regression with drone flight data
Regression predicts a number rather than a class, such as hover current from takeoff mass. The simplest model is linear regression, , whose coefficients are chosen by least squares, that is, to make the sum of squared errors as small as possible (NIST/SEMATECH e-Handbook). A regression model is judged with error measures in the units of the answer: the root-mean-square error (RMSE) and the mean absolute error (MAE), and with the coefficient of determination , the share of the variation in the data that the model explains (scikit-learn metrics documentation). The error that matters is the error on flights the model has not seen.
Example 3 Predicting hover current and endurance from takeoff mass
Flight logs from 8 hover tests of an inspection quadcopter, each with a different payload, give the mean current in hover (assumed data). The team wants to predict the current and the hover endurance (8 Ah usable) for a new camera payload.
import numpy as np
mass = np.array([2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4]) # takeoff mass, kg
amps = np.array([18.2, 21.3, 23.9, 25.9, 30.4, 33.3, 36.1, 40.2]) # mean hover current, A
def fit(x, y):
A = np.c_[np.ones_like(x), x]
return np.linalg.lstsq(A, y, rcond=None)[0] # [intercept, slope]
b0, b1 = fit(mass, amps)
pred = b0 + b1 * mass
r2 = 1 - np.sum((amps - pred) ** 2) / np.sum((amps - amps.mean()) ** 2)
print(f"current = {b0:.1f} + {b1:.2f} x mass, R^2 = {r2:.3f}")
errs = []
for k in range(len(mass)): # leave one flight out
keep = np.arange(len(mass)) != k
c0, c1 = fit(mass[keep], amps[keep])
errs.append(amps[k] - (c0 + c1 * mass[k]))
print(f"leave-one-flight-out RMSE {np.sqrt(np.mean(np.square(errs))):.2f} A")
USABLE_AH = 8.0 # 80% of a 10 Ah battery
i_33 = b0 + b1 * 3.3
print(f"3.3 kg (inside the data): predicted {i_33:.1f} A, endurance {USABLE_AH / i_33 * 60:.1f} min")
i_40, measured = b0 + b1 * 4.0, 50.9 # a later flight at 4.0 kg (assumed)
print(f"4.0 kg (outside the data): predicted {i_40:.1f} A, endurance {USABLE_AH / i_40 * 60:.1f} min; "
f"measured {measured} A, endurance {USABLE_AH / measured * 60:.1f} min")
current = -13.2 + 15.52 x mass, R^2 = 0.994
leave-one-flight-out RMSE 0.73 A
3.3 kg (inside the data): predicted 38.0 A, endurance 12.6 min
4.0 kg (outside the data): predicted 48.8 A, endurance 9.8 min; measured 50.9 A, endurance 9.4 min
The straight line fits very well ( = 0.994), and leaving one flight out at a time gives an honest error of about 0.7 A. Inside the logged range (3.3 kg) the prediction can be used. At 4.0 kg, outside the range, the line underestimates the current by 2.1 A and overestimates endurance by 0.4 min. This is expected from rotor physics: momentum theory says ideal hover power grows with thrust to the power 1.5 (Leishman, 2006), so the true curve bends upward. Rule: report the range of the training data with every regression model, and do not plan flights on predictions outside it.
Module lab
Lab: training by hand and comparing with a library
- Run Example 1 with learning rates of 0.01, 0.5 and 100 and observe the loss
- Train the same data with scikit-learn’s
LogisticRegressionand compare accuracy and the direction of the weights (the sizes need not match, because the library has its own default settings) - Run Example 2 for degrees 1 to 12 and plot both errors
- Reduce the data to 15 points and see whether the best degree changes
- Write a summary of how to tell whether your own model underfits or overfits
- Optional extension outside class (when flight logs are available): replace the data in Example 3 with hover current from your own drone’s logs, fit the line and report the leave-one-flight-out RMSE and the mass range
Common mistakes
Watch out
- Not standardising features, so training converges slowly or not at all
- Setting the learning rate too high, so the loss oscillates or explodes
- Looking only at training error
- Using the test set to choose complexity
- Increasing complexity when data is scarce
- Using a regression model outside the range of its training data
Summary
- Logistic regression predicts probabilities with a sigmoid and is trained by minimising cross-entropy with gradient descent
- The learning rate sets the step size; standardising features speeds convergence
- Underfitting is wrong on both sets; overfitting is right on the training set but wrong on validation
- k-fold cross-validation chooses complexity without touching the test set
- Regression predicts a number; judge it with RMSE, MAE and on unseen flights, and use it only inside the range of its data
Check your understanding
- If , what probability is predicted?
- If the model predicts but the answer is 0, what is that example’s loss?
- Very low training error and high validation error indicate what problem?
- A hover-current model was fitted on flights from 2.0 to 3.4 kg. Why should it not be trusted at 4.0 kg?
- Why should the test set not be used to choose the degree?
Answers
- 0.5
- Overfitting
- 4.0 kg is outside the training range, and hover power grows faster than linearly with weight, so a straight line underestimates the current there
- The test result would look better than it is, because that data has already been used to decide
Key formulas
| Root-mean-square error | |
| Logistic regression | |
| Cross-entropy and its gradient | |
| Weight update |
Key references
- Géron, A. (2022). Hands-on machine learning with Scikit-Learn, Keras, and TensorFlow (3rd ed.). O'Reilly.
- Prince, S. J. D. (2023). Understanding deep learning. MIT Press. link
- scikit-learn developers. Cross-validation: Evaluating estimator performance (scikit-learn 1.9). link
- NIST/SEMATECH. Linear least squares regression (section 4.1.4.1). e-Handbook of statistical methods. link
- scikit-learn developers. Metrics and scoring: Quantifying the quality of predictions (scikit-learn 1.9). link
- Leishman, J. G. (2006). Principles of helicopter aerodynamics (2nd ed.). Cambridge University Press.
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
In class / field
Lecture, case discussion and in-class problem solving
Learning evidence: Quiz results and submitted exercises