Regression in Machine Learning

Linear and Polynomial Regression

1. Problem setting

We consider supervised regression with scalar input xRx \in \mathbb{R} and scalar output yRy \in \mathbb{R}. Given a dataset {(xi,yi)}i=1n\{(x_i, y_i)\}_{i=1}^n, we fit a function f^(x)\hat f(x) from a specified model class and evaluate its agreement with the observed targets.

A central point: a model can be nonlinear in the input xx while remaining linear in its parameters. Polynomial regression is the canonical example.


2. Data generation model

We generate inputs on an interval and synthesize targets from a function that is mostly linear but contains systematic curvature:

y=2.4x+5+2sin(0.9x)+0.12(x5)2+ε,wherey = 2.4x + 5 + 2\sin(0.9x) + 0.12(x - 5)^2 + \varepsilon, \quad where εN(0,σ2).\varepsilon \sim \mathcal{N}(0, \sigma^2).

Interpretation:

  • 2.4x+52.4x + 5 provides a dominant linear trend.
  • 2sin(0.9x)2\sin(0.9x) adds oscillatory structure that cannot be captured by a polynomial of very low degree without approximation error.
  • 0.12(x5)20.12(x-5)^2 adds global curvature.
  • ε\varepsilon injects irreducible noise; no deterministic regressor can interpolate the data without overfitting.

All models below are trained on the same dataset (same random seed and generation procedure) so differences in fit are attributable to the model class, not to resampling.


3. Linear regression (degree 1)

3.1 Model

The linear model is

y^=β1x+β0.\hat y = \beta_1 x + \beta_0.

3.2 Least-squares solution (closed form)

Minimizing i(yi(β1xi+β0))2\sum_i (y_i - (\beta_1 x_i + \beta_0))^2 yields the standard closed-form solution:

β1=i=1n(xixˉ)(yiyˉ)i=1n(xixˉ)2,β0=yˉβ1xˉ.\beta_1 = \frac{\sum_{i=1}^n (x_i - \bar x)(y_i - \bar y)}{\sum_{i=1}^n (x_i - \bar x)^2}, \qquad \beta_0 = \bar y - \beta_1 \bar x. Expected behavior on this dataset
  • The fit captures the global trend.
  • Residuals retain structure (systematic nonlinearity), indicating model misspecification rather than random noise.
  • Training R2R^2 is limited by the inability of a line to represent curvature.

Linear regression

python
Idle.
 
 
matplotlib output

4. Quadratic regression (degree 2)

4.1 Model

A quadratic regressor is

y^=a2x2+a1x+a0.\hat y = a_2 x^2 + a_1 x + a_0.

This is nonlinear in xx but linear in parameters (a2,a1,a0)(a_2,a_1,a_0).

4.2 Design matrix formulation

Define the design matrix

X=[x12x11x22x21xn2xn1],a=[a2a1a0],y=[y1yn].X = \begin{bmatrix} x_1^2 & x_1 & 1 \\ x_2^2 & x_2 & 1 \\ \vdots & \vdots & \vdots \\ x_n^2 & x_n & 1 \end{bmatrix}, \qquad a = \begin{bmatrix} a_2 \\ a_1 \\ a_0 \end{bmatrix}, \qquad y = \begin{bmatrix} y_1 \\ \vdots \\ y_n \end{bmatrix}.

Then y^=Xa\hat y = Xa and the least-squares problem is

minaXay22.\min_a \|Xa - y\|_2^2. Expected behavior on this dataset
  • Adds curvature and typically improves training fit relative to the linear model.
  • Still cannot represent oscillations well, but approximates the global quadratic component.
  • Training R2R^2 increases because the model class is strictly richer than degree 1.

Quadratic regression (least squares)

python
Idle.
 
 
matplotlib output

5. Cubic regression (degree 3)

5.1 Model

The cubic model is

y^=c3x3+c2x2+c1x+c0.\hat y = c_3 x^3 + c_2 x^2 + c_1 x + c_0.

5.2 Least squares (linear in parameters)

As with degree 2, we construct a polynomial design matrix with columns (x3,x2,x,1)(x^3, x^2, x, 1) and solve a linear least-squares problem.

Expected behavior on this dataset
  • Greater flexibility enables closer tracking of systematic structure.
  • Training error typically decreases again.
  • Increased flexibility also increases sensitivity to noise, especially near domain boundaries.

Cubic regression (least squares)

python
Idle.
 
 
matplotlib output

6. Degree-5 polynomial regression (degree 5)

6.1 Model

A degree-5 polynomial is

y^=d5x5+d4x4+d3x3+d2x2+d1x+d0.\hat y = d_5 x^5 + d_4 x^4 + d_3 x^3 + d_2 x^2 + d_1 x + d_0. Expected behavior on this dataset
  • Training fit typically improves further (lower residual norms, higher training R2R^2).
  • However, improved training metrics do not imply improved test performance.
  • High-degree polynomials can show undesirable oscillations and boundary artifacts, especially without regularization.

This section exists to make the bias–variance point concrete: capacity increases training fit monotonically, but generalization is not monotone.

Degree-5 polynomial regression (least squares)

python
Idle.
 
 
matplotlib output

7. Training metrics and interpretation

7.1 Coefficient of determination R2R^2

For observed targets yy and predictions y^\hat y, the (training) coefficient of determination is

R2=1i=1n(yiy^i)2i=1n(yiyˉ)2.R^2 = 1 - \frac{\sum_{i=1}^n (y_i - \hat y_i)^2}{\sum_{i=1}^n (y_i - \bar y)^2}.

Key facts:

  • R2R^2 measures the fraction of variance (around yˉ\bar y) explained by the fitted model on the data evaluated.
  • When computed on the training set, R2R^2 usually increases with model flexibility.
  • A higher training R2R^2 does not certify better out-of-sample performance.

7.2 L2 error and RMSE (training set)

Two complementary training diagnostics are:

  • 2\ell_2 residual norm: yy^2\|y-\hat y\|_2
  • RMSE: 1ni(yiy^i)2\sqrt{\frac{1}{n}\sum_i (y_i-\hat y_i)^2}

Both decrease as the model class becomes more expressive (on training data), but neither prevents overfitting.

Compare L2 error across models (same data)

python
Idle.
 
 
matplotlib output

8. k-Nearest Neighbors (k-NN): a nonparametric local model

Polynomial regression is a parametric approach: the hypothesis class is determined by a fixed set of parameters (the coefficients). In contrast, k-Nearest Neighbors (k-NN) is a nonparametric method: it stores the training set and predicts using local neighborhoods at query time.

8.1 Classification vs. regression

k-NN can be used for both tasks:

  • k-NN classification: predict a class label by majority vote among the k nearest training points.
  • k-NN regression: predict a real value by averaging the neighbors’ targets (often with distance weights).

In both cases, the inductive bias is the same: nearby points in input space should have similar outputs.

8.2 Decision boundary geometry

For classification, the k-NN decision boundary is determined by the local arrangement of labeled samples:

  • Small k yields a high-variance boundary that can track noise.
  • Large k yields a smoother, higher-bias boundary that can wash out fine structure.

A common refinement is distance-weighted voting, which reduces sensitivity to the arbitrary choice of k by giving more influence to closer neighbors. One typical weighting is

w(d)=exp(λd2),w(d) = \exp(-\lambda d^2),

where dd is Euclidean distance and λ>0\lambda > 0 controls how quickly influence decays with distance.

k-NN classification (distance-weighted) and the effect of k

python
Idle.
 
 
matplotlib output

9. Logistic Regression

Logistic regression models

p(y=1x)=σ(wx+b),p(y=1 \mid x) = \sigma(w^\top x + b),

with

σ(z)=11+ez.\sigma(z) = \frac{1}{1+e^{-z}}.

Equivalently,

logp(y=1x)p(y=0x)=wx+b.\log\frac{p(y=1 \mid x)}{p(y=0 \mid x)} = w^\top x + b.

The model is linear in the log-odds, but it produces calibrated probabilities rather than hard decisions.


10. The Logistic Loss

Let z=wx+bz=w^\top x + b. Maximizing the conditional likelihood of labels is equivalent to minimizing the negative log-likelihood, which yields the logistic loss. For data (xi,yi)(x_i,y_i):

minw,b i=1n[log(1+ezi)yizi].\min_{w,b}\ \sum_{i=1}^n \left[\log(1+e^{z_i}) - y_i z_i\right].

This objective is convex in (w,b)(w,b).


9. Demonstration: Logistic Regression Trained by Gradient Descent

The next cell trains logistic regression using NumPy gradient descent and visualizes the decision boundary.

Supervised classification with logistic regression (NumPy training)

python
Idle.
 
 
matplotlib output