import numpy as np
import matplotlib.pyplot as plt
import scipy
from numpy.linalg import cond, matrix_rank, norm
from scipy.linalg import solve, eigvalsh
from scipy.linalg import cholesky, solve_triangular
np.random.seed(526)Graduate Quantitative Economics and Datascience
lstsq will still return an answerThis section uses the following packages:
Note
For a symmetric matrix \(A \in {\mathbb{R}}^{N \times N}\), consider \(x^{\top} A x\) for \(x \in {\mathbb{R}}^N\).
| Classification | Definition |
|---|---|
| Positive definite | \(x^{\top} A x > 0\) for every \(x \neq \mathbf{0}\) |
| Negative definite | \(x^{\top} A x < 0\) for every \(x \neq \mathbf{0}\) |
| Positive semi-definite | \(x^{\top} A x \geq 0\) for every \(x\) |
| Negative semi-definite | \(x^{\top} A x \leq 0\) for every \(x\) |
| Indefinite | Positive for some vectors and negative for others |
A definite matrix is also semi-definite with the same sign. Semi-definite but not definite means equality holds for some nonzero vector.
x^T A x = 5
x^T A x = 0
Is \(A\) positive definite?
A. Yes, since \(x^{\top} A x = 6 > 0\)
B. No, it is negative definite
C. Need more vectors or an alternative method, and might be negative definite
D. Need more vectors or an alternative method, but cannot be negative definite
eigvalsh is specialized for symmetric matrices and returns real eigenvalueseigs = [0.17157288 5.82842712], pos-def? True
eigs = [0. 1.], pos-def? False, pos-semi-def? True
For a symmetric matrix \(A\), we obtain
How should we classify \(A\)?
A. Positive definite
B. Positive semi-definite, but not positive definite
C. Indefinite
D. Singular
[-3.00990195 -1.99009805]
neg-def? True, neg-semi-def? True
For a symmetric \(3 \times 3\) matrix \(A\)
Which is true, and what does the last line print?
A. Negative definite, True
B. Negative semi-definite and singular, False
C. Indefinite, False
D. Negative semi-definite and invertible, True
np.all(A_eigs < 0) is False.A symmetric matrix \(A\) has the reported eigenvalues
\[ \left[-10^{-17},\; 0.5,\; 1.1\right]. \]
How would you categorize \(A\)? What if I told you this was solved in float64?
Consider the unconstrained problem
\[ \min_{x \in {\mathbb{R}}^2} f(x), \qquad f(x) = \tfrac{1}{2} x_1^2 + x_2. \]
The Hessian has eigenvalues \(0\) and \(1\).
What can we conclude?
A. A unique minimum at the origin
B. Every point with \(x_1 = 0\) is a minimizer
C. No minimum: the objective is unbounded below
D. The origin is a saddle point
eigs(A) = [-6.1925824 -0.8074176]
neg-def? True




A. neg def, pos semi-def
B. neg def, pos def
C. neg semi-def, pos semi-def
D. pos def, neg semi-def
solve with assume_a="pos" does exactly thismu = np.array([1.0, 2.0])
Sigma = np.array([[1.0, 0.8],
[0.8, 2.0]])
N = 10000
X = np.random.multivariate_normal(mu, Sigma, size=N)
print(f"mean =\n{np.mean(X, axis=0)}")
print(f"cov =\n{np.cov(X, rowvar=False)}")
print(f"||mean - mu|| = {norm(np.mean(X, axis=0) - mu):.4f}")
print(f"||cov - Sigma|| = {norm(np.cov(X, rowvar=False) - Sigma):.4f}")mean =
[1.00890785 1.99134466]
cov =
[[1.01849699 0.81993007]
[0.81993007 2.01162319]]
||mean - mu|| = 0.0124
||cov - Sigma|| = 0.0357
L = cholesky(Sigma, lower=True) # Sigma = L @ L.T
Z = np.random.randn(N, 2) # one independent draw per row
Y = mu + Z @ L.T # mu broadcasts across rows
print(f"L =\n{L}")
mean_error = norm(Y.mean(axis=0) - mu)
cov_error = norm(np.cov(Y, rowvar=False) - Sigma)
print(f"Mean error: {mean_error:.4f}")
print(f"Cov error: {cov_error:.4f}")
fig, ax = plt.subplots(figsize=(5, 2.8))
ax.scatter(Y[:500, 0], Y[:500, 1], s=5)
ax.set(xlabel="$Y_1$", ylabel="$Y_2$",
title="Correlated draws")
plt.show()L =
[[1. 0. ]
[0.8 1.16619038]]
Mean error: 0.0034
Cov error: 0.0239

\[ \operatorname{Var}(Y) = L \operatorname{Var}(Z) L^{\top} = L I L^{\top} = L L^{\top} = \Sigma \]
Given a matrix \(X \in {\mathbb{R}}^{N \times M}\) and a vector \(y \in {\mathbb{R}}^N\), we want to find \(\beta \in {\mathbb{R}}^M\) such that
\[ \begin{aligned} \min_{\beta} &\lVert y - X \beta \rVert^2, \text{ that is,}\\ \min_{\beta} &\sum_{n=1}^N (y_n - X_n \cdot \beta)^2 \end{aligned} \]
Where \(X_n\) is the \(n\)th row. Take FOCs and rearrange to get
\[ (X^{\top} X) \beta = X^{\top} y \]
The \(X\) is often referred to as the “design matrix” and \(X^{\top} X\) as the Gram matrix of the features (columns)
Can form \(A = X^{\top} X\) and \(b = X^{\top} y\) and solve \(A \beta = b\).
\[ \beta = (X^{\top} X)^{-1} X^{\top} y \]
The Hessian of \(\lVert y - X \beta \rVert_2^2\) is \(2 X^{\top} X\): positive definite when \(\operatorname{rank}(X) = M\), so the normal equations give the unique minimum
Let \(X\) have full column rank, and let \(\hat{\beta}\) solve
\[ \min_{\beta} \lVert y - X\beta \rVert_2^2. \]
with FONC: \((X^{\top} X)\hat{\beta} = X^{\top} y\).
For \(e = y - X\hat{\beta}\), which statement must hold?
A. \(e = \mathbf{0}\)
B. \(y^{\top} e = 0\)
C. The residuals sum to zero, whether or not an intercept is included
D. \(X^{\top} e = \mathbf{0}\): the residual vector is orthogonal to every column of \(X\)
lstsq uses better algorithms (more numerically stable, same “order”, possibly slightly slower)statsmodels (integrates with pandas and seaborn)
lstsq, or the normal equations with assume_a="pos" so it can use a Choleskybeta = [-2.10378865 1.08556707 -2.78329393 -0.68383148 2.16714994]
lstsq = [-2.10292981 1.08372188 -2.77870538 -0.67543023 2.17412533]
normal = [-2.10292981 1.08372188 -2.77870538 -0.67543023 2.17412533]
cond(X) = 53.1, cond(X'X) = 2819.3
cond(X_col'X_col) = 1.1e+16
lstsq Solves it? Careful on Interpretation!solve(X_col.T@X_col, X_col.T@y)beta_hat_col = [0.99857143 1.99714286]
rank=1, cols=2
norm(X_col @ beta_hat - y)=0.13887301496588172
lstsq reports the number of singular values above a cutoff relative to the largestsingular values of X_col = [8.36660027e+00 8.88178420e-16]
eigenvalues of X_col'X_col = [70. 0.]
rank, before trusting a coefficient vectorbeta_hat = [0.8 0.6 1. ], rank=2
norm(X @ beta_hat - y) = 4e-15
For each shape of \(X \in {\mathbb{R}}^{N \times M}\), does \(\min_{\beta} \lVert y - X \beta \rVert_2^2\) have a unique minimizer?
| \(5 \times 3\), rank 3 | \(3 \times 5\), rank 3 | \(5 \times 3\), rank 2 | |
|---|---|---|---|
| A. | unique | continuum | continuum |
| B. | unique | unique | continuum |
| C. | unique | continuum | unique |
| D. | continuum | continuum | continuum |
lstsq is giving\[ \min_{\beta} \lVert \beta \rVert_2^2 \,\text{s.t.}\,X \beta = y \]
Which describes the solutions to \(X \beta = y\)?
A. \(\hat{\beta}\) and \(\hat{z}\)
B. \(\hat{\beta}\) only
C. \(\hat{\beta} + c\hat{z}\) for all \(c \in {\mathbb{R}}\)
eigenvalues of A: [0. 2.]

eigenvalues of A: [1.00000e-05 2.00001e+00]
Previously solved \(\min_x\left\{\tfrac{1}{2} x^{\top} A x\right\}\), which only has a unique solution if \(A\) is positive definite.
Replace with
\[ \min_x\left\{\tfrac{1}{2} x^{\top} A x + \tfrac{\lambda}{2} \lVert x \rVert_2^2\right\} \]
What are the first order conditions? Let’s look at least squares
More generally, for OLS think of the following
\[ \min_{\beta}\left\{ \lVert y - X \beta \rVert_2^2 + \lambda \lVert \beta \rVert_2^2\right\} \]
Take the FOCs and rearrange to get
\[ (X^{\top} X + \lambda I) \beta = X^{\top} y \]
Two columns of \(X\) are identical. With \(\lambda > 0\), we estimate
\[ \hat{\beta}_{\lambda} = \arg\min_{\beta} \left\{\lVert y - X\beta \rVert_2^2 + \lambda\lVert\beta\rVert_2^2\right\}. \]
Which statement is correct?
A. A unique penalized estimate, but the data still cannot distinguish the columns’ separate effects
B. The data now identify both coefficients separately
C. Ridge guarantees zero training residuals
D. Ridge guarantees better predictions on new data
The min-norm solution lstsq returns for a fat \(X\), \(\min_{\beta} \lVert \beta \rVert_2^2 \,\text{s.t.}\,X \beta = y\), is the limit of ridge regression (i.e., “ridgeless”)
\[ \lim_{\lambda \to 0} \arg\min_{\beta}\left\{ \lVert y - X \beta \rVert_2^2 + \lambda \lVert \beta \rVert_2^2\right\} \]
\(f(x) = x_1^2 + x_2^2 + 4 x_1 x_2\) has \(\nabla f(x) = \mathbf{0}\) only at \(x^* = \mathbf{0}\).
What kind of point is \(x^*\)?
A. A unique minimum
B. A unique maximum
C. A saddle point
D. A minimum with a flat direction
Draws from \({\mathcal{N}}(\mathbf{0}, \Sigma_i)\) for \(i = 1, 2\)

\(\Sigma_1 = \begin{bmatrix} 1 & 0.8 \\ 0.8 & 1 \end{bmatrix}\), \(\Sigma_2 = \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix}\)
A. Left \(\Sigma_1\), Right \(\Sigma_2\)
B. Left \(\Sigma_2\), Right \(\Sigma_1\)
C. Both \(\Sigma_1\), different seeds
D. Neither can be \(\Sigma_2\)
cholesky(Sigma_2) fails, but multivariate_normal uses an SVD and simulates the degenerate case.Which is true of \(X^{\top} X\)?
A. Positive definite, so solve(X.T @ X, X.T @ y, assume_a="pos") works
B. Positive semi-definite and singular; lstsq still returns the minimum-norm \(\beta\)
C. Indefinite
D. Negative semi-definite
What are the new eigenvalues (rounded to two decimals), and is \((X^{\top} X + 0.1 I) \beta = X^{\top} y\) uniquely solvable?
A. [0.10, 0.20, 148.00], positive definite
B. [0.00, 0.20, 148.00], still singular
C. [0.10, 0.10, 147.90], positive definite
D. Unchanged: adding \(\lambda I\) only changes the eigenvectors
The fit is exact. What can we conclude?
A. beta_hat is the unique OLS estimate: a perfect fit identifies it
B. A line of \(\beta\) fits exactly; lstsq returned the one with the smallest norm
C. \(X^{\top} X\) is positive definite, since the fit is perfect
D. Adding more regressors would improve identification
lstsq returns \(\min_{\beta} \lVert \beta \rVert_2 \,\text{s.t.}\,X \beta = y\), the ridgeless limit \(\lambda \to 0\).