Numerical Examples for Linear and Logistic Regression¶
Course: MCE5919-Gaussian Process for Machine Learning and Signal Processing
Topic: Linear and Logistic Regression
Instructor: Wenqiang PU
Date: Jan. 2026
Learning Objectives¶
- Understand least-squares (LS) estimation geometrically
- Visualize the effect of noise and Fisher information
- Verify the Cramér–Rao lower bound (CRLB) via simulation
- Understand why logistic regression is needed for classification
Environment: Use your Anaconda environment
Ensure numpy, matplotlib, sklearn are installed.
Optional install commands:
conda install numpy matplotlib
or
pip install numpy matplotlib
Imports and Global Setup¶
%matplotlib widget
# %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Global plotting style for consistency
plt.style.use('seaborn-v0_8-whitegrid')
# plt.rcParams['figure.figsize'] = (7, 5)
plt.rcParams.update({
'axes.grid': True,
'grid.alpha': 0.4,
'grid.linestyle': '--',
'legend.frameon': True,
'legend.loc': 'best'
})
np.random.seed(0)
Simple Linear Regression (1D)¶
Math¶
Assume observations satisfy $y_i = \beta_0 + \beta_1 x_i + \varepsilon_i$, with $\varepsilon_i \sim \mathcal{N}(0,\sigma^2)$ i.i.d. Define the design matrix $X = [\mathbf{1},\,\mathbf{x}] \in \mathbb{R}^{n\times 2}$ and parameter vector $\beta = [\beta_0,\beta_1]^\top$. Least squares minimizes $$\min_{\beta} \; \lVert y - X\beta \rVert_2^2.$$ The normal equations are $$X^\top X\,\hat\beta = X^\top y,$$ giving the closed-form solution $$\hat\beta = (X^\top X)^{-1} X^\top y.$$ Predictions are $\hat y = X\hat\beta$. Under Gaussian noise and full-rank $X$, LS is unbiased and $$\operatorname{Cov}(\hat\beta) = \sigma^2 (X^\top X)^{-1}.$$
Code¶
- Build a 1D grid
xand assemble the design matrixXfrom a constant column andx. - Set true parameters $\beta_{\text{true}}=[1,2]$ and noise $\sigma=0.5$; generate $y = X\beta_{\text{true}} + \sigma\,\varepsilon$.
- Compute $\hat\beta = (X^\top X)^{-1}X^\top y$ using the normal equations.
- Plot the samples, the true line, and the LS fitted line for comparison.
n = 20
x = np.linspace(0, 5, n)
X = np.column_stack((np.ones(n), x))
beta_true = np.array([1.0, 2.0])
sigma = 0.5
y = X @ beta_true + sigma * np.random.randn(n)
beta_hat = np.linalg.inv(X.T @ X) @ X.T @ y
plt.close(1)
plt.figure(1)
plt.scatter(x, y, s=55, alpha=0.85, edgecolors='k', linewidths=0.5, label="Observations")
plt.plot(x, X @ beta_true, "k--", linewidth=2, label="True model")
plt.plot(x, X @ beta_hat, color='crimson', linewidth=2, label="LS estimate")
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.title("1D Linear Regression (Least Squares)")
plt.grid(True, ls='--', alpha=0.5)
plt.tight_layout()
plt.show()
Multiple Linear Regression¶
Math¶
Model: $y_i = \beta_0 + \beta_1 x_{1,i} + \beta_2 x_{2,i} + \varepsilon_i$. Let $X = [\mathbf{1},\,\mathbf{x}_1,\,\mathbf{x}_2] \in \mathbb{R}^{n\times 3}$ and $\beta=[\beta_0,\beta_1,\beta_2]^\top$. OLS objective: $\min_\beta \lVert y - X\beta \rVert_2^2$, solution: $$\hat\beta = (X^\top X)^{-1} X^\top y.$$ Geometry: the fit is a plane in 3D with $$\hat y = \hat\beta_0 + \hat\beta_1 x_1 + \hat\beta_2 x_2.$$
Code¶
- Randomly generate 2D inputs
x1, x2and build a three-column design matrixX=[1, x1, x2]. - Choose true parameters $\beta_{\text{true}}=[1,2,-1]$ and add Gaussian noise to produce $y$.
- Estimate $\hat\beta=(X^\top X)^{-1}X^\top y$ via the closed form.
- Plot the 3D scatter and the fitted plane (
ax.plot_surface(...)) to visualize the plane fit.
n = 50
x1 = np.random.uniform(-2, 2, n)
x2 = np.random.uniform(-2, 2, n)
X = np.column_stack((np.ones(n), x1, x2))
beta_true = np.array([1, 2, -1])
y = X @ beta_true + 0.3 * np.random.randn(n)
beta_hat = np.linalg.inv(X.T @ X) @ X.T @ y
plt.close(2)
fig = plt.figure(2, figsize=(8,6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x1, x2, y, color='royalblue', s=35, alpha=0.85, edgecolors='k', linewidths=0.4, label="Data")
x1g, x2g = np.meshgrid(
np.linspace(-2,2,30),
np.linspace(-2,2,30)
)
yg = beta_hat[0] + beta_hat[1]*x1g + beta_hat[2]*x2g
surf = ax.plot_surface(x1g, x2g, yg, alpha=0.5, cmap='viridis', edgecolor='none')
ax.set_xlabel('$x_1$')
ax.set_ylabel('$x_2$')
ax.set_zlabel('$y$')
ax.set_title("Multiple Linear Regression (Plane Fit)")
ax.view_init(elev=25, azim=-60)
ax.set_box_aspect((1, 1, 0.6))
ax.grid(True)
plt.tight_layout()
plt.show()
CRLB Simulation (Gaussian Mean)¶
Math¶
Let $y_i \stackrel{\text{i.i.d.}}\sim \mathcal{N}(\mu,\sigma^2)$. For parameter $\mu$, the Fisher information is $$I(\mu) = \sum_{i=1}^n \mathbb{E}\Big[\Big(\tfrac{\partial}{\partial\mu} \log p(y_i\mid\mu)\Big)^2\Big] = \frac{n}{\sigma^2}.$$ The Cramér–Rao lower bound (CRLB) gives $$\operatorname{Var}(\hat\mu) \ge \frac{1}{I(\mu)} = \frac{\sigma^2}{n}.$$ The sample mean $\bar y$ attains this bound for Gaussian data, hence is efficient. The Monte Carlo below verifies $\operatorname{Var}(\bar y) \approx \sigma^2/n$ under different noise variances.
Code¶
- Fix
mu_trueand sample sizen; iterate over noise standard deviationssigma. - For each
sigma, runMCtrials: draw i.i.d. Gaussian samples and compute the sample mean. - Compute the empirical variance
var_empiricalof the means and compare with the theoretical valuesigma**2 / n(CRLB). - Plot empirical variance against the bound to verify the mean achieves CRLB.
mu_true = 2.0
n = 50
MC = 1000
sigmas = [0.2, 0.5, 1.0]
plt.close(3)
plt.figure(3)
for sigma in sigmas:
estimates = []
for _ in range(MC):
y = mu_true + sigma * np.random.randn(n)
estimates.append(np.mean(y))
var_empirical = np.var(estimates)
crlb = sigma**2 / n
plt.scatter(crlb, var_empirical, s=60, alpha=0.85, edgecolors='k', linewidths=0.4, label=f"σ = {sigma}")
plt.plot([0, 0.05], [0, 0.05], 'k--', lw=1, label='CRLB=Emp. Var.')
plt.xlabel("CRLB")
plt.ylabel("Empirical Variance")
plt.legend()
plt.title("CRLB Verification via Monte Carlo")
plt.grid(True, ls='--', alpha=0.5)
plt.tight_layout()
plt.show()
Effect on Noise on LS Estimation¶
Math¶
In the linear Gaussian model, the covariance of LS is $$\operatorname{Cov}(\hat\beta) = \sigma^2 (X^\top X)^{-1}.$$ With fixed design $X$, larger $\sigma^2$ yields larger parameter variance, so fitted lines fluctuate more across trials. This experiment keeps the same $X$ and varies $\sigma$ to show how the fitted curve changes with noise.
Code¶
- Keep the same design matrix
Xand true parametersbeta_true. - Loop over
sigmas, generate newy_noisyand estimatebeta_hat. - Plot each fitted curve versus the true model; observe the increased variability under higher noise.
# Re-run a simple 1D setup and vary noise
import numpy as np
import matplotlib.pyplot as plt
n = 20
x = np.linspace(0, 5, n)
X = np.column_stack((np.ones(n), x))
beta_true = np.array([1.0, 2.0])
sigmas = [0.1, 0.5, 1.0]
plt.close(4)
plt.figure(4)
for s in sigmas:
y_noisy = X @ beta_true + s * np.random.randn(n)
beta_hat = np.linalg.inv(X.T @ X) @ X.T @ y_noisy
plt.plot(x, X @ beta_hat, linewidth=2, label=f"σ = {s}")
plt.plot(x, X @ beta_true, "k--", linewidth=2, label="True model")
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.title("Effect of Noise Variance on LS Estimates")
plt.grid(True, ls='--', alpha=0.5)
plt.tight_layout()
plt.show()
Logistic Regression for Classification¶
Linear Regression Is Not Suitable for Classification¶
For binary labels $y\in\{0,1\}$, the conditional expectation $\mathbb{E}[y\mid x]=p(x)$ represents a probability. Linear regression output $\hat y = X\hat\beta$ can be any real number, is not constrained to $[0,1]$, and is not probabilistic. Fitting binary data with squared loss yields outputs that are hard to interpret as probabilities, making decisions unstable. We therefore use a probabilistic model with a logit link and Bernoulli likelihood—logistic regression.
Math¶
For each sample $(x_i, y_i)$, let $z_i = \beta_0 + \beta_1 x_i$ and define the sigmoid $\sigma(z)=\frac{1}{1+e^{-z}}$. Bernoulli likelihood: $$p(y_i\mid x_i,\beta) = \sigma(z_i)^{y_i}\,[1-\sigma(z_i)]^{1-y_i}.$$ Log-likelihood: $$\ell(\beta) = \sum_{i=1}^n \big[ y_i\log\sigma(z_i) + (1-y_i)\log(1-\sigma(z_i)) \big].$$ Parameters are estimated by numerical optimization (e.g., Newton or quasi-Newton). The predicted probability is $p(y=1\mid x)=\sigma(\beta_0+\beta_1 x)$, and a threshold of 0.5 is commonly used for classification.
Code¶
- Construct simple binary data:
y = 1_{x>0}. - Fit an LS line
beta_lson the binary labels and plot. - Predictions leave the $[0,1]$ interval and cannot be interpreted as probabilities—this motivates logistic regression.
from sklearn.linear_model import LogisticRegression
x = np.random.uniform(-4, 4, 50)
y = (x > 0).astype(int)
X = np.column_stack((np.ones(len(x)), x))
beta_ls = np.linalg.inv(X.T @ X) @ X.T @ y
model = LogisticRegression()
model.fit(x.reshape(-1, 1), y)
x_test = np.linspace(-5, 5, 200)
p = model.predict_proba(x_test.reshape(-1, 1))[:, 1]
plt.close(5)
plt.figure(5)
plt.scatter(x, y, s=55, alpha=0.9, edgecolors='k', linewidths=0.4, label="Binary data")
plt.plot(x, X @ beta_ls, color='crimson', linewidth=2, label="LS output")
plt.plot(x_test, p, color='darkorange', linewidth=2, label="Logistic P(y=1|x)")
plt.axhline(0, color='gray', lw=1)
plt.axhline(1, color='gray', lw=1)
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.title("Linear & Logistic Regression for Classification")
plt.ylim(-0.1, 1.1)
plt.grid(True, ls='--', alpha=0.5)
plt.tight_layout()
plt.show()