BRAGA

02 Writing02-02 Notes02-02-442

Feature Matrix (Phi) Formulation

Published 16 Apr 20267 min read
Contents
  1. 01Deep Breakdown
  2. 02Flowchart
  3. 03Real-world use
  4. 04The formula, piece by piece
  5. 05The formula in words
  6. 06Critical Concepts
  7. 07Step-by-step calculation (tiny example)
  8. 08Code examples
  9. 09Self-check: mathematical verification
  10. 10Common Pitfalls and Edge Cases
  11. 11References and Standard Results
θML=(Φ⊤Φ)−1Φ⊤y\theta_{ML} = (\Phi^\top \Phi)^{-1}\Phi^\top y
(1)

Deep Breakdown

What it tells me (Situation Awareness): The Φ\Phi (Phi) notation generalises the normal equations to feature-mapped inputs. While XX typically denotes raw input features, Φ\Phi denotes the feature matrix after applying a basis function transformation ϕ(x)\phi(x): for example, polynomial features (ϕ(x)=[1,x,x2,x3]\phi(x) = [1, x, x^2, x^3]), Fourier features, or radial basis functions. Each row of Φ\Phi is ϕ(xi)T\phi(x_i)^T. This notation clarifies that linear regression in the weight space of Φ\Phi is equivalent to a nonlinear model in the original input space xx — the model is linear in the parameters θ\theta, not necessarily in xx. This is the foundation of the "kernel trick": when feature maps are high-dimensional or infinite-dimensional, we switch from weight-space to data-space representations.

Flowchart

YesNoRaw inputs X: nsamples x dfeaturesApply basisfunction phi: x_i- phi(x_i) in R^mBuild Phi: n x mfeature matrix,row i =phi(x_i)^TGram matrix:Phi^T Phi inR^(m x m)Normalequations:theta_ML =(Phi^T Phi)^-1Phi^T yPredict: y_hat =Phi theta_MLIs m large (manybasisfunctions)?Consider kerneltrick: K = PhiPhi^T (n x n)Directweight-spacesolution isefficient

Real-world use

Where it is used

Polynomial regression (adding x2,x3x^2, x^3 terms to a linear model), radial basis function networks, Gaussian Process regression weight-space view, basis expansion in spline models, and any feature engineering pipeline where raw inputs are transformed before fitting OLS.

Problem it solves

Raw features are often linearly insufficient to model the target. By mapping inputs to a richer feature space via ϕ(⋅)\phi(\cdot), the model remains linear in parameters (easy to optimise with normal equations) while being nonlinear in inputs (expressive enough to fit complex patterns).

How it solves the problem

The feature matrix Φ\Phi is an n×mn \times m matrix where mm is the number of basis functions (possibly m>dm > d). The normal equations θML=(ΦTΦ)−1ΦTy\theta_{ML} = (\Phi^T \Phi)^{-1} \Phi^T y are structurally identical to the raw-feature version — the optimisation is the same; only the input representation has changed.

Example in a business

A DS models the nonlinear relationship between ad spend (xx) and revenue (yy) using polynomial basis functions: ϕ(x)=[1,x,x2,x3]\phi(x) = [1, x, x^2, x^3]. The feature matrix Φ\Phi has 4 columns. The normal equations yield 4 coefficients θ=[θ0,θ1,θ2,θ3]\theta = [\theta_0, \theta_1, \theta_2, \theta_3]. The model captures saturation effects (diminishing returns at high spend) without requiring any iterative optimiser.

The formula, piece by piece

Symbol Meaning
ϕ:Rd→Rm\phi: \mathbb{R}^d \to \mathbb{R}^m Basis function mapping inputs to feature space
Φ∈Rn×m\Phi \in \mathbb{R}^{n \times m} Feature matrix: row i=ϕ(xi)Ti = \phi(x_i)^T
θ∈Rm\theta \in \mathbb{R}^m Weight vector in feature space
ΦTΦ∈Rm×m\Phi^T \Phi \in \mathbb{R}^{m \times m} Feature Gram matrix
(ΦTΦ)−1(\Phi^T \Phi)^{-1} Inverse of feature Gram (exists when Φ\Phi has full column rank)
ΦTy∈Rm\Phi^T y \in \mathbb{R}^m Feature-target cross-correlation
θML\theta_{ML} MLE weights in feature space

Full formula: θML=(ΦTΦ)−1ΦTy\theta_{ML} = (\Phi^T \Phi)^{-1} \Phi^T y Prediction: y^=ΦθML\hat{y} = \Phi \theta_{ML} Dual (kernel) form: y^=Φ(ΦTΦ)−1ΦTy=K(K+0⋅I)−1y\hat{y} = \Phi (\Phi^T \Phi)^{-1} \Phi^T y = K(K + 0 \cdot I)^{-1} y where K=ΦΦTK = \Phi \Phi^T

The formula in words

"Apply a nonlinear transformation ϕ(⋅)\phi(\cdot) to each input, build the resulting feature matrix Φ\Phi, then solve the normal equations in this feature space. The model is linear in θ\theta but nonlinear in the original inputs xx."

Critical Concepts

  • Φ\Phi vs. XX: XX is raw input; Φ\Phi is feature-mapped input. The formula is structurally identical but Φ\Phi can be much higher-dimensional.
  • Expressiveness vs. overfitting: more basis functions = richer model but higher risk of overfitting on small nn. Ridge regularisation of Φ\Phi is standard.
  • Kernel trick: when m≫nm \gg n (many basis functions, few samples), compute K=ΦΦT∈Rn×nK = \Phi \Phi^T \in \mathbb{R}^{n \times n} instead. This avoids ever materialising Φ\Phi explicitly — useful in Gaussian Processes and SVMs with RBF kernels.
  • sklearn's PolynomialFeatures: generates Φ\Phi from raw XX automatically, then LinearRegression applies the normal equations to Φ\Phi.
  • Regularisation is critical: polynomial basis functions produce ill-conditioned ΦTΦ\Phi^T \Phi (especially high-degree terms).

Always use ridge or cross-validation.

Step-by-step calculation (tiny example)

Fit a quadratic model y=θ0+θ1x+θ2x2y = \theta_0 + \theta_1 x + \theta_2 x^2 to 3 points: (x,y)={(1,2),(2,5),(3,10)}(x, y) = \{(1, 2), (2, 5), (3, 10)\}.

Step 1: Build Φ\Phi with basis ϕ(x)=[1,x,x2]\phi(x) = [1, x, x^2] Φ=[111124139]\Phi = \begin{bmatrix} 1 & 1 & 1 \\ 1 & 2 & 4 \\ 1 & 3 & 9 \end{bmatrix}

Step 2: Compute ΦTΦ\Phi^T \Phi ΦTΦ=[361461436143698]\Phi^T \Phi = \begin{bmatrix} 3 & 6 & 14 \\ 6 & 14 & 36 \\ 14 & 36 & 98 \end{bmatrix}

Step 3: Compute ΦTy\Phi^T y ΦTy=[2+5+10,2+10+30,2+20+90]T=[17,42,112]T\Phi^T y = [2+5+10, 2+10+30, 2+20+90]^T = [17, 42, 112]^T

Step 4: Solve θ=(ΦTΦ)−1ΦTy\theta = (\Phi^T\Phi)^{-1} \Phi^T y Using a solver: θ=[1,0,1]T\theta = [1, 0, 1]^T (intercept=1, linear=0, quadratic=1). Prediction: y^(x)=1+x2\hat{y}(x) = 1 + x^2. Check: y^(1)=2\hat{y}(1)=2, y^(2)=5\hat{y}(2)=5, y^(3)=10\hat{y}(3)=10 (exact fit).

Code examples

Beginner example (Python)

python
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
x = np.array([1, 2, 3, 4, 5], dtype=float).reshape(-1, 1)
y = np.array([1.0, 4.0, 9.0, 16.1, 25.2])

# Build Phi with degree-2 polynomial features
poly = PolynomialFeatures(degree=2, include_bias=True)
Phi = poly.fit_transform(x)
theta = np.linalg.solve(Phi.T @ Phi, Phi.T @ y)
print("Phi feature names:", poly.get_feature_names_out())
print(f"Theta: {theta.round(4)}")

# sklearn LinearRegression on Phi
lr = LinearRegression(fit_intercept=False)
lr.fit(Phi, y)
print(f"sklearn theta: {lr.coef_.round(4)}")

Beginner example (R)

r
x <- c(1, 2, 3, 4, 5)
y <- c(1.0, 4.0, 9.0, 16.1, 25.2)

# Build Phi: design matrix with polynomial features
Phi <- cbind(1, x, x^2)
theta <- solve(t(Phi) %*% Phi, t(Phi) %*% y)
cat("Theta (intercept, linear, quadratic):", round(theta, 4), "\n")

# Using poly() in lm for comparison
fit <- lm(y ~ poly(x, degree = 2, raw = TRUE))
cat("lm coefficients:", round(coef(fit), 4), "\n")

Professional example (Python)

python
import numpy as np
import pandas as pd
from sklearn.metrics import r2_score, mean_absolute_error
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge


def fit_basis_regression(
    x_train: np.ndarray,
    y_train: np.ndarray,
    x_test: np.ndarray,
    y_test: np.ndarray,
    max_degree: int = 5,
    ridge_alpha: float = 0.01,
) -> pd.DataFrame:
    # Fit polynomial basis regression for degrees 1..max_degree and compare.
    rows = []
    for degree in range(1, max_degree + 1):
        pipeline = Pipeline([
            ("poly", PolynomialFeatures(degree=degree, include_bias=True)),
            ("ridge", Ridge(alpha=ridge_alpha, fit_intercept=False)),
        ])
        pipeline.fit(x_train.reshape(-1, 1), y_train)
        y_pred = pipeline.predict(x_test.reshape(-1, 1))
        rows.append({
            "degree": degree,
            "r2": round(r2_score(y_test, y_pred), 4),
            "mae": round(mean_absolute_error(y_test, y_pred), 4),
        })
    return pd.DataFrame(rows)


if __name__ == "__main__":
    rng = np.random.default_rng(seed=42)
    n = 200
    x = rng.uniform(-3, 3, n)
    y = 0.5 * x**3 - 2 * x + rng.normal(0, 1.0, n)
    split = int(0.8 * n)
    x_tr, x_te = x[:split], x[split:]
    y_tr, y_te = y[:split], y[split:]
    print("Polynomial basis regression comparison:")
    results = fit_basis_regression(x_tr, y_tr, x_te, y_te, max_degree=6)
    print(results.to_string(index=False))

`` Domain knowledge.

Self-check: mathematical verification

  • With nn observations and pp features, the design matrix Φ\Phi has shape n×pn\times p; the linear model vector is Φw\Phi w with parameters w∈Rpw\in\mathbb{R}^p.
  • Adding a column of ones implements an intercept; polynomial bases stack powers of raw inputs column-wise.
  • The least-squares normal equations Φ⊤Φw=Φ⊤y\Phi^\top \Phi w = \Phi^\top y require Φ⊤Φ\Phi^\top\Phi invertible (full column rank Φ\Phi) for a unique minimizer.

Common Pitfalls and Edge Cases

  • Multicollinearity: near-duplicate columns make Φ⊤Φ\Phi^\top\Phi ill-conditioned; use regularization or orthogonalize features.
  • Out-of-sample extrapolation: high-degree polynomials explode beyond the training range.
  • Categorical features: must be encoded (dummy, effect, target encoding) before they appear as numeric columns of Φ\Phi.

References and Standard Results

  • Linear regression as linear algebra on the feature matrix; QR and SVD routes to stable least squares.
  • Feature engineering and basis expansion in generalized linear models and kernel methods (where Φ\Phi may be implicit).

#machine-learning#machine-learning-algorithms#linear-regression-and-maximum-likelihood-estimation-mle

Keyboard shortcuts

Single keys, ignored while typing in a field or with Cmd, Ctrl or Alt held.

0
Home
1 2 3 4
Work, Writing, Tools, About
j / k
Next / previous section on this page
n / p
Next / previous project or essay
u
Up one level
l
Deutsch
t
Light or dark theme
?
This list
Esc
Close